commit 30795b7316dc7f971118e44939efb72bff81c76d Author: Vickenty Zherebov Date: Thu Nov 5 14:26:28 2026 +0300 Publish portable Telegram MCP with bundled Teleproto CLI diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4242e75 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.env +.env.* +*.session +*.session.* +*.log +*.sock +*.pid +*.tgz +__pycache__/ +*.py[cod] +.venv/ +node_modules/ +dist/ +coverage/ +.private/ +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..2543328 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Разработка + +Клонируйте https://git.flowmasters.ru/vik/telegram-mcp.git, перейдите в его корень и выполните: + +```sh +python3 scripts/manage.py setup +python3 scripts/manage.py test +python3 scripts/export_source.py /tmp/telegram-mcp-source.tar.gz +``` + +Проверки выполняются без реальных Telegram-отправок. TypeScript: strict, ESM, tsup, vitest. MCP: Python 3.11+, unittest и настоящий stdio smoke на закреплённом SDK. Не добавляйте live Telegram-вызовы в тесты по умолчанию. + +Сохраните stdout как структурированные данные. Не меняйте форму CLI envelope, daemon wire protocol, destroy()/блокировки сессий и правило отсутствия повторной отправки после таймаута. Новые операции MCP должны быть типизированы; изменения начинать с предпросмотра. Файлы `dist` не редактируются и не публикуются как исходники. + +Для изменения Python-зависимостей редактируйте requirements.in и пересобирайте requirements.lock через `uv pip compile requirements.in --generate-hashes -o requirements.lock --python-version 3.11`. npm-зависимости фиксируются cli/package-lock.json. Сохраняйте Teleproto pin и локальные дополнения при обновлении upstream. + +Каждое изменение — отдельная ветка и review перед merge; исходники и данные аккаунтов не смешиваются. Публичная публикация этого подготовительного комплекта требует решения владельца. + +Экспорт работает по allowlist, не включает Git history, node_modules, .venv, runtime state или произвольные файлы. Проверки экспорта не заменяют review: перед релизом просмотрите весь manifest и назначьте приватный security contact. + +## Related + +- [README](README.md) +- [Подключение](docs/setup-development.md) +- [Происхождение](UPSTREAM.md) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e3a079f --- /dev/null +++ b/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2026 Telegram MCP contributors + +Bundled CLI: Copyright (c) 2026 miolamio; see cli/LICENSE. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ece5ed6 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# Telegram MCP + +61 инструмент для работы с Telegram из ИИ-помощника: новости, переписки, папки, черновики, файлы и планы поездок. Пользовательский клиент, работающий от вашего аккаунта. + +Открытый репозиторий: [vik/telegram-mcp](https://git.flowmasters.ru/vik/telegram-mcp). В комплект входят MCP и исходники нашей сборки CLI. Готовые бинарные релизы пока не выпускаются. + +## Быстрый старт + +1. **Выберите окружение:** macOS или Linux, Python 3.11+, Node.js 20+. Windows — через WSL; нативная Windows не поддерживается этим комплектом. +2. **Скачайте исходники:** [ZIP ветки main](https://git.flowmasters.ru/vik/telegram-mcp/archive/main.zip), распакуйте и откройте терминал в папке проекта. **Установите:** `python3 scripts/manage.py setup`. Зависимости и сборка останутся внутри папки проекта; глобальный CLI не заменяется. +3. **Войдите в Telegram:** `python3 scripts/manage.py login`. Команду запускает человек в своём терминале; код и пароль вводятся интерактивно. Для WSS: `python3 scripts/manage.py login --transport wss`. +4. **Подключите MCP и попробуйте:** ручная настройка описана в [инструкции подключения](docs/setup-development.md). Первый запрос: «Прочитай выбранный мной канал и составь краткую сводку со ссылками. Пока ничего не отправляй». + +Установка не входит в аккаунт и не редактирует настройки вашего ИИ-приложения. `python3 scripts/manage.py check` проверяет 61 схему и пробный предпросмотр без Telegram. + +## Возможности + +| Задача | Что даёт связка | +|---|---| +| Новости без повторов | История и поиск → сводка ИИ с источниками | +| Где нужен мой ответ | Контекст обсуждений → вопросы и договорённости | +| Черновики | Подготовка ответа → сохранение в нужном чате | +| Поездка | Даты и варианты → план, опрос, папка | +| Порядок | Папки, пересечения, архив, закрепления, уведомления | +| Медиа | Поиск, скачивание, отправка файлов и доступные истории | + +ИИ анализирует полученные данные; MCP сам не генерирует картинки, не распознаёт речь и не запускает регулярные дайджесты. Для этих задач нужны отдельные инструменты или расписание. + +## Документация + +- [Четыре сценария](examples/scenarios.md) +- [Каталог 61 инструмента](docs/tools.md) +- [Документация и архитектура](docs/README.md) +- [Конфиденциальность и управление действиями](SECURITY.md) +- [Разработка и тестирование](CONTRIBUTING.md) +- [Происхождение и лицензия](UPSTREAM.md) + +## Related + +- [Подключение и обслуживание](docs/setup-development.md) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..a5d599e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,22 @@ +# Конфиденциальность и действия + +MCP предоставляет ИИ доступ к вашему пользовательскому аккаунту Telegram в пределах его прав. Тексты, возвращённые инструментами, попадают в выбранное вами ИИ-приложение: локальный транспорт не означает, что модель работает локально. + +Сессия даёт доступ к аккаунту. Не публикуйте каталог состояния, config, `.env`, session strings, коды входа или пароли. Вход выполняйте вручную в терминале. Не отдавайте эти данные в запросах ИИ. Стандартный каталог состояния находится вне checkout. + +Новые 49 методов требуют явного account. Команды изменения из этого набора по умолчанию возвращают предпросмотр (`dry_run=true`). Это не система авторизации: поручение человека всё равно требуется. Старые `send_message`, `send_html`, `send_file`, `schedule_message` выполняют отправку непосредственно — вызывайте их только после явного поручения. Каталог описывает эту разницу. + +Перед применением изменений папок требуется revision свежего чтения/предпросмотра. Общие папки не изменяются. Проверка optimistic, не атомарная транзакция Telegram. Аудит ограничен заданным количеством диалогов: `complete=false` обозначает частичный результат. + +Не повторяйте отправку после неизвестного исхода. MCP повторяет вызов только при доказанном отсутствии отправки в daemon (`DAEMON_NOT_RUNNING`). Таймаут, разрыв связи и ошибки API не повторяются автоматически. + +В MCP нет generic eval/raw invoke, экспорта авторизации или массового удаления участников. Сам CLI имеет более широкие команды, включая управление сессиями: наличие CLI не означает разрешения агенту их использовать. Не используйте комплект для спама. + +Скачанные файлы — данные из внешнего источника; не исполняйте их автоматически. Часть инструментов пишет локальные файлы, хотя для Telegram это чтение. Истории с запретом сохранения не скачиваются; скачивание ограничено 30 МиБ. OCR и транскрибация требуют отдельных инструментов. + +Не публикуйте потенциальные секреты и exploit-данные в общедоступных issues. Для получения приватного канала связи создайте [issue](https://git.flowmasters.ru/vik/telegram-mcp/issues) с темой «Нужен приватный канал для security report», без технических деталей, вложений или секретов. Передайте подробности только после согласования приватного канала с владельцем. + +## Related + +- [Подключение](docs/setup-development.md) +- [README](README.md) diff --git a/UPSTREAM.md b/UPSTREAM.md new file mode 100644 index 0000000..355be9a --- /dev/null +++ b/UPSTREAM.md @@ -0,0 +1,17 @@ +# Upstream attribution + +CLI: [miolamio/tg-cli](https://github.com/miolamio/tg-cli), MIT, original notice retained in [cli/LICENSE](cli/LICENSE). + +Snapshot base commit: `d8dd9a4cbbddfe38e77d8e226cbb8e89d72de297`. This is a source snapshot with local modifications, not a claim that upstream released this version. CLI version: `0.6.1-teleproto.1`; Teleproto: `1.232.1`. + +Local additions include Teleproto migration, daemon bridge, folder organization/audit, notification settings, drafts and scheduled queue operations. MCP is packaged separately here, with portable isolated state and no dependency on a personal workspace. + +The original npm name is retained to preserve source/package provenance; `private: true` prevents accidental npm publication. This bundle does not report issues to the upstream project automatically. + +Dependency licenses belong to their respective authors; see the generated [license inventory](docs/dependency-licenses.json). The Python dependency inventory is in [python-dependency-licenses.json](docs/python-dependency-licenses.json). The CLI test-only `gramjs-reference` dependency brings `@cryptography/aes` (GPL-3.0-or-later); it is not the runtime SDK and is not vendored in the source archive. Inventories cover installed packages on the verification platform; lockfiles also contain optional packages for other platforms. + +No upstream Git history, private operational documents, credentials or sessions are included. + +## Related + +- [README](README.md) diff --git a/cli/LICENSE b/cli/LICENSE new file mode 100644 index 0000000..9b1629f --- /dev/null +++ b/cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 miolamio + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/cli/package-lock.json b/cli/package-lock.json new file mode 100644 index 0000000..1b22187 --- /dev/null +++ b/cli/package-lock.json @@ -0,0 +1,4084 @@ +{ + "name": "@miolamio/tg-cli", + "version": "0.6.1-teleproto.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@miolamio/tg-cli", + "version": "0.6.1-teleproto.1", + "license": "MIT", + "dependencies": { + "@toon-format/toon": "^2.3.1", + "commander": "^14.0.3", + "conf": "^15.1.0", + "picocolors": "^1.1.1", + "proper-lockfile": "^4.1.2", + "teleproto": "1.232.1", + "ws": "8.22.1", + "zod": "^4.3.6" + }, + "bin": { + "telegram-cli": "dist/bin/tg.js", + "tg": "dist/bin/tg.js" + }, + "devDependencies": { + "@types/node": "^25.4.0", + "@types/proper-lockfile": "^4.1.4", + "@types/ws": "8.18.1", + "@vitest/coverage-v8": "^3.2.7", + "gpt-tokenizer": "^3.4.0", + "gramjs-reference": "npm:telegram@2.26.22", + "tsup": "^8.5.1", + "typescript": "^5.9.3", + "vitest": "^3.2.7" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@ampproject/remapping": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", + "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@cifrante/darwin-arm64": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/darwin-arm64/-/darwin-arm64-0.8.1.tgz", + "integrity": "sha512-CSHC3rayWsjNWWa0FxQe5nCVKa5TKCurTPnj00EZxk7y6P+1ApFUdB8Qdsw1HcVR1trSO8arvYc31R2y6LZWRQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@cifrante/darwin-x64": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/darwin-x64/-/darwin-x64-0.8.1.tgz", + "integrity": "sha512-UROiCYX3a3xyQBy3LOMH4TnzkTWoCtmEjETCpWb1PPiIEeE/rAjFh9831XlR9ZfrUg0TUysPcV5sBju3EHrK7w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@cifrante/linux-arm64-gnu": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/linux-arm64-gnu/-/linux-arm64-gnu-0.8.1.tgz", + "integrity": "sha512-6OvNHT6hrBupku8PBCF2yGC0133KdaKpaHDz7w2N18nwewjFqdRaX5DDBoUusqzO7f4bfX1a36oYWArNeMfVqQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@cifrante/linux-arm64-musl": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/linux-arm64-musl/-/linux-arm64-musl-0.8.1.tgz", + "integrity": "sha512-o8rrO4olBigzSvCXssyByP+5JUSuniN//OIM3FVkMY9oYXkoZcTBTCmsC45ggZlhcUAxK/+HxMfWJ2n4QApE5Q==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@cifrante/linux-x64-gnu": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/linux-x64-gnu/-/linux-x64-gnu-0.8.1.tgz", + "integrity": "sha512-qP7FBxZb25WUlXZcX4I6cT62H41YxEaGGkvoo/NzJNL2Wezk0ifJpylFUoiXnxsVmyyhtWZ7EcaFDwHthmo2Eg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@cifrante/linux-x64-musl": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/linux-x64-musl/-/linux-x64-musl-0.8.1.tgz", + "integrity": "sha512-p1A/uhcsB8nLb5b6yEBlMOFAR21GgBscHjp0BCie5iz8PGp/Ty5GvAuh+9nNeY4bube5Gy6iUDC7OXkpG4TdwA==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@cifrante/win32-arm64": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/win32-arm64/-/win32-arm64-0.8.1.tgz", + "integrity": "sha512-VxkF/WJlDeeq5oY5T9fX632TzqN7yJ0KW6Xc4AA0PKSKi5EfFuBmVlpkShnQOBg5zkCJ7D02Yrm6xz1ByNm/8w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@cifrante/win32-x64": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cifrante/win32-x64/-/win32-x64-0.8.1.tgz", + "integrity": "sha512-GGxGANoFAfe1VCkFcsAaHyFNCnP6DKFcKG6RJRabGDQRuoDT55Uy/bqn72r9azchcDCkcckz385+M9WTmBb72g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@cryptography/aes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@cryptography/aes/-/aes-0.1.1.tgz", + "integrity": "sha512-PcYz4FDGblO6tM2kSC+VzhhK62vml6k6/YAkiWtyPvrgJVfnDRoHGDtKn5UiaRRUrvUTTocBpvc2rRgTCqxjsg==", + "dev": true, + "license": "GPL-3.0-or-later" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@toon-format/toon": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@toon-format/toon/-/toon-2.3.1.tgz", + "integrity": "sha512-sWqEMeAJGMda9qRrfPKrX3C4c33CO9SJuvJzzrcBEn5sbDB+k6pSLkDsfN0rVnLQwR97MV3sDgVbcxQNsq8xVw==", + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.4.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.4.0.tgz", + "integrity": "sha512-9wLpoeWuBlcbBpOY3XmzSTG3oscB6xjBEEtn+pYXTfhyXhIxC5FsBer2KTopBlvKEiW9l13po9fq+SJY/5lkhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/proper-lockfile": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@types/proper-lockfile/-/proper-lockfile-4.1.4.tgz", + "integrity": "sha512-uo2ABllncSqg9F1D4nugVl9v93RmjxF6LJzQLMLDdPaXCUIDPeOJ21Gbqi43xNKzBi/WQ0Q0dICqufzQbMjipQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/retry": "*" + } + }, + "node_modules/@types/retry": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.5.tgz", + "integrity": "sha512-3xSjTp3v03X/lSQLkczaN9UIEwJMoMCA1+Nb5HfbJEQWogdeQIyVtTvxPXDQjZ5zws8rFQfVfRdz03ARihPJgw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vitest/coverage-v8": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-3.2.7.tgz", + "integrity": "sha512-NEGWJS2XNu2PfRLQwOO3CTKj1tTETxNBdk454vDxVBhxJYhPaA/eS0nAI0c+1El1P7a60z8+i+ZrQoGESweGKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.3.0", + "@bcoe/v8-coverage": "^1.0.2", + "ast-v8-to-istanbul": "^0.3.3", + "debug": "^4.4.1", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.6", + "istanbul-reports": "^3.1.7", + "magic-string": "^0.30.17", + "magicast": "^0.3.5", + "std-env": "^3.9.0", + "test-exclude": "^7.0.1", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "3.2.7", + "vitest": "3.2.7" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/@vitest/coverage-v8/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.12", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.12.tgz", + "integrity": "sha512-BRRC8VRZY2R4Z4lFIL35MwNXmwVqBityvOIwETtsCSwvjl0IdgFsy9NhdaA6j74nUdtJJlIypeRhpDam19Wq3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-mutex": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz", + "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/atomically": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/atomically/-/atomically-2.1.1.tgz", + "integrity": "sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ==", + "license": "MIT", + "dependencies": { + "stubborn-fs": "^2.0.0", + "when-exit": "^2.1.4" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, + "node_modules/bufferutil": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.1.0.tgz", + "integrity": "sha512-ZMANVnAixE6AWWnPzlW2KpUrxhm9woycYvPOo67jWHyFowASTEd9s+QN1EIMsSDtwhIxN4sWE1jotpuDUIgyIw==", + "devOptional": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/cifrante": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/cifrante/-/cifrante-0.8.1.tgz", + "integrity": "sha512-6IKK0R5Ur37hgktw1KyJO14jIMpjcj0q5H+gSt/Xev9aYNv7k7cOLNCXHFzNNOR3jbot2d+6ae/dqvS+7Ebtaw==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@cifrante/darwin-arm64": "0.8.1", + "@cifrante/darwin-x64": "0.8.1", + "@cifrante/linux-arm64-gnu": "0.8.1", + "@cifrante/linux-arm64-musl": "0.8.1", + "@cifrante/linux-x64-gnu": "0.8.1", + "@cifrante/linux-x64-musl": "0.8.1", + "@cifrante/win32-arm64": "0.8.1", + "@cifrante/win32-x64": "0.8.1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/conf": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/conf/-/conf-15.1.0.tgz", + "integrity": "sha512-Uy5YN9KEu0WWDaZAVJ5FAmZoaJt9rdK6kH+utItPyGsCqCgaTKkrmZx3zoE0/3q6S3bcp3Ihkk+ZqPxWxFK5og==", + "license": "MIT", + "dependencies": { + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "atomically": "^2.0.3", + "debounce-fn": "^6.0.0", + "dot-prop": "^10.0.0", + "env-paths": "^3.0.0", + "json-schema-typed": "^8.0.1", + "semver": "^7.7.2", + "uint8array-extras": "^1.5.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/d": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/d/-/d-1.0.2.tgz", + "integrity": "sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==", + "dev": true, + "license": "ISC", + "dependencies": { + "es5-ext": "^0.10.64", + "type": "^2.7.2" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/debounce-fn": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/debounce-fn/-/debounce-fn-6.0.0.tgz", + "integrity": "sha512-rBMW+F2TXryBwB54Q0d8drNEI+TfoS9JpNTAoVpukbWEhjXQq4rySFYLaqXMFXwdv61Zb2OHtj5bviSoimqxRQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/dom-serializer": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-1.4.1.tgz", + "integrity": "sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.2.0", + "entities": "^2.0.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", + "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-4.3.1.tgz", + "integrity": "sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.2.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/domutils": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-2.8.0.tgz", + "integrity": "sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^1.0.1", + "domelementtype": "^2.2.0", + "domhandler": "^4.2.0" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dot-prop": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-10.1.0.tgz", + "integrity": "sha512-MVUtAugQMOff5RnBy2d9N31iG0lNwg1qAoAOn7pOK5wf94WIaE3My2p3uwTQuvS2AcqchkcR3bHByjaM0mmi7Q==", + "license": "MIT", + "dependencies": { + "type-fest": "^5.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", + "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "dev": true, + "license": "BSD-2-Clause", + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es5-ext": { + "version": "0.10.64", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", + "integrity": "sha512-p2snDhiLaXe6dahss1LddxqEm+SkuDvV8dnIQG0MWjyHpcMNfXKPE+/Cc0y+PhxJX3A4xGNeFCj5oc0BUh6deg==", + "dev": true, + "hasInstallScript": true, + "license": "ISC", + "dependencies": { + "es6-iterator": "^2.0.3", + "es6-symbol": "^3.1.3", + "esniff": "^2.0.1", + "next-tick": "^1.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/es6-iterator": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", + "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "dev": true, + "license": "MIT", + "dependencies": { + "d": "1", + "es5-ext": "^0.10.35", + "es6-symbol": "^3.1.1" + } + }, + "node_modules/es6-symbol": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.4.tgz", + "integrity": "sha512-U9bFFjX8tFiATgtkJ1zg25+KviIXpgRvRHS8sau3GfhVzThRQrOeksPeT0BWW2MNZs1OEWJ1DPXOQMn0KKRkvg==", + "dev": true, + "license": "ISC", + "dependencies": { + "d": "^1.0.2", + "ext": "^1.7.0" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/esniff": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/esniff/-/esniff-2.0.1.tgz", + "integrity": "sha512-kTUIGKQ/mDPFoJ0oVfcmyJn4iBDRptjNVIzwIFR7tqWXdVI9xfA2RMwY/gbSpJG3lkdWNEjLap/NqVHZiJsdfg==", + "dev": true, + "license": "ISC", + "dependencies": { + "d": "^1.0.1", + "es5-ext": "^0.10.62", + "event-emitter": "^0.3.5", + "type": "^2.7.2" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/event-emitter": { + "version": "0.3.7", + "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.7.tgz", + "integrity": "sha512-R9h/VgWniW4ZRqx3Pd2/n3aGGbPmWilvHwzgrc6YQcFd2HzwPsIFLbrtfoU0hWorKUowd5Iqr5x3ZNv5H6bP+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "d": "^1.0.2", + "es5-ext": "^0.10.64", + "type": "^2.7.3" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/ext": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", + "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", + "dev": true, + "license": "ISC", + "dependencies": { + "type": "^2.7.2" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", + "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/gpt-tokenizer": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/gpt-tokenizer/-/gpt-tokenizer-3.4.0.tgz", + "integrity": "sha512-wxFLnhIXTDjYebd9A9pGl3e31ZpSypbpIJSOswbgop5jLte/AsZVDvjlbEuVFlsqZixVKqbcoNmRlFDf6pz/UQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/gramjs-reference": { + "name": "telegram", + "version": "2.26.22", + "resolved": "https://registry.npmjs.org/telegram/-/telegram-2.26.22.tgz", + "integrity": "sha512-EIj7Yrjiu0Yosa3FZ/7EyPg9s6UiTi/zDQrFmR/2Mg7pIUU+XjAit1n1u9OU9h2oRnRM5M+67/fxzQluZpaJJg==", + "deprecated": "This package is archived and no longer maintained. Development continues in teleproto (https://npmjs.com/package/teleproto), a largely compatible, actively maintained fork. See the migration guide at https://docs.teleproto.dev/migrating-from-gramjs", + "dev": true, + "license": "MIT", + "dependencies": { + "@cryptography/aes": "^0.1.1", + "async-mutex": "^0.3.0", + "big-integer": "^1.6.48", + "buffer": "^6.0.3", + "htmlparser2": "^6.1.0", + "mime": "^3.0.0", + "node-localstorage": "^2.2.1", + "pako": "^2.0.3", + "path-browserify": "^1.0.1", + "real-cancellable-promise": "^1.1.1", + "socks": "^2.6.2", + "store2": "^2.13.0", + "ts-custom-error": "^3.2.0", + "websocket": "^1.0.34" + }, + "optionalDependencies": { + "bufferutil": "^4.0.3", + "utf-8-validate": "^5.0.5" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/htmlparser2": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-6.1.0.tgz", + "integrity": "sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.0.1", + "domhandler": "^4.0.0", + "domutils": "^2.5.2", + "entities": "^2.0.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/ip-address": { + "version": "10.7.5", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.5.tgz", + "integrity": "sha512-t2v0rkILYv9WXmSL7TpAaU3HXgaFYOPUcH3QHgwQ++gpJuH3bqyMy4Fvt/DJCTKwzH3Cf+bAp5W/mFL39KPLzA==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/istanbul-lib-source-maps/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.3.5.tgz", + "integrity": "sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.25.4", + "@babel/types": "^7.25.4", + "source-map-js": "^1.2.0" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz", + "integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mlly": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.1.tgz", + "integrity": "sha512-SnL6sNutTwRWWR/vcmCYHSADjiEesp5TGQQ0pXyLhW5IoeibRlF/CbSLailbB3CNqJUk9cVJ9dUDnbD7GrcHBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "dev": true, + "license": "MIT" + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/next-tick": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "devOptional": true, + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-localstorage": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-2.2.1.tgz", + "integrity": "sha512-vv8fJuOUCCvSPjDjBLlMqYMHob4aGjkmrkaE42/mZr0VT+ZAU10jRF8oTnX9+pgU9/vYJ8P7YT3Vd6ajkmzSCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "write-file-atomic": "^1.1.4" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/pako": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz", + "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "(MIT AND Zlib)" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/real-cancellable-promise": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/real-cancellable-promise/-/real-cancellable-promise-1.2.3.tgz", + "integrity": "sha512-hBI5Gy/55VEeeMtImMgEirD7eq5UmqJf1J8dFZtbJZA/3rB0pYFZ7PayMGueb6v4UtUtpKpP+05L0VwyE1hI9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/slide": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", + "integrity": "sha512-NwrtjCg+lZoqhFU8fOwl4ay2ei8PaqCBOUV3/ektPY9trO1yQ1oXEfmHAhKArUVUr/hOHvy5f6AdP17dCM0zMw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "*" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/store2": { + "version": "2.14.4", + "resolved": "https://registry.npmjs.org/store2/-/store2-2.14.4.tgz", + "integrity": "sha512-srTItn1GOvyvOycgxjAnPA63FZNwy0PTyUBFMHRM+hVFltAeoh0LmNBz9SZqUS9mMqGk8rfyWyXn3GH5ReJ8Zw==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/stubborn-fs": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/stubborn-fs/-/stubborn-fs-2.0.0.tgz", + "integrity": "sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==", + "license": "MIT", + "dependencies": { + "stubborn-utils": "^1.0.1" + } + }, + "node_modules/stubborn-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stubborn-utils/-/stubborn-utils-1.0.2.tgz", + "integrity": "sha512-zOh9jPYI+xrNOyisSelgym4tolKTJCQd5GBhK0+0xJvcYDcwlOoxF/rnFKQ2KRZknXSG9jWAp66fwP6AxN9STg==", + "license": "MIT" + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/teleproto": { + "version": "1.232.1", + "resolved": "https://registry.npmjs.org/teleproto/-/teleproto-1.232.1.tgz", + "integrity": "sha512-39fQMS12G+yyGqRmcwRrAzPMGiyOKGDM8sU9eS2ubSzG6UD13X+qnebr/EPmToJ3TqkLlnJuxFJGG69k+jToFg==", + "license": "MIT", + "dependencies": { + "big-integer": "^1.6.48", + "buffer": "^6.0.3", + "cifrante": "0.8.1", + "mime": "^3.0.0", + "node-localstorage": "^3.0.5", + "socks": "^2.6.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/sanyok12345" + } + }, + "node_modules/teleproto/node_modules/node-localstorage": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/node-localstorage/-/node-localstorage-3.0.5.tgz", + "integrity": "sha512-GCwtK33iwVXboZWYcqQHu3aRvXEBwmPkAMRBLeaX86ufhqslyUkLGsi4aW3INEfdQYpUB5M9qtYf3eHvAk2VBg==", + "license": "MIT", + "dependencies": { + "write-file-atomic": "^5.0.1" + }, + "engines": { + "node": ">=0.12" + } + }, + "node_modules/teleproto/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/teleproto/node_modules/write-file-atomic": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", + "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/test-exclude": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", + "integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==", + "dev": true, + "license": "ISC", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^10.4.1", + "minimatch": "^10.2.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-custom-error": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz", + "integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD" + }, + "node_modules/tsup": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz", + "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.27.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "^0.7.6", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/tsup/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/tsup/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/type": { + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/type/-/type-2.7.3.tgz", + "integrity": "sha512-8j+1QmAbPvLZow5Qpi6NCaN8FB60p/6x8/vfNqOk/hC+HuvFZhL4+WfekuhQLiqFZXOgQdrs3B+XxEmCc6b3FQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/type-fest": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.4.4.tgz", + "integrity": "sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.3.tgz", + "integrity": "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/uint8array-extras": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "devOptional": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite-node/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/vite-node/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/websocket": { + "version": "1.0.35", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.35.tgz", + "integrity": "sha512-/REy6amwPZl44DDzvRCkaI1q1bIiQB0mEFQLUrhz3z2EK91cp3n72rAjUlrTP0zV22HJIUOVHQGPxhFRjxjt+Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bufferutil": "^4.0.1", + "debug": "^2.2.0", + "es5-ext": "^0.10.63", + "typedarray-to-buffer": "^3.1.5", + "utf-8-validate": "^5.0.2", + "yaeti": "^0.0.6" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/when-exit": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/when-exit/-/when-exit-2.1.5.tgz", + "integrity": "sha512-VGkKJ564kzt6Ms1dbgPP/yuIoQCrsFAnRbptpC5wOEsDaNsbCB2bnfnaA8i/vRs5tjUSEOtIuvl9/MyVsvQZCg==", + "license": "MIT" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/write-file-atomic": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-1.3.4.tgz", + "integrity": "sha512-SdrHoC/yVBPpV0Xq/mUZQIpW2sWXAShb/V4pomcJXh92RuaO+f3UTWItiR3Px+pLnV2PvC2/bfn5cwr5X6Vfxw==", + "dev": true, + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "slide": "^1.1.5" + } + }, + "node_modules/ws": { + "version": "8.22.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", + "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yaeti": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "integrity": "sha512-MvQa//+KcZCUkBTIC9blM+CU9J2GzuTytsOUwf2lidtvkx/6gnEp1QvJv34t9vdjhFmha/mUiNDbN0D0mJWdug==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.32" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/cli/package.json b/cli/package.json new file mode 100644 index 0000000..eef0b9b --- /dev/null +++ b/cli/package.json @@ -0,0 +1,67 @@ +{ + "name": "@miolamio/tg-cli", + "version": "0.6.1-teleproto.1", + "type": "module", + "description": "Telegram CLI client for Claude Code agents and power users", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "bin": { + "tg": "./dist/bin/tg.js", + "telegram-cli": "./dist/bin/tg.js" + }, + "engines": { + "node": ">=20" + }, + "scripts": { + "build": "tsup", + "prepack": "npm run build", + "dev": "tsup --watch", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage", + "typecheck": "tsc --noEmit" + }, + "files": [ + "dist", + "CHANGELOG.md" + ], + "keywords": [ + "telegram", + "cli", + "mtproto", + "teleproto" + ], + "license": "MIT", + "dependencies": { + "@toon-format/toon": "^2.3.1", + "commander": "^14.0.3", + "conf": "^15.1.0", + "picocolors": "^1.1.1", + "proper-lockfile": "^4.1.2", + "teleproto": "1.232.1", + "ws": "8.22.1", + "zod": "^4.3.6" + }, + "overrides": { + "esbuild": "^0.28.2", + "vite": "^6.4.3" + }, + "devDependencies": { + "@types/node": "^25.4.0", + "@types/proper-lockfile": "^4.1.4", + "@types/ws": "8.18.1", + "@vitest/coverage-v8": "^3.2.7", + "gpt-tokenizer": "^3.4.0", + "gramjs-reference": "npm:telegram@2.26.22", + "tsup": "^8.5.1", + "typescript": "^5.9.3", + "vitest": "^3.2.7" + }, + "private": true +} diff --git a/cli/src/bin/tg.ts b/cli/src/bin/tg.ts new file mode 100644 index 0000000..e8839f3 --- /dev/null +++ b/cli/src/bin/tg.ts @@ -0,0 +1,180 @@ +import { createBridgeCommand } from '../commands/bridge/index.js'; +import { Command, CommanderError } from 'commander'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; +import { createAuthCommand } from '../commands/auth/index.js'; +import { createSessionCommand } from '../commands/session/index.js'; +import { createChatCommand } from '../commands/chat/index.js'; +import { createMessageCommand } from '../commands/message/index.js'; +import { createMediaCommand } from '../commands/media/index.js'; +import { createUserCommand } from '../commands/user/index.js'; +import { createContactCommand } from '../commands/contact/index.js'; +import { createDaemonCommand } from '../commands/daemon/index.js'; +import { createCompletionCommand } from '../commands/completion/index.js'; +import { setOutputMode, setJsonlMode, setToonMode, setFieldSelection, outputError } from '../lib/output.js'; +import { setQuietMode, setVerboseMode } from '../lib/cli-mode.js'; +import { ErrorCode } from '../lib/error-codes.js'; +import { validateProfile } from '../lib/validate.js'; +import { validateTransport } from '../lib/transport.js'; +import { formatError, TgError } from '../lib/errors.js'; +import { installCliConsoleGuard } from '../lib/cli-console.js'; +import { DaemonCommandHandled, routeThroughDaemon } from '../lib/daemon/route.js'; +import { formatHelpBanner } from '../lib/branding.js'; + +installCliConsoleGuard(); + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +// Read package version and gramjs version for --version output +let pkgVersion = '0.0.0'; +let gramjsVersion = 'unknown'; +try { + const pkg = JSON.parse( + readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8'), + ); + pkgVersion = pkg.version; +} catch {} +try { + const gramjsPkg = JSON.parse( + readFileSync( + createRequire(import.meta.url).resolve('teleproto/package.json'), + 'utf-8', + ), + ); + gramjsVersion = gramjsPkg.version; +} catch {} +const versionString = `${pkgVersion} (teleproto ${gramjsVersion})`; + +// Create root program +const program = new Command() + .name('tg') + .description('Telegram CLI - Agent-first Telegram client') + .version(versionString, '-V, --version'); + +// Global options available on all commands via optsWithGlobals() +program + .option('--json', 'JSON output (default)', true) + .option('--no-json', 'Human-readable output (alias for --human)') + .option('--human', 'Human-readable output') + .option('-v, --verbose', 'Show extra info') + .option('-q, --quiet', 'Suppress stderr output') + .option('--profile ', 'Named profile', 'default') + .option('--config ', 'Config file path') + .option('--transport ', 'Telegram transport: tcp or wss (default: saved profile or tcp)') + .option('--fields ', 'Select output fields (comma-separated, dot notation for nested)') + .option('--jsonl', 'Output one JSON object per line (list commands only)') + .option('--toon', 'Token-efficient TOON output (LLM-optimized)') + .option('--daemon', 'Route command through persistent daemon connection'); + +program.addHelpText('before', ({ error }) => error ? '' : formatHelpBanner(!!program.opts().quiet)); + +// Global options are parsed at any position in the command line + +// Set output mode before any action runs based on --human or --no-json flags +function configureOutput(): void { + const opts = program.optsWithGlobals(); + const isHuman = opts.human === true || opts.json === false; + setOutputMode(isHuman); + setQuietMode(!!opts.quiet); + setVerboseMode(!!opts.verbose); + // Invalid combinations use a deterministic error format. + setToonMode(!!opts.toon && !isHuman && !opts.jsonl); + setJsonlMode(!!opts.jsonl && !isHuman && !opts.toon); + if (opts.fields) setFieldSelection(opts.fields.split(',').map((f: string) => f.trim())); +} + +program.hook('preAction', async (thisCommand, actionCommand) => { + configureOutput(); + const opts = thisCommand.optsWithGlobals(); + validateProfile(opts.profile); + if (opts.transport !== undefined) { + validateTransport(opts.transport); + if (opts.daemon || (actionCommand.name() === 'watch' && actionCommand.parent?.name() === 'message')) { + throw new TgError('Choose --transport when starting the daemon; commands use its existing connection', ErrorCode.INVALID_OPTIONS); + } + } + const isHuman = opts.human === true || opts.json === false; + + // --toon mutual exclusion checks + if (opts.toon && isHuman) { + throw new TgError('--toon and --human are mutually exclusive', ErrorCode.INVALID_OPTIONS); + } + if (opts.toon && opts.jsonl) { + throw new TgError('--toon and --jsonl are mutually exclusive', ErrorCode.INVALID_OPTIONS); + } + + // --jsonl and --human are mutually exclusive + if (opts.jsonl && isHuman) { + throw new TgError('--jsonl and --human are mutually exclusive', ErrorCode.INVALID_OPTIONS); + } + + if (await routeThroughDaemon(actionCommand)) throw new DaemonCommandHandled(); + +}); + +// Wire command groups with help group headings +const authCmd = createAuthCommand(); +authCmd.helpGroup('Auth'); +program.addCommand(authCmd); + +const sessionCmd = createSessionCommand(); +sessionCmd.helpGroup('Session'); +program.addCommand(sessionCmd); + +const chatCmd = createChatCommand(); +chatCmd.helpGroup('Chat'); +program.addCommand(chatCmd); + +const messageCmd = createMessageCommand(); +messageCmd.helpGroup('Message'); +program.addCommand(messageCmd); + +const mediaCmd = createMediaCommand(); +mediaCmd.helpGroup('Media'); +program.addCommand(mediaCmd); + +const userCmd = createUserCommand(); +userCmd.helpGroup('User'); +program.addCommand(userCmd); + +const contactCmd = createContactCommand(); +contactCmd.helpGroup('Contact'); +program.addCommand(contactCmd); +const bridgeCmd = createBridgeCommand(); +bridgeCmd.helpGroup('Utility'); +program.addCommand(bridgeCmd); + +const daemonCmd = createDaemonCommand(); +daemonCmd.helpGroup('Daemon'); +program.addCommand(daemonCmd); + +const completionCmd = createCompletionCommand(); +completionCmd.helpGroup('Utility'); +program.addCommand(completionCmd); + +// Groups are constructed separately, so install the exit hook on every level. +// Commander parse errors must use the same output contract as async actions. +function configureCommandErrors(command: Command): void { + command.exitOverride(); + command.configureOutput({ outputError: () => {} }); + for (const child of command.commands) configureCommandErrors(child); +} +configureCommandErrors(program); + +try { + await program.parseAsync(); +} catch (err: unknown) { + if (err instanceof DaemonCommandHandled) { + // The daemon result has already been rendered, including its exit status. + } else if (err instanceof CommanderError && err.exitCode === 0) { + // Explicit --help and --version have already rendered their normal output. + process.exitCode = 0; + } else { + configureOutput(); + const { message, code } = formatError(err); + outputError(message, err instanceof CommanderError ? ErrorCode.INVALID_OPTIONS : code ?? ErrorCode.UNKNOWN_ERROR); + } +} diff --git a/cli/src/commands/auth/index.ts b/cli/src/commands/auth/index.ts new file mode 100644 index 0000000..caedca2 --- /dev/null +++ b/cli/src/commands/auth/index.ts @@ -0,0 +1,36 @@ +import { Command } from 'commander'; +import { loginAction } from './login.js'; +import { statusAction } from './status.js'; +import { logoutAction } from './logout.js'; + +/** + * Create the `auth` command group with login, status, and logout subcommands. + * + * Usage: + * tg auth login - Log in with phone number + code + optional 2FA + * tg auth status - Check current authentication status + * tg auth logout - Log out and destroy session + */ +export function createAuthCommand(): Command { + const auth = new Command('auth') + .description('Authentication commands'); + + auth + .command('login') + .description('Log in with phone number + code + optional 2FA') + .option('--client ', 'Use official client preset (desktop, android, ios, macos, web-z)') + .option('--phone ', 'Phone number in international format (skips the phone prompt)') + .action(loginAction); + + auth + .command('status') + .description('Check current authentication status') + .action(statusAction); + + auth + .command('logout') + .description('Log out and destroy session') + .action(logoutAction); + + return auth; +} diff --git a/cli/src/commands/auth/login.ts b/cli/src/commands/auth/login.ts new file mode 100644 index 0000000..3e3182b --- /dev/null +++ b/cli/src/commands/auth/login.ts @@ -0,0 +1,124 @@ +import type { Command } from 'commander'; +import { LogLevel } from 'teleproto/extensions/Logger.js'; +import { createConfig, getCredentialsOrThrow } from '../../lib/config.js'; +import { resolveTransport } from '../../lib/transport.js'; +import { createPrompt } from '../../lib/prompt.js'; +import { createClientForAuth } from '../../lib/client.js'; +import { connectOrThrow } from '../../lib/connect.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { formatError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js'; +import { showLoginBanner } from '../../lib/branding.js'; +import { validatePhone } from '../../lib/validate.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Login action handler for `tg auth login`. + * + * Requires an interactive terminal (TTY). Fails fast with a structured + * error when stdin is not a TTY (CI, piped input, agent automation). + * + * Invokes gramjs client.start() with interactive prompts for + * phone number, verification code, and optional 2FA password. + * Saves the resulting session string to disk on success. + */ +export async function loginAction(this: Command): Promise { + const opts = this.optsWithGlobals() as GlobalOptions & { client?: string; phone?: string }; + const { profile, quiet } = opts; + + if (await refuseDirectConnectIfDaemon(opts)) return; + + // Fail fast when not running in an interactive terminal + if (!process.stdin.isTTY) { + outputError( + 'Interactive login requires a terminal (TTY). Use `tg session import` for non-interactive auth.', + ErrorCode.NOT_INTERACTIVE, + ); + return; + } + + const config = createConfig(opts.config); + const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, '')); + try { + await store.withLock(profile, async () => { + const prompt = createPrompt(); + let client: Awaited> | undefined; + let phone = ''; + const ask = async (question: string, secret = false): Promise => { + // Only this client's SDK logger is paused; restore it even on rejection. + const logger = client?.logger; + const previousLevel = logger?.logLevel; + logger?.setLevel(LogLevel.NONE); + try { return await (secret ? prompt.askSecret(question) : prompt.ask(question)); } + finally { if (logger && previousLevel !== undefined) logger.setLevel(previousLevel); } + }; + try { + showLoginBanner(quiet); + // Collect the phone before credential fetching, connect(), or the SDK's + // authorization check can block or fill the terminal with diagnostics. + phone = validatePhone(opts.phone ?? await ask('Phone number (international format): ')); + const { apiId, apiHash } = await getCredentialsOrThrow(config, opts.client, profile); + const transport = resolveTransport(config, profile, opts.transport); + client = await createClientForAuth(apiId, apiHash, transport); + + logStatus('Starting authentication...', quiet); + + await connectOrThrow(client); + logStatus('Connected. Starting sign-in...', quiet); + let phoneRequests = 0; + await client.start({ + // A literal --phone makes gramjs propagate sendCode failures instead + // of repeatedly submitting the same invalid phone via a callback. + phoneNumber: opts.phone !== undefined ? phone : async () => { + if (phoneRequests++ > 0) phone = validatePhone(await ask('Phone number (international format): ')); + logStatus('Requesting login code...', quiet); + return phone; + }, + phoneCode: async (isCodeViaApp?: boolean) => { + const msg = isCodeViaApp + ? 'Code (from Telegram app): ' + : 'Code (from SMS): '; + return ask(msg); + }, + password: async (hint?: string) => { + const msg = hint + ? `2FA password (hint: ${hint}): ` + : '2FA password: '; + return ask(msg, true); + }, + onError: (err: Error) => { + logStatus(`Auth error: ${err.message}`, quiet); + }, + }); + + // Save session string + const sessionString = client.session.save() as unknown as string; + store.saveUnlocked(profile, sessionString); + + // Update profile in config + const clientName = opts.client ?? config.get(`profiles.${profile}.client`); + config.set(`profiles.${profile}`, { + ...(clientName ? { client: clientName } : {}), + transport, + phone, + created: new Date().toISOString(), + }); + + logStatus('Login successful!', quiet); + outputSuccess({ + loggedIn: true, + profile, + phone, + }); + } finally { + if (client) await client.destroy().catch(() => {}); + prompt.close(); + } + }); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code ?? ErrorCode.UNKNOWN_ERROR); + } +} diff --git a/cli/src/commands/auth/logout.ts b/cli/src/commands/auth/logout.ts new file mode 100644 index 0000000..cb736d2 --- /dev/null +++ b/cli/src/commands/auth/logout.ts @@ -0,0 +1,52 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { createConfig, getCredentialsOrThrow } from '../../lib/config.js'; +import { resolveTransport } from '../../lib/transport.js'; +import { withClient } from '../../lib/client.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { formatError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Logout action handler for `tg auth logout`. + * + * Connects with the existing session, invokes auth.LogOut on the server, + * then deletes the local session file and removes the profile from config. + */ +export async function logoutAction(this: Command): Promise { + const opts = this.optsWithGlobals() as GlobalOptions; + const { profile, quiet } = opts; + if (await refuseDirectConnectIfDaemon(opts)) return; + + const config = createConfig(opts.config); + const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, '')); + + try { + await store.withLock(profile, async (sessionString, holdUntil) => { + if (!sessionString) { + outputError('Not logged in', ErrorCode.NOT_LOGGED_IN); + return; + } + + const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile); + + await withClient({ apiId, apiHash, sessionString, transport: resolveTransport(config, opts.profile, opts.transport) }, async (client) => { + logStatus('Logging out...', quiet); + await client.invoke(new Api.auth.LogOut()); + }, { holdUntil }); + + // Delete file without re-acquiring lock (we're already inside withLock) + store.deleteUnlocked(profile); + config.delete(`profiles.${profile}` as never); + + logStatus('Logged out successfully.', quiet); + outputSuccess({ loggedOut: true }); + }); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code ?? ErrorCode.UNKNOWN_ERROR); + } +} diff --git a/cli/src/commands/auth/status.ts b/cli/src/commands/auth/status.ts new file mode 100644 index 0000000..83c51b8 --- /dev/null +++ b/cli/src/commands/auth/status.ts @@ -0,0 +1,65 @@ +import type { Command } from 'commander'; +import { createConfig, getCredentialsOrThrow } from '../../lib/config.js'; +import { resolveTransport } from '../../lib/transport.js'; +import { withClient } from '../../lib/client.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { formatError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Status action handler for `tg auth status`. + * + * Checks whether the current session is authorized. + * If no session file exists, outputs { authorized: false } without connecting. + * If session exists, connects and checks authorization state. + */ +export async function statusAction(this: Command): Promise { + const opts = this.optsWithGlobals() as GlobalOptions; + const { profile, quiet } = opts; + if (await refuseDirectConnectIfDaemon(opts)) return; + + const config = createConfig(opts.config); + const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, '')); + + try { + await store.withLock(profile, async (sessionString, holdUntil) => { + if (!sessionString) { + outputSuccess({ authorized: false, reason: 'No session found' }); + return; + } + + const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile); + + await withClient({ apiId, apiHash, sessionString, transport: resolveTransport(config, opts.profile, opts.transport) }, async (client, signal) => { + const authorized = await client.checkAuthorization(); + signal.throwIfAborted(); + + if (authorized) { + const me = await client.getMe(); + signal.throwIfAborted(); + outputSuccess({ + authorized: true, + user: { + id: bigIntToString((me as any)?.id), + phone: (me as any)?.phone, + username: (me as any)?.username, + firstName: (me as any)?.firstName, + }, + }); + } else { + outputSuccess({ + authorized: false, + reason: 'Session expired or invalid', + }); + } + }, { holdUntil }); + }); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code ?? ErrorCode.UNKNOWN_ERROR); + } +} diff --git a/cli/src/commands/bridge/dialog-scan.ts b/cli/src/commands/bridge/dialog-scan.ts new file mode 100644 index 0000000..6c8855d --- /dev/null +++ b/cli/src/commands/bridge/dialog-scan.ts @@ -0,0 +1,121 @@ +import { Api, type TelegramClient } from 'teleproto'; +import { getPeerId, getInputPeer, getDisplayName } from 'teleproto/Utils.js'; +import bigInt from 'big-integer'; +import { randomUUID } from 'node:crypto'; +import { TgError } from '../../lib/errors.js'; + +// In-memory state on the existing daemon/session. Never serialize input peers, +// access hashes, message bodies or session data into a continuation token. +interface Scan { + token: string; created: number; touched: number; rows: any[]; seen: Set; + offsetId: number; offsetDate: number; offsetPeer: Api.TypeInputPeer; + excludePinned: boolean; complete: boolean; busy: boolean; + pages: number; skipped: number; lastOffset?: string; +} +interface Owner { scans: Map; current?: string; retryAt: number } +const owners = new WeakMap>(); +const TTL = 30 * 60_000; + +function owner(client: TelegramClient, account: string): Owner { + const key = client.session ?? client; + let accounts = owners.get(key); + if (!accounts) owners.set(key, accounts = new Map()); + let value = accounts.get(account); + if (!value) accounts.set(account, value = { scans: new Map(), retryAt: 0 }); + return value; +} + +export function floodSeconds(error: unknown): number | undefined { + const e = error as any; + const name = `${e?.errorMessage ?? ''} ${e?.message ?? ''} ${e?.code ?? ''}`; + if (!/FLOOD(?:_PREMIUM)?_WAIT/i.test(name)) return; + const seconds = Number(e?.seconds ?? name.match(/FLOOD(?:_PREMIUM)?_WAIT_?(\d+)/i)?.[1]); + return Number.isFinite(seconds) && seconds >= 0 ? Math.max(1, Math.ceil(seconds)) : undefined; +} + +export function recordReadFlood(client: TelegramClient, account: string, error: unknown) { + const seconds = floodSeconds(error); + if (seconds === undefined) throw error; + const o = owner(client, account); + o.retryAt = Math.max(o.retryAt, Date.now() + seconds * 1000); + return { retry_after_seconds: Math.ceil((o.retryAt - Date.now()) / 1000), retry_at: new Date(o.retryAt).toISOString() }; +} + +/** At most five server pages per call. FloodWait preserves the last committed + * cursor and returns a deadline; the caller resumes, never replays a write. */ +export async function scanDialogs(client: TelegramClient, account: string, target: number, + cursor?: string, refresh = false) { + if (cursor && refresh) throw new TgError('Use cursor to resume OR refresh to restart', 'INVALID_OPTIONS'); + const o = owner(client, account), now = Date.now(); + for (const [key, s] of o.scans) if (!s.busy && now - s.touched > TTL) o.scans.delete(key); + let s = o.scans.get(cursor ?? (refresh ? '' : o.current ?? '')); + if (cursor && !s) throw new TgError('Dialog cursor expired or belongs to another session/account; restart explicitly', 'CURSOR_EXPIRED'); + if (!s) { + if (o.scans.size >= 4) throw new TgError('Too many active dialog snapshots; reuse a cursor or wait for expiry', 'SCAN_LIMIT'); + s = { token: randomUUID(), created: now, touched: now, rows: [], seen: new Set(), + offsetId: 0, offsetDate: 0, offsetPeer: new Api.InputPeerEmpty(), excludePinned: false, + complete: false, busy: false, pages: 0, skipped: 0 }; + o.scans.set(s.token, s); o.current = s.token; + } + if (s.busy) throw new TgError('Dialog snapshot is in use; resume sequentially', 'SCAN_BUSY'); + s.busy = true; s.touched = now; + try { + for (let page = 0; page < 5 && !s.complete && s.rows.length < target; page++) { + if (Date.now() < o.retryAt) break; + let r: any; + try { + r = await client.invoke(new Api.messages.GetDialogs({ offsetId: s.offsetId, + offsetDate: s.offsetDate, offsetPeer: s.offsetPeer, excludePinned: s.excludePinned, + limit: 100, hash: bigInt.zero })); + } catch (e) { + const seconds = floodSeconds(e); + if (seconds === undefined) throw e; + o.retryAt = Date.now() + seconds * 1000; + break; + } + if (!(r instanceof Api.messages.Dialogs || r instanceof Api.messages.DialogsSlice)) + throw new TgError('Unexpected dialog response; cursor preserved', 'DIALOG_RESPONSE'); + const entities = new Map(); + for (const e of [...r.users, ...r.chats]) entities.set(getPeerId(e), e); + const messages = new Map(); + for (const m of r.messages) if (m.peerId) messages.set(`${getPeerId(m.peerId)}:${m.id}`, m); + const unsupported = r.dialogs.filter((d: any) => !(d instanceof Api.Dialog) && !(d instanceof Api.DialogFolder)).length; + const dialogs = r.dialogs.filter((d: any) => d instanceof Api.Dialog); + const last = dialogs.at(-1); + let next: { id: number; date: number; peer: Api.TypeInputPeer; key: string } | undefined; + const end = r instanceof Api.messages.Dialogs || r.dialogs.length < 100; + if (!end && last) { + const id = getPeerId(last.peer), entity = entities.get(id); + if (!entity) throw new TgError('Missing cursor entity; snapshot incomplete', 'DIALOG_ENTITY'); + next = { id: last.topMessage, date: messages.get(`${id}:${last.topMessage}`)?.date ?? 0, + peer: getInputPeer(entity), key: `${id}:${last.topMessage}` }; + if (next.key === s.lastOffset) throw new TgError('Dialog cursor did not advance; snapshot incomplete', 'CURSOR_STALLED'); + } else if (!end && !last) throw new TgError('No usable dialog cursor; snapshot incomplete', 'CURSOR_STALLED'); + // Commit only after cursor validation. Discard all message bodies here. + for (const d of dialogs) { + const id = getPeerId(d.peer), e = entities.get(id); + if (s.seen.has(id)) continue; + if (!e || e instanceof Api.UserEmpty || e instanceof Api.ChatEmpty) { s.skipped++; continue; } + const m = messages.get(`${id}:${d.topMessage}`), mute = d.notifySettings?.muteUntil; + s.rows.push({ id, title: getDisplayName(e), username: e.username ?? null, + type: e.bot ? 'bot' : e instanceof Api.User ? 'user' : e.broadcast ? 'channel' : 'group', + contact: !!e.contact, self: !!e.self, archived: d.folderId === 1, pinned: !!d.pinned, + unread_count: d.unreadCount, unread_mentions: d.unreadMentionsCount, unread_mark: !!d.unreadMark, + mute_until: mute ?? null, muted: mute == null ? null : mute > Date.now() / 1000, + notifications_inherited: mute == null, last_message_id: d.topMessage, + last_message_at: m?.date ? new Date(m.date * 1000).toISOString() : null, + has_draft: !!(d.draft instanceof Api.DraftMessage && d.draft.message) }); + s.seen.add(id); + } + s.skipped += unsupported; s.pages++; s.complete = end; + if (next) { s.offsetId = next.id; s.offsetDate = next.date; s.offsetPeer = next.peer; + s.lastOffset = next.key; s.excludePinned = true; } + } + s.touched = Date.now(); + return { rows: s.rows, cursor: s.token, complete: s.complete && s.skipped === 0, + exhausted: s.complete, scanned: s.rows.length, skipped: s.skipped, pages_fetched: s.pages, + snapshot_started_at: new Date(s.created).toISOString(), + retry_after_seconds: Math.max(0, Math.ceil((o.retryAt - Date.now()) / 1000)), + retry_at: o.retryAt > Date.now() ? new Date(o.retryAt).toISOString() : null }; + } finally { s.busy = false; } +} diff --git a/cli/src/commands/bridge/index.ts b/cli/src/commands/bridge/index.ts new file mode 100644 index 0000000..c071077 --- /dev/null +++ b/cli/src/commands/bridge/index.ts @@ -0,0 +1,151 @@ +import { Command } from 'commander'; +import { Api, type TelegramClient } from 'teleproto'; +import bigInt from 'big-integer'; +import { CustomFile } from 'teleproto/client/uploads.js'; +import { readFile, writeFile, mkdtemp } from 'node:fs/promises'; +import { basename, isAbsolute, join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess } from '../../lib/output.js'; +import { TgError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { runOrganize } from './organize.js'; + +export const BRIDGE_OPERATIONS = ['html', 'schedule', 'send-dialog', 'delete', 'download-media', 'download-photo', 'download-photo-at', 'contact-photo', 'recent-dms', 'stories', 'organize'] as const; +function invalid(message: string): never { throw new TgError(message, ErrorCode.INVALID_OPTIONS); } +function storyFailure(code: string): never { throw new TgError(code, code); } +function text(value: unknown): string { if (typeof value !== 'string' || !value) invalid('Expected nonempty string'); return value as string; } +function integer(value: unknown, min = 0, max = 2147483647): number { + if (!/^\d+$/.test(String(value))) invalid('Expected integer'); + const n = Number(value); if (!Number.isSafeInteger(n) || n < min || n > max) invalid('Integer out of range'); return n; +} +function file(value: unknown): string { const s = text(value); if (!isAbsolute(s)) invalid('File path must be absolute'); return s; } +async function target(client: TelegramClient, value: string, bare = false): Promise { + // Bare positive IDs can refer to channels as well as users. Require an + // unambiguous cached dialog, never silently send to a different peer kind. + if (bare || /^\d+$/.test(value)) { + const dialogs = await client.getDialogs({ limit: 500 }); + const id = value.startsWith('-100') ? value.slice(4) : value.replace(/^-/, ''); + const matches = dialogs.filter(d => String(d.entity?.id) === id); + if (matches.length !== 1 || !matches[0].entity) invalid('Dialog ID is missing or ambiguous'); + return matches[0].entity; + } + return client.getEntity(value); +} +function storyDescription(story: any, chat: string) { + const media = story.media; + const type = media instanceof Api.MessageMediaPhoto ? 'photo' : media instanceof Api.MessageMediaDocument ? media.document instanceof Api.Document && media.document.mimeType.startsWith('video/') ? 'video' : 'document' : 'unknown'; + const date = (n: number) => n ? new Date(n * 1000).toISOString() : null; + return { id: story.id, state: story.className, date: date(story.date), expires_at: date(story.expireDate), caption: story.caption ?? null, + pinned: Boolean(story.pinned), noforwards: Boolean(story.noforwards), media_type: type, + mime_type: media?.document?.mimeType ?? (type === 'photo' ? 'image/jpeg' : null), link: `https://t.me/${chat}/s/${story.id}` }; +} + +/** Fixed operations for the existing local wrappers; no arbitrary invoke/eval. */ +export async function runBridge(client: TelegramClient, operation: string, payload: unknown): Promise { + if (operation === 'organize') return runOrganize(client, payload); + if (!BRIDGE_OPERATIONS.includes(operation as any)) invalid('Unsupported bridge operation'); + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) invalid('Expected payload object'); + const p = payload as Record; + if (!['main', 'reserve'].includes(p.account)) invalid('Account must be main or reserve'); + const account = p.account; + if (operation === 'stories') { + const chat = text(p.chat); + if (!['list', 'get', 'download'].includes(p.action)) invalid('Invalid story action'); + const peer = await client.getInputEntity(chat); + if (p.action === 'list') { + if (!['pinned', 'active'].includes(p.kind)) invalid('Invalid story kind'); + const limit = integer(p.limit, 1, 100), offsetId = integer(p.offset_id ?? 0); + const result: any = p.kind === 'pinned' ? await client.invoke(new Api.stories.GetPinnedStories({ peer, offsetId, limit })) : await client.invoke(new Api.stories.GetPeerStories({ peer })); + const all = p.kind === 'pinned' ? result.stories : result.stories.stories; + const items = all.slice(0, limit).map((s: any) => storyDescription(s, chat)); + return { kind: p.kind, total: p.kind === 'pinned' ? result.count : all.length, stories: items, + next_offset_id: p.kind === 'pinned' && items.length ? items.at(-1).id : null, truncated: p.kind === 'active' && all.length > items.length }; + } + const storyId = integer(p.story_id, 1); + const result = await client.invoke(new Api.stories.GetStoriesByID({ peer, id: [storyId] })); + const story = result.stories.find(s => s.id === storyId); + if (!(story instanceof Api.StoryItem)) storyFailure('STORY_UNAVAILABLE'); + const meta = storyDescription(story, chat); + if (p.action === 'get') return meta; + if (story.noforwards) storyFailure('MEDIA_PROTECTED'); + if (!['photo', 'video'].includes(meta.media_type)) storyFailure('UNSUPPORTED_MEDIA'); + const max = 30 * 1024 * 1024; + if (Number((story.media as any)?.document?.size ?? 0) > max) storyFailure('MEDIA_TOO_LARGE'); + const bytes = await client.downloadMedia(story.media, {}); + if (!Buffer.isBuffer(bytes) || !bytes.length) storyFailure('EMPTY_MEDIA'); + if (bytes.length > max) storyFailure('MEDIA_TOO_LARGE'); + const dir = await mkdtemp(join(tmpdir(), 'telegram-story-')); + const path = join(dir, `story-${story.id}.${meta.media_type === 'photo' ? 'jpg' : 'mp4'}`); + await writeFile(path, bytes, { mode: 0o600, flag: 'wx' }); + return { ...meta, path, size: bytes.length }; + } + if (operation === 'recent-dms') { + const since = integer(p.since ?? 0, 0, Number.MAX_SAFE_INTEGER), limit = integer(p.limit ?? 100, 1, 1000); + const dialogs = await client.getDialogs({ limit }); + return dialogs.filter(d => d.entity instanceof Api.User && !d.entity.bot && (d.message?.date ?? 0) > since).map(d => { + const e = d.entity as Api.User; + return { user_id: String(e.id), username: e.username ?? null, first_name: e.firstName ?? null, last_name: e.lastName ?? null, + last_msg_date: d.message?.date ?? 0, last_msg_preview: (d.message?.message ?? '').slice(0, 200), unread_count: d.unreadCount ?? 0, is_self: !!e.self }; + }); + } + const chat = text(p.chat); + // Validate all write inputs before resolving peers or uploading anything. + let message: string | undefined, schedule: Date | undefined; + if (['html', 'schedule', 'send-dialog'].includes(operation)) { + message = text(p.text); if (message.length > 4096) invalid('Message too long'); + if (operation === 'schedule') { + schedule = new Date(text(p.when)); + if (!Number.isFinite(schedule.getTime()) || schedule.getTime() <= Date.now() + 10000) invalid('schedule must be at least 10s in the future'); + } + } + if (operation === 'delete' && typeof p.revoke !== 'boolean') invalid('Explicit revoke boolean required'); + const ids = operation === 'delete' ? text(p.ids).split(',').map(id => integer(id, 1)) : []; + const output = ['download-media', 'download-photo', 'download-photo-at'].includes(operation) ? file(p.path) : undefined; + const input = operation === 'contact-photo' ? file(p.path) : undefined; + const messageId = operation === 'download-media' ? integer(p.id, 1) : undefined; + const index = operation === 'download-photo-at' ? integer(p.index, 0, 49) : undefined; + const entity = await target(client, chat, operation === 'send-dialog'); + if (message !== undefined) { + const sent = await client.sendMessage(entity, { message, parseMode: operation === 'html' ? 'html' : undefined, schedule: schedule ? Math.floor(schedule.getTime() / 1000) : undefined }); + if (!sent) throw new TgError('Send outcome unknown; verify before retrying', ErrorCode.MESSAGE_RESULT_UNAVAILABLE); + if (operation === 'html') return { message_id: sent.id, format: 'html', entities: (sent.entities ?? []).map(e => e.className) }; + if (operation === 'schedule') return { id: sent.id, scheduled_for: schedule!.toISOString(), chat, account, preview: message.length > 80 ? message.slice(0, 80) + '…' : message }; + return { sent_to: String(entity.id), title: entity.title || entity.username, message_id: sent.id }; + } + if (operation === 'delete') return { chat, ids, account, result: String(await client.deleteMessages(entity, ids, { revoke: p.revoke })) }; + if (operation === 'contact-photo') { + const bytes = await readFile(input!); + const uploaded = await client.uploadFile({ file: new CustomFile(basename(input!), bytes.length, input!, bytes), workers: 1 }); + const result = await client.invoke(new Api.photos.UploadContactProfilePhoto({ userId: entity, file: uploaded, suggest: false, save: true })); + return { user: chat, entity_id: String(entity.id), photo_id: String(result.photo.id), bytes: bytes.length, account }; + } + let bytes: string | Buffer | undefined, count: number | undefined; + if (operation === 'download-media') { + const messages = await client.getMessages(entity, { ids: [messageId!] }); + if (!messages[0]?.media) invalid('Message has no media'); + bytes = await client.downloadMedia(messages[0], {}); + } else if (operation === 'download-photo') bytes = await client.downloadProfilePhoto(entity, { isBig: true }); + else if (operation === 'download-photo-at') { + const result = await client.invoke(new Api.photos.GetUserPhotos({ userId: entity, offset: 0, maxId: bigInt.zero, limit: 50 })); + count = result.photos.length; + const photo = result.photos[index!]; + if (!(photo instanceof Api.Photo)) invalid('Photo index unavailable'); + bytes = await client.downloadFile(new Api.InputPhotoFileLocation({ id: photo.id, accessHash: photo.accessHash, fileReference: photo.fileReference, thumbSize: 'x' }), { dcId: photo.dcId }); + } + if (!Buffer.isBuffer(bytes) || !bytes.length) invalid('Empty media'); + await writeFile(output!, bytes, { mode: 0o600 }); + if (operation === 'download-photo') return { user: chat, entity_id: String(entity.id), path: output, bytes: bytes.length, account }; + if (operation === 'download-photo-at') return { count, used_index: index, size: bytes.length, path: output }; + return { id: messageId, size: bytes.length, path: output }; +} +export function createBridgeCommand(): Command { + const group = new Command('bridge').description('Compatibility operations for local Telegram wrappers'); + group.command('call ').description('Run a named wrapper operation with JSON payload').action(async function (this: Command, operation: string, payload: string) { + let parsed: unknown; + try { parsed = JSON.parse(payload); } catch { invalid('Invalid JSON payload'); } + await withAuth(this.optsWithGlobals() as GlobalOptions, async client => { outputSuccess(await runBridge(client, operation, parsed)); }); + }); + return group; +} diff --git a/cli/src/commands/bridge/organize.ts b/cli/src/commands/bridge/organize.ts new file mode 100644 index 0000000..9269ef5 --- /dev/null +++ b/cli/src/commands/bridge/organize.ts @@ -0,0 +1,186 @@ +import { Api, type TelegramClient } from 'teleproto'; +import { z } from 'zod'; +import { createHash } from 'node:crypto'; +import bigInt from 'big-integer'; +import { scanDialogs, recordReadFlood } from './dialog-scan.js'; +import { TgError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { serializeMessage } from '../../lib/serialize.js'; + +const peer = z.string().min(1).max(256).refine(s => !s.includes('\0') && !s.startsWith('--')); +const ids = z.array(z.number().int().positive()).min(1).max(100); +const peers = z.array(peer).max(200); +const rules = z.object({ contacts: z.boolean().optional(), nonContacts: z.boolean().optional(), + groups: z.boolean().optional(), broadcasts: z.boolean().optional(), bots: z.boolean().optional(), + excludeMuted: z.boolean().optional(), excludeRead: z.boolean().optional(), excludeArchived: z.boolean().optional() }).strict(); +const patchSchema = z.object({ title: z.string().min(1).max(12).optional(), emoticon: z.string().max(32).optional(), + color: z.number().int().min(0).max(6).optional(), include: peers.optional(), exclude: peers.optional(), + pinned: peers.optional(), rules: rules.optional() }).strict(); +const common = { account: z.enum(['main', 'reserve']) }; +const mutation = { dry_run: z.boolean().default(true) }; +const folderId = z.number().int().min(2).max(255); +const revision = z.string().regex(/^[a-f0-9]{64}$/).optional(); +const schema = z.discriminatedUnion('action', [ + z.object({ ...common, action: z.literal('folders') }).strict(), + z.object({ ...common, action: z.literal('audit'), scan_limit: z.number().int().min(1).max(50000).default(1000), folder_id: folderId.optional(), cursor: z.string().uuid().optional(), refresh: z.boolean().default(false) }).strict(), + z.object({ ...common, action: z.literal('dialogs'), limit: z.number().int().min(1).max(500).default(100), offset: z.number().int().min(0).max(50000).default(0), cursor: z.string().uuid().optional(), refresh: z.boolean().default(false) }).strict(), + z.object({ ...common, action: z.literal('folder-put'), id: folderId, create: z.boolean().default(false), patch: patchSchema, revision, ...mutation }).strict(), + z.object({ ...common, action: z.literal('folder-delete'), id: folderId, revision, ...mutation }).strict(), + z.object({ ...common, action: z.literal('folder-order'), order: z.array(z.number().int().min(0).max(255)).min(1).max(30), revision, ...mutation }).strict(), + z.object({ ...common, action: z.literal('archive'), chat: peer, archived: z.boolean(), ...mutation }).strict(), + z.object({ ...common, action: z.literal('dialog-pin'), chat: peer, pinned: z.boolean(), ...mutation }).strict(), + z.object({ ...common, action: z.literal('unread'), chat: peer, unread: z.boolean(), ...mutation }).strict(), + z.object({ ...common, action: z.literal('read'), chat: peer, max_id: z.number().int().positive(), ...mutation }).strict(), + z.object({ ...common, action: z.literal('notify-get'), chat: peer }).strict(), + z.object({ ...common, action: z.literal('notify-set'), chat: peer, mute_until: z.number().int().min(0).max(2147483647), ...mutation }).strict(), + z.object({ ...common, action: z.literal('scheduled-list'), chat: peer }).strict(), + z.object({ ...common, action: z.enum(['scheduled-delete', 'scheduled-send']), chat: peer, ids, ...mutation }).strict(), + z.object({ ...common, action: z.literal('draft-save'), chat: peer, text: z.string().max(4096), ...mutation }).strict(), +]); + +function fail(message: string): never { throw new TgError(message, ErrorCode.INVALID_OPTIONS); } +function inputPeer(client: TelegramClient, value: string) { + // Numeric strings can otherwise enter username/phone resolution in the SDK. + return client.getInputEntity(/^-?\d+$/.test(value) ? bigInt(value) : value); +} +/** Stable marked peer IDs only: never expose access hashes or file references. */ +export function peerId(p: any): string { + if (p.userId != null) return String(p.userId); + if (p.channelId != null) return `-100${p.channelId}`; + if (p.chatId != null) return `-${p.chatId}`; + if (p instanceof Api.InputPeerSelf) return 'me'; + return fail('Unsupported folder peer'); +} +export function folderDto(f: any) { + if (f instanceof Api.DialogFilterDefault) return { id: 0, kind: 'default' }; + return { id: f.id, kind: f.className, title: f.title?.text ?? '', emoticon: f.emoticon ?? null, + color: f.color ?? null, title_noanimate: !!f.titleNoanimate, + include: (f.includePeers ?? []).map(peerId), exclude: (f.excludePeers ?? []).map(peerId), + pinned: (f.pinnedPeers ?? []).map(peerId), + rules: Object.fromEntries(Object.keys(rules.shape).map(k => [k, !!f[k]])) }; +} +async function folders(client: TelegramClient) { + const raw = await client.getDialogFilters(); + const dto = { tags_enabled: !!raw.tagsEnabled, folders: raw.filters.map(folderDto) }; + return { raw, dto: { ...dto, revision: createHash('sha256').update(JSON.stringify(dto)).digest('hex') } }; +} + +/** Named account-management operations, with previews and optimistic folder revisions. */ +export async function runOrganize(client: TelegramClient, payload: unknown): Promise { + const parsed = schema.safeParse(payload); + if (!parsed.success) fail(parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ')); + const p = parsed.data; + if (p.action === 'folders') return (await folders(client)).dto; + if (p.action === 'audit') { + const scan = await scanDialogs(client, p.account, p.scan_limit + 1, p.cursor, p.refresh); + const { rows: all, ...progress } = scan; + if (scan.retry_after_seconds) return { ...progress, complete: false, audit_pending: true, chats: [], note: 'Wait until retry_at, then resume with cursor; collected metadata retained in daemon.' }; + let state: Awaited>; + const defaults: Record = {}; + try { + state = await folders(client); + for (const [key, scope] of [['user', new Api.InputNotifyUsers()], ['group', new Api.InputNotifyChats()], ['channel', new Api.InputNotifyBroadcasts()]] as const) + defaults[key] = (await client.getNotifySettings(scope)).muteUntil ?? 0; + } catch (error) { + return { ...progress, ...recordReadFlood(client, p.account, error), complete: false, audit_pending: true, chats: [], + note: 'Audit settings rate limited; resume with cursor after retry_at. Dialog metadata retained.' }; + } + const ordinary = state.dto.folders.filter(f => f.kind !== 'default'); + if (p.folder_id !== undefined && !ordinary.some(f => f.id === p.folder_id)) fail('Folder not found'); + const complete = scan.complete && all.length <= p.scan_limit; + const rows = all.slice(0, p.scan_limit); + const chats = rows.map(d => { + const id = d.id; + const category = d.type === 'bot' ? 'user' : d.type; + const muted = (d.mute_until ?? defaults[category]) > Date.now() / 1000; + const unread = d.unread_count > 0 || d.unread_mark || d.unread_mentions > 0; + const memberships = ordinary.filter((f: any) => { + const match = (items: string[]) => items.includes(id) || (d.self && items.includes('me')); + if (match(f.exclude)) return false; + if (match(f.include) || match(f.pinned)) return true; + const r = f.rules; + if (r.excludeArchived && d.archived || r.excludeRead && !unread || r.excludeMuted && muted && d.unread_mentions === 0) return false; + return d.type === 'bot' ? r.bots : d.type === 'user' ? d.contact ? r.contacts : r.nonContacts : category === 'channel' ? r.broadcasts : r.groups; + }).map(f => f.id); + return { ...d, muted, folders: memberships }; + }); + return { ...state.dto, ...progress, complete, scanned: rows.length, scan_limit: p.scan_limit, notification_defaults: defaults, + folders_summary: ordinary.map((f: any) => ({ id: f.id, title: f.title, + matched_in_scan: chats.filter(c => c.folders.includes(f.id)).length })), + outside_folders: chats.filter(c => c.folders.length === 0).map(c => c.id), + overlaps: chats.filter(c => c.folders.length > 1).map(c => ({ id: c.id, folders: c.folders })), + chats: p.folder_id === undefined ? chats : chats.filter(c => c.folders.includes(p.folder_id!)), + note: 'Computed membership from a bounded snapshot, not atomic. Counts are lower bounds when complete=false. Muted mentions may render differently across Telegram clients. Overlap is informational, not an error.' }; + } + if (p.action === 'dialogs') { + const scan = await scanDialogs(client, p.account, p.offset + p.limit + 1, p.cursor, p.refresh); + if (p.offset > scan.rows.length) throw new TgError('Offset not yet collected; resume sequentially with the returned cursor', 'OFFSET_NOT_READY'); + const rows = scan.rows.slice(p.offset, p.offset + p.limit); + const { rows: _all, ...progress } = scan; + const more = !scan.exhausted || scan.rows.length > p.offset + rows.length; + return { ...progress, chats: rows, next_offset: more ? p.offset + rows.length : null, has_more: more, + note: 'Daemon snapshot; resume with cursor and next_offset. Wait retry_after_seconds before resuming. No message bodies/read receipts. Not atomic; muted=null inherits defaults.' }; + } + + if (p.action === 'folder-put' || p.action === 'folder-delete' || p.action === 'folder-order') { + const state = await folders(client); + if (p.revision && p.revision !== state.dto.revision) fail('FOLDER_CONFLICT: read current folders and preview again'); + if (!p.dry_run && !p.revision) fail('Applying folder changes requires the revision returned by a fresh preview'); + if (p.action === 'folder-order') { + const current = state.raw.filters.map(f => f instanceof Api.DialogFilterDefault ? 0 : f.id); + if (new Set(p.order).size !== p.order.length || [...current].sort().join() !== [...p.order].sort().join()) fail('Order must contain every current folder exactly once'); + if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: current, after: p.order }; + const accepted = await client.updateDialogFiltersOrder(p.order); + return { accepted, state: (await folders(client)).dto }; + } + const old = state.raw.filters.find(f => !(f instanceof Api.DialogFilterDefault) && f.id === p.id); + if (p.action === 'folder-delete') { + if (!(old instanceof Api.DialogFilter)) fail('Only existing ordinary folders can be deleted; shared folders require a separate workflow'); + if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: folderDto(old), after: null }; + const accepted = await client.updateDialogFilter(p.id); + return { accepted, state: (await folders(client)).dto }; + } + if (p.create ? !!old : !old) fail(p.create ? 'Folder ID already exists' : 'Folder not found'); + if (old && !(old instanceof Api.DialogFilter)) fail('Shared folder editing is not supported'); + if (p.create && !p.patch.title) fail('New folder requires title'); + const original = old as Api.DialogFilter | undefined; + const args: any = original ? { ...original } : { id: p.id, title: new Api.TextWithEntities({ text: p.patch.title!, entities: [] }), includePeers: [], excludePeers: [], pinnedPeers: [] }; + if (p.patch.title !== undefined) args.title = new Api.TextWithEntities({ text: p.patch.title, entities: [] }); + if (p.patch.emoticon !== undefined) args.emoticon = p.patch.emoticon || undefined; + if (p.patch.color !== undefined) args.color = p.patch.color; + Object.assign(args, p.patch.rules ?? {}); + for (const [key, field] of [['include', 'includePeers'], ['exclude', 'excludePeers'], ['pinned', 'pinnedPeers']] as const) { + if (p.patch[key] !== undefined) { + args[field] = []; + for (const name of p.patch[key]!) args[field].push(await inputPeer(client, name)); + if (new Set(args[field].map(peerId)).size !== args[field].length) fail(`Duplicate ${key} peers`); + } + } + const included = new Set([...args.includePeers, ...args.pinnedPeers].map(peerId)); + if (args.excludePeers.some((e: any) => included.has(peerId(e)))) fail('Peer cannot be both included/pinned and excluded'); + const next = new Api.DialogFilter(args); + if (p.dry_run) return { dry_run: true, revision: state.dto.revision, before: old ? folderDto(old) : null, after: folderDto(next) }; + const accepted = await client.updateDialogFilter(p.id, next); + return { accepted, state: (await folders(client)).dto }; + } + const entity = await inputPeer(client, p.chat); + if (p.action === 'notify-get') { + const n = await client.getNotifySettings(entity); + return { mute_until: n.muteUntil ?? null, silent: n.silent ?? null, show_previews: n.showPreviews ?? null, + inherited: n.muteUntil == null }; + } + if (p.action === 'scheduled-list') return { messages: (await client.getScheduledMessages(entity)).map(m => serializeMessage(m)) }; + if (p.dry_run) return { dry_run: true, operation: p.action, target: p.chat, parameters: p }; + if (p.action === 'archive') await client.editPeerFolders(entity, p.archived ? 1 : 0); + else if (p.action === 'dialog-pin') await client.invoke(new Api.messages.ToggleDialogPin({ peer: entity, pinned: p.pinned })); + else if (p.action === 'unread') await client.invoke(new Api.messages.MarkDialogUnread({ peer: entity, unread: p.unread })); + else if (p.action === 'read') await client.markAsRead(entity, p.max_id); + else if (p.action === 'notify-set') { + const accepted = await client.updateNotifySettings(entity, { muteUntil: p.mute_until }); + const n = await client.getNotifySettings(entity); + return { accepted, mute_until: n.muteUntil ?? null }; + } else if (p.action === 'scheduled-delete') await client.deleteScheduledMessages(entity, p.ids); + else if (p.action === 'scheduled-send') return { messages: (await client.sendScheduledMessages(entity, p.ids)).map(m => serializeMessage(m)) }; + else if (p.action === 'draft-save') return { accepted: await client.saveDraft(entity, { message: p.text, formattingEntities: [] }) }; + return { submitted: true, operation: p.action, chat: p.chat }; +} diff --git a/cli/src/commands/chat/create.ts b/cli/src/commands/chat/create.ts new file mode 100644 index 0000000..90c01bf --- /dev/null +++ b/cli/src/commands/chat/create.ts @@ -0,0 +1,93 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +const CHAT_TYPES = new Set(['group', 'supergroup', 'channel']); + +/** + * Action handler for `tg chat create `. + * + * Creates a new group, supergroup, or channel. + * Options: --type (group|supergroup|channel, default supergroup), --description, --members + */ +export async function chatCreateAction(this: Command, title: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { + type?: string; + description?: string; + members?: string; + }; + + if (!title) { + outputError('Chat title is required', ErrorCode.INVALID_INPUT); + return; + } + + const chatType = opts.type ?? 'supergroup'; + if (!CHAT_TYPES.has(chatType)) { + outputError( + `Invalid chat type '${chatType}'. Use: group, supergroup, channel`, + ErrorCode.INVALID_CHAT_TYPE, + ); + return; + } + + const members = (opts.members ?? '') + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + + if (chatType === 'group' && members.length === 0) { + outputError( + 'Basic groups require at least one other member. Pass --members or use --type supergroup.', + ErrorCode.INVALID_OPTIONS, + ); + return; + } + + await withAuth(opts, async (client) => { + let result: any; + + if (chatType === 'channel' || chatType === 'supergroup') { + result = await client.invoke( + new Api.channels.CreateChannel({ + title, + about: opts.description ?? '', + broadcast: chatType === 'channel', + megagroup: chatType === 'supergroup', + }), + ); + } else { + const users = []; + for (const member of members) { + users.push(await resolveEntity(client, member)); + } + result = await client.invoke( + new Api.messages.CreateChat({ + title, + users, + }), + ); + } + + // messages.CreateChat returns messages.InvitedUsers; channels.CreateChannel + // returns Updates directly. + const updates = chatType === 'group' ? (result.updates ?? result) : result; + const chat = updates.chats?.[0]; + outputSuccess({ + id: chat + ? markedPeerId({ + ...chat, + className: chat.className ?? (chatType === 'group' ? 'Chat' : 'Channel'), + megagroup: chat.megagroup ?? chatType === 'supergroup', + }) + : null, + title, + type: chatType, + }); + }); +} diff --git a/cli/src/commands/chat/edit.ts b/cli/src/commands/chat/edit.ts new file mode 100644 index 0000000..f051a38 --- /dev/null +++ b/cli/src/commands/chat/edit.ts @@ -0,0 +1,53 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Action handler for `tg chat edit <chat>`. + * + * Edits a chat's title and/or description. + * At least one of --title or --description is required. + */ +export async function chatEditAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { title?: string; description?: string }; + + if (!opts.title && !opts.description) { + outputError('At least one of --title or --description is required', ErrorCode.INVALID_INPUT); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + if (entity instanceof Api.Channel) { + if (opts.title) { + await client.invoke(new Api.channels.EditTitle({ channel: entity, title: opts.title })); + } + if (opts.description) { + await client.invoke(new Api.messages.EditChatAbout({ peer: entity, about: opts.description })); + } + } else if (entity instanceof Api.Chat) { + if (opts.title) { + await client.invoke(new Api.messages.EditChatTitle({ chatId: entity.id, title: opts.title })); + } + if (opts.description) { + await client.invoke(new Api.messages.EditChatAbout({ peer: entity, about: opts.description })); + } + } else { + outputError('Cannot edit a user chat', ErrorCode.INVALID_CHAT_TYPE); + return; + } + + outputSuccess({ + chatId: markedPeerId(entity), + updated: true, + title: opts.title ?? null, + description: opts.description ?? null, + }); + }); +} diff --git a/cli/src/commands/chat/index.ts b/cli/src/commands/chat/index.ts new file mode 100644 index 0000000..f1d7c3b --- /dev/null +++ b/cli/src/commands/chat/index.ts @@ -0,0 +1,123 @@ +import { Command } from 'commander'; +import { chatListAction } from './list.js'; +import { chatInfoAction } from './info.js'; +import { chatJoinAction } from './join.js'; +import { chatLeaveAction } from './leave.js'; +import { chatResolveAction } from './resolve.js'; +import { chatInviteInfoAction } from './invite-info.js'; +import { chatMembersAction } from './members.js'; +import { chatTopicsAction } from './topics.js'; +import { chatSearchAction } from './search.js'; +import { chatCreateAction } from './create.js'; +import { chatEditAction } from './edit.js'; +import { chatKickAction } from './kick.js'; + +/** + * Create the `chat` command group (12 subcommands). + * + * Usage: + * tg chat list - List all chats/dialogs + * tg chat info <chat> - Get detailed chat info + * tg chat join <target> - Join a group or channel + * tg chat leave <chat> - Leave a group or channel + * tg chat resolve <input> - Resolve a peer to entity info + * tg chat invite-info <link> - Check invite link info without joining + * tg chat members <chat> - List members of a group/channel + * tg chat topics <chat> - List forum topics in a supergroup + * tg chat search <query> - Search public channels and groups + * tg chat create <title> - Create a group, supergroup, or channel + * tg chat edit <chat> - Edit chat title or description + * tg chat kick <chat> <user> - Kick a user from a group or channel + */ +export function createChatCommand(): Command { + const chat = new Command('chat') + .description('Chat discovery and management'); + + chat + .command('list') + .description('List all chats/dialogs') + .option('--type <type>', 'Filter by type: user, group, channel, supergroup') + .option('--limit <n>', 'Max results', '50') + .option('--offset <n>', 'Skip results', '0') + .action(chatListAction); + + chat + .command('info') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Get detailed chat info') + .action(chatInfoAction); + + chat + .command('join') + .argument('<target>', 'Username, @username, or invite link') + .description('Join a group or channel') + .action(chatJoinAction); + + chat + .command('leave') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Leave a group or channel') + .action(chatLeaveAction); + + chat + .command('resolve') + .argument('<input>', 'Username, ID, or phone number') + .description('Resolve a peer to entity info') + .action(chatResolveAction); + + chat + .command('invite-info') + .argument('<link>', 'Invite link (t.me/+HASH)') + .description('Check invite link info without joining') + .action(chatInviteInfoAction); + + chat + .command('members') + .argument('<chat>', 'Chat ID, username, or @username') + .description('List members of a group/channel') + .option('--limit <n>', 'Max results', '50') + .option('--offset <n>', 'Skip results', '0') + .option('--search <query>', 'Filter members by name') + .action(chatMembersAction); + + chat + .command('topics') + .argument('<chat>', 'Chat ID, username, or @username') + .description('List forum topics in a supergroup') + .option('--limit <n>', 'Max topics', '50') + .option('--offset <n>', 'Skip topics', '0') + .action(chatTopicsAction); + + chat + .command('search') + .argument('<query>', 'Search query') + .description('Search for public channels and groups globally') + .option('--limit <n>', 'Max results', '20') + .action(chatSearchAction); + + chat + .command('create') + .argument('<title>', 'Chat title') + .description('Create a new group, supergroup, or channel') + .option('--type <type>', 'Chat type: group, supergroup, channel', 'supergroup') + .option('--description <text>', 'Chat description') + .option('--members <users>', 'Comma-separated users (required for --type group)') + .action(chatCreateAction); + + chat + .command('edit') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Edit chat title or description') + .option('--title <text>', 'New title') + .option('--description <text>', 'New description') + .action(chatEditAction); + + chat + .command('kick') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<user>', 'User ID, username, or @username') + .description('Kick a user from a group or channel') + .action(chatKickAction); + + return chat; +} diff --git a/cli/src/commands/chat/info.ts b/cli/src/commands/chat/info.ts new file mode 100644 index 0000000..03f59cb --- /dev/null +++ b/cli/src/commands/chat/info.ts @@ -0,0 +1,98 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId, serializeChatPhoto, serializeBannedRights } from '../../lib/serialize.js'; +import type { GlobalOptions, ChatInfo } from '../../lib/types.js'; + +/** + * Action handler for `tg chat info <chat>`. + * + * Gets detailed information for a chat by username, ID, or @username. + * Returns kitchen-sink fields: description, member count, permissions, etc. + */ +export async function chatInfoAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + let chatInfo: ChatInfo; + + if (entity instanceof Api.Channel) { + // Channel or Supergroup + const full = await client.invoke( + new Api.channels.GetFullChannel({ channel: entity }), + ); + const fc = full.fullChat as any; + const type = entity.megagroup ? 'supergroup' : 'channel'; + + chatInfo = { + id: markedPeerId(entity), + title: entity.title ?? '', + type, + username: (entity as any).username ?? null, + description: fc.about ?? null, + memberCount: fc.participantsCount ?? null, + creationDate: entity.date ? new Date(entity.date * 1000).toISOString() : null, + photo: serializeChatPhoto((entity as any).photo), + linkedChatId: fc.linkedChatId + ? markedPeerId({ id: fc.linkedChatId, className: 'Channel' }) + : null, + slowmodeSeconds: fc.slowmodeSeconds ?? null, + permissions: serializeBannedRights((entity as any).defaultBannedRights), + inviteLink: fc.exportedInvite?.link ?? null, + migratedFrom: fc.migratedFromChatId + ? markedPeerId({ id: fc.migratedFromChatId, className: 'Chat' }) + : null, + }; + } else if (entity instanceof Api.Chat) { + // Basic group + const full = await client.invoke( + new Api.messages.GetFullChat({ chatId: entity.id }), + ); + const fc = full.fullChat as any; + + chatInfo = { + id: markedPeerId(entity), + title: entity.title ?? '', + type: 'group', + username: null, + description: fc.about ?? null, + memberCount: fc.participants?.participants?.length ?? null, + creationDate: entity.date ? new Date(entity.date * 1000).toISOString() : null, + photo: serializeChatPhoto((entity as any).photo), + linkedChatId: null, + slowmodeSeconds: null, + permissions: serializeBannedRights((entity as any).defaultBannedRights), + inviteLink: fc.exportedInvite?.link ?? null, + migratedFrom: null, + }; + } else { + // User - basic info only + const user = entity as Api.User; + const firstName = (user as any).firstName ?? ''; + const lastName = (user as any).lastName ?? ''; + const title = lastName ? `${firstName} ${lastName}` : firstName; + + chatInfo = { + id: markedPeerId(user), + title, + type: 'user', + username: (user as any).username ?? null, + description: null, + memberCount: null, + creationDate: null, + photo: serializeChatPhoto((user as any).photo), + linkedChatId: null, + slowmodeSeconds: null, + permissions: null, + inviteLink: null, + migratedFrom: null, + }; + } + + outputSuccess(chatInfo); + }); +} diff --git a/cli/src/commands/chat/invite-info.ts b/cli/src/commands/chat/invite-info.ts new file mode 100644 index 0000000..df76762 --- /dev/null +++ b/cli/src/commands/chat/invite-info.ts @@ -0,0 +1,61 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { extractInviteHash } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg chat invite-info <link>`. + * + * Checks invite link info without joining. + * Handles three result types: + * - ChatInviteAlready: already a member + * - ChatInvite: preview info (title, about, member count) + * - ChatInvitePeek: temporary peek with expiry + */ +export async function chatInviteInfoAction(this: Command, link: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const hash = extractInviteHash(link); + const result = await client.invoke( + new Api.messages.CheckChatInvite({ hash }), + ); + + if (result instanceof Api.ChatInviteAlready) { + const chat = (result as any).chat; + outputSuccess({ + alreadyMember: true, + chat: { + id: markedPeerId(chat), + title: chat?.title ?? '', + }, + }); + } else if (result instanceof Api.ChatInvitePeek) { + const chat = (result as any).chat; + outputSuccess({ + alreadyMember: false, + chat: { + id: markedPeerId(chat), + title: chat?.title ?? '', + }, + expires: new Date((result as any).expires * 1000).toISOString(), + }); + } else if (result instanceof Api.ChatInvite) { + outputSuccess({ + alreadyMember: false, + title: (result as any).title, + about: (result as any).about ?? null, + participantsCount: (result as any).participantsCount ?? 0, + channel: !!(result as any).channel, + broadcast: !!(result as any).broadcast, + }); + } else { + outputError('Unknown invite result type', ErrorCode.UNKNOWN_INVITE_TYPE); + return; + } + }); +} diff --git a/cli/src/commands/chat/join.ts b/cli/src/commands/chat/join.ts new file mode 100644 index 0000000..5a0b147 --- /dev/null +++ b/cli/src/commands/chat/join.ts @@ -0,0 +1,80 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity, extractInviteHash } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Detect if a target string looks like an invite link (contains /+ or /joinchat/). + */ +function isInviteLink(target: string): boolean { + return /(?:t\.me|telegram\.me)\/(?:joinchat\/|\+)/.test(target); +} + +/** + * Action handler for `tg chat join <target>`. + * + * Joins a group or channel by username or invite link. + * - Username/ID: resolves entity, calls JoinChannel + * - Invite link: extracts hash, calls ImportChatInvite + */ +export async function chatJoinAction(this: Command, target: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + if (isInviteLink(target)) { + // Join via invite link + const hash = extractInviteHash(target); + try { + const result = await client.invoke( + new Api.messages.ImportChatInvite({ hash }), + ); + const chat = (result as any)?.chats?.[0]; + outputSuccess({ + joined: true, + chat: chat ? { + id: markedPeerId(chat), + title: chat.title ?? '', + } : { id: '', title: '' }, + }); + } catch (err: unknown) { + const errMsg = err instanceof Error ? err.message : String(err); + if (errMsg.includes('USER_ALREADY_PARTICIPANT')) { + outputError('You are already a member of this chat', ErrorCode.USER_ALREADY_PARTICIPANT); + return; + } + throw err; + } + } else { + // Join by username/ID + const entity = await resolveEntity(client, target); + try { + const inputEntity = await client.getInputEntity(entity); + await client.invoke( + new Api.channels.JoinChannel({ channel: inputEntity as any }), + ); + outputSuccess({ + joined: true, + chat: { + id: markedPeerId(entity), + title: (entity as any).title ?? '', + }, + }); + } catch (err: unknown) { + const errMsg = err instanceof Error ? err.message : String(err); + if (errMsg.includes('USER_ALREADY_PARTICIPANT')) { + outputError('You are already a member of this chat', ErrorCode.USER_ALREADY_PARTICIPANT); + return; + } + if (errMsg.includes('CHANNELS_TOO_MUCH')) { + outputError('Cannot join: you have reached the channel/supergroup limit', ErrorCode.CHANNELS_TOO_MUCH); + return; + } + throw err; + } + } + }); +} diff --git a/cli/src/commands/chat/kick.ts b/cli/src/commands/chat/kick.ts new file mode 100644 index 0000000..93294ab --- /dev/null +++ b/cli/src/commands/chat/kick.ts @@ -0,0 +1,56 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { bigIntToString, markedPeerId } from '../../lib/serialize.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Action handler for `tg chat kick <chat> <user>`. + * + * Kicks a user from a group or supergroup. + */ +export async function chatKickAction(this: Command, chatInput: string, userInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const chatEntity = await resolveEntity(client, chatInput); + const userEntity = await resolveEntity(client, userInput); + + if (!(userEntity instanceof Api.User)) { + outputError('Target must be a user', ErrorCode.NOT_A_USER); + return; + } + + if (chatEntity instanceof Api.Channel) { + await client.invoke( + new Api.channels.EditBanned({ + channel: chatEntity, + participant: userEntity, + bannedRights: new Api.ChatBannedRights({ + untilDate: 0, + viewMessages: true, + }), + }), + ); + } else if (chatEntity instanceof Api.Chat) { + await client.invoke( + new Api.messages.DeleteChatUser({ + chatId: chatEntity.id, + userId: userEntity, + }), + ); + } else { + outputError('Cannot kick from a user chat', ErrorCode.INVALID_CHAT_TYPE); + return; + } + + outputSuccess({ + chatId: markedPeerId(chatEntity), + userId: bigIntToString(userEntity.id), + kicked: true, + }); + }); +} diff --git a/cli/src/commands/chat/leave.ts b/cli/src/commands/chat/leave.ts new file mode 100644 index 0000000..33e03e5 --- /dev/null +++ b/cli/src/commands/chat/leave.ts @@ -0,0 +1,50 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg chat leave <chat>`. + * + * Leaves a group or channel. + * - Channel/Supergroup: uses LeaveChannel + * - Basic group: uses DeleteChatUser with self as user + */ +export async function chatLeaveAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + if (entity instanceof Api.Channel) { + // Channel or supergroup + await client.invoke( + new Api.channels.LeaveChannel({ channel: entity }), + ); + } else if (entity instanceof Api.Chat) { + // Basic group: remove self + const me = await client.getMe(); + await client.invoke( + new Api.messages.DeleteChatUser({ + chatId: entity.id, + userId: (me as any).id, + }), + ); + } else { + outputError('Cannot leave a user chat', ErrorCode.INVALID_CHAT_TYPE); + return; + } + + outputSuccess({ + left: true, + chat: { + id: markedPeerId(entity), + title: (entity as any).title ?? '', + }, + }); + }); +} diff --git a/cli/src/commands/chat/list.ts b/cli/src/commands/chat/list.ts new file mode 100644 index 0000000..915ad64 --- /dev/null +++ b/cli/src/commands/chat/list.ts @@ -0,0 +1,103 @@ +import type { Command } from 'commander'; +import type { TelegramClient } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { bigIntToString, serializeDialog } from '../../lib/serialize.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { ChatListItem, GlobalOptions } from '../../lib/types.js'; + +const DIALOG_BATCH = 100; +const MAX_DIALOGS = 5000; + +/** + * Keep fetching dialogs until we have `offset + limit` matches of `type`, + * or the dialog list is exhausted. + */ +async function fetchTypedPage( + client: TelegramClient, + type: string, + offset: number, + limit: number, +): Promise<{ chats: ChatListItem[]; total: number; hasMore: boolean }> { + const needed = offset + limit; + const matching: ChatListItem[] = []; + const seen = new Set<string>(); + let last: any; + let fetched = 0; + let exhausted = false; + + while (matching.length < needed && fetched < MAX_DIALOGS) { + const params: Record<string, unknown> = { limit: DIALOG_BATCH }; + if (last) { + params.offsetDate = last.date ?? last.message?.date; + params.offsetId = last.message?.id ?? last.topMessage ?? 0; + params.offsetPeer = last.inputEntity ?? last.entity; + } + const batch = await client.getDialogs(params as any); + if (!batch.length) { + exhausted = true; + break; + } + fetched += batch.length; + for (const dialog of batch) { + const key = bigIntToString((dialog as any).id) || String((dialog as any).id); + if (seen.has(key)) continue; + seen.add(key); + last = dialog; + const chat = serializeDialog(dialog); + if (chat.type === type) matching.push(chat); + } + if (batch.length < DIALOG_BATCH) { + exhausted = true; + break; + } + } + + return { + chats: matching.slice(offset, offset + limit), + total: matching.length, + hasMore: + matching.length > offset + limit + || (matching.length >= needed && !exhausted && fetched < MAX_DIALOGS), + }; +} + +/** + * Action handler for `tg chat list`. + * + * Lists all chats/dialogs with optional type filtering and pagination. + * Options: --type (user|group|channel|supergroup), --limit (default 50), --offset (default 0) + */ +export async function chatListAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { type?: string; limit: string; offset: string }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + if (opts.type) { + const { chats, total, hasMore } = await fetchTypedPage(client, opts.type, offset, limit); + outputSuccess({ chats, total, hasMore }); + return; + } + + const dialogs = await client.getDialogs({ + limit: offset + limit, + }); + + const chats = dialogs.map(serializeDialog).slice(offset, offset + limit); + + outputSuccess({ + chats, + total: (dialogs as any).total ?? 0, + }); + }); +} diff --git a/cli/src/commands/chat/members.ts b/cli/src/commands/chat/members.ts new file mode 100644 index 0000000..68ae392 --- /dev/null +++ b/cli/src/commands/chat/members.ts @@ -0,0 +1,46 @@ +import type { Command } from 'commander'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeMember } from '../../lib/serialize.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import type { Api } from 'teleproto'; + +/** + * Action handler for `tg chat members <chat>`. + * + * Lists members of a group or channel with pagination and search. + * Options: --limit (default 50), --offset (default 0), --search <query> + */ +export async function chatMembersAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { limit: string; offset: string; search?: string }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + const participants = await client.getParticipants(entity, { + limit, + offset, + search: opts.search, + }); + + const members = participants.map((p: any) => serializeMember(p as Api.User)); + + outputSuccess({ + members, + total: (participants as any).total ?? 0, + }); + }); +} diff --git a/cli/src/commands/chat/resolve.ts b/cli/src/commands/chat/resolve.ts new file mode 100644 index 0000000..dfb9871 --- /dev/null +++ b/cli/src/commands/chat/resolve.ts @@ -0,0 +1,51 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Determine the entity type string from a resolved entity. + */ +function entityType(entity: Api.User | Api.Chat | Api.Channel): string { + if (entity instanceof Api.Channel) { + return (entity as any).megagroup ? 'supergroup' : 'channel'; + } + if (entity instanceof Api.Chat) return 'group'; + return 'user'; +} + +/** + * Get a display title from a resolved entity. + */ +function entityTitle(entity: Api.User | Api.Chat | Api.Channel): string { + if (entity instanceof Api.User) { + const first = (entity as any).firstName ?? ''; + const last = (entity as any).lastName ?? ''; + return last ? `${first} ${last}` : first; + } + return (entity as any).title ?? ''; +} + +/** + * Action handler for `tg chat resolve <input>`. + * + * Resolves a peer by username, numeric ID, or phone number. + * Outputs the entity's id, type, title, and username. + */ +export async function chatResolveAction(this: Command, input: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, input); + + outputSuccess({ + id: markedPeerId(entity), + type: entityType(entity), + title: entityTitle(entity), + username: (entity as any).username ?? null, + }); + }); +} diff --git a/cli/src/commands/chat/search.ts b/cli/src/commands/chat/search.ts new file mode 100644 index 0000000..09dd2fd --- /dev/null +++ b/cli/src/commands/chat/search.ts @@ -0,0 +1,57 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Determine chat type from a gramjs Chat or Channel entity. + */ +function chatType(entity: any): string { + if (entity.className === 'Channel') { + return entity.megagroup ? 'supergroup' : 'channel'; + } + if (entity.className === 'Chat') return 'group'; + return 'unknown'; +} + +/** + * Action handler for `tg chat search <query>`. + * + * Searches for public channels and groups globally via contacts.Search. + * Returns the chats array from the API response (channels, supergroups, groups). + * Options: --limit (default 20) + */ +export async function chatSearchAction(this: Command, query: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string }; + + let limit: number; + try { + ({ limit } = validatePagination({ limit: opts.limit }, 20)); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const found = await client.invoke( + new Api.contacts.Search({ q: query, limit }), + ); + + const chats = ((found as any).chats ?? []) + .filter((c: any) => c.className === 'Channel' || c.className === 'Chat') + .map((c: any) => ({ + id: markedPeerId(c), + title: c.title ?? '', + type: chatType(c), + username: c.username ?? null, + membersCount: c.participantsCount ?? null, + })); + + outputSuccess({ chats, total: chats.length }); + }); +} diff --git a/cli/src/commands/chat/topics.ts b/cli/src/commands/chat/topics.ts new file mode 100644 index 0000000..0f4006c --- /dev/null +++ b/cli/src/commands/chat/topics.ts @@ -0,0 +1,87 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { withAuth } from '../../lib/with-auth.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { TgError, formatError } from '../../lib/errors.js'; +import { validatePagination } from '../../lib/validate.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeTopic } from '../../lib/serialize.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Action handler for `tg chat topics <chat>`. + * + * Lists forum topics in a supergroup with pagination. + * Options: --limit (default 50), --offset (default 0) + * + * Forum guard: rejects non-forum chats with NOT_A_FORUM error code. + * Filters out ForumTopicDeleted items from API results. + * Applies client-side offset slicing for simple pagination. + */ +export async function chatTopicsAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { limit: string; offset: string }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + // Forum guard: entity must be a Channel with forum enabled + if ((entity as any).className !== 'Channel') { + throw new TgError('Chat is not a forum-enabled supergroup', ErrorCode.NOT_A_FORUM); + } + if ((entity as any).forum !== true) { + throw new TgError('Chat is not a forum-enabled supergroup', ErrorCode.NOT_A_FORUM); + } + + const TOPIC_BATCH = 100; + const needed = offset + limit; + const collected: any[] = []; + let offsetDate = 0; + let offsetId = 0; + let offsetTopic = 0; + let total = 0; + + while (collected.length < needed) { + const result = await client.invoke( + new Api.messages.GetForumTopics({ + peer: entity as Api.Channel, + offsetDate, + offsetId, + offsetTopic, + limit: TOPIC_BATCH, + }), + ); + total = (result as any).count ?? total; + const raw = ((result as any).topics ?? []) as any[]; + // ForumTopicDeleted items count toward the API limit and are the + // pagination placeholders. Filter them only from the user-facing list. + if (!raw.length) break; + for (const t of raw) { + if (t.className !== 'ForumTopicDeleted') collected.push(t); + } + const last = raw[raw.length - 1]; + offsetTopic = last.id ?? offsetTopic; + offsetId = last.topMessage ?? 0; + offsetDate = last.date ?? 0; + if (raw.length < TOPIC_BATCH) break; + } + + const serialized = collected.map(serializeTopic); + const sliced = serialized.slice(offset, offset + limit); + + outputSuccess({ + topics: sliced, + total, + }); + }); +} diff --git a/cli/src/commands/completion/index.ts b/cli/src/commands/completion/index.ts new file mode 100644 index 0000000..677dc1e --- /dev/null +++ b/cli/src/commands/completion/index.ts @@ -0,0 +1,121 @@ +import { Command } from 'commander'; +import { outputError } from '../../lib/output.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Generate shell completion scripts for bash, zsh, or fish. + * Install via: eval "$(tg completion bash)" + */ +export function createCompletionCommand(): Command { + const completion = new Command('completion') + .argument('<shell>', 'Shell type: bash, zsh, or fish') + .description('Generate shell completion script') + .action((shell: string) => { + const scripts: Record<string, string> = { + bash: generateBashCompletion(), + zsh: generateZshCompletion(), + fish: generateFishCompletion(), + }; + + const script = scripts[shell]; + if (!script) { + outputError(`Unknown shell: ${shell}. Use: bash, zsh, or fish`, ErrorCode.INVALID_INPUT); + return; + } + + process.stdout.write(script); + }); + + return completion; +} + +function generateBashCompletion(): string { + return `# tg bash completion +_tg_completions() { + local cur prev commands + cur="\${COMP_WORDS[COMP_CWORD]}" + prev="\${COMP_WORDS[COMP_CWORD-1]}" + + commands="auth session chat message media user contact daemon completion" + + case "\${COMP_WORDS[1]}" in + auth) COMPREPLY=( $(compgen -W "login status logout" -- "$cur") ) ;; + session) COMPREPLY=( $(compgen -W "export import" -- "$cur") ) ;; + chat) COMPREPLY=( $(compgen -W "list info join leave resolve invite-info members topics search create edit kick" -- "$cur") ) ;; + message) COMPREPLY=( $(compgen -W "history search get pinned send forward react replies edit delete pin unpin poll watch" -- "$cur") ) ;; + media) COMPREPLY=( $(compgen -W "download send" -- "$cur") ) ;; + user) COMPREPLY=( $(compgen -W "profile block unblock blocked" -- "$cur") ) ;; + contact) COMPREPLY=( $(compgen -W "list add delete search" -- "$cur") ) ;; + daemon) COMPREPLY=( $(compgen -W "start stop status" -- "$cur") ) ;; + *) COMPREPLY=( $(compgen -W "$commands" -- "$cur") ) ;; + esac +} +complete -F _tg_completions tg +`; +} + +function generateZshCompletion(): string { + return `#compdef tg +_tg() { + local -a commands + local state + _arguments -C \\ + '1: :->command' \\ + '*:: :->args' + + case $state in + command) + commands=( + 'auth:Authentication management' + 'session:Session import/export' + 'chat:Chat discovery and management' + 'message:Message reading and sending' + 'media:Media upload/download' + 'user:User profiles and blocking' + 'contact:Contact management' + 'daemon:Persistent connection daemon' + 'completion:Generate shell completions' + ) + _describe 'command' commands + ;; + args) + case $words[1] in + auth) _describe 'subcommand' '(login:Log in status:Auth status logout:Log out)' ;; + session) _describe 'subcommand' '(export:Export session import:Import session)' ;; + chat) _describe 'subcommand' '(list:List chats info:Chat info join:Join leave:Leave resolve:Resolve invite-info:Invite info members:Members topics:Topics search:Search create:Create edit:Edit kick:Kick)' ;; + message) _describe 'subcommand' '(history:History search:Search get:Get pinned:Pinned send:Send forward:Forward react:React replies:Replies edit:Edit delete:Delete pin:Pin unpin:Unpin poll:Poll watch:Watch)' ;; + media) _describe 'subcommand' '(download:Download send:Send)' ;; + user) _describe 'subcommand' '(profile:Profile block:Block unblock:Unblock blocked:Blocked)' ;; + contact) _describe 'subcommand' '(list:List add:Add delete:Delete search:Search)' ;; + daemon) _describe 'subcommand' '(start:Start stop:Stop status:Status)' ;; + esac + ;; + esac +} +_tg "$@" +`; +} + +function generateFishCompletion(): string { + return `# tg fish completion +complete -c tg -n '__fish_use_subcommand' -a auth -d 'Authentication management' +complete -c tg -n '__fish_use_subcommand' -a session -d 'Session import/export' +complete -c tg -n '__fish_use_subcommand' -a chat -d 'Chat discovery and management' +complete -c tg -n '__fish_use_subcommand' -a message -d 'Message reading and sending' +complete -c tg -n '__fish_use_subcommand' -a media -d 'Media upload/download' +complete -c tg -n '__fish_use_subcommand' -a user -d 'User profiles and blocking' +complete -c tg -n '__fish_use_subcommand' -a contact -d 'Contact management' +complete -c tg -n '__fish_use_subcommand' -a daemon -d 'Persistent connection daemon' +complete -c tg -n '__fish_use_subcommand' -a completion -d 'Generate shell completions' + +complete -c tg -n '__fish_seen_subcommand_from auth' -a 'login status logout' +complete -c tg -n '__fish_seen_subcommand_from session' -a 'export import' +complete -c tg -n '__fish_seen_subcommand_from chat' -a 'list info join leave resolve invite-info members topics search create edit kick' +complete -c tg -n '__fish_seen_subcommand_from message' -a 'history search get pinned send forward react replies edit delete pin unpin poll watch' +complete -c tg -n '__fish_seen_subcommand_from media' -a 'download send' +complete -c tg -n '__fish_seen_subcommand_from user' -a 'profile block unblock blocked' +complete -c tg -n '__fish_seen_subcommand_from contact' -a 'list add delete search' +complete -c tg -n '__fish_seen_subcommand_from daemon' -a 'start stop status' +complete -c tg -n '__fish_seen_subcommand_from completion' -a 'bash zsh fish' +`; +} diff --git a/cli/src/commands/contact/add.ts b/cli/src/commands/contact/add.ts new file mode 100644 index 0000000..9ed168e --- /dev/null +++ b/cli/src/commands/contact/add.ts @@ -0,0 +1,120 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity, isPhoneNumber } from '../../lib/peer.js'; +import { buildUserProfile } from '../../lib/user-profile.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import type { BatchItemError, GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Detect whether input is a phone number. + * Phone numbers start with '+' or are all digits. + */ +function isPhoneInput(input: string): boolean { + return isPhoneNumber(input); +} + +/** + * Action handler for `tg contact add <input>`. + * + * Adds a contact with dual routing: + * - Phone number (starts with '+' or all digits): uses ImportContacts API + * - Username/ID: uses resolveEntity + AddContact API + * + * Both routes fetch full profile via GetFullUser after adding. + * Returns UserProfile on success. + * + * Phone-based add requires --first-name flag. + * Idempotent: adding an existing contact returns success with profile. + */ +export async function contactAddAction(this: Command, input: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { firstName?: string; lastName?: string }; + const { firstName, lastName } = opts; + + await withAuth(opts, async (client) => { + let targetUser: Api.User; + + try { + if (isPhoneInput(input)) { + // Phone route: ImportContacts + if (!firstName) { + outputError('--first-name is required when adding by phone number', ErrorCode.MISSING_FIRST_NAME); + return; + } + + const phoneNumber = input.startsWith('+') ? input : `+${input}`; + + const importResult = await client.invoke( + new Api.contacts.ImportContacts({ + contacts: [ + new Api.InputPhoneContact({ + clientId: BigInt(Math.floor(Math.random() * 2 ** 32)) as any, + phone: phoneNumber, + firstName, + lastName: lastName ?? '', + }), + ], + }), + ); + + if (importResult.users.length === 0) { + outputError('Phone number not found on Telegram', ErrorCode.PHONE_NOT_FOUND); + return; + } + + targetUser = importResult.users[0] as Api.User; + } else { + // Username/ID route: resolveEntity + AddContact + const entity = await resolveEntity(client, input); + + if (!(entity instanceof Api.User)) { + outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER); + return; + } + + targetUser = entity; + + await client.invoke( + new Api.contacts.AddContact({ + id: entity, + firstName: entity.firstName ?? '', + lastName: entity.lastName ?? '', + phone: '', + }), + ); + } + + // The contact has already been added. Keep that fact in the response even + // when the subsequent read fails, so callers need not repeat the mutation. + let fullResult; + try { + fullResult = await client.invoke(new Api.users.GetFullUser({ id: targetUser })); + } catch (err: unknown) { + outputBatchResult({ + added: true, + id: bigIntToString(targetUser.id), + firstName: targetUser.firstName ?? null, + lastName: targetUser.lastName ?? null, + username: targetUser.username ?? null, + }, [batchError(input, err, 'Could not fetch added contact profile')]); + return; + } + + const fullUser = fullResult.fullUser; + const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(targetUser.id)) ?? targetUser) as Api.User; + + const errors: BatchItemError[] = []; + const profileData = await buildUserProfile(client, targetUser, fullUser, userFromResult, err => { + errors.push(batchError(input, err, 'Could not fetch profile photos')); + }); + outputBatchResult({ ...profileData, added: true }, errors); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/contact/delete.ts b/cli/src/commands/contact/delete.ts new file mode 100644 index 0000000..4047d2b --- /dev/null +++ b/cli/src/commands/contact/delete.ts @@ -0,0 +1,53 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions, ContactDeleteResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg contact delete <user>`. + * + * Deletes a single contact. Validates that the resolved entity is a User + * (not a Channel or Chat). Idempotent: deleting a non-contact returns + * success silently. + * + * Returns ContactDeleteResult with userId, username, firstName, action: 'deleted'. + */ +export async function contactDeleteAction(this: Command, userInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, userInput); + + // Validate entity is a User (not Channel/Chat) + if (!(entity instanceof Api.User)) { + outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER); + return; + } + + const user = entity; + + try { + await client.invoke( + new Api.contacts.DeleteContacts({ id: [user] }), + ); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + return; + } + + const result: ContactDeleteResult = { + userId: bigIntToString(user.id), + username: user.username ?? null, + firstName: user.firstName ?? null, + action: 'deleted', + }; + + outputSuccess(result); + }); +} diff --git a/cli/src/commands/contact/index.ts b/cli/src/commands/contact/index.ts new file mode 100644 index 0000000..e961302 --- /dev/null +++ b/cli/src/commands/contact/index.ts @@ -0,0 +1,53 @@ +import { Command } from 'commander'; +import { contactSetPhotoAction } from './set-photo.js'; +import { contactListAction } from './list.js'; +import { contactAddAction } from './add.js'; +import { contactDeleteAction } from './delete.js'; +import { contactSearchAction } from './search.js'; + +/** + * Create the `contact` command group with list, add, delete, search subcommands. + * + * Usage: + * tg contact list - List all contacts (--limit, --offset) + * tg contact add <input> - Add a contact by username/ID or phone (--first-name, --last-name) + * tg contact delete <user> - Delete a contact + * tg contact search <query> - Search contacts (--global, --limit) + */ +export function createContactCommand(): Command { + const contact = new Command('contact') + .description('Contact management: list, add, delete, search'); + + contact.command('list') + .description('List all contacts') + .option('--limit <n>', 'Max results', '50') + .option('--offset <n>', 'Skip results', '0') + .action(contactListAction); + + contact.command('add') + .argument('<input>', 'Username, user ID, or phone number') + .description('Add a contact') + .option('--first-name <name>', 'First name (required for phone)') + .option('--last-name <name>', 'Last name') + .action(contactAddAction); + + contact.command('delete') + .argument('<user>', 'Username or user ID') + .description('Delete a contact') + .action(contactDeleteAction); + + contact.command('search') + .argument('<query>', 'Search query') + .description('Search contacts') + .option('--global', 'Include non-contact Telegram users') + .option('--limit <n>', 'Max results', '20') + .action(contactSearchAction); + + contact.command('set-photo') + .argument('<user>', 'Contact username or user ID') + .argument('<file>', 'JPEG or PNG file') + .description('Set a personal contact photo visible only to you (no suggestion sent)') + .action(contactSetPhotoAction); + + return contact; +} diff --git a/cli/src/commands/contact/list.ts b/cli/src/commands/contact/list.ts new file mode 100644 index 0000000..964bc65 --- /dev/null +++ b/cli/src/commands/contact/list.ts @@ -0,0 +1,109 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputError } from '../../lib/output.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { buildUserProfile } from '../../lib/user-profile.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError, TgError } from '../../lib/errors.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { BatchItemError, GlobalOptions, UserProfile } from '../../lib/types.js'; + +/** + * Action handler for `tg contact list`. + * + * Lists all contacts with full UserProfile enrichment. + * Supports pagination via --limit (default 50) and --offset (default 0). + * Results are sorted alphabetically by firstName + lastName. + * + * Returns ContactListResult { contacts: UserProfile[], total: number } + * where total is the full count before pagination. + */ +export async function contactListAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string; offset?: string }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const result = await client.invoke( + new Api.contacts.GetContacts({ hash: BigInt(0) as any }), + ); + + // Handle ContactsNotModified + if ((result as any).className === 'contacts.ContactsNotModified') { + outputBatchResult({ contacts: [], total: 0 }, []); + return; + } + + // Build userMap from result.users keyed by bigIntToString(user.id) + const userMap = new Map<string, Api.User>(); + for (const user of (result as any).users ?? []) { + userMap.set(bigIntToString(user.id), user); + } + + // Get contact user IDs from result.contacts + const contactUserIds: string[] = []; + for (const contact of (result as any).contacts ?? []) { + contactUserIds.push(bigIntToString(contact.userId)); + } + + // Sort alphabetically by firstName + lastName + contactUserIds.sort((a, b) => { + const userA = userMap.get(a); + const userB = userMap.get(b); + const nameA = [userA?.firstName ?? '', userA?.lastName ?? ''].join(' ').trim().toLowerCase(); + const nameB = [userB?.firstName ?? '', userB?.lastName ?? ''].join(' ').trim().toLowerCase(); + return nameA.localeCompare(nameB); + }); + + const total = contactUserIds.length; + + // Apply pagination + const page = contactUserIds.slice(offset, offset + limit); + + // Enrich with GetFullUser in batches of 5 + const profiles: UserProfile[] = []; + const errors: BatchItemError[] = []; + const BATCH_SIZE = 5; + + for (let i = 0; i < page.length; i += BATCH_SIZE) { + const batch = page.slice(i, i + BATCH_SIZE); + const results = await Promise.allSettled( + batch.map(async (userId) => { + const user = userMap.get(userId); + if (!user) throw new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND); + + const fullResult = await client.invoke( + new Api.users.GetFullUser({ id: user }), + ); + + const fullUser = fullResult.fullUser; + const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User; + + return buildUserProfile(client, user, fullUser, userFromResult, err => { + errors.push(batchError(userId, err, 'Could not fetch profile photos')); + }); + }), + ); + + for (const [index, r] of results.entries()) { + if (r.status === 'fulfilled' && r.value != null) { + profiles.push(r.value); + } else if (r.status === 'rejected') { + errors.push(batchError(batch[index], r.reason)); + } + } + } + + outputBatchResult({ contacts: profiles, total }, errors); + }); +} diff --git a/cli/src/commands/contact/search.ts b/cli/src/commands/contact/search.ts new file mode 100644 index 0000000..974d4f4 --- /dev/null +++ b/cli/src/commands/contact/search.ts @@ -0,0 +1,146 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { outputError } from '../../lib/output.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError, TgError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { buildUserProfile } from '../../lib/user-profile.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; +import type { BatchItemError, GlobalOptions, ContactSearchItem } from '../../lib/types.js'; + +function normalizeSearchText(value: string): string { + return value.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim(); +} + +/** + * Action handler for `tg contact search <query>`. + * + * Searches the address book locally by name/username. With --global, appends + * remote username matches after local contacts, within the same result limit. + * + * Returns ContactSearchResult { results: ContactSearchItem[], total: number } + * Contact membership comes from the address book, not contacts.Search.myResults. + */ +export async function contactSearchAction(this: Command, query: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { global?: boolean; limit?: string }; + + const globalMode = !!opts.global; + const normalizedQuery = normalizeSearchText(query); + const usernameQuery = normalizedQuery.replace(/^@/, ''); + if (!usernameQuery) { + outputError('Search query cannot be empty', ErrorCode.INVALID_INPUT); + return; + } + let limit: number; + try { + ({ limit } = validatePagination({ limit: opts.limit }, 20)); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const errors: BatchItemError[] = []; + const userMap = new Map<string, Api.User>(); + const myContactIds = new Set<string>(); + const peerUserIds: string[] = []; + const seenIds = new Set<string>(); + const addCandidate = (id: string) => { + if (!seenIds.has(id)) { + peerUserIds.push(id); + seenIds.add(id); + } + }; + + // contacts.Search excludes the address book. Fetch it without a cache hash + // and match names/usernames locally, including queries shorter than 3 chars. + try { + const contacts = await client.invoke(new Api.contacts.GetContacts({ hash: bigInt.zero })); + if (!('contacts' in contacts)) { + throw new TgError('Telegram returned unchanged contacts without a cached contact list', ErrorCode.UNKNOWN_ERROR); + } + for (const u of contacts.users) userMap.set(bigIntToString(u.id), u as Api.User); + for (const contact of contacts.contacts) { + const id = bigIntToString(contact.userId); + if (myContactIds.has(id)) continue; + myContactIds.add(id); + const user = userMap.get(id); + if (!user) { + errors.push(batchError(id, new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND))); + continue; + } + const fullName = normalizeSearchText([user.firstName, user.lastName].filter(Boolean).join(' ')); + const username = normalizeSearchText(user.username ?? ''); + if ((!normalizedQuery.startsWith('@') && fullName.includes(normalizedQuery)) + || username.includes(usernameQuery)) { + addCandidate(id); + } + } + } catch (err: unknown) { + errors.push(batchError('contacts', err, 'Could not read contacts')); + } + + // Local contacts take precedence. Avoid a remote lookup when they already + // fill the page, so remote query limits do not hide usable local matches. + if (globalMode && peerUserIds.length < limit) { + try { + const found = await client.invoke(new Api.contacts.Search({ q: query.trim().replace(/^@/, ''), limit })); + for (const u of found.users) { + const id = bigIntToString(u.id); + if (!userMap.has(id)) userMap.set(id, u as Api.User); + } + for (const peer of [...found.myResults, ...found.results]) { + if ('userId' in peer) addCandidate(bigIntToString(peer.userId)); + } + } catch (err: unknown) { + errors.push(batchError(query, err, 'Global username search failed')); + } + } + + // Apply the CLI limit after deduplication, before expensive enrichment RPCs. + const selectedUserIds = peerUserIds.slice(0, limit); + + // Enrich with GetFullUser in batches of 5 + const results: ContactSearchItem[] = []; + const BATCH_SIZE = 5; + + for (let i = 0; i < selectedUserIds.length; i += BATCH_SIZE) { + const batch = selectedUserIds.slice(i, i + BATCH_SIZE); + const enriched = await Promise.allSettled( + batch.map(async (userId) => { + const user = userMap.get(userId); + if (!user) throw new TgError('Contact user was absent from the Telegram response', ErrorCode.PEER_NOT_FOUND); + + const fullResult = await client.invoke( + new Api.users.GetFullUser({ id: user }), + ); + + const fullUser = fullResult.fullUser; + const userFromResult = (fullResult.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User; + + const profile = await buildUserProfile(client, user, fullUser, userFromResult, err => { + errors.push(batchError(userId, err, 'Could not fetch profile photos')); + }); + return { + ...profile, + isContact: myContactIds.has(userId) || userFromResult.contact === true, + } as ContactSearchItem; + }), + ); + + for (const [index, r] of enriched.entries()) { + if (r.status === 'fulfilled' && r.value != null) { + results.push(r.value); + } else if (r.status === 'rejected') { + errors.push(batchError(batch[index], r.reason)); + } + } + } + + outputBatchResult({ results, total: results.length }, errors); + }); +} diff --git a/cli/src/commands/contact/set-photo.ts b/cli/src/commands/contact/set-photo.ts new file mode 100644 index 0000000..397a7b8 --- /dev/null +++ b/cli/src/commands/contact/set-photo.ts @@ -0,0 +1,55 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { CustomFile } from 'teleproto/client/uploads.js'; +import { readFileSync, statSync } from 'node:fs'; +import { resolve, basename, isAbsolute } from 'node:path'; +import { withAuth } from '../../lib/with-auth.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; +import type { GlobalOptions, ContactPhotoResult } from '../../lib/types.js'; + +/** Set a personal contact photo visible only to the current account. */ +export async function contactSetPhotoAction(this: Command, user: string, file: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + const context = getDaemonContext(); + if (context && (!context.cwd || !isAbsolute(context.cwd))) { + outputError('Contact photo commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS); + return; + } + const filePath = resolve(context?.cwd ?? process.cwd(), file); + let bytes: Buffer; + try { + if (!statSync(filePath).isFile()) throw new Error('Not a regular file'); + bytes = readFileSync(filePath); + } catch { + outputError('Photo must be a readable regular file', ErrorCode.FILE_NOT_FOUND); + return; + } + const jpeg = bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff; + const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); + if (!jpeg && !png) { + outputError('Photo must contain a JPEG or PNG image', ErrorCode.INVALID_PHOTO); + return; + } + await withAuth(opts, async client => { + const entity = await resolveEntity(client, user); + if (!(entity instanceof Api.User)) { + outputError('Personal photos require a user contact', ErrorCode.NOT_A_USER); + return; + } + const uploaded = await client.uploadFile({ file: new CustomFile(basename(filePath), bytes.length, filePath, bytes), workers: 1 }); + const result = await client.invoke(new Api.photos.UploadContactProfilePhoto({ + userId: entity, file: uploaded, save: true, suggest: false, + })); + const photoId = bigIntToString(result.photo?.id); + if (!photoId) { + outputError('Telegram did not return the personal photo result; verify before retrying', ErrorCode.PHOTO_RESULT_UNAVAILABLE); + return; + } + const data: ContactPhotoResult = { userId: bigIntToString(entity.id)!, photoId, personal: true, size: bytes.length }; + outputSuccess(data); + }); +} diff --git a/cli/src/commands/daemon/index.ts b/cli/src/commands/daemon/index.ts new file mode 100644 index 0000000..b9e6cca --- /dev/null +++ b/cli/src/commands/daemon/index.ts @@ -0,0 +1,28 @@ +import { Command } from 'commander'; +import { daemonStartAction } from './start.js'; +import { daemonStopAction } from './stop.js'; +import { daemonStatusAction } from './status.js'; + +export function createDaemonCommand(): Command { + const daemon = new Command('daemon') + .description('Manage persistent Telegram connection daemon'); + + daemon + .command('start') + .description('Start the daemon for persistent connection') + .option('--idle-timeout <seconds>', 'Auto-stop after N seconds of inactivity (0 = keep running)', '300') + .option('--foreground', 'Run in foreground (do not fork)') + .action(daemonStartAction); + + daemon + .command('stop') + .description('Stop the running daemon') + .action(daemonStopAction); + + daemon + .command('status') + .description('Check daemon status') + .action(daemonStatusAction); + + return daemon; +} diff --git a/cli/src/commands/daemon/start.ts b/cli/src/commands/daemon/start.ts new file mode 100644 index 0000000..4331d41 --- /dev/null +++ b/cli/src/commands/daemon/start.ts @@ -0,0 +1,158 @@ +import type { Command } from 'commander'; +import { fork } from 'node:child_process'; +import { createConfig, getCredentialsOrThrow } from '../../lib/config.js'; +import { resolveTransport } from '../../lib/transport.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { DaemonPaths } from '../../lib/daemon/pid.js'; +import { DaemonClient } from '../../lib/daemon/client.js'; +import { DaemonServer } from '../../lib/daemon/server.js'; +import { resolveDaemonEntry } from '../../lib/daemon/entry-path.js'; +import { daemonChildEnv, installDaemonSignals, isProcessAlive, waitWhile } from '../../lib/daemon/lifecycle.js'; +import { cleanupStaleDaemon, daemonPidAlive } from '../../lib/daemon/guard.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { parseIntegerOption, validateProfile } from '../../lib/validate.js'; + +export async function daemonStartAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { idleTimeout?: string; foreground?: boolean }; + const { profile, quiet } = opts; + validateProfile(profile); + const idleTimeout = parseIntegerOption(opts.idleTimeout ?? '300', '--idle-timeout', { + max: 2_147_483, + }) * 1000; + + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, profile); + + // Check if already running + if (paths.socketExists()) { + try { + const client = new DaemonClient(paths.socketPath); + const status = await client.call('ping', {}); + client.close(); + if (status === 'pong') { + outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING); + return; + } + if (!cleanupStaleDaemon(paths)) { + outputError( + 'Daemon is not responding. Try: tg daemon stop && tg daemon start', + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + return; + } + } catch { + if (!cleanupStaleDaemon(paths)) { + outputError( + 'Daemon is not responding. Try: tg daemon stop && tg daemon start', + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + return; + } + } + } + + if (daemonPidAlive(paths)) { + outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING); + return; + } + + // Load session + const store = new SessionStore(configDir); + const sessionString = await store.load(profile); + if (!sessionString) { + outputError('Not logged in. Run: tg auth login', ErrorCode.NOT_AUTHENTICATED); + return; + } + + const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile); + + const transport = resolveTransport(config, profile, opts.transport); + + if (opts.foreground) { + logStatus('Starting daemon in foreground...', quiet); + const server = new DaemonServer( + paths, + { apiId, apiHash, transport }, + { idleTimeout, onIdle: () => process.exit(0) }, + ); + const uninstallSignals = installDaemonSignals(() => server.stop()); + try { + await server.start(); + } catch (err: unknown) { + uninstallSignals(); + outputError( + `Daemon failed to start: ${(err as Error).message}`, + ErrorCode.DAEMON_START_FAILED, + ); + return; + } + logStatus(`Daemon running on ${paths.socketPath} (PID ${process.pid})`, quiet); + outputSuccess({ pid: process.pid, socket: paths.socketPath, profile }); + await new Promise(() => {}); + } else { + const daemonEntry = resolveDaemonEntry(import.meta.url); + + const child = fork(daemonEntry, [], { + detached: true, + stdio: 'ignore', + env: daemonChildEnv({ + configDir, + profile, + idleTimeout, + configPath: opts.config, + transport, + }), + }); + + // fork() creates an IPC channel even with ignored stdio. Readiness uses the + // Unix socket, so close unused IPC before unref or it keeps this CLI alive. + if (child.connected) child.disconnect(); + child.unref(); + + const childPid = child.pid; + if (childPid == null) { + outputError('Daemon failed to start (fork returned no pid)', ErrorCode.DAEMON_START_FAILED); + return; + } + + if (!paths.writePidExclusive(childPid)) { + try { process.kill(childPid, 'SIGTERM'); } catch { /* already gone */ } + outputError('Daemon is already running', ErrorCode.DAEMON_ALREADY_RUNNING); + return; + } + + const maxWait = 10_000; + const started = Date.now(); + while (Date.now() - started < maxWait) { + if (paths.socketExists()) { + try { + const ready = new DaemonClient(paths.socketPath); + const pong = await ready.call('ping', {}, { timeoutMs: 1000 }); + ready.close(); + if (pong === 'pong') { + outputSuccess({ + pid: paths.readPid() ?? childPid, + socket: paths.socketPath, + profile, + }); + return; + } + } catch { + // Socket exists but not accepting yet + } + } + await new Promise(r => setTimeout(r, 100)); + } + + try { process.kill(childPid, 'SIGTERM'); } catch { /* already gone */ } + await waitWhile(() => isProcessAlive(childPid), 5_000); + if (isProcessAlive(childPid)) { + try { process.kill(childPid, 'SIGKILL'); } catch { /* already gone */ } + } + paths.cleanupOwned(childPid); + outputError('Daemon failed to start within 10 seconds', ErrorCode.DAEMON_START_FAILED); + } +} diff --git a/cli/src/commands/daemon/status.ts b/cli/src/commands/daemon/status.ts new file mode 100644 index 0000000..cc338dd --- /dev/null +++ b/cli/src/commands/daemon/status.ts @@ -0,0 +1,29 @@ +import type { Command } from 'commander'; +import { createConfig } from '../../lib/config.js'; +import { outputSuccess } from '../../lib/output.js'; +import { DaemonPaths } from '../../lib/daemon/pid.js'; +import { DaemonClient } from '../../lib/daemon/client.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +export async function daemonStatusAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + const { profile } = opts; + + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, profile); + + if (!paths.socketExists()) { + outputSuccess({ running: false, profile }); + return; + } + + try { + const client = new DaemonClient(paths.socketPath); + const status = await client.call('status', {}) as Record<string, unknown>; + client.close(); + outputSuccess({ ...status, profile }); + } catch { + outputSuccess({ running: false, profile, stale: true }); + } +} diff --git a/cli/src/commands/daemon/stop.ts b/cli/src/commands/daemon/stop.ts new file mode 100644 index 0000000..4b59006 --- /dev/null +++ b/cli/src/commands/daemon/stop.ts @@ -0,0 +1,75 @@ +import type { Command } from 'commander'; +import { createConfig } from '../../lib/config.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { DaemonPaths } from '../../lib/daemon/pid.js'; +import { DaemonClient } from '../../lib/daemon/client.js'; +import { isProcessAlive, waitWhile } from '../../lib/daemon/lifecycle.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +export async function daemonStopAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + const { profile, quiet } = opts; + + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, profile); + + const pid = paths.readPid(); + + if (!pid && !paths.socketExists()) { + outputError('Daemon is not running', ErrorCode.DAEMON_NOT_RUNNING); + return; + } + + if (paths.socketExists()) { + try { + const client = new DaemonClient(paths.socketPath); + await client.call('shutdown', {}); + client.close(); + } catch { + // Socket unresponsive + } + await waitWhile(() => paths.socketExists(), 5_000); + } + + if (pid && isProcessAlive(pid)) { + try { + process.kill(pid, 'SIGTERM'); + } catch { + // Process already dead + } + await waitWhile(() => isProcessAlive(pid), 5_000); + } + + if (pid && isProcessAlive(pid)) { + outputError('Daemon did not stop (process still running)', ErrorCode.DAEMON_STOP_FAILED); + return; + } + + const now = paths.readPid(); + if (now !== null && now !== pid) { + // Successor already claimed the pid file. Do not unlink its files. + logStatus('Daemon stopped.', quiet); + outputSuccess({ stopped: true, profile }); + return; + } + + if (paths.socketExists()) { + try { + const client = new DaemonClient(paths.socketPath); + const pong = await client.call('ping', {}); + client.close(); + if (pong === 'pong') { + outputError('Daemon did not stop (socket still accepting connections)', ErrorCode.DAEMON_STOP_FAILED); + return; + } + } catch { + // Unresponsive and no live pid: stale socket + } + } + + paths.cleanup(); + logStatus('Daemon stopped.', quiet); + outputSuccess({ stopped: true, profile }); +} diff --git a/cli/src/commands/media/download.ts b/cli/src/commands/media/download.ts new file mode 100644 index 0000000..4096236 --- /dev/null +++ b/cli/src/commands/media/download.ts @@ -0,0 +1,162 @@ +import type { Command } from 'commander'; +import { existsSync } from 'node:fs'; +import { resolve, basename, sep, isAbsolute } from 'node:path'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { TgError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { extractMediaInfo, detectMedia } from '../../lib/serialize.js'; +import { generateFilename, formatBytes } from '../../lib/media-utils.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageIds } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions, DownloadResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; + +const DOWNLOADABLE = new Set(['photo', 'video', 'voice', 'document', 'audio']); + +/** + * Action handler for `tg media download <chat> <msg-ids>`. + * + * Downloads media from one or more messages. Supports: + * - Single download: `tg media download @chat 123` + * - Batch download: `tg media download @chat 123,456,789` + * - Output override: `-o <path>` (file for single, directory for batch) + * - Auto-naming from Telegram metadata or generateFilename fallback + * - Progress output on stderr (suppressed with --quiet) + * + * Returns DownloadResult for single, { files, downloaded, failed } for batch. + */ +export async function mediaDownloadAction(this: Command): Promise<void> { + const chat = this.args[0]; + const rawIds = this.args[1]; + const opts = this.optsWithGlobals() as GlobalOptions & { output?: string; force?: boolean }; + const { quiet } = opts; + const context = getDaemonContext(); + if (context && (!context.cwd || !isAbsolute(context.cwd))) { + outputError('Media commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS); + return; + } + const cwd = context?.cwd ?? process.cwd(); + + let messageIds: number[]; + try { + messageIds = parseMessageIds(rawIds); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + const isBatch = messageIds.length > 1; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + const results: DownloadResult[] = []; + const failed: { messageId: number; error: string; code: string }[] = []; + + const downloadOne = async (msgId: number): Promise<DownloadResult> => { + const messages = await client.getMessages(entity, { ids: [msgId] }); + const msg = messages[0]; + + if (!msg || !msg.media) { + throw new TgError( + `Message ${msgId} has no downloadable media`, + ErrorCode.NO_MEDIA, + ); + } + + const { mediaType } = detectMedia((msg as any).media); + if (!mediaType || !DOWNLOADABLE.has(mediaType)) { + throw new TgError( + `Message ${msgId} has no downloadable media`, + ErrorCode.NO_MEDIA, + ); + } + + const mediaInfo = extractMediaInfo((msg as any).media); + const rawFilename = mediaInfo?.filename; + const filename = rawFilename + ? basename(rawFilename) + : generateFilename(mediaType, msgId, mediaInfo?.mimeType ?? null); + + let targetPath: string; + if (opts.output) { + if (isBatch) { + targetPath = resolve(cwd, opts.output, filename); + } else { + targetPath = resolve(cwd, opts.output); + } + } else { + targetPath = resolve(cwd, filename); + } + + const allowedDir = opts.output ? resolve(cwd, opts.output) : cwd; + const baseDir = isBatch || !opts.output ? allowedDir : resolve(allowedDir, '..'); + if (targetPath !== baseDir && !targetPath.startsWith(baseDir + sep)) { + throw new TgError( + `Path traversal detected: ${targetPath} is outside ${baseDir}`, + ErrorCode.PATH_TRAVERSAL, + ); + } + + if (existsSync(targetPath) && !opts.force) { + throw new TgError( + `File exists: ${targetPath} (use --force to overwrite)`, + ErrorCode.FILE_EXISTS, + ); + } + + let lastProgressTime = 0; + await client.downloadMedia(msg as any, { + outputFile: targetPath, + progressCallback: (downloaded: any, total: any) => { + const now = Date.now(); + if (now - lastProgressTime < 1000) return; + lastProgressTime = now; + const dl = typeof downloaded?.toJSNumber === 'function' + ? downloaded.toJSNumber() : Number(downloaded); + const tot = typeof total?.toJSNumber === 'function' + ? total.toJSNumber() : Number(total); + const pct = tot > 0 ? Math.round((dl / tot) * 100) : 0; + logStatus( + `Downloading ${filename}: ${pct}% (${formatBytes(dl)}/${formatBytes(tot)})`, + quiet, + ); + }, + }); + + const savedFilename = (!isBatch && opts.output) + ? basename(targetPath) + : filename; + + return { + path: targetPath, + filename: savedFilename, + size: mediaInfo?.fileSize ?? 0, + mediaType, + messageId: msgId, + }; + }; + + for (const msgId of messageIds) { + try { + results.push(await downloadOne(msgId)); + } catch (err: unknown) { + if (!isBatch) throw err; + const { message, code } = formatError(err); + failed.push({ + messageId: msgId, + error: message, + code: code ?? ErrorCode.UNKNOWN_ERROR, + }); + } + } + + if (isBatch) { + outputSuccess({ files: results, downloaded: results.length, failed }); + } else { + outputSuccess(results[0]); + } + }); +} diff --git a/cli/src/commands/media/index.ts b/cli/src/commands/media/index.ts new file mode 100644 index 0000000..fd65a44 --- /dev/null +++ b/cli/src/commands/media/index.ts @@ -0,0 +1,36 @@ +import { Command } from 'commander'; +import { mediaDownloadAction } from './download.js'; +import { mediaSendAction } from './send.js'; + +/** + * Create the `media` command group with download and send subcommands. + * + * Usage: + * tg media download <chat> <msg-ids> - Download media from messages + * tg media send <chat> <files...> - Upload and send files to a chat + */ +export function createMediaCommand(): Command { + const media = new Command('media') + .description('Download and upload media files'); + + media + .command('download') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<msg-ids>', 'Message ID(s), comma-separated for batch') + .description('Download media from messages') + .option('-o, --output <path>', 'Output path (file for single, directory for batch)') + .option('--force', 'Overwrite existing files') + .action(mediaDownloadAction); + + media + .command('send') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<files...>', 'File path(s) to send (multiple = album)') + .description('Upload and send files to a chat') + .option('--caption <text>', 'Caption for the media') + .option('--reply-to <msgId>', 'Reply to message ID') + .option('--topic <topicId>', 'Forum topic ID') + .action(mediaSendAction); + + return media; +} diff --git a/cli/src/commands/media/send.ts b/cli/src/commands/media/send.ts new file mode 100644 index 0000000..fa76e63 --- /dev/null +++ b/cli/src/commands/media/send.ts @@ -0,0 +1,158 @@ +import type { Command } from 'commander'; +import { resolve, extname, isAbsolute } from 'node:path'; +import { access } from 'node:fs/promises'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { resolveEntity, assertForum } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { detectFileType } from '../../lib/media-utils.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { parseMessageId, parseTopicId } from '../../lib/validate.js'; +import { outputBatchResult } from '../../lib/batch-results.js'; +import type { BatchItemError } from '../../lib/types.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; + +/** + * Action handler for `tg media send <chat> <files...>`. + * + * Uploads and sends files to a chat. Supports: + * - Single file send: `tg media send @chat photo.jpg` + * - Album send (multiple files, max 10): `tg media send @chat a.jpg b.jpg c.jpg` + * - Caption: `--caption "My caption"` + * - Reply: `--reply-to 42` + * - Voice note auto-detection for .ogg/.opus files + * - Force document mode for non-photo/video/voice files + * - Progress output on stderr (suppressed with --quiet) + * + * Returns MessageItem for single, { messages, sent } for album. + */ +export async function mediaSendAction(this: Command): Promise<void> { + const chat = this.args[0]; + const files = this.args.slice(1); + const opts = this.optsWithGlobals() as GlobalOptions & { + caption?: string; + replyTo?: string; + topic?: string; + }; + const { quiet } = opts; + const context = getDaemonContext(); + if (context && (!context.cwd || !isAbsolute(context.cwd))) { + outputError('Media commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS); + return; + } + const cwd = context?.cwd ?? process.cwd(); + + // Validate file count for albums + if (files.length > 10) { + outputError('Albums support a maximum of 10 files', ErrorCode.ALBUM_TOO_LARGE); + return; + } + + // Validate all files exist before attempting upload + for (const fp of files) { + try { + await access(resolve(cwd, fp)); + } catch { + outputError(`File not found: ${fp}`, ErrorCode.FILE_NOT_FOUND); + return; + } + } + + let topicId: number | undefined; + if (opts.topic !== undefined) { + try { + topicId = parseTopicId(opts.topic); + } catch (err: unknown) { + outputError( + err instanceof Error ? err.message : 'Invalid topic ID: must be a number', + ErrorCode.INVALID_TOPIC_ID, + ); + return; + } + } + + let replyTo: number | undefined; + if (opts.replyTo !== undefined) { + try { + replyTo = parseMessageId(opts.replyTo); + } catch { + outputError('Invalid reply-to message ID: must be a positive message ID', ErrorCode.INVALID_REPLY_TO); + return; + } + } + + if (topicId !== undefined && replyTo !== undefined) { + outputError( + '--topic and --reply-to cannot be combined yet. Use --reply-to to reply in-topic, or --topic to post to the topic root.', + ErrorCode.INVALID_OPTIONS, + ); + return; + } + const effectiveReplyTo = topicId !== undefined ? topicId : replyTo; + + const isAlbum = files.length > 1; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + // Forum guard: reject --topic on non-forum chats + await assertForum(entity, topicId); + + // Build send params + const sendParams: any = { + file: isAlbum + ? files.map(f => resolve(cwd, f)) + : resolve(cwd, files[0]), + caption: opts.caption ?? '', + replyTo: effectiveReplyTo, + progressCallback: (progress: number) => { + logStatus( + `Uploading: ${Math.round(progress * 100)}%`, + quiet, + ); + }, + }; + + // Single file type detection + if (!isAlbum) { + const ext = extname(files[0]); + const fileType = detectFileType(ext); + + if (fileType === 'voice') { + sendParams.voiceNote = true; + } else if (fileType === 'document') { + sendParams.forceDocument = true; + } + } + + const result = await client.sendFile(entity, sendParams); + + if (!isAlbum && result == null) { + outputError('Telegram did not return the sent message ID; the file may have been sent and retrying may create a duplicate', ErrorCode.MESSAGE_RESULT_UNAVAILABLE); + return; + } + + if (isAlbum) { + // gramjs returns each sent message; their IDs need not be consecutive. + const returnedMessages = Array.isArray(result) ? result : [result]; + const sentMessages = returnedMessages.filter(message => message != null); + const serialized = sentMessages.map(message => serializeMessage(message)); + const output: Record<string, unknown> = { messages: serialized, sent: serialized.length }; + const errors: BatchItemError[] = []; + for (let index = 0; index < files.length; index++) { + if (returnedMessages[index] == null) { + errors.push({ input: files[index], error: `Message ID for album item ${index + 1} is unavailable after sending; retrying may create a duplicate`, code: ErrorCode.MESSAGE_RESULT_UNAVAILABLE }); + } + } + if (sentMessages.length !== files.length) { + output.warning = `Telegram returned ${sentMessages.length} messages for ${files.length} files; missing message IDs are unknown`; + } + outputBatchResult(output, errors); + } else { + // Single file: serialize and return + const serialized = serializeMessage(result as any); + outputSuccess(serialized); + } + }); +} diff --git a/cli/src/commands/message/delete.ts b/cli/src/commands/message/delete.ts new file mode 100644 index 0000000..e1c8187 --- /dev/null +++ b/cli/src/commands/message/delete.ts @@ -0,0 +1,69 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageIds } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions, DeleteResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg message delete <chat> <ids>`. + * + * Deletes messages in a chat. Requires explicit --revoke (delete for everyone) + * or --for-me (delete for self only) flag for safety. + * + * Accepts comma-separated IDs (max 100). Returns DeleteResult shape. + * Uses translateTelegramError for Telegram-specific permission errors. + */ +export async function messageDeleteAction(this: Command, chat: string, idsInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { revoke?: boolean; forMe?: boolean }; + + // Safety: require explicit mode selection, mutually exclusive + if (!opts.revoke && !opts.forMe) { + outputError('Specify --revoke (delete for everyone) or --for-me (delete for self)', ErrorCode.DELETE_MODE_REQUIRED); + return; + } + if (opts.revoke && opts.forMe) { + outputError('--revoke and --for-me are mutually exclusive', ErrorCode.INVALID_OPTIONS); + return; + } + + let numericIds: number[]; + try { + numericIds = parseMessageIds(idsInput); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + const mode: 'revoke' | 'for-me' = opts.revoke ? 'revoke' : 'for-me'; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + // Telegram only supports deleting for everyone in channels and supergroups. + // gramjs silently ignores revoke:false for these peers, so reject before RPC. + if (mode === 'for-me' && ['Channel', 'ChannelForbidden', 'InputPeerChannel', 'PeerChannel'].includes(entity.className)) { + outputError('--for-me is not supported in channels or supergroups. Use --revoke to delete for everyone.', ErrorCode.INVALID_OPTIONS); + return; + } + + try { + await client.deleteMessages(entity, numericIds, { revoke: mode === 'revoke' }); + + // If no error thrown, all deletions succeeded + const result: DeleteResult = { + deleted: numericIds, + failed: [], + mode, + }; + outputSuccess(result); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/message/edit.ts b/cli/src/commands/message/edit.ts new file mode 100644 index 0000000..44a1303 --- /dev/null +++ b/cli/src/commands/message/edit.ts @@ -0,0 +1,85 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError, formatError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageId } from '../../lib/validate.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; + +/** + * Read all data from stdin as a UTF-8 string. + * Used when the text argument is "-" (dash placeholder) to support piped input. + */ +async function readStdin(): Promise<string> { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) { + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf-8').trimEnd(); +} + +/** + * Action handler for `tg message edit <chat> <id> <text>`. + * + * Edits a text message in any chat. Supports: + * - Piped stdin input via dash placeholder: echo "new text" | tg message edit <chat> <id> - + * - gramjs built-in markdown parsing for **bold**, __italic__, `code`, [links](url) + * + * Returns the edited message as a serialized MessageItem (includes editDate). + * Uses translateTelegramError for Telegram-specific permission errors. + */ +export async function messageEditAction(this: Command, chat: string, msgId: string, text: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + let messageId: number; + try { + messageId = parseMessageId(msgId); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + // Handle stdin pipe via dash placeholder + if (text === '-') { + const context = getDaemonContext(); + if (context ? context.stdin === undefined : process.stdin.isTTY) { + outputError('"-" requires piped input. Example: echo "new text" | tg message edit @user 42 -', ErrorCode.STDIN_REQUIRED); + return; + } + text = context ? context.stdin!.trimEnd() : await readStdin(); + } + + // Validate non-empty text + if (!text) { + outputError('Message text is required', ErrorCode.EMPTY_MESSAGE); + return; + } + + // Telegram message length limit + if (text.length > 4096) { + outputError('Message too long (max 4096 chars)', ErrorCode.MESSAGE_TOO_LONG); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + try { + // gramjs built-in MarkdownParser handles **bold**, __italic__, `code`, [links](url) automatically + const editedMsg = await client.editMessage(entity, { + message: messageId, + text, + }); + + const serialized = serializeMessage(editedMsg as any, (editedMsg as any)._sender); + outputSuccess(serialized); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/message/forward.ts b/cli/src/commands/message/forward.ts new file mode 100644 index 0000000..75f32e0 --- /dev/null +++ b/cli/src/commands/message/forward.ts @@ -0,0 +1,50 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageIds } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Action handler for `tg message forward <from-chat> <msg-ids> <to-chat>`. + * + * Forwards one or more messages from a source chat to a destination chat. + * Message IDs are comma-separated: `tg message forward @source 123,456,789 @dest` + * + * Uses Telegram's native batch forward API via gramjs forwardMessages. + * Always passes fromPeer to avoid PEER_ID_INVALID when using integer IDs. + * + * Returns: { forwarded: N, messages: MessageItem[] } + */ +export async function messageForwardAction(this: Command, fromChat: string, msgIds: string, toChat: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + let ids: number[]; + try { + ids = parseMessageIds(msgIds); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const fromEntity = await resolveEntity(client, fromChat); + const toEntity = await resolveEntity(client, toChat); + + // MUST pass fromPeer when using integer IDs (pitfall #2 from research) + const forwarded = await client.forwardMessages(toEntity, { + messages: ids, + fromPeer: fromEntity, + }); + + const messages = forwarded.map((msg: any) => serializeMessage(msg)); + + outputSuccess({ + forwarded: messages.length, + messages, + }); + }); +} diff --git a/cli/src/commands/message/get.ts b/cli/src/commands/message/get.ts new file mode 100644 index 0000000..a1096bb --- /dev/null +++ b/cli/src/commands/message/get.ts @@ -0,0 +1,67 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { messagePeerMarkedId, serializeMessage } from '../../lib/serialize.js'; +import { buildEntityMap } from '../../lib/entity-map.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageIds } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions, MessageItem } from '../../lib/types.js'; + +/** + * Action handler for `tg message get <chat> <ids>`. + * + * Fetches specific messages by ID from a chat. Accepts comma-separated IDs (max 100). + * Returns found messages and a list of IDs that were not found. + * + * Output shape: { messages: MessageItem[], notFound: number[] } + */ +export async function messageGetAction( + this: Command, + chatInput: string, + idsInput: string, +): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + let numericIds: number[]; + try { + numericIds = parseMessageIds(idsInput); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + // getMessages returns array where missing entries are undefined + const result = await client.getMessages(entity, { ids: numericIds }); + + const found: MessageItem[] = []; + const notFound: number[] = []; + + // Build entity map as fallback for sender resolution + const entityMap = buildEntityMap(result); + + // Iterate by index to preserve input order + for (let i = 0; i < numericIds.length; i++) { + const msg = result[i]; + if (msg) { + // Prefer _sender from gramjs _finishInit, fall back to entity map + let senderEntity = (msg as any)._sender; + if (!senderEntity) { + const senderId = messagePeerMarkedId({ peerId: (msg as any).fromId }); + if (senderId) { + senderEntity = entityMap.get(senderId); + } + } + found.push(serializeMessage(msg, senderEntity)); + } else { + notFound.push(numericIds[i]); + } + } + + outputSuccess({ messages: found, notFound }); + }); +} diff --git a/cli/src/commands/message/history.ts b/cli/src/commands/message/history.ts new file mode 100644 index 0000000..88b62c5 --- /dev/null +++ b/cli/src/commands/message/history.ts @@ -0,0 +1,98 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity, assertForum } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { validatePagination, parseIsoDate, parseTopicId } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions, MessageItem } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg message history <chat>`. + * + * Reads message history from a chat with pagination and date filtering. + * Options: --limit (default 50), --offset (default 0), --since <date>, --until <date> + * + * Date options use ISO 8601 format (e.g., 2026-03-01T00:00:00Z). + * --until uses server-side offsetDate for efficiency. + * --since uses post-filtering (newest-first ordering ensures early stop). + */ +export async function messageHistoryAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { + limit: string; + offset: string; + since?: string; + until?: string; + topic?: string; + }; + let limit: number; + let offset: number; + let untilDate: Date | undefined; + let sinceDate: Date | undefined; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + if (opts.until) untilDate = parseIsoDate(opts.until, '--until'); + if (opts.since) sinceDate = parseIsoDate(opts.since, '--since'); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + let topicId: number | undefined; + if (opts.topic !== undefined) { + try { + topicId = parseTopicId(opts.topic); + } catch (err: unknown) { + outputError( + err instanceof Error ? err.message : 'Invalid topic ID: must be a number', + ErrorCode.INVALID_TOPIC_ID, + ); + return; + } + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + // Forum guard: reject --topic on non-forum chats + await assertForum(entity, topicId); + + // Build getMessages parameters + const params: Record<string, any> = { + limit, + addOffset: offset, + }; + + // --topic: scope messages to a specific forum topic + if (topicId !== undefined) { + params.replyTo = topicId; + } + + // --until: server-side date filter via offsetDate + if (untilDate) { + params.offsetDate = Math.floor(untilDate.getTime() / 1000); + } + + const messages = await client.getMessages(entity, params); + + // Serialize messages + let serialized: MessageItem[] = messages.map((msg: any) => + serializeMessage(msg), + ); + + // --since: post-filter messages after the given date + if (sinceDate) { + const sinceMs = sinceDate.getTime(); + serialized = serialized.filter( + (m) => new Date(m.date).getTime() >= sinceMs, + ); + } + + outputSuccess({ + messages: serialized, + total: (messages as any).total ?? 0, + }); + }); +} diff --git a/cli/src/commands/message/index.ts b/cli/src/commands/message/index.ts new file mode 100644 index 0000000..abf146d --- /dev/null +++ b/cli/src/commands/message/index.ts @@ -0,0 +1,185 @@ +import { Command } from 'commander'; +import { messageHistoryAction } from './history.js'; +import { messageSearchAction } from './search.js'; +import { messageSendAction } from './send.js'; +import { messageForwardAction } from './forward.js'; +import { messageReactAction } from './react.js'; +import { messageRepliesAction } from './replies.js'; +import { messageGetAction } from './get.js'; +import { messagePinnedAction } from './pinned.js'; +import { messageEditAction } from './edit.js'; +import { messageDeleteAction } from './delete.js'; +import { messagePinAction } from './pin.js'; +import { messageUnpinAction } from './unpin.js'; +import { messagePollAction } from './poll.js'; +import { messageWatchAction } from './watch.js'; + +/** + * Create the `message` command group with history, search, get, pinned, send, forward, react, replies, + * edit, delete, pin, unpin, poll, and watch subcommands. + * + * Usage: + * tg message history <chat> - Read message history from a chat + * tg message search - Search messages by keyword + * tg message get <chat> <ids> - Get specific messages by ID (comma-separated, max 100) + * tg message pinned <chat> - Get pinned messages from a chat + * tg message send <chat> <text> - Send a text message + * tg message forward <from> <ids> <to> - Forward messages between chats + * tg message react <chat> <id> <emoji> - React to a message + * tg message replies <channel> <msg-ids> - Read replies/comments on channel posts (comma-separated) + * tg message edit <chat> <id> <text> - Edit a sent message + * tg message delete <chat> <ids> - Delete messages (--revoke or --for-me required) + * tg message pin <chat> <id> - Pin a message (silent by default) + * tg message unpin <chat> <id> - Unpin a message + * tg message poll <chat> - Send a poll to a chat + */ +export function createMessageCommand(): Command { + const message = new Command('message') + .description('Message reading, sending, and interaction'); + + message + .command('history') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Read message history from a chat') + .option('--limit <n>', 'Max messages', '50') + .option('--offset <n>', 'Skip messages', '0') + .option('--since <date>', 'Messages after this date (ISO 8601)') + .option('--until <date>', 'Messages before this date (ISO 8601)') + .option('--topic <topicId>', 'Forum topic ID') + .action(messageHistoryAction); + + message + .command('search') + .description('Search messages by keyword or media type') + .option('--chat <chat>', 'Search in specific chat or comma-separated chats (omit for global search)') + .option('--query <text>', 'Search query') + .option('--filter <type>', 'Filter by type (photos|videos|documents|urls|voice|music|gifs|round|photo_video|round_voice|chat_photos|phone_calls|mentions|geo|contacts|pinned)') + .option('--limit <n>', 'Max results', '50') + .option('--offset <n>', 'Skip results', '0') + .option('--topic <topicId>', 'Forum topic ID (single --chat only)') + .option('--public', 'Search public channel posts by hashtag (including channels you have not joined)') + .option('--peer <chat>', 'Public-search pagination peer (nextOffsetPeer from the previous page)') + .option('--after <msgId>', 'Public-search pagination message id (nextOffsetId)') + .addHelpText('after', ` +Valid filters: photos, videos, photo_video, documents, urls, gifs, voice, music, round, round_voice, chat_photos, phone_calls, mentions, geo, contacts, pinned + +Public hashtag search (CLI contract remains hashtag-only): + tg message search --public --query bitcoin + tg message search --public --query bitcoin --offset <nextRate> --peer <nextOffsetPeer> --after <nextOffsetId>`) + .action(messageSearchAction); + + message + .command('get') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<ids>', 'Message IDs (comma-separated, max 100)') + .description('Get specific messages by ID') + .action(messageGetAction); + + message + .command('pinned') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Get pinned messages from a chat') + .option('--limit <n>', 'Max messages', '50') + .option('--offset <n>', 'Skip messages', '0') + .action(messagePinnedAction); + + message + .command('send') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<text>', 'Message text (use - for stdin)') + .description('Send a text message to a chat') + .option('--reply-to <msgId>', 'Reply to message ID') + .option('--topic <topicId>', 'Forum topic ID') + .option('--comment-to <postId>', 'Comment on a channel post') + .option('--schedule <iso>', 'Schedule on Telegram (ISO timestamp with timezone)') + .action(messageSendAction); + + message + .command('forward') + .argument('<from-chat>', 'Source chat') + .argument('<msg-ids>', 'Message IDs (comma-separated)') + .argument('<to-chat>', 'Destination chat') + .description('Forward messages between chats') + .action(messageForwardAction); + + message + .command('react') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<msg-id>', 'Message ID') + .argument('<emoji>', 'Emoji to react with') + .description('React to a message with an emoji') + .option('--remove', 'Remove reaction') + .action(messageReactAction); + + message + .command('replies') + .argument('<channel>', 'Channel ID, username, or @username') + .argument('<msg-ids>', 'Post message IDs (comma-separated for batch)') + .description('Read replies/comments on channel posts') + .option('--limit <n>', 'Max replies per post', '50') + .option('--offset <n>', 'Skip replies', '0') + .action(messageRepliesAction); + + message + .command('edit') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<msg-id>', 'Message ID') + .argument('<text>', 'New message text (use - for stdin)') + .description('Edit a sent message') + .action(messageEditAction); + + message + .command('delete') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<ids>', 'Message IDs (comma-separated, max 100)') + .description('Delete messages') + .option('--revoke', 'Delete for everyone') + .option('--for-me', 'Delete only for self') + .action(messageDeleteAction); + + message + .command('pin') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<msg-id>', 'Message ID') + .description('Pin a message in a chat') + .option('--notify', 'Notify members (silent by default)') + .action(messagePinAction); + + message + .command('unpin') + .argument('<chat>', 'Chat ID, username, or @username') + .argument('<msg-id>', 'Message ID') + .description('Unpin a message from a chat') + .action(messageUnpinAction); + + message + .command('poll') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Send a poll to a chat') + .requiredOption('--question <text>', 'Poll question (max 300 chars)') + .option('--option <text>', 'Poll option (repeat 2-10 times)', collect, []) + .option('--quiz', 'Quiz mode (one correct answer)') + .option('--correct <index>', 'Correct answer index, 1-based (requires --quiz)') + .option('--solution <text>', 'Solution explanation (requires --quiz)') + .option('--multiple', 'Allow multiple choices') + .option('--public', 'Show voter names (non-anonymous)') + .option('--close-in <seconds>', 'Auto-close after N seconds') + .action(messagePollAction); + + message + .command('watch') + .argument('<chat>', 'Chat ID, username, or @username') + .description('Watch for new messages in real-time (requires daemon)') + .option('--topic <topicId>', 'Forum topic ID') + .action(messageWatchAction); + + return message; +} + +/** + * Commander repeatable option accumulator. + * Used for --option flags that can be specified multiple times. + */ +function collect(value: string, previous: string[]): string[] { + return [...previous, value]; +} diff --git a/cli/src/commands/message/pin.ts b/cli/src/commands/message/pin.ts new file mode 100644 index 0000000..7a26421 --- /dev/null +++ b/cli/src/commands/message/pin.ts @@ -0,0 +1,51 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError, formatError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageId } from '../../lib/validate.js'; +import type { GlobalOptions, PinResult } from '../../lib/types.js'; + +/** + * Action handler for `tg message pin <chat> <msg-id>`. + * + * Pins a message in a chat. Silent by default (no notification). + * Use --notify to send a notification to chat members. + * + * Returns PinResult with messageId, chatId, action, and silent indicator. + * Uses translateTelegramError for Telegram-specific permission errors. + */ +export async function messagePinAction(this: Command, chat: string, msgId: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { notify?: boolean }; + + let messageId: number; + try { + messageId = parseMessageId(msgId); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + const notify = opts.notify ?? false; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + try { + await client.pinMessage(entity, messageId, { notify }); + + const result: PinResult = { + messageId, + chatId: markedPeerId(entity), + action: 'pinned', + silent: !notify, + }; + outputSuccess(result); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/message/pinned.ts b/cli/src/commands/message/pinned.ts new file mode 100644 index 0000000..0e70ff9 --- /dev/null +++ b/cli/src/commands/message/pinned.ts @@ -0,0 +1,60 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { validatePagination } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions, MessageItem } from '../../lib/types.js'; + +/** + * Action handler for `tg message pinned <chat>`. + * + * Fetches pinned messages from a chat using the pinned filter. + * Returns serialized messages with total count for pagination. + * + * Output shape: { messages: MessageItem[], total: number } + */ +export async function messagePinnedAction( + this: Command, + chatInput: string, +): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { + limit: string; + offset: string; + }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chatInput); + + // CRITICAL: Pass search: '' alongside the pinned filter to ensure gramjs + // creates a messages.Search request. Without this, gramjs falls through + // to GetHistory which ignores filters. + const messages = await client.getMessages(entity, { + search: '', + filter: new Api.InputMessagesFilterPinned(), + limit, + addOffset: offset, + }); + + const serialized: MessageItem[] = messages.map(msg => + serializeMessage(msg, (msg as any)._sender), + ); + + outputSuccess({ + messages: serialized, + total: (messages as any).total ?? 0, + }); + }); +} diff --git a/cli/src/commands/message/poll.ts b/cli/src/commands/message/poll.ts new file mode 100644 index 0000000..93bc604 --- /dev/null +++ b/cli/src/commands/message/poll.ts @@ -0,0 +1,165 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { generateRandomLong } from 'teleproto/Helpers.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import type { GlobalOptions } from '../../lib/types.js'; +import { parseIntegerOption } from '../../lib/validate.js'; + +/** + * Options for the poll subcommand. + */ +interface PollOpts { + question: string; + option: string[]; + quiz?: boolean; + correct?: string; + solution?: string; + multiple?: boolean; + public?: boolean; + closeIn?: string; +} + +/** + * Validate poll options before sending to Telegram API. + * Returns null if valid, or { error, code } describing the first validation failure. + * + * Fail-fast: reports first error found. + */ +export function validatePollOpts(opts: Pick<PollOpts, 'question' | 'option' | 'quiz' | 'correct' | 'solution' | 'multiple' | 'closeIn'>): { error: string; code: string } | null { + // Question validation + if (!opts.question || opts.question.trim().length === 0) { + return { error: 'Poll question cannot be empty', code: ErrorCode.EMPTY_QUESTION }; + } + if (opts.question.length > 300) { + return { error: 'Question too long (max 300 chars)', code: ErrorCode.QUESTION_TOO_LONG }; + } + + // Options count validation + if (opts.option.length < 2) { + return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_FEW_OPTIONS }; + } + if (opts.option.length > 10) { + return { error: 'Poll requires 2-10 options', code: ErrorCode.TOO_MANY_OPTIONS }; + } + + // Individual option validation + for (const opt of opts.option) { + if (!opt || opt.trim().length === 0) { + return { error: 'Poll option cannot be empty', code: ErrorCode.EMPTY_OPTION }; + } + if (opt.length > 100) { + return { error: 'Option too long (max 100 chars)', code: ErrorCode.OPTION_TOO_LONG }; + } + } + + // Duplicate detection + const seen = new Set<string>(); + for (const opt of opts.option) { + if (seen.has(opt)) { + return { error: `Duplicate option text: '${opt}'`, code: ErrorCode.DUPLICATE_OPTION }; + } + seen.add(opt); + } + + // Quiz constraints + if (opts.quiz && !opts.correct) { + return { error: 'Quiz mode requires --correct <index>', code: ErrorCode.QUIZ_MISSING_CORRECT }; + } + if (opts.solution && !opts.quiz) { + return { error: '--solution requires --quiz mode', code: ErrorCode.SOLUTION_WITHOUT_QUIZ }; + } + if (opts.quiz && opts.multiple) { + return { error: 'Quiz mode cannot use --multiple', code: ErrorCode.QUIZ_MULTIPLE_CONFLICT }; + } + + // --correct range validation + if (opts.correct !== undefined) { + try { + parseIntegerOption(opts.correct, 'Correct index', { min: 1, max: opts.option.length }); + } catch { + return { error: `Correct index must be 1-${opts.option.length}`, code: ErrorCode.INVALID_CORRECT_INDEX }; + } + } + + // --close-in validation + if (opts.closeIn !== undefined) { + try { + parseIntegerOption(opts.closeIn, 'Close-in seconds', { min: 1 }); + } catch { + return { error: 'Close-in seconds must be > 0', code: ErrorCode.INVALID_CLOSE_IN }; + } + } + + return null; +} + +/** + * Action handler for `tg message poll <chat>`. + * + * Sends a poll to a chat with full configuration support: + * basic polls, quiz mode, multiple choice, anonymous/public, auto-close timer. + * + * Validates all options client-side before making the API call. + * Returns serialized MessageItem via outputSuccess on success. + */ +export async function messagePollAction(this: Command, chat: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & PollOpts; + + // Client-side validation + const validation = validatePollOpts(opts); + if (validation) { + outputError(validation.error, validation.code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + try { + // Build poll answers + const answers = opts.option.map((text) => new Api.InputPollAnswer({ + text: new Api.TextWithEntities({ text, entities: [] }), + })); + + const closeInSeconds = opts.closeIn !== undefined ? Number(opts.closeIn.trim()) : undefined; + + const poll = new Api.Poll({ + id: generateRandomLong(), + hash: bigInt.zero, + question: new Api.TextWithEntities({ text: opts.question, entities: [] }), + answers, + quiz: opts.quiz || undefined, + publicVoters: opts.public || undefined, + multipleChoice: opts.multiple || undefined, + closePeriod: closeInSeconds || undefined, + }); + + const correctIdx = opts.correct !== undefined ? Number(opts.correct.trim()) - 1 : undefined; + const inputMedia = new Api.InputMediaPoll({ + poll, + correctAnswers: opts.quiz && correctIdx !== undefined + ? [correctIdx] + : undefined, + solution: opts.solution || undefined, + solutionEntities: opts.solution ? [] : undefined, + }); + + const sentMsg = await client.sendFile(entity, { file: inputMedia }); + if (!sentMsg) { + outputError('Telegram did not return the sent poll result; retrying may create a duplicate.', ErrorCode.MESSAGE_RESULT_UNAVAILABLE); + return; + } + const serialized = serializeMessage(sentMsg as any); + outputSuccess(serialized); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/message/react.ts b/cli/src/commands/message/react.ts new file mode 100644 index 0000000..8ac6ab0 --- /dev/null +++ b/cli/src/commands/message/react.ts @@ -0,0 +1,56 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageId } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Action handler for `tg message react <chat> <msg-id> <emoji>`. + * + * Adds or removes an emoji reaction on a message. + * Uses Api.messages.SendReaction with Api.ReactionEmoji wrapper (NOT plain string). + * Remove with --remove flag sends empty reaction array. + * + * Returns: { messageId, chatId, emoji, action: 'added'|'removed' } + */ +export async function messageReactAction(this: Command, chat: string, msgId: string, emoji: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { remove?: boolean }; + const remove = opts.remove ?? false; + + let messageId: number; + try { + messageId = parseMessageId(msgId); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + // CRITICAL: reaction MUST be Api.ReactionEmoji[], NOT plain string (pitfall #1) + const reaction = remove + ? [] + : [new Api.ReactionEmoji({ emoticon: emoji })]; + + await client.invoke( + new Api.messages.SendReaction({ + peer: entity, + msgId: messageId, + reaction, + }), + ); + + outputSuccess({ + messageId, + chatId: markedPeerId(entity), + emoji, + action: remove ? 'removed' : 'added', + }); + }); +} diff --git a/cli/src/commands/message/replies.ts b/cli/src/commands/message/replies.ts new file mode 100644 index 0000000..e8eb7fb --- /dev/null +++ b/cli/src/commands/message/replies.ts @@ -0,0 +1,107 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { messagePeerMarkedId, serializeMessage } from '../../lib/serialize.js'; +import { buildEntityMap } from '../../lib/entity-map.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageIds, validatePagination } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; +import type { BatchItemError, GlobalOptions, MessageItem } from '../../lib/types.js'; + +/** + * Serialize messages from a GetReplies result, resolving sender names. + */ +function serializeReplies(result: any): MessageItem[] { + const entityMap = buildEntityMap(result); + return result.messages.map((msg: any) => { + const senderId = messagePeerMarkedId({ peerId: msg.fromId }); + const senderEntity = entityMap.get(senderId); + return serializeMessage(msg, senderEntity); + }); +} + +/** + * Action handler for `tg message replies <channel> <msg-ids>`. + * + * Reads replies/comments on channel posts using messages.GetReplies. + * Accepts comma-separated msg IDs for batch fetching in a single connection. + * Options: --limit (default 50), --offset (default 0) + */ +export async function messageRepliesAction( + this: Command, + channelInput: string, + msgIdsInput: string, +): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { + limit: string; + offset: string; + }; + + let limit: number; + let offset: number; + let msgIds: number[]; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + msgIds = parseMessageIds(msgIdsInput); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, channelInput); + + // Single post — original simple output + if (msgIds.length === 1) { + const result = await client.invoke( + new Api.messages.GetReplies({ + peer: entity, + msgId: msgIds[0], + limit, + addOffset: offset, + }), + ); + + outputSuccess({ + messages: serializeReplies(result), + total: (result as any).count ?? 0, + postId: msgIds[0], + }); + return; + } + + // Batch mode — iterate over post IDs within one connection + const posts: Array<{ + postId: number; + messages: MessageItem[]; + total: number; + }> = []; + const errors: BatchItemError[] = []; + + for (const msgId of msgIds) { + try { + const result = await client.invoke( + new Api.messages.GetReplies({ + peer: entity, + msgId, + limit, + addOffset: offset, + }), + ); + + posts.push({ + postId: msgId, + messages: serializeReplies(result), + total: (result as any).count ?? 0, + }); + } catch (err: unknown) { + errors.push(batchError(String(msgId), err)); + } + } + + outputBatchResult({ posts }, errors); + }); +} diff --git a/cli/src/commands/message/search.ts b/cli/src/commands/message/search.ts new file mode 100644 index 0000000..ee32cef --- /dev/null +++ b/cli/src/commands/message/search.ts @@ -0,0 +1,362 @@ +import type { Command } from 'commander'; +import type { TelegramClient } from 'teleproto'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { resolveEntity, assertForum } from '../../lib/peer.js'; +import { + serializeMessage, + serializeSearchResult, + bigIntToString, + markedPeerId, + messagePeerMarkedId, +} from '../../lib/serialize.js'; +import { FILTER_MAP, VALID_FILTERS } from '../../lib/media-utils.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { validatePagination, parseTopicId, parseMessageId } from '../../lib/validate.js'; +import { formatError } from '../../lib/errors.js'; +import { buildEntityMap } from '../../lib/entity-map.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; +import type { BatchItemError, GlobalOptions, PublicPostSearchResult, SearchResultItem } from '../../lib/types.js'; + +/** + * Action handler for `tg message search`. + * + * Searches messages by keyword within a specific chat (--chat), across multiple + * chats (comma-separated --chat), or globally (no --chat). + * + * Options: --query, --filter, --chat <chat>, --topic <topicId>, --limit (default 50), --offset (default 0) + * + * Single-chat search (--chat with one value): resolves entity, passes search param to getMessages. + * Multi-chat search (--chat with comma-separated values): resolves each, searches sequentially, merges results. + * Global search (no --chat): iterates cross-chat search and skips --offset results; + * results include marked chatId/chatTitle. Multi-chat failures include partial/errors. + */ +export async function messageSearchAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { + query?: string; + filter?: string; + chat?: string; + topic?: string; + public?: boolean; + peer?: string; + after?: string; + limit: string; + offset: string; + }; + const { quiet } = opts; + + if (opts.public) { + if (opts.chat) { + outputError('--public cannot be combined with --chat', ErrorCode.INVALID_OPTIONS); + return; + } + if (opts.filter) { + outputError('--public cannot be combined with --filter', ErrorCode.INVALID_OPTIONS); + return; + } + if (opts.topic !== undefined) { + outputError('--public cannot be combined with --topic', ErrorCode.INVALID_OPTIONS); + return; + } + if (!opts.query) { + outputError( + '--public requires --query (a public-channel hashtag, with or without #)', + ErrorCode.MISSING_QUERY, + ); + return; + } + } else if (opts.peer !== undefined || opts.after !== undefined) { + outputError('--peer and --after require --public', ErrorCode.INVALID_OPTIONS); + return; + } + + // Validate: either --query or --filter (or both) must be provided + if (!opts.query && !opts.filter) { + outputError( + 'Either --query or --filter is required. Use --filter to browse by media type.', + ErrorCode.MISSING_QUERY, + ); + return; + } + + // Validate filter name if provided + if (opts.filter && !FILTER_MAP[opts.filter]) { + outputError( + `Unknown filter: ${opts.filter}. Valid: ${VALID_FILTERS.join(', ')}`, + ErrorCode.INVALID_FILTER, + ); + return; + } + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + let topicId: number | undefined; + if (opts.topic !== undefined) { + try { + topicId = parseTopicId(opts.topic); + } catch (err: unknown) { + outputError( + err instanceof Error ? err.message : 'Invalid topic ID: must be a number', + ErrorCode.INVALID_TOPIC_ID, + ); + return; + } + } + + if (topicId !== undefined && !opts.chat) { + outputError('--topic requires a single --chat', ErrorCode.INVALID_OPTIONS); + return; + } + + let afterId = 0; + if (opts.after !== undefined) { + try { + afterId = parseMessageId(opts.after); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + } + + await withAuth(opts, async (client) => { + if (opts.public) { + await searchPublicPosts(client, { + query: opts.query!, + limit, + offsetRate: offset, + afterId, + peer: opts.peer, + }); + return; + } + + const baseSearchParams: Record<string, any> = { + search: opts.query || '', + }; + + if (opts.filter) { + baseSearchParams.filter = FILTER_MAP[opts.filter](); + } + + if (opts.chat) { + const chatIds = opts.chat.split(',').map(c => c.trim()).filter(Boolean); + + if (chatIds.length === 1) { + // Single-chat search (READ-03) with optional topic scoping + const entity = await resolveEntity(client, chatIds[0]); + + if (topicId !== undefined) { + await assertForum(entity, topicId); + const peer = await client.getInputEntity(entity); + const messages = []; + let total = 0; + let offsetId = 0; + while (messages.length < limit) { + const pageLimit = Math.min(100, limit - messages.length); + const result = await client.invoke(new Api.messages.Search({ + peer, + q: opts.query ?? '', + filter: opts.filter ? FILTER_MAP[opts.filter]() : new Api.InputMessagesFilterEmpty(), + topMsgId: topicId, + offsetId, + addOffset: offsetId === 0 ? offset : 0, + limit: pageLimit, + minDate: 0, + maxDate: 0, + maxId: 0, + minId: 0, + hash: bigInt.zero, + })); + if (!('messages' in result)) break; + total = 'count' in result ? result.count : result.messages.length; + const nextOffsetId = result.messages.at(-1)?.id; + if (!nextOffsetId || (offsetId !== 0 && nextOffsetId >= offsetId)) break; + const entities = buildEntityMap(result); + for (const message of result.messages) { + if (offsetId !== 0 && message.id >= offsetId) continue; + const senderId = messagePeerMarkedId({ peerId: (message as any).fromId }); + messages.push(serializeMessage(message as any, entities.get(senderId))); + } + if (result.messages.length < pageLimit) break; + offsetId = nextOffsetId; + } + outputSuccess({ messages: messages.slice(0, limit), total }); + return; + } + + const messages = await client.getMessages(entity, { ...baseSearchParams, limit, addOffset: offset }); + + const serialized = messages.map((msg: any) => + serializeMessage(msg), + ); + + outputSuccess({ + messages: serialized, + total: (messages as any).total ?? 0, + }); + } else { + // Multi-chat search (READ-06) + // Topic flag not supported on multi-chat search (ambiguous which chat) + if (topicId !== undefined) { + outputError('--topic cannot be used with multi-chat search', ErrorCode.INVALID_OPTIONS); + return; + } + + const allResults: SearchResultItem[] = []; + const errors: BatchItemError[] = []; + // Fetch enough results from each chat to satisfy offset + limit after merge + const perChatLimit = offset + limit; + for (const chatId of chatIds) { + try { + const entity = await resolveEntity(client, chatId); + const messages = await client.getMessages(entity, { ...baseSearchParams, addOffset: 0, limit: perChatLimit }); + for (const msg of messages) { + const msgChatId = messagePeerMarkedId(msg); + const chat = (msg as any).chat || (msg as any)._chat; + let chatTitle: string; + if (chat?.firstName) { + const last = chat.lastName ? ` ${chat.lastName}` : ''; + chatTitle = `${chat.firstName}${last}`; + } else { + chatTitle = chat?.title || msgChatId; + } + allResults.push(serializeSearchResult(msg as any, msgChatId, chatTitle)); + } + } catch (err) { + const error = batchError(chatId, err); + errors.push(error); + logStatus(`Warning: failed to search ${chatId}: ${error.error}`, quiet); + } + } + + // Sort newest first, apply offset, truncate to limit + allResults.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()); + const paged = allResults.slice(offset, offset + limit); + outputBatchResult({ messages: paged, total: paged.length }, errors); + } + } else { + // Global search (READ-04) + // SearchGlobal has no addOffset. Let gramjs advance its full cursor + // (offsetRate, offsetPeer, offsetId), then skip the requested result count. + const iterator = client.iterMessages(undefined, { ...baseSearchParams, limit: offset + limit }); + const messages: Api.Message[] = []; + let skipped = 0; + for await (const message of iterator) { + if (skipped < offset) { + skipped++; + continue; + } + messages.push(message); + if (messages.length >= limit) break; + } + + const serialized = messages.map((msg: any) => { + const chatId = messagePeerMarkedId(msg); + const chat = msg.chat || (msg as any)._chat; + let chatTitle: string; + if (chat?.firstName) { + // User entity (DM): use firstName + lastName + const last = chat.lastName ? ` ${chat.lastName}` : ''; + chatTitle = `${chat.firstName}${last}`; + } else { + chatTitle = chat?.title || chatId; + } + + return serializeSearchResult(msg, chatId, chatTitle); + }); + + outputSuccess({ + messages: serialized, + total: (iterator as any).total ?? 0, + }); + } + }); +} + +/** + * Global hashtag search over public channel posts (`channels.searchPosts`). + * The CLI preserves its hashtag-only public search contract on Teleproto. + */ +async function searchPublicPosts( + client: TelegramClient, + opts: { query: string; limit: number; offsetRate: number; afterId: number; peer?: string }, +): Promise<void> { + const hashtag = opts.query.trim().replace(/^#/, ''); + if (!hashtag) { + outputError('Search query cannot be empty', ErrorCode.MISSING_QUERY); + return; + } + if (/\s/.test(hashtag)) { + outputError( + 'Public post search looks up hashtags in public channels (including those you have not joined). Use a single token, with or without #.', + ErrorCode.INVALID_OPTIONS, + ); + return; + } + + let offsetPeer: any = new Api.InputPeerEmpty(); + if (opts.peer) { + const entity = await resolveEntity(client, opts.peer); + offsetPeer = await client.getInputEntity(entity); + } + + const result = await client.invoke( + new Api.channels.SearchPosts({ + hashtag, + offsetRate: opts.offsetRate, + offsetPeer, + offsetId: opts.afterId, + limit: opts.limit, + }), + ); + + const chats = ((result as any).chats ?? []) as any[]; + const rawMessages = ((result as any).messages ?? []) as any[]; + const messages = rawMessages.map((msg: any) => { + const chatId = messagePeerMarkedId(msg); + const chat = chats.find((c) => markedPeerId(c) === chatId) + ?? chats.find((c) => bigIntToString(c.id) === bigIntToString(msg.peerId?.channelId)); + const title = chat?.title || chat?.username || chatId; + return serializeSearchResult(msg, chatId, title); + }); + + const lastRaw = rawMessages[rawMessages.length - 1]; + const last = messages[messages.length - 1]; + const hasMore = messages.length > 0 + && ((result as any).nextRate != null || messages.length >= opts.limit); + const nextRate = hasMore + ? ((result as any).nextRate ?? lastRaw?.date ?? null) + : null; + + const floodRaw = (result as any).searchFlood; + const data: PublicPostSearchResult = { + messages, + total: (result as any).count ?? messages.length, + hasMore, + nextRate, + nextOffsetId: hasMore ? (last?.id ?? null) : null, + nextOffsetPeer: hasMore ? (last?.chatId ?? null) : null, + }; + if (floodRaw) { + data.flood = { + remains: floodRaw.remains ?? null, + totalDaily: floodRaw.totalDaily ?? null, + waitTill: floodRaw.waitTill ?? null, + starsAmount: floodRaw.starsAmount != null ? String(floodRaw.starsAmount) : null, + queryIsFree: floodRaw.queryIsFree === true, + }; + } + + outputSuccess(data); +} diff --git a/cli/src/commands/message/send.ts b/cli/src/commands/message/send.ts new file mode 100644 index 0000000..264c3bb --- /dev/null +++ b/cli/src/commands/message/send.ts @@ -0,0 +1,141 @@ +import type { Command } from 'commander'; +import { parseSchedule } from '../../lib/schedule.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { resolveEntity, assertForum } from '../../lib/peer.js'; +import { serializeMessage } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions, ScheduledMessageResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; +import { parseTopicId, parseMessageId } from '../../lib/validate.js'; + +/** + * Read all data from stdin as a UTF-8 string. + * Used when the text argument is "-" (dash placeholder) to support piped input. + */ +async function readStdin(): Promise<string> { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) { + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf-8').trimEnd(); +} + +/** + * Action handler for `tg message send <chat> <text>`. + * + * Sends a text message to any chat. Supports: + * - Server-side scheduled delivery via --schedule <zoned ISO timestamp> + * - Reply to a specific message via --reply-to <msgId> + * - Piped stdin input via dash placeholder: echo "msg" | tg message send <chat> - + * - gramjs built-in markdown parsing for **bold**, __italic__, `code`, [links](url) + * + * Returns the sent message as a serialized MessageItem. + */ +export async function messageSendAction(this: Command, chat: string, text: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { replyTo?: string; topic?: string; commentTo?: string; schedule?: string }; + + let schedule: number | undefined; + if (opts.schedule !== undefined) { + try { schedule = parseSchedule(opts.schedule); } + catch (err) { + outputError((err as Error).message, ErrorCode.INVALID_SCHEDULE); + return; + } + } + + // Handle stdin pipe via dash placeholder + if (text === '-') { + const context = getDaemonContext(); + if (context ? context.stdin === undefined : process.stdin.isTTY) { + outputError('"-" requires piped input. Example: echo "msg" | tg message send @user -', ErrorCode.STDIN_REQUIRED); + return; + } + text = context ? context.stdin!.trimEnd() : await readStdin(); + } + + // Validate non-empty text + if (!text) { + outputError('Message text is required', ErrorCode.EMPTY_MESSAGE); + return; + } + + // Telegram message length limit + if (text.length > 4096) { + outputError('Message too long (max 4096 chars)', ErrorCode.MESSAGE_TOO_LONG); + return; + } + + let topicId: number | undefined; + if (opts.topic !== undefined) { + try { + topicId = parseTopicId(opts.topic); + } catch (err: unknown) { + outputError( + err instanceof Error ? err.message : 'Invalid topic ID: must be a number', + ErrorCode.INVALID_TOPIC_ID, + ); + return; + } + } + + // Parse replyTo as integer + let replyTo: number | undefined; + try { + if (opts.replyTo !== undefined) replyTo = parseMessageId(opts.replyTo); + } catch { + outputError('Invalid reply-to message ID: must be a positive integer', ErrorCode.INVALID_REPLY_TO); + return; + } + + // Parse commentTo as integer (for channel post comments) + let commentTo: number | undefined; + try { + if (opts.commentTo !== undefined) commentTo = parseMessageId(opts.commentTo); + } catch { + outputError('Invalid comment-to message ID: must be a positive integer', ErrorCode.INVALID_COMMENT_TO); + return; + } + + if (topicId !== undefined && replyTo !== undefined) { + outputError( + '--topic and --reply-to cannot be combined yet. Use --reply-to to reply in-topic, or --topic to post to the topic root.', + ErrorCode.INVALID_OPTIONS, + ); + return; + } + if (commentTo !== undefined && (topicId !== undefined || replyTo !== undefined)) { + outputError('--comment-to cannot be combined with --topic or --reply-to', ErrorCode.INVALID_OPTIONS); + return; + } + const effectiveReplyTo = topicId !== undefined ? topicId : replyTo; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + // Forum guard: reject --topic on non-forum chats + await assertForum(entity, topicId); + + // Auth/peer resolution may have taken long enough to expire the requested time. + if (opts.schedule !== undefined) schedule = parseSchedule(opts.schedule); + + // gramjs built-in MarkdownParser handles **bold**, __italic__, `code`, [links](url) automatically + const sentMsg = await client.sendMessage(entity, { + message: text, + replyTo: effectiveReplyTo, + ...(commentTo !== undefined && { commentTo }), + ...(schedule !== undefined && { schedule }), + }); + + if (!sentMsg) { + outputError('Telegram did not return the sent message result; retrying may create a duplicate.', ErrorCode.MESSAGE_RESULT_UNAVAILABLE); + return; + } + const serialized = serializeMessage(sentMsg as any); + if (schedule === undefined) outputSuccess(serialized); + else { + const scheduled: ScheduledMessageResult = { ...serialized, scheduledAt: new Date(schedule * 1000).toISOString() }; + outputSuccess(scheduled); + } + }); +} diff --git a/cli/src/commands/message/unpin.ts b/cli/src/commands/message/unpin.ts new file mode 100644 index 0000000..54ab5f1 --- /dev/null +++ b/cli/src/commands/message/unpin.ts @@ -0,0 +1,50 @@ +import type { Command } from 'commander'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError, formatError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { markedPeerId } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import { parseMessageId } from '../../lib/validate.js'; +import type { GlobalOptions, PinResult } from '../../lib/types.js'; + +/** + * Action handler for `tg message unpin <chat> <msg-id>`. + * + * Unpins a specific message from a chat. + * API returns undefined (no confirmation payload), so we synthesize a PinResult. + * + * Returns PinResult with messageId, chatId, action: 'unpinned' (no silent field). + * Uses translateTelegramError for Telegram-specific permission errors. + */ +export async function messageUnpinAction(this: Command, chat: string, msgId: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + let messageId: number; + try { + messageId = parseMessageId(msgId); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, chat); + + try { + // API returns undefined — that's expected (Pitfall 2 from research) + await client.unpinMessage(entity, messageId); + + // Synthesize confirmation since API gives no response payload + const result: PinResult = { + messageId, + chatId: markedPeerId(entity), + action: 'unpinned', + }; + outputSuccess(result); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + }); +} diff --git a/cli/src/commands/message/watch.ts b/cli/src/commands/message/watch.ts new file mode 100644 index 0000000..bec9c8b --- /dev/null +++ b/cli/src/commands/message/watch.ts @@ -0,0 +1,68 @@ +import type { Command } from 'commander'; +import { createConfig } from '../../lib/config.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { DaemonPaths } from '../../lib/daemon/pid.js'; +import { DaemonClient } from '../../lib/daemon/client.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { parseTopicId } from '../../lib/validate.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Stream new messages in a chat via the daemon. Stays up until Ctrl+C. + * Each message is written through outputSuccess (JSON envelope / --human / --toon). + */ +export async function messageWatchAction(this: Command, chatInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { topic?: string }; + const { profile, quiet } = opts; + + let topicId: number | undefined; + if (opts.topic !== undefined) { + try { + topicId = parseTopicId(opts.topic); + } catch (err: unknown) { + outputError( + err instanceof Error ? err.message : 'Invalid topic ID: must be a number', + ErrorCode.INVALID_TOPIC_ID, + ); + return; + } + } + + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, profile); + + if (!paths.socketExists()) { + outputError( + 'message watch requires a running daemon. Start one with: tg daemon start', + ErrorCode.DAEMON_NOT_RUNNING, + ); + return; + } + + logStatus(`Watching ${chatInput} for new messages... (Ctrl+C to stop)`, quiet); + + const client = new DaemonClient(paths.socketPath); + + const stop = () => client.close(); + process.once('SIGINT', stop); + process.once('SIGTERM', stop); + + try { + await client.watch( + { chat: chatInput, topic: topicId }, + (payload) => { + outputSuccess(payload); + }, + ); + } catch (err: unknown) { + outputError( + `Watch failed: ${(err as Error).message}`, + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + } finally { + process.removeListener('SIGINT', stop); + process.removeListener('SIGTERM', stop); + client.close(); + } +} diff --git a/cli/src/commands/session/export.ts b/cli/src/commands/session/export.ts new file mode 100644 index 0000000..e2d0d57 --- /dev/null +++ b/cli/src/commands/session/export.ts @@ -0,0 +1,55 @@ +import type { Command } from 'commander'; +import { createConfig } from '../../lib/config.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js'; +import type { GlobalOptions, ProfileData } from '../../lib/types.js'; + +/** + * Export action handler for `tg session export`. + * + * By default, outputs the raw session string to stdout (ideal for piping). + * When --json is explicitly passed on the CLI, outputs a JSON envelope + * with session string plus metadata (phone, created). + * + * Uses Commander's getOptionValueSource to detect explicit --json + * vs the app default (json: true by default). + */ +export async function exportAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + const { profile, quiet } = opts; + if (await refuseDirectConnectIfDaemon(opts)) return; + + const config = createConfig(opts.config); + const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, '')); + + const sessionString = await store.load(profile); + + if (!sessionString) { + outputError(`No session found for profile '${profile}'`, ErrorCode.NO_SESSION); + return; + } + + // Raw string is the default (piping). Structured modes still go through outputSuccess. + const jsonSource = this.getOptionValueSourceWithGlobals('json'); + const jsonExplicit = jsonSource === 'cli'; + const structured = + jsonExplicit || + opts.human === true || + opts.json === false || + !!opts.toon || + !!opts.jsonl; + + if (structured) { + const profileData = config.get(`profiles.${profile}`) as ProfileData | undefined; + outputSuccess({ + session: sessionString, + phone: profileData?.phone, + created: profileData?.created, + }); + } else { + logStatus('Exporting session...', quiet); + process.stdout.write(sessionString + '\n'); + } +} diff --git a/cli/src/commands/session/import.ts b/cli/src/commands/session/import.ts new file mode 100644 index 0000000..1b51f90 --- /dev/null +++ b/cli/src/commands/session/import.ts @@ -0,0 +1,136 @@ +import type { Command } from 'commander'; +import { createConfig, resolveCredentials, getCredentialsOrThrow } from '../../lib/config.js'; +import { resolveTransport } from '../../lib/transport.js'; +import { withClient } from '../../lib/client.js'; +import { SessionStore } from '../../lib/session-store.js'; +import { outputSuccess, outputError, logStatus } from '../../lib/output.js'; +import { formatError } from '../../lib/errors.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { refuseDirectConnectIfDaemon } from '../../lib/daemon/guard.js'; +import type { GlobalOptions } from '../../lib/types.js'; + +/** + * Read all data from stdin until EOF. + * Used when session string is piped via stdin instead of passed as argument. + */ +function readStdin(): Promise<string> { + return new Promise((resolve, reject) => { + let data = ''; + process.stdin.setEncoding('utf-8'); + process.stdin.on('data', (chunk: string) => { + data += chunk; + }); + process.stdin.on('end', () => resolve(data)); + process.stdin.on('error', reject); + }); +} + +/** + * Import action handler for `tg session import [session]`. + * + * Accepts a session string as a positional argument, or reads from stdin + * when piped. By default validates the session by connecting to Telegram + * and checking authorization. Use --skip-verify to skip validation. + * + * Saves the session to the SessionStore and updates the config profile + * with the session string and creation timestamp. + */ +export async function importAction( + this: Command, + sessionString: string | undefined, +): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { skipVerify?: boolean }; + const { profile, quiet } = opts; + if (await refuseDirectConnectIfDaemon(opts)) return; + const skipVerify = opts.skipVerify ?? false; + + let session = sessionString; + + if (!session) { + // Check if stdin is piped (not a TTY) + if (process.stdin.isTTY) { + outputError( + 'Provide session string as argument or pipe via stdin', + ErrorCode.NO_INPUT, + ); + return; + } + + logStatus('Reading session from stdin...', quiet); + session = await readStdin(); + } + + // Trim and validate + session = session.trim(); + if (!session) { + outputError( + 'Provide session string as argument or pipe via stdin', + ErrorCode.NO_INPUT, + ); + return; + } + + const config = createConfig(opts.config); + const store = new SessionStore(config.path.replace(/[/\\][^/\\]+$/, '')); + + const importedSession = session; + await store.withLock(profile, async (_previousSession, holdUntil) => { + const transport = resolveTransport(config, profile, opts.transport); + // Validate session unless --skip-verify is set + let wasVerified = false; + + if (!skipVerify) { + const hasCredentials = config.get(`profiles.${profile}.client`) || resolveCredentials(config); + const creds = hasCredentials ? await getCredentialsOrThrow(config, undefined, profile) : null; + if (!creds) { + logStatus( + 'Warning: Cannot verify session — API credentials not configured. Saving without verification.', + quiet, + ); + } else { + try { + let authorized = false; + await withClient( + { apiId: creds.apiId, apiHash: creds.apiHash, sessionString: importedSession, transport }, + async (client) => { + authorized = await client.checkAuthorization(); + }, + { holdUntil }, + ); + + if (!authorized) { + outputError( + 'Session is not authorized. The session string may be invalid or expired. Use --skip-verify to import anyway.', + ErrorCode.INVALID_SESSION, + ); + return; + } + + wasVerified = true; + logStatus('Session verified — authorized.', quiet); + } catch (err: unknown) { + const { message } = formatError(err); + outputError( + `Session verification failed: ${message}. Use --skip-verify to import anyway.`, + ErrorCode.VERIFY_FAILED, + ); + return; + } + } + } + + // Save session to file store + store.saveUnlocked(profile, importedSession); + + // Update config profile with metadata + const clientName = config.get(`profiles.${profile}.client`); + config.set(`profiles.${profile}`, { + ...(clientName ? { client: clientName } : {}), + transport, + created: new Date().toISOString(), + }); + + logStatus('Session imported successfully!', quiet); + outputSuccess({ imported: true, profile, verified: wasVerified }); + }); +} diff --git a/cli/src/commands/session/index.ts b/cli/src/commands/session/index.ts new file mode 100644 index 0000000..36d6d76 --- /dev/null +++ b/cli/src/commands/session/index.ts @@ -0,0 +1,29 @@ +import { Command } from 'commander'; +import { exportAction } from './export.js'; +import { importAction } from './import.js'; + +/** + * Create the `session` command group with export and import subcommands. + * + * Usage: + * tg session export - Export session string for portability + * tg session import - Import a session string (argument or stdin pipe) + */ +export function createSessionCommand(): Command { + const session = new Command('session') + .description('Session management commands'); + + session + .command('export') + .description('Export session string for portability') + .action(exportAction); + + session + .command('import') + .argument('[session]', 'Session string to import') + .option('--skip-verify', 'Skip session validation via Telegram API') + .description('Import a session string') + .action(importAction); + + return session; +} diff --git a/cli/src/commands/user/block.ts b/cli/src/commands/user/block.ts new file mode 100644 index 0000000..a7d6557 --- /dev/null +++ b/cli/src/commands/user/block.ts @@ -0,0 +1,51 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions, BlockResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg user block <user>`. + * + * Blocks a single user. Validates that the resolved entity is a User + * (not a Channel or Chat). Idempotent: blocking an already-blocked user + * returns success silently. + * + * Returns BlockResult with userId, username, firstName, action: 'blocked'. + */ +export async function userBlockAction(this: Command, userInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, userInput); + + // Validate entity is a User (not Channel/Chat) + if (!(entity instanceof Api.User)) { + outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER); + return; + } + + const user = entity; + + try { + await client.invoke(new Api.contacts.Block({ id: user })); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + return; + } + + const result: BlockResult = { + userId: bigIntToString(user.id), + username: user.username ?? null, + firstName: user.firstName ?? null, + action: 'blocked', + }; + + outputSuccess(result); + }); +} diff --git a/cli/src/commands/user/blocked.ts b/cli/src/commands/user/blocked.ts new file mode 100644 index 0000000..376cad9 --- /dev/null +++ b/cli/src/commands/user/blocked.ts @@ -0,0 +1,69 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError, formatError } from '../../lib/errors.js'; +import { validatePagination } from '../../lib/validate.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions, BlockedListItem, BlockedListResult } from '../../lib/types.js'; + +/** + * Action handler for `tg user blocked`. + * + * Lists blocked users with pagination support. + * Handles both contacts.Blocked (full list, no .count) and + * contacts.BlockedSlice (paginated, has .count) response types. + * + * Returns BlockedListResult { users: BlockedListItem[], total: number }. + */ +export async function userBlockedAction(this: Command): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { limit?: string; offset?: string }; + + let limit: number; + let offset: number; + try { + ({ limit, offset } = validatePagination({ limit: opts.limit, offset: opts.offset })); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + await withAuth(opts, async (client) => { + let result: any; + try { + result = await client.invoke( + new Api.contacts.GetBlocked({ offset, limit }), + ); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + return; + } + + const total: number = (result as any).count ?? (result as any).blocked?.length ?? 0; + + // Build userMap from result.users keyed by stringified user ID + const userMap = new Map<string, any>(); + for (const user of (result as any).users ?? []) { + userMap.set(bigIntToString(user.id), user); + } + + // Map blocked entries to BlockedListItem + const users: BlockedListItem[] = []; + for (const entry of (result as any).blocked ?? []) { + const userId = bigIntToString(entry.peerId.userId); + const user = userMap.get(userId); + users.push({ + id: userId, + firstName: user?.firstName ?? null, + lastName: user?.lastName ?? null, + username: user?.username ?? null, + isBot: !!user?.bot, + }); + } + + const output: BlockedListResult = { users, total }; + outputSuccess(output); + }); +} diff --git a/cli/src/commands/user/download-photo.ts b/cli/src/commands/user/download-photo.ts new file mode 100644 index 0000000..e033442 --- /dev/null +++ b/cli/src/commands/user/download-photo.ts @@ -0,0 +1,50 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { existsSync, writeFileSync } from 'node:fs'; +import { resolve, isAbsolute } from 'node:path'; +import { withAuth } from '../../lib/with-auth.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { getDaemonContext } from '../../lib/daemon/execution-context.js'; +import type { GlobalOptions, UserPhotoDownloadResult } from '../../lib/types.js'; + +/** Download the current visible profile photo; preserve existing files unless --force. */ +export async function userDownloadPhotoAction(this: Command, user: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions & { output: string; force?: boolean }; + const context = getDaemonContext(); + if (context && (!context.cwd || !isAbsolute(context.cwd))) { + outputError('Profile photo commands through the daemon require an absolute cwd', ErrorCode.INVALID_OPTIONS); + return; + } + const target = resolve(context?.cwd ?? process.cwd(), opts.output); + if (existsSync(target) && !opts.force) { + outputError('Output file exists (use --force to overwrite)', ErrorCode.FILE_EXISTS); + return; + } + await withAuth(opts, async client => { + const entity = await resolveEntity(client, user); + if (!(entity instanceof Api.User)) { + outputError('Profile photo download requires a user', ErrorCode.NOT_A_USER); + return; + } + const buffer = await client.downloadProfilePhoto(entity, { isBig: true }); + if (!Buffer.isBuffer(buffer) || buffer.length === 0) { + outputError('No visible profile photo available', ErrorCode.NO_PROFILE_PHOTO); + return; + } + try { + // wx also closes the race between the initial existence check and download. + writeFileSync(target, buffer, { flag: opts.force ? 'w' : 'wx', mode: 0o600 }); + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'EEXIST') { + outputError('Output file exists (use --force to overwrite)', ErrorCode.FILE_EXISTS); + return; + } + throw err; + } + const data: UserPhotoDownloadResult = { userId: bigIntToString(entity.id)!, path: target, size: buffer.length, profilePhoto: true }; + outputSuccess(data); + }); +} diff --git a/cli/src/commands/user/index.ts b/cli/src/commands/user/index.ts new file mode 100644 index 0000000..4fd75e1 --- /dev/null +++ b/cli/src/commands/user/index.ts @@ -0,0 +1,50 @@ +import { Command } from 'commander'; +import { userDownloadPhotoAction } from './download-photo.js'; +import { userProfileAction } from './profile.js'; +import { userBlockAction } from './block.js'; +import { userUnblockAction } from './unblock.js'; +import { userBlockedAction } from './blocked.js'; + +/** + * Create the `user` command group with profile, block, unblock, blocked subcommands. + * + * Usage: + * tg user profile <users> - Get detailed user profile(s) (comma-separated) + * tg user block <user> - Block a user + * tg user unblock <user> - Unblock a user + * tg user blocked - List blocked users (--limit, --offset) + */ +export function createUserCommand(): Command { + const user = new Command('user') + .description('User profiles and block management'); + + user.command('profile') + .argument('<users>', 'User ID(s) or username(s), comma-separated') + .description('Get detailed user profile(s)') + .action(userProfileAction); + + user.command('block') + .argument('<user>', 'User ID or username') + .description('Block a user') + .action(userBlockAction); + + user.command('unblock') + .argument('<user>', 'User ID or username') + .description('Unblock a user') + .action(userUnblockAction); + + user.command('blocked') + .description('List blocked users') + .option('--limit <n>', 'Max results', '50') + .option('--offset <n>', 'Skip results', '0') + .action(userBlockedAction); + + user.command('download-photo') + .argument('<user>', 'User ID or username') + .requiredOption('-o, --output <file>', 'Destination file') + .option('--force', 'Overwrite an existing file') + .description('Download the current visible user profile photo') + .action(userDownloadPhotoAction); + + return user; +} diff --git a/cli/src/commands/user/profile.ts b/cli/src/commands/user/profile.ts new file mode 100644 index 0000000..f9375c4 --- /dev/null +++ b/cli/src/commands/user/profile.ts @@ -0,0 +1,80 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputError } from '../../lib/output.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { buildUserProfile } from '../../lib/user-profile.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { BatchItemError, GlobalOptions, UserProfile } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; +import { batchError, outputBatchResult } from '../../lib/batch-results.js'; + +/** + * Action handler for `tg user profile <users>`. + * + * Fetches detailed user profiles. Accepts comma-separated usernames/IDs. + * Returns profiles, genuinely missing inputs, and per-input errors. Any failed + * input sets partial:true and a nonzero exit status without dropping successes. + * + * - Privacy-restricted phone shows '[restricted]' for non-bot users + * - Bots include botInlinePlaceholder and supportsInline fields + * - All 6 UserStatus types mapped to lastSeen strings + * - Bots always have lastSeen: null + */ +export async function userProfileAction(this: Command, usersInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + const inputs = usersInput.split(',').map(s => s.trim()).filter(Boolean); + + if (inputs.length === 0) { + outputError('No users specified', ErrorCode.INVALID_INPUT); + return; + } + + if (inputs.length > 50) { + outputError('Too many users (max 50)', ErrorCode.TOO_MANY_USERS); + return; + } + + await withAuth(opts, async (client) => { + const profiles: UserProfile[] = []; + const notFound: string[] = []; + const errors: BatchItemError[] = []; + + for (const input of inputs) { + try { + const entity = await resolveEntity(client, input); + + // Validate entity is a User (not Channel/Chat) + if (!(entity instanceof Api.User)) { + notFound.push(input); + errors.push({ input, error: 'Peer is not a user', code: ErrorCode.NO_USERS_FOUND }); + continue; + } + + const user = entity; + + // Fetch full user details + const result = await client.invoke( + new Api.users.GetFullUser({ id: user }), + ); + + const fullUser = result.fullUser; + const userFromResult = (result.users?.find(candidate => bigIntToString(candidate.id) === bigIntToString(user.id)) ?? user) as Api.User; + + const profileData = await buildUserProfile(client, user, fullUser, userFromResult, err => { + errors.push(batchError(input, err, 'Could not fetch profile photos')); + }); + profiles.push(profileData); + } catch (err: unknown) { + const error = batchError(input, err); + errors.push(error); + if ([ErrorCode.PEER_NOT_FOUND, 'USERNAME_NOT_OCCUPIED', 'USER_ID_INVALID'].includes(error.code)) { + notFound.push(input); + } + } + } + + outputBatchResult({ profiles, notFound }, errors); + }); +} diff --git a/cli/src/commands/user/unblock.ts b/cli/src/commands/user/unblock.ts new file mode 100644 index 0000000..470859a --- /dev/null +++ b/cli/src/commands/user/unblock.ts @@ -0,0 +1,51 @@ +import type { Command } from 'commander'; +import { Api } from 'teleproto'; +import { outputSuccess, outputError } from '../../lib/output.js'; +import { translateTelegramError } from '../../lib/errors.js'; +import { resolveEntity } from '../../lib/peer.js'; +import { bigIntToString } from '../../lib/serialize.js'; +import { withAuth } from '../../lib/with-auth.js'; +import type { GlobalOptions, BlockResult } from '../../lib/types.js'; +import { ErrorCode } from '../../lib/error-codes.js'; + +/** + * Action handler for `tg user unblock <user>`. + * + * Unblocks a single user. Validates that the resolved entity is a User + * (not a Channel or Chat). Idempotent: unblocking an already-unblocked user + * returns success silently. + * + * Returns BlockResult with userId, username, firstName, action: 'unblocked'. + */ +export async function userUnblockAction(this: Command, userInput: string): Promise<void> { + const opts = this.optsWithGlobals() as GlobalOptions; + + await withAuth(opts, async (client) => { + const entity = await resolveEntity(client, userInput); + + // Validate entity is a User (not Channel/Chat) + if (!(entity instanceof Api.User)) { + outputError('Not a user: this is a group/channel', ErrorCode.NOT_A_USER); + return; + } + + const user = entity; + + try { + await client.invoke(new Api.contacts.Unblock({ id: user })); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + return; + } + + const result: BlockResult = { + userId: bigIntToString(user.id), + username: user.username ?? null, + firstName: user.firstName ?? null, + action: 'unblocked', + }; + + outputSuccess(result); + }); +} diff --git a/cli/src/index.ts b/cli/src/index.ts new file mode 100644 index 0000000..5a0053c --- /dev/null +++ b/cli/src/index.ts @@ -0,0 +1,29 @@ +/** + * Public API for programmatic use of @miolamio/tg-cli. + * + * import { withAuth, resolveEntity, ErrorCode } from '@miolamio/tg-cli'; + */ + +export { outputSuccess, outputError, logStatus } from './lib/output.js'; +export { createConfig, resolveCredentials, getCredentialsOrThrow } from './lib/config.js'; +export { SessionStore } from './lib/session-store.js'; +export { withClient } from './lib/client.js'; +export { withAuth } from './lib/with-auth.js'; +export type { WithAuthOptions } from './lib/with-auth.js'; +export { resolveEntity } from './lib/peer.js'; +export { ErrorCode } from './lib/error-codes.js'; +export { TgError, CredentialError, SessionError, FloodWaitError } from './lib/errors.js'; +export { DaemonClient, DaemonRpcError } from './lib/daemon/client.js'; +export { DaemonPaths } from './lib/daemon/pid.js'; +export { DAEMON_COMMANDS } from './lib/daemon/command-protocol.js'; +export type { DaemonCommandOptions, DaemonCommandRequest, DaemonExecutionResult } from './lib/daemon/command-protocol.js'; + +export type { + GlobalOptions, + Transport, + TgConfig, + ProfileData, + OutputEnvelope, + SuccessEnvelope, + ErrorEnvelope, +} from './lib/types.js'; diff --git a/cli/src/lib/batch-results.ts b/cli/src/lib/batch-results.ts new file mode 100644 index 0000000..18aba00 --- /dev/null +++ b/cli/src/lib/batch-results.ts @@ -0,0 +1,18 @@ +import { translateTelegramError } from './errors.js'; +import { outputSuccess } from './output.js'; +import type { BatchItemError } from './types.js'; +import { markExitFailure } from './daemon/execution-context.js'; + +/** Preserve the failed input and the original Telegram or application error code. */ +export function batchError(input: string, err: unknown, operation?: string): BatchItemError { + const { message, code } = translateTelegramError(err); + const transportCode = err != null && typeof err === 'object' && 'code' in err && typeof err.code === 'string' + ? err.code : undefined; + return { input, error: operation ? `${operation}: ${message}` : message, code: code === 'UNKNOWN_ERROR' ? (transportCode ?? code) : code }; +} + +/** Emit one batch result, retaining successes and making failures visible to scripts. */ +export function outputBatchResult<T extends object>(data: T, errors: BatchItemError[]): void { + if (errors.length > 0) markExitFailure(); + outputSuccess({ ...data, partial: errors.length > 0, errors }); +} diff --git a/cli/src/lib/branding.ts b/cli/src/lib/branding.ts new file mode 100644 index 0000000..40b897a --- /dev/null +++ b/cli/src/lib/branding.ts @@ -0,0 +1,31 @@ +import pc from 'picocolors'; + +/** Printable ASCII mascot, shared by interactive login and the README. */ +const LITTLE_DAEMON = String.raw` .------. + / o o \ + | \__/ | + | | + | /\ /\ | + \/ \/ \/`; + +const TAGLINE = 'Telegram, from your terminal.'; + +function colors() { + return pc.createColors(pc.isColorSupported + && process.env.NO_COLOR === undefined && process.env.FORCE_COLOR !== '0'); +} + +/** Main help runs before preAction, so it must use the parsed quiet flag. */ +export function formatHelpBanner(quiet = false): string { + if (quiet || !process.stdout.isTTY || process.env.TERM === 'dumb') return ''; + const color = colors(); + return `${color.cyan('(. .)')} ${color.bold('tg')} / ${TAGLINE}\n`; +} + +/** Keep authentication data on stdout and omit decoration when any stream is redirected. */ +export function showLoginBanner(quiet = false): void { + if (quiet || !process.stdin.isTTY || !process.stdout.isTTY || !process.stderr.isTTY + || process.env.TERM === 'dumb') return; + const color = colors(); + process.stderr.write(`\n${color.cyan(LITTLE_DAEMON)}\n\n${color.bold('tg')} / ${TAGLINE}\n\n`); +} diff --git a/cli/src/lib/cli-console.ts b/cli/src/lib/cli-console.ts new file mode 100644 index 0000000..4e706ed --- /dev/null +++ b/cli/src/lib/cli-console.ts @@ -0,0 +1,26 @@ +import { isQuietMode, isVerboseMode } from './cli-mode.js'; + +/** + * Keep dependency console dumps out of CLI data and avoid exposing SDK objects. + * Only executable entry points install this guard; library imports leave the + * embedding application's console unchanged. Use the returned function in tests. + */ +export function installCliConsoleGuard(): () => void { + const methods = ['log', 'info', 'debug', 'warn', 'error', 'dir', 'dirxml', 'table', 'trace', 'assert', 'count', 'countReset', 'time', 'timeLog', 'timeEnd', 'group', 'groupCollapsed', 'groupEnd', 'clear'] as const; + const target = console as unknown as Record<string, (...args: unknown[]) => void>; + const originals = methods.map(method => [method, target[method]] as const); + for (const method of methods) { + const diagnostic = (...args: unknown[]) => { + if (method === 'assert' && args[0]) return; + if (isQuietMode()) return; + if (!isVerboseMode() && !['warn', 'error', 'trace', 'assert'].includes(method)) return; + // gramjs has console.log(message) error branches outside its logger. Such + // objects can contain client/session data, so never format their arguments. + process.stderr.write(`[diagnostic] Dependency console.${method} output omitted.\n`); + }; + target[method] = diagnostic; + } + return () => { + for (const [method, original] of originals) target[method] = original; + }; +} diff --git a/cli/src/lib/cli-mode.ts b/cli/src/lib/cli-mode.ts new file mode 100644 index 0000000..062d139 --- /dev/null +++ b/cli/src/lib/cli-mode.ts @@ -0,0 +1,21 @@ +/** Global --quiet / --verbose flags set from the preAction hook. */ +import { getDaemonContext } from './daemon/execution-context.js'; + +let _quietMode = false; +let _verboseMode = false; + +export function setQuietMode(enabled: boolean): void { + _quietMode = enabled; +} + +export function setVerboseMode(enabled: boolean): void { + _verboseMode = enabled; +} + +export function isQuietMode(): boolean { + return getDaemonContext() ? true : _quietMode; +} + +export function isVerboseMode(): boolean { + return getDaemonContext() ? false : _verboseMode; +} diff --git a/cli/src/lib/client.ts b/cli/src/lib/client.ts new file mode 100644 index 0000000..568b152 --- /dev/null +++ b/cli/src/lib/client.ts @@ -0,0 +1,205 @@ +import { TelegramClient, sessions } from 'teleproto'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; +import { createGramjsLogger } from './gramjs-logger.js'; +import { installClientErrorDiagnostics } from './transport-diagnostics.js'; +import { connectionOptions } from './connection-options.js'; +import type { Transport } from './types.js'; +import { connectOrThrow } from './connect.js'; + +const { StringSession } = sessions; + +/** + * Options for creating and connecting a TelegramClient. + */ +export interface ClientOptions { + apiId: number; + apiHash: string; + sessionString: string; + transport?: Transport; +} + +/** + * Options for withClient behavior. + */ +export interface WithClientOptions { + /** Timeout in milliseconds. Defaults to 120_000 (2 minutes). */ + timeout?: number; + /** Additional attempts after a retryable failure. Default 0 (one attempt). */ + retries?: number; + /** Base delay in ms between retries (doubles each attempt). Default 1000. */ + retryDelay?: number; + /** Keep session ownership until all started work and teardown have finished. */ + holdUntil?: (cleanup: Promise<unknown>) => void; +} + +/** + * Determine if an error is retryable (network/transient errors only). + * TgError and its subclasses are never retryable (they represent app-level errors). + * Telegram RPCErrors are not retryable (they represent API rejection). + */ +function isRetryable(err: unknown): boolean { + if (err instanceof TgError) return false; + if (err instanceof Error) { + const code = (err as any).code; + if (typeof code === 'string' && ['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN'].includes(code)) { + return true; + } + } + return false; +} + +/** A retry wait owns its timer and removes it as soon as the deadline fires. */ +function waitForRetry(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve, reject) => { + signal.throwIfAborted(); + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort); + resolve(); + }, ms); + const abort = () => { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + reject(signal.reason); + }; + signal.addEventListener('abort', abort, { once: true }); + }); +} + +/** + * Execute a function with a connected TelegramClient, ensuring proper cleanup. + * + * - Creates the client with the given session string + * - Sets a configurable safety timeout (default 120s) that rejects with a structured TgError + * - Connects, runs the callback, and destroys the client in a finally block + * - Uses destroy() (not disconnect()) to avoid zombie _updateLoop + * - Aborts the callback signal at the deadline and cancels pending retries. + * An already running callback must observe the signal before further work; + * JavaScript cannot forcibly cancel an arbitrary promise or undo an RPC. + * A late completion is destroyed again. When holdUntil is supplied, session + * ownership remains held until that cleanup succeeds, even after TIMEOUT. + * + * @param opts - Client connection options + * @param fn - Async function to execute with the connected client + * @param options - Optional behavior config (timeout) + * @returns The result of the callback function + */ +export async function withClient<T>( + opts: ClientOptions, + fn: (client: TelegramClient, signal: AbortSignal) => Promise<T>, + options?: WithClientOptions, +): Promise<T> { + const timeoutMs = options?.timeout ?? 120_000; + const timeoutSeconds = Math.round(timeoutMs / 1000); + const retries = options?.retries ?? 0; + const baseDelay = options?.retryDelay ?? 1000; + if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647 + || !Number.isSafeInteger(retries) || retries < 0 + || !Number.isFinite(baseDelay) || baseDelay < 0 || baseDelay > 2_147_483_647) { + throw new TgError('Invalid client timeout or retry options', ErrorCode.INVALID_OPTIONS); + } + + const session = new StringSession(opts.sessionString); + const logger = createGramjsLogger([opts.apiHash, opts.sessionString]); + const client = new TelegramClient(session, opts.apiId, opts.apiHash, { + connectionRetries: 3, + requestRetries: 1, + catchUp: true, + retryDelay: 1000, + floodSleepThreshold: 60, + baseLogger: logger, + ...connectionOptions(opts.transport), + }); + installClientErrorDiagnostics(client, logger); + + const cancellation = new AbortController(); + let timeoutId: ReturnType<typeof setTimeout>; + const timeoutPromise = new Promise<never>((_, reject) => { + timeoutId = setTimeout(() => { + const error = new TgError(`Client operation timed out after ${timeoutSeconds} seconds`, ErrorCode.TIMEOUT); + cancellation.abort(error); + reject(error); + }, timeoutMs); + }); + + // Prevent unhandled rejection if timeout fires during microtask gap + // (Promise.race handles this, but detection can race in some runtimes) + timeoutPromise.catch(() => {}); + + // Defer execution to a microtask so the ownership hook is registered before + // connect or user work starts. Operation failure does not mean cleanup failed. + const operation = Promise.resolve().then(async () => { + await connectOrThrow(client); + for (let attempt = 0; ; attempt++) { + cancellation.signal.throwIfAborted(); + try { + const result = await fn(client, cancellation.signal); + cancellation.signal.throwIfAborted(); + return result; + } catch (err) { + cancellation.signal.throwIfAborted(); + if (!isRetryable(err) || attempt >= retries) throw err; + const backoff = Math.min(baseDelay * Math.pow(2, attempt), 2_147_483_647); + await waitForRetry(backoff, cancellation.signal); + } + } + }); + + type TeardownResult = { ok: true } | { ok: false; error: unknown }; + let finishTeardown!: (result: TeardownResult) => void; + const teardown = new Promise<TeardownResult>(resolve => { finishTeardown = resolve; }); + const cleanup = Promise.all([operation.then(() => {}, () => {}), teardown]).then(async ([, result]) => { + // An SDK connect or callback can outlive the immediate timeout teardown. + // Final destruction runs after every started operation has settled. + if (cancellation.signal.aborted) await client.destroy(); + if (!result.ok) throw result.error; + }); + // Consumers without an ownership hook still get late cleanup, without an + // unhandled rejection. A lock owner receives the original success/failure. + cleanup.catch(() => {}); + options?.holdUntil?.(cleanup); + + try { + return await Promise.race([operation, timeoutPromise]); + } finally { + clearTimeout(timeoutId!); + // Use destroy() NOT disconnect() -- avoids zombie _updateLoop + try { + await client.destroy(); + finishTeardown({ ok: true }); + } catch (error) { + finishTeardown({ ok: false, error }); + } + } +} + +/** + * Create a TelegramClient for interactive auth flow (login). + * + * Returns an unconnected client with an empty StringSession. + * The caller manages the lifecycle: call client.start() for auth, + * then client.destroy() when done. + * + * @param apiId - Telegram API ID + * @param apiHash - Telegram API hash + * @returns Unconnected TelegramClient instance + */ +export async function createClientForAuth( + apiId: number, + apiHash: string, + transport: Transport = 'tcp', +): Promise<TelegramClient> { + const session = new StringSession(''); + const logger = createGramjsLogger([apiHash]); + const client = new TelegramClient(session, apiId, apiHash, { + connectionRetries: 3, + catchUp: true, + retryDelay: 1000, + floodSleepThreshold: 60, + baseLogger: logger, + ...connectionOptions(transport), + }); + installClientErrorDiagnostics(client, logger); + + return client; +} diff --git a/cli/src/lib/config.ts b/cli/src/lib/config.ts new file mode 100644 index 0000000..7502f5f --- /dev/null +++ b/cli/src/lib/config.ts @@ -0,0 +1,113 @@ +import Conf from 'conf'; +import { dirname, basename, extname } from 'node:path'; +import type { TgConfig } from './types.js'; +import { CredentialError, TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** Telegram API IDs are positive TL int values; reject partial numeric strings. */ +function parseApiId(value: unknown, source: string): number { + const parsed = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value; + if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed <= 0 || parsed > 2_147_483_647) { + throw new CredentialError(`${source} must be a positive integer within Telegram's 32-bit range`); + } + return parsed; +} + +/** + * Create a Conf instance for tg-cli configuration. + * Default path: ~/.config/tg-cli/config.json (XDG via projectName). + * When configPath is provided (--config flag), uses that exact file path. + * + * @param configPath - Optional custom config file path from --config flag + */ +export function createConfig(configPath?: string): Conf<TgConfig> { + try { + if (configPath) { + return new Conf<TgConfig>({ + projectName: 'tg-cli', + configName: basename(configPath, extname(configPath)), + cwd: dirname(configPath), + defaults: { + profiles: {}, + }, + }); + } + return new Conf<TgConfig>({ + projectName: 'telegram-cli', + configName: 'config', + defaults: { + profiles: {}, + }, + }); + } catch { + // Do not expose malformed JSON contents: config files contain credentials. + throw new TgError('Cannot read configuration. Check that the config file is accessible and contains valid JSON.', ErrorCode.CONFIG_ERROR); + } +} + +/** + * Resolve API credentials from environment variables or config file. + * Priority: env vars (TG_API_ID, TG_API_HASH) > config file values. + * + * @returns Credentials object or null if neither source has them. + */ +export function resolveCredentials( + config: Conf<TgConfig>, +): { apiId: number; apiHash: string } | null { + const envApiId = process.env.TG_API_ID; + const envApiHash = process.env.TG_API_HASH; + + const rawApiId = envApiId || config.get('apiId'); + const apiId = rawApiId == null ? undefined : parseApiId(rawApiId, envApiId ? 'TG_API_ID' : 'Config apiId'); + const apiHash = envApiHash ?? config.get('apiHash'); + + if (apiHash != null && typeof apiHash !== 'string') { + throw new CredentialError('API hash must be a string'); + } + if (apiId && apiHash) { + return { apiId, apiHash }; + } + + return null; +} + +/** + * Resolve API credentials or throw a helpful error. + * Provides a clear message with link to https://my.telegram.org/apps. + * + * When clientName is provided, fetches credentials from opentele presets + * (runtime fetch, no keys stored in source). Env vars still take priority. + * Otherwise, a selected profile's saved client preset precedes global config + * credentials. Older profiles without a client name retain config fallback. + */ +export async function getCredentialsOrThrow( + config: Conf<TgConfig>, + clientName?: string, + profile?: string, +): Promise<{ apiId: number; apiHash: string }> { + // Env vars always take priority + const envApiId = process.env.TG_API_ID; + const envApiHash = process.env.TG_API_HASH; + if (envApiId && envApiHash) { + const apiId = parseApiId(envApiId, 'TG_API_ID'); + return { apiId, apiHash: envApiHash }; + } + + // Client preset (fetched at runtime from opentele) + const presetName = clientName ?? (profile ? config.get(`profiles.${profile}.client`) as string | undefined : undefined); + if (presetName) { + const { getPreset } = await import('./presets.js'); + return getPreset(config, presetName); + } + + // Config file values + const creds = resolveCredentials(config); + if (!creds) { + throw new CredentialError( + 'API credentials required. Get them at https://my.telegram.org/apps\n' + + 'Set TG_API_ID and TG_API_HASH environment variables, or put apiId/apiHash in the config file.\n' + + 'Or use a preset: tg auth login --client desktop', + ); + } + return creds; +} diff --git a/cli/src/lib/connect.ts b/cli/src/lib/connect.ts new file mode 100644 index 0000000..107b68d --- /dev/null +++ b/cli/src/lib/connect.ts @@ -0,0 +1,14 @@ +import type { TelegramClient } from 'teleproto'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** gramjs returns false after failed retries as well as for an existing connection. */ +export async function connectOrThrow(client: TelegramClient): Promise<void> { + const connected = await client.connect(); + if (connected === false && !client.connected) { + throw new TgError( + 'Could not establish a Telegram connection after retries. Check the transport diagnostics on stderr; use --verbose for connection stages.', + ErrorCode.CONNECTION_FAILED, + ); + } +} diff --git a/cli/src/lib/connection-options.ts b/cli/src/lib/connection-options.ts new file mode 100644 index 0000000..6486b50 --- /dev/null +++ b/cli/src/lib/connection-options.ts @@ -0,0 +1,11 @@ +import type { Transport } from './types.js'; +import { validateTransport } from './transport.js'; +import { DiagnosticTCPFull } from './transport-diagnostics.js'; +import { DiagnosticWSS, WssSocket } from './wss.js'; + +/** Shared transport selection for auth, direct commands and the daemon. */ +export function connectionOptions(transport: Transport = 'tcp') { + return validateTransport(transport) === 'wss' + ? { connection: DiagnosticWSS, networkSocket: WssSocket, useWSS: true } + : { connection: DiagnosticTCPFull, useWSS: false }; +} diff --git a/cli/src/lib/daemon/client.ts b/cli/src/lib/daemon/client.ts new file mode 100644 index 0000000..e2c8453 --- /dev/null +++ b/cli/src/lib/daemon/client.ts @@ -0,0 +1,139 @@ +import { createConnection, type Socket } from 'node:net'; +import { encodeRequest, parseMessage } from './protocol.js'; +import { JsonLineDecoder } from './frames.js'; +import { isDaemonExecutionResult, validateDaemonCommand, type DaemonCommandOptions, type DaemonExecutionResult } from './command-protocol.js'; + +/** Preserve the daemon's JSON-RPC code and structured error details. */ +export class DaemonRpcError extends Error { + constructor(readonly code: number, message: string, readonly data?: unknown) { + super(message); + this.name = 'DaemonRpcError'; + } +} + +/** JSON-RPC client. Each call or subscription owns a separate Unix socket. */ +export class DaemonClient { + private nextId = 1; + private readonly pending = new Set<() => void>(); + + constructor(private readonly socketPath: string) {} + + /** Execute a known CLI operation on the daemon's existing MTProto connection. */ + async execute(argv: string[], opts?: DaemonCommandOptions): Promise<DaemonExecutionResult> { + const request = validateDaemonCommand({ argv, ...opts }); + // The server owns the operation deadline; leave a small response grace period. + const result = await this.call('execute', { ...request }, { timeoutMs: (request.timeoutMs ?? 120_000) + 5_000 }); + if (!isDaemonExecutionResult(result)) throw new Error('Invalid daemon execute response'); + return result; + } + + /** Send a request with one deadline covering both connection and response. */ + async call( + method: string, + params: Record<string, unknown>, + opts?: { timeoutMs?: number }, + ): Promise<unknown> { + return this.exchange(method, params, opts?.timeoutMs ?? 30_000); + } + + /** + * Deliver notifications after the subscribe ack. Unexpected EOF/error rejects; + * close() is intentional cancellation and resolves the subscription cleanly. + * The deadline covers connection and ack, not the lifetime of the stream. + */ + async watch( + params: Record<string, unknown>, + onMessage: (payload: Record<string, unknown>) => void, + opts?: { timeoutMs?: number }, + ): Promise<void> { + await this.exchange('subscribe', params, opts?.timeoutMs ?? 30_000, onMessage); + } + + private exchange( + method: string, + params: Record<string, unknown>, + timeoutMs: number, + onMessage?: (payload: Record<string, unknown>) => void, + ): Promise<unknown> { + if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) { + return Promise.reject(new Error('Invalid daemon timeout')); + } + const id = this.nextId++; + return new Promise((resolve, reject) => { + let socket: Socket | undefined; + let settled = false; + let connected = false; + let acked = false; + const decoder = new JsonLineDecoder(); + const finish = (err?: unknown, result?: unknown) => { + if (settled) return; + settled = true; + clearTimeout(timeout); + this.pending.delete(cancel); + // Keep the error handler until close: already queued socket errors must + // remain contained even when a response or cancellation wins the race. + socket?.destroy(); + if (err !== undefined) reject(err); + else resolve(result); + }; + const cancel = () => finish(onMessage ? undefined : new Error('Daemon request cancelled')); + const timeout = setTimeout(() => { + const label = timeoutMs % 1000 === 0 ? `${timeoutMs / 1000}s` : `${timeoutMs}ms`; + finish(new Error(`Daemon ${onMessage ? 'subscribe' : 'request'} timed out (${label})`)); + }, timeoutMs); + this.pending.add(cancel); + + try { + socket = createConnection(this.socketPath); + socket.on('error', (err) => finish(connected ? err : new Error( + `Cannot connect to daemon at ${this.socketPath}: ${err.message}`, + ))); + const disconnected = () => finish(new Error(onMessage + ? acked ? 'Daemon disconnected while watching' : 'Daemon closed before subscribe ack' + : 'Daemon closed before response')); + socket.on('end', disconnected); + socket.on('close', disconnected); + socket.on('connect', () => { + if (settled) return; + connected = true; + socket!.write(encodeRequest(method, params, id) + '\n'); + }); + socket.on('data', (chunk: Buffer) => { + if (settled) return; + try { + decoder.push(chunk, (line) => { + if (settled) return; + const msg = parseMessage(line); + if (msg.type === 'response' || msg.type === 'error') { + // Ignore unrelated responses; they cannot satisfy this request + // or disable its deadline, including unrelated RPC errors. + if (msg.id !== id) return; + if (msg.type === 'error') { + finish(new DaemonRpcError(msg.error.code, msg.error.message, msg.error.data)); + } else if (onMessage) { + acked = true; + clearTimeout(timeout); + } else { + finish(undefined, msg.result); + } + } else if (msg.type === 'notification') { + if (acked && onMessage && msg.method === 'message') onMessage(msg.params); + } else { + finish(new Error('Unexpected request from daemon')); + } + }); + } catch (err) { + finish(err); + } + }); + } catch (err) { + finish(err); + } + }); + } + + /** Cancel all active requests/subscriptions and release their sockets. */ + close(): void { + for (const cancel of [...this.pending]) cancel(); + } +} diff --git a/cli/src/lib/daemon/command-protocol.ts b/cli/src/lib/daemon/command-protocol.ts new file mode 100644 index 0000000..7e2c027 --- /dev/null +++ b/cli/src/lib/daemon/command-protocol.ts @@ -0,0 +1,83 @@ +import type { OutputEnvelope } from '../types.js'; +import { TgError } from '../errors.js'; +import { ErrorCode } from '../error-codes.js'; +import { MAX_FRAME_BYTES } from './frames.js'; +import { isAbsolute } from 'node:path'; + +/** Named CLI operations exposed by execute; lifecycle/auth remain separate. */ +export const DAEMON_COMMANDS: Readonly<Record<string, readonly string[]>> = Object.freeze({ + bridge: Object.freeze(['call']), + chat: Object.freeze(['list', 'info', 'join', 'leave', 'resolve', 'invite-info', 'members', 'topics', 'search', 'create', 'edit', 'kick']), + message: Object.freeze(['history', 'search', 'get', 'pinned', 'send', 'forward', 'react', 'replies', 'edit', 'delete', 'pin', 'unpin', 'poll']), + media: Object.freeze(['download', 'send']), + user: Object.freeze(['profile', 'block', 'unblock', 'blocked', 'download-photo']), + contact: Object.freeze(['list', 'add', 'delete', 'search', 'set-photo']), +}); + +export interface DaemonCommandOptions { + /** Explicit stdin for commands accepting a dash as message text. */ + stdin?: string; + /** Absolute caller working directory; required for media operations. */ + cwd?: string; + /** Server deadline, 1–120000 ms. A timed-out send may already have happened. */ + timeoutMs?: number; +} + +export interface DaemonCommandRequest extends DaemonCommandOptions { + /** Command group, action and CLI arguments, without global output/auth flags. */ + argv: string[]; +} + +export interface DaemonExecutionResult { + /** The usual CLI envelope, before fields/JSONL/TOON/human rendering. */ + output: OutputEnvelope<unknown>; + /** Includes partial failures that still have a success envelope. */ + exitCode: number; +} + +export function isDaemonCommand(path: readonly string[]): boolean { + return path.length === 2 && Object.hasOwn(DAEMON_COMMANDS, path[0]) + && DAEMON_COMMANDS[path[0]].includes(path[1]); +} + +/** Bound and validate the new API without interpreting any shell text. */ +export function validateDaemonCommand(params: Record<string, unknown>): DaemonCommandRequest { + const invalid = (message: string): never => { throw new TgError(message, ErrorCode.INVALID_OPTIONS); }; + if (!params || typeof params !== 'object' || Array.isArray(params)) invalid('execute params must be an object'); + if (Object.keys(params).some(key => !['argv', 'stdin', 'cwd', 'timeoutMs'].includes(key))) { + invalid('execute accepts only argv, stdin, cwd and timeoutMs'); + } + if (!Array.isArray(params.argv) || params.argv.length < 2 || params.argv.length > 1024 + || params.argv.some(arg => typeof arg !== 'string' || arg.includes('\0'))) { + invalid('execute argv must contain 2–1024 strings without NUL characters'); + } + const argv = params.argv as string[]; + if (!isDaemonCommand(argv.slice(0, 2))) { + throw new TgError('This command cannot run through execute; auth/session/lifecycle and watch use their own commands', ErrorCode.DAEMON_PROXY_UNAVAILABLE); + } + if (params.stdin !== undefined && typeof params.stdin !== 'string') invalid('execute stdin must be a string'); + if (params.cwd !== undefined && (typeof params.cwd !== 'string' || !isAbsolute(params.cwd) || params.cwd.includes('\0'))) { + invalid('execute cwd must be an absolute path'); + } + if (argv[0] === 'media' && params.cwd === undefined) invalid('Media commands require an absolute cwd'); + const photoCommand = (argv[0] === 'user' && argv[1] === 'download-photo') + || (argv[0] === 'contact' && argv[1] === 'set-photo'); + if (photoCommand && params.cwd === undefined) invalid('Photo commands require an absolute cwd'); + if (params.timeoutMs !== undefined && (!Number.isInteger(params.timeoutMs) || (params.timeoutMs as number) < 1 || (params.timeoutMs as number) > 120_000)) { + invalid('execute timeoutMs must be an integer from 1 to 120000'); + } + // Leave room for the JSON-RPC envelope and request ID. + if (Buffer.byteLength(JSON.stringify(params), 'utf8') > MAX_FRAME_BYTES - 256) invalid('execute request exceeds the 1 MiB frame limit'); + return { argv: [...argv], ...(params.stdin !== undefined && { stdin: params.stdin as string }), + ...(params.cwd !== undefined && { cwd: params.cwd as string }), + ...(params.timeoutMs !== undefined && { timeoutMs: params.timeoutMs as number }) }; +} + +export function isDaemonExecutionResult(value: unknown): value is DaemonExecutionResult { + if (!value || typeof value !== 'object') return false; + const result = value as DaemonExecutionResult; + if (![0, 1].includes(result.exitCode) || !result.output || typeof result.output !== 'object') return false; + return result.output.ok === true ? Object.hasOwn(result.output, 'data') + : result.output.ok === false && typeof result.output.error === 'string' + && (result.output.code === undefined || typeof result.output.code === 'string'); +} diff --git a/cli/src/lib/daemon/entry-path.ts b/cli/src/lib/daemon/entry-path.ts new file mode 100644 index 0000000..969833b --- /dev/null +++ b/cli/src/lib/daemon/entry-path.ts @@ -0,0 +1,44 @@ +import { existsSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** + * Resolve the compiled daemon entry for `fork()`. + * + * After tsup, command code lives in `dist/bin/tg.js` (or a dist/ chunk). + * The entry file is always `dist/lib/daemon/entry.js`. A path computed + * as if we were still under `src/commands/daemon/` misses that file. + * + * Tries `import.meta.url` of the caller and `process.argv[1]` (the + * running binary) against a few relative layouts; first existing path wins. + */ +export function resolveDaemonEntry(moduleUrl: string = import.meta.url): string { + const bases: string[] = []; + try { + bases.push(dirname(fileURLToPath(moduleUrl))); + } catch { + // moduleUrl is not a file URL + } + if (process.argv[1]) { + bases.push(dirname(process.argv[1])); + } + + const relatives = [ + join('..', 'lib', 'daemon', 'entry.js'), // dist/bin/tg.js + join('lib', 'daemon', 'entry.js'), // dist/chunk.js + join('..', '..', 'lib', 'daemon', 'entry.js'), // src/commands/daemon (built colocated) + ]; + + const candidates: string[] = []; + for (const base of bases) { + for (const rel of relatives) { + candidates.push(join(base, rel)); + } + } + + for (const p of candidates) { + if (existsSync(p)) return p; + } + + return candidates[0] ?? join('lib', 'daemon', 'entry.js'); +} diff --git a/cli/src/lib/daemon/entry.ts b/cli/src/lib/daemon/entry.ts new file mode 100644 index 0000000..6223a3e --- /dev/null +++ b/cli/src/lib/daemon/entry.ts @@ -0,0 +1,53 @@ +import { DaemonServer } from './server.js'; +import { DaemonPaths } from './pid.js'; +import { installDaemonSignals } from './lifecycle.js'; +import { createConfig, getCredentialsOrThrow } from '../config.js'; +import { parseIntegerOption, validateProfile } from '../validate.js'; +import { installCliConsoleGuard } from '../cli-console.js'; +import { resolveTransport, validateTransport } from '../transport.js'; + +installCliConsoleGuard(); + +async function main(): Promise<void> { + const configDir = process.env.TG_DAEMON_CONFIG_DIR; + const profile = process.env.TG_DAEMON_PROFILE; + const idleInput = process.env.TG_DAEMON_IDLE_TIMEOUT; + const configPath = process.env.TG_DAEMON_CONFIG; + const transportInput = process.env.TG_DAEMON_TRANSPORT; + const pidPreclaimed = process.env.TG_DAEMON_PID_PRECLAIMED === '1'; + + delete process.env.TG_DAEMON_SESSION; + delete process.env.TG_DAEMON_API_HASH; + delete process.env.TG_DAEMON_API_ID; + delete process.env.TG_DAEMON_CONFIG_DIR; + delete process.env.TG_DAEMON_PROFILE; + delete process.env.TG_DAEMON_IDLE_TIMEOUT; + delete process.env.TG_DAEMON_CONFIG; + delete process.env.TG_DAEMON_TRANSPORT; + delete process.env.TG_DAEMON_PID_PRECLAIMED; + + if (!configDir || !profile || idleInput == null) { + process.stderr.write('Daemon missing TG_DAEMON_CONFIG_DIR / PROFILE / IDLE_TIMEOUT\n'); + process.exit(1); + } + validateProfile(profile); + const idleTimeout = parseIntegerOption(idleInput, 'daemon idle timeout'); + + const config = createConfig(configPath); + const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, profile); + const transport = resolveTransport(config, profile, transportInput === undefined ? undefined : validateTransport(transportInput)); + const paths = new DaemonPaths(configDir, profile); + const server = new DaemonServer( + paths, + { apiId, apiHash, transport }, + { idleTimeout, onIdle: () => process.exit(0), pidPreclaimed }, + ); + + installDaemonSignals(() => server.stop()); + await server.start(); +} + +main().catch((err) => { + process.stderr.write(`Daemon start failed: ${(err as Error).message}\n`); + process.exit(1); +}); diff --git a/cli/src/lib/daemon/execute.ts b/cli/src/lib/daemon/execute.ts new file mode 100644 index 0000000..759ce4e --- /dev/null +++ b/cli/src/lib/daemon/execute.ts @@ -0,0 +1,66 @@ +import { createBridgeCommand } from '../../commands/bridge/index.js'; +import { Command, CommanderError } from 'commander'; +import type { TelegramClient } from 'teleproto'; +import { createChatCommand } from '../../commands/chat/index.js'; +import { createMessageCommand } from '../../commands/message/index.js'; +import { createMediaCommand } from '../../commands/media/index.js'; +import { createUserCommand } from '../../commands/user/index.js'; +import { createContactCommand } from '../../commands/contact/index.js'; +import { outputError } from '../output.js'; +import { TgError, translateTelegramError } from '../errors.js'; +import { ErrorCode } from '../error-codes.js'; +import { isDaemonCommand, validateDaemonCommand, type DaemonExecutionResult } from './command-protocol.js'; +import { runWithDaemonContext, type DaemonExecutionContext } from './execution-context.js'; + +export type { DaemonExecutionResult } from './command-protocol.js'; + +/** Fresh Commander instances isolate arguments/defaults across API requests. */ +function createExecutionProgram(profile: string): Command { + const program = new Command('tg'); + program.setOptionValue('profile', profile).setOptionValue('quiet', true) + .setOptionValue('json', true).setOptionValue('daemon', false); + for (const group of [createBridgeCommand(), createChatCommand(), createMessageCommand(), createMediaCommand(), createUserCommand(), createContactCommand()]) { + program.addCommand(group); + } + program.hook('preAction', (_program, action) => { + if (!isDaemonCommand([action.parent?.name() ?? '', action.name()])) { + throw new TgError('This action is not available through execute', ErrorCode.DAEMON_PROXY_UNAVAILABLE); + } + }); + const configure = (command: Command) => { + command.exitOverride().helpOption(false).addHelpCommand(false).allowExcessArguments(false); + command.configureOutput({ writeOut: () => {}, writeErr: () => {}, outputError: () => {} }); + for (const child of command.commands) configure(child); + }; + configure(program); + return program; +} + +/** Run known handlers on the daemon's client, capturing DTOs rather than stdout. */ +export async function executeDaemonCommand( + client: TelegramClient, + profile: string, + params: Record<string, unknown>, + signal: AbortSignal, +): Promise<DaemonExecutionResult> { + const context: DaemonExecutionContext = { client, profile, signal, exitCode: 0 }; + return runWithDaemonContext(context, async () => { + try { + signal.throwIfAborted(); + const request = validateDaemonCommand(params); + context.stdin = request.stdin; + context.cwd = request.cwd; + await createExecutionProgram(profile).parseAsync(request.argv, { from: 'user' }); + signal.throwIfAborted(); + if (!context.output) outputError('Command completed without a result', ErrorCode.UNKNOWN_ERROR); + } catch (error) { + const formatted = translateTelegramError(error); + outputError(formatted.message, error instanceof CommanderError ? ErrorCode.INVALID_OPTIONS : formatted.code); + } + if (signal.aborted) { + const { message, code } = translateTelegramError(signal.reason); + return { output: { ok: false, error: message, code }, exitCode: 1 }; + } + return { output: context.output!, exitCode: context.exitCode }; + }); +} diff --git a/cli/src/lib/daemon/execution-context.ts b/cli/src/lib/daemon/execution-context.ts new file mode 100644 index 0000000..63deff3 --- /dev/null +++ b/cli/src/lib/daemon/execution-context.ts @@ -0,0 +1,49 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { TelegramClient } from 'teleproto'; +import type { OutputEnvelope } from '../types.js'; + +/** State belonging to one command on the daemon's existing Telegram client. */ +export interface DaemonExecutionContext { + client: TelegramClient; + profile: string; + signal: AbortSignal; + stdin?: string; + cwd?: string; + output?: OutputEnvelope<unknown>; + exitCode: number; +} + +const contexts = new AsyncLocalStorage<DaemonExecutionContext>(); + +/** Keep async continuations attached to their request, including concurrent commands. */ +export async function runWithDaemonContext<T>( + context: DaemonExecutionContext, + fn: () => T | Promise<T>, +): Promise<T> { + return contexts.run(context, fn); +} + +/** Undefined outside a daemon command; direct CLI and library calls keep their behavior. */ +export function getDaemonContext(): DaemonExecutionContext | undefined { + return contexts.getStore(); +} + +/** Shared SDK timers and transport loops must outlive requests without retaining their DTOs. */ +export function runOutsideDaemonContext<T>(fn: () => T): T { + return contexts.exit(fn); +} + +/** A failed command must not change the exit status of the daemon hosting it. */ +export function markExitFailure(): void { + const context = getDaemonContext(); + if (context) context.exitCode = 1; + else process.exitCode = 1; +} + +/** Capture raw DTOs before formatting. Later output cannot replace the first response. */ +export function captureDaemonOutput(envelope: OutputEnvelope<unknown>): boolean { + const context = getDaemonContext(); + if (!context) return false; + context.output ??= envelope; + return true; +} diff --git a/cli/src/lib/daemon/frames.ts b/cli/src/lib/daemon/frames.ts new file mode 100644 index 0000000..c0d1d5e --- /dev/null +++ b/cli/src/lib/daemon/frames.ts @@ -0,0 +1,29 @@ +/** Maximum UTF-8 bytes in one NDJSON frame, excluding the newline delimiter. */ +export const MAX_FRAME_BYTES = 1_048_576; + +/** + * Incremental, byte-bounded NDJSON framing. Counts individual frames rather than + * whole data events, which may contain several lines or fragments of UTF-8 text. + */ +export class JsonLineDecoder { + private chunks: Buffer[] = []; + private bytes = 0; + + push(chunk: Buffer, onLine: (line: string) => void): void { + let offset = 0; + while (offset < chunk.length) { + const newline = chunk.indexOf(10, offset); + const end = newline === -1 ? chunk.length : newline; + const part = chunk.subarray(offset, end); + this.bytes += part.length; + if (this.bytes > MAX_FRAME_BYTES) throw new Error('Message too large'); + if (part.length) this.chunks.push(part); + if (newline === -1) return; + const line = Buffer.concat(this.chunks, this.bytes).toString('utf-8'); + this.chunks = []; + this.bytes = 0; + onLine(line); + offset = newline + 1; + } + } +} diff --git a/cli/src/lib/daemon/guard.ts b/cli/src/lib/daemon/guard.ts new file mode 100644 index 0000000..d555f10 --- /dev/null +++ b/cli/src/lib/daemon/guard.ts @@ -0,0 +1,82 @@ +import { outputError } from '../output.js'; +import { ErrorCode } from '../error-codes.js'; +import { createConfig } from '../config.js'; +import { DaemonPaths } from './pid.js'; +import { DaemonClient } from './client.js'; +import { isProcessAlive } from './lifecycle.js'; + +const PROXY_MSG = + 'This operation cannot be proxied. Use CLI --daemon or DaemonClient.execute for supported commands; auth/session operations require stopping the daemon.'; + +const RUNNING_MSG = + 'A daemon is running for this profile. Use --daemon for commands, or tg daemon stop before auth/session operations.'; + +/** Refuse --daemon on commands that open their own MTProto client. */ +export function rejectDaemonProxy(opts: { daemon?: boolean }): boolean { + if (!opts.daemon) return false; + outputError(PROXY_MSG, ErrorCode.DAEMON_PROXY_UNAVAILABLE); + return true; +} + +export function daemonPidAlive(paths: DaemonPaths): boolean { + const pid = paths.readPid(); + return pid != null && isProcessAlive(pid); +} + +/** Unlink socket/pid only when no live process is holding them. */ +export function cleanupStaleDaemon(paths: DaemonPaths): boolean { + if (daemonPidAlive(paths)) return false; + paths.cleanup(); + return true; +} + +/** True if the unix socket answers JSON-RPC ping. Never unlinks. */ +export async function pingDaemon(paths: DaemonPaths, timeoutMs = 1500): Promise<boolean> { + if (!paths.socketExists()) return false; + const daemon = new DaemonClient(paths.socketPath); + try { + const pong = await daemon.call('ping', {}, { timeoutMs }); + return pong === 'pong'; + } catch { + return false; + } finally { + daemon.close(); + } +} + +/** + * True if a live daemon answered ping or a live PID still holds the files. + * Prints an error when blocking. + */ +export async function blockIfDaemonRunning(paths: DaemonPaths): Promise<boolean> { + if (paths.socketExists()) { + if (await pingDaemon(paths)) { + outputError(RUNNING_MSG, ErrorCode.DAEMON_ALREADY_RUNNING); + return true; + } + if (!cleanupStaleDaemon(paths)) { + outputError( + 'Daemon is not responding. Try: tg daemon stop && tg daemon start', + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + return true; + } + } + if (daemonPidAlive(paths)) { + outputError(RUNNING_MSG, ErrorCode.DAEMON_ALREADY_RUNNING); + return true; + } + return false; +} + +/** --daemon refuse, or block a direct MTProto connect beside a live daemon. */ +export async function refuseDirectConnectIfDaemon(opts: { + profile: string; + config?: string; + daemon?: boolean; +}): Promise<boolean> { + if (rejectDaemonProxy(opts)) return true; + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + return blockIfDaemonRunning(new DaemonPaths(configDir, opts.profile)); +} diff --git a/cli/src/lib/daemon/lifecycle.ts b/cli/src/lib/daemon/lifecycle.ts new file mode 100644 index 0000000..1465859 --- /dev/null +++ b/cli/src/lib/daemon/lifecycle.ts @@ -0,0 +1,70 @@ +/** + * Daemon process helpers: liveness, signals, child env without secrets. + */ +import type { Transport } from '../types.js'; + +export function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (err) { + // EPERM: process exists but we cannot signal it (other uid). Not dead. + return (err as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +/** Env passed to a forked daemon. Never includes session string or apiHash. */ +export function daemonChildEnv(opts: { + configDir: string; + profile: string; + idleTimeout: number; + configPath?: string; + transport?: Transport; +}): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...process.env }; + delete env.TG_DAEMON_SESSION; + delete env.TG_DAEMON_API_HASH; + delete env.TG_DAEMON_API_ID; + env.TG_DAEMON_CONFIG_DIR = opts.configDir; + env.TG_DAEMON_PROFILE = opts.profile; + env.TG_DAEMON_IDLE_TIMEOUT = String(opts.idleTimeout); + env.TG_DAEMON_PID_PRECLAIMED = '1'; + delete env.TG_DAEMON_TRANSPORT; + if (opts.transport) env.TG_DAEMON_TRANSPORT = opts.transport; + if (opts.configPath) env.TG_DAEMON_CONFIG = opts.configPath; + return env; +} + +/** + * SIGTERM/SIGINT → await stop(), then process.exit. + * Returns an uninstall function (for tests). + */ +export function installDaemonSignals(stop: () => Promise<void>): () => void { + let stopping = false; + const onSignal = () => { + if (stopping) return; + stopping = true; + stop() + .then(() => process.exit(0)) + .catch(() => process.exit(1)); + }; + process.on('SIGTERM', onSignal); + process.on('SIGINT', onSignal); + return () => { + process.off('SIGTERM', onSignal); + process.off('SIGINT', onSignal); + }; +} + +export async function waitWhile( + predicate: () => boolean, + timeoutMs: number, + stepMs = 50, +): Promise<boolean> { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + if (!predicate()) return true; + await new Promise((r) => setTimeout(r, stepMs)); + } + return !predicate(); +} diff --git a/cli/src/lib/daemon/pid.ts b/cli/src/lib/daemon/pid.ts new file mode 100644 index 0000000..5ca91aa --- /dev/null +++ b/cli/src/lib/daemon/pid.ts @@ -0,0 +1,106 @@ +// src/lib/daemon/pid.ts +import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'; +import { join, dirname, basename } from 'node:path'; + +/** + * Manages daemon PID file and socket path for a given profile. + * + * Paths: + * Socket: {configDir}/daemon/{profile}.sock + * PID: {configDir}/daemon/{profile}.pid + */ +export class DaemonPaths { + readonly socketPath: string; + readonly pidPath: string; + readonly logPath: string; + + constructor(readonly configDir: string, readonly profile: string) { + const daemonDir = join(configDir, 'daemon'); + const safe = basename(profile); + this.socketPath = join(daemonDir, `${safe}.sock`); + this.pidPath = join(daemonDir, `${safe}.pid`); + this.logPath = join(daemonDir, `${safe}.log`); + } + + /** + * Validate that the socket path fits within AF_UNIX limits. + * macOS: 104 bytes, Linux: 108 bytes. Use 104 for portability. + */ + validateSocketPath(): void { + if (Buffer.byteLength(this.socketPath, 'utf-8') > 104) { + throw new Error( + `Socket path too long (${this.socketPath.length} chars, max 104). ` + + 'Use --config to set a shorter config directory path.', + ); + } + } + + /** Ensure the daemon directory exists with owner-only access. */ + ensureDir(): void { + const dir = dirname(this.socketPath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + } + } + + /** Write the current process PID. */ + writePid(pid: number): void { + this.ensureDir(); + writeFileSync(this.pidPath, String(pid), { encoding: 'utf-8', mode: 0o600 }); + } + + /** Create the PID file exclusively. False if it already exists. */ + writePidExclusive(pid: number): boolean { + this.ensureDir(); + try { + writeFileSync(this.pidPath, String(pid), { encoding: 'utf-8', flag: 'wx', mode: 0o600 }); + return true; + } catch (err: unknown) { + if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; + throw err; + } + } + + unlinkSocket(): void { + if (existsSync(this.socketPath)) { + try { unlinkSync(this.socketPath); } catch { /* stale socket */ } + } + } + + /** Read the stored PID, or null if file doesn't exist or PID is invalid. */ + readPid(): number | null { + if (!existsSync(this.pidPath)) return null; + const content = readFileSync(this.pidPath, 'utf-8').trim(); + const pid = /^\d+$/.test(content) ? Number(content) : NaN; + // Reject non-positive, NaN, and implausibly large PIDs to prevent + // process.kill(0) (kill process group) or kill(-1) (kill all user procs) + if (!Number.isSafeInteger(pid) || pid <= 0 || pid > 4_194_304) return null; + return pid; + } + + /** Check whether the socket file exists. */ + socketExists(): boolean { + return existsSync(this.socketPath); + } + + /** Remove PID file and socket file. Caller must have checked nothing live owns them. */ + cleanup(): void { + for (const p of [this.pidPath, this.socketPath]) { + if (existsSync(p)) { + try { unlinkSync(p); } catch {} + } + } + } + + /** + * Unlink socket then pid, each only if the pid file still contains `pid`. + * Socket first: unlinking pid first lets a successor take `wx` and then + * get its socket deleted. No-op when another process owns the files. + */ + cleanupOwned(pid: number): void { + if (this.readPid() === pid) this.unlinkSocket(); + if (this.readPid() === pid) { + try { unlinkSync(this.pidPath); } catch { /* gone */ } + } + } +} diff --git a/cli/src/lib/daemon/protocol.ts b/cli/src/lib/daemon/protocol.ts new file mode 100644 index 0000000..01c8366 --- /dev/null +++ b/cli/src/lib/daemon/protocol.ts @@ -0,0 +1,76 @@ +// src/lib/daemon/protocol.ts + +/** + * JSON-RPC 2.0 message types for daemon IPC. + * Messages are newline-delimited JSON over Unix domain sockets. + */ + +export interface JsonRpcRequest { + jsonrpc: '2.0'; + method: string; + params: Record<string, unknown>; + id: number; +} + +export interface JsonRpcResponse { + jsonrpc: '2.0'; + result: unknown; + id: number; +} + +export interface JsonRpcError { + jsonrpc: '2.0'; + error: { code: number; message: string; data?: unknown }; + id: number | null; +} + +export type JsonRpcMessage = + | { type: 'request'; method: string; params: Record<string, unknown>; id: number } + | { type: 'notification'; method: string; params: Record<string, unknown> } + | { type: 'response'; result: unknown; id: number } + | { type: 'error'; error: { code: number; message: string; data?: unknown }; id: number | null }; + +export function encodeRequest(method: string, params: Record<string, unknown>, id: number): string { + return JSON.stringify({ jsonrpc: '2.0', method, params, id }); +} + +export function encodeResponse(result: unknown, id: number): string { + return JSON.stringify({ jsonrpc: '2.0', result, id }); +} + +export function encodeError(code: number, message: string, data: unknown, id: number | null): string { + return JSON.stringify({ jsonrpc: '2.0', error: { code, message, data }, id }); +} + +/** Server-push event. No `id` — JSON-RPC notification. */ +export function encodeNotification(method: string, params: Record<string, unknown>): string { + return JSON.stringify({ jsonrpc: '2.0', method, params }); +} + +export function parseMessage(raw: string): JsonRpcMessage { + let msg: any; + try { + msg = JSON.parse(raw); + } catch { + throw new Error(`Invalid JSON: ${raw.slice(0, 100)}`); + } + + if (msg.jsonrpc !== '2.0') { + throw new Error('Invalid JSON-RPC: missing jsonrpc 2.0 field'); + } + + if ('method' in msg) { + if (msg.id === undefined || msg.id === null) { + return { type: 'notification', method: msg.method, params: msg.params ?? {} }; + } + return { type: 'request', method: msg.method, params: msg.params ?? {}, id: msg.id }; + } + if ('result' in msg) { + return { type: 'response', result: msg.result, id: msg.id }; + } + if ('error' in msg) { + return { type: 'error', error: msg.error, id: msg.id }; + } + + throw new Error('Invalid JSON-RPC message: neither request, response, nor error'); +} diff --git a/cli/src/lib/daemon/request-client.ts b/cli/src/lib/daemon/request-client.ts new file mode 100644 index 0000000..6814153 --- /dev/null +++ b/cli/src/lib/daemon/request-client.ts @@ -0,0 +1,114 @@ +import type { TelegramClient } from 'teleproto'; +import { runOutsideDaemonContext } from './execution-context.js'; + +// These SDK methods create/cache transport objects, retain callbacks or change +// the shared connection. They must never retain the lifetime of one request. +// Once started, their maintenance finishes even if that request is cancelled. +const SHARED_LIFETIME_METHODS = new Set<PropertyKey>([ + '_leaseSender', '_makeSender', '_createConnection', 'getSender', '_borrowExportedSender', '_createExportedSender', '_connectSender', + '_switchDC', 'connect', '_disconnect', 'disconnect', 'destroy', + '_authKeyCallback', '_cleanupExportedSender', '_handleReconnect', +]); + +/** SDK view and outstanding work owned by one daemon command. */ +export interface RequestClient { + client: TelegramClient; + /** Wait for every already-started SDK promise, including detached calls. */ + settled(): Promise<void>; +} + +/** + * A request-local client view: cancellation never destroys the shared client. + * Calls keep this view as `this`, so SDK helpers that make another client call + * after an await also observe cancellation. Shared transport maintenance keeps + * the real client as `this`; it must complete and its retained callbacks must + * remain usable after this request ends. Lazy iterators and sender queue entry + * points are guarded as well. Existing RPCs remain tracked until settled. + */ +export function createRequestClient(client: TelegramClient, signal: AbortSignal): RequestClient { + const pending = new Set<Promise<unknown>>(); + const views = new WeakMap<object, object>(); + let reconnectRequired = false; + + const track = (promise: PromiseLike<unknown>, transform: (value: unknown) => unknown): Promise<unknown> => { + const tracked = Promise.resolve(promise).then(transform); + pending.add(tracked); + // Both branches handle rejection even if an SDK helper detaches its promise. + void tracked.then(() => pending.delete(tracked), () => pending.delete(tracked)); + return tracked; + }; + + const wrapResult = (value: unknown, sender = false): unknown => { + if (value == null || (typeof value !== 'object' && typeof value !== 'function')) return value; + if (typeof (value as PromiseLike<unknown>).then === 'function') { + return track(value as PromiseLike<unknown>, (result) => wrapResult(result, sender)); + } + if (sender || typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function' + || typeof (value as Iterator<unknown>).next === 'function') { + return wrap(value as object, sender ? 'sender' : 'iterator'); + } + return value; + }; + + const wrap = (target: object, kind: 'client' | 'sender' | 'iterator'): object => { + const existing = views.get(target); + if (existing) return existing; + const functions = new Map<PropertyKey, { original: Function; guarded: Function }>(); + const view = new Proxy(target, { + get(object, key, receiver) { + // Avoid SDK request replay without changing the shared client's options. + if (kind === 'client' && key === '_requestRetries') { signal.throwIfAborted(); return 1; } + if (kind === 'client' && key === 'floodSleepThreshold') return 0; + const value = Reflect.get(object, key, receiver); + if (kind === 'client' && key === '_sender' && value) return wrap(value, 'sender'); + if (kind === 'client' && (key === '_connection' || key === 'networkSocket')) return value; + if (typeof value !== 'function' || key === 'constructor') return value; + const cached = functions.get(key); + if (cached && cached.original === value) return cached.guarded; + // SDK properties also include classes such as MarkdownParser. A + // function proxy preserves their static APIs and constructor behavior. + const guarded = new Proxy(value, { + apply(fn, _thisArg, args: unknown[]) { + // SDK invoke repairs CONNECTION_NOT_INITED with disconnect(), a + // delay, then connect(). Complete that repair across cancellation; + // the next user RPC still passes through the guarded sender queue. + if (!(kind === 'client' && key === 'connect' && reconnectRequired)) signal.throwIfAborted(); + if (kind === 'client' && key === 'disconnect') reconnectRequired = true; + const sharedLifetime = kind === 'client' && SHARED_LIFETIME_METHODS.has(key); + const result = sharedLifetime + ? runOutsideDaemonContext(() => Reflect.apply(fn, object, args)) + : Reflect.apply(fn, receiver, args); + if (kind === 'client' && key === 'connect') reconnectRequired = false; + if (kind === 'client' && key === '_leaseSender') { + return track(Promise.resolve(result), (lease: any) => ({ sender: wrap(lease.sender, 'sender'), release: lease.release.bind(lease) })); + } + return wrapResult(result, kind === 'client' && ( + key === 'getSender' || key === '_borrowExportedSender' || key === '_createExportedSender' || key === '_connectSender' + )); + }, + construct(fn, args, newTarget) { + signal.throwIfAborted(); + return Reflect.construct(fn, args, newTarget); + }, + }); + functions.set(key, { original: value, guarded }); + return guarded; + }, + set(object, key, value) { + return Reflect.set(object, key, value, object); + }, + }); + views.set(target, view); + views.set(view, view); + return view; + }; + + return { + client: wrap(client, 'client') as TelegramClient, + async settled() { + while (pending.size > 0) { + await Promise.allSettled([...pending]); + } + }, + }; +} diff --git a/cli/src/lib/daemon/route.ts b/cli/src/lib/daemon/route.ts new file mode 100644 index 0000000..2c0210c --- /dev/null +++ b/cli/src/lib/daemon/route.ts @@ -0,0 +1,91 @@ +import type { Command } from 'commander'; +import { createConfig } from '../config.js'; +import { outputError, outputSuccess } from '../output.js'; +import { ErrorCode } from '../error-codes.js'; +import { TgError, formatError } from '../errors.js'; +import { DaemonPaths } from './pid.js'; +import { DaemonClient, DaemonRpcError } from './client.js'; +import { daemonPidAlive } from './guard.js'; +import { isDaemonCommand, type DaemonCommandRequest } from './command-protocol.js'; +import { MAX_FRAME_BYTES } from './frames.js'; + +/** Stop Commander before the local action once its remote result is rendered. */ +export class DaemonCommandHandled extends Error {} + +export function commandPath(command: Command): string[] { + const path: string[] = []; + for (let current: Command | null = command; current?.parent; current = current.parent) path.unshift(current.name()); + return path; +} + +/** Re-encode parsed values as argv, preserving positional dashes and repeated options. */ +export function daemonRequestForCommand(command: Command): DaemonCommandRequest { + const argv = commandPath(command); + const opts = command.opts(); + for (const option of command.options) { + const value = opts[option.attributeName()]; + if (value === undefined || !option.long) continue; + if (option.negate) { + if (value === false) argv.push(option.long); + } else if (option.required || option.optional) { + for (const entry of Array.isArray(value) ? value : [value]) argv.push(`${option.long}=${String(entry)}`); + } else if (value === true) argv.push(option.long); + } + const args = command.processedArgs.flatMap(arg => Array.isArray(arg) ? arg : [arg]) + .filter(arg => arg !== undefined).map(String); + if (args.length) argv.push('--', ...args); + return { argv, cwd: process.cwd() }; +} + +async function readRequestStdin(): Promise<string> { + if (process.stdin.isTTY) throw new TgError('"-" requires piped message input', ErrorCode.STDIN_REQUIRED); + const chunks: Buffer[] = []; + let bytes = 0; + for await (const chunk of process.stdin) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + bytes += buffer.length; + if (bytes > MAX_FRAME_BYTES - 4096) throw new TgError('Piped message exceeds the daemon frame limit', ErrorCode.MESSAGE_TOO_LONG); + chunks.push(buffer); + } + return Buffer.concat(chunks).toString('utf8'); +} + +/** Route supported --daemon actions once; never fall back to a direct session. */ +export async function routeThroughDaemon(command: Command): Promise<boolean> { + const opts = command.optsWithGlobals(); + const path = commandPath(command); + if (!opts.daemon || !isDaemonCommand(path)) return false; + let daemon: DaemonClient | undefined; + try { + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, opts.profile); + if (!paths.socketExists()) { + throw new TgError(daemonPidAlive(paths) ? 'Daemon is starting or not responding' : 'Daemon is not running. Start one with: tg daemon start', + daemonPidAlive(paths) ? ErrorCode.DAEMON_CONNECTION_FAILED : ErrorCode.DAEMON_NOT_RUNNING); + } + const request = daemonRequestForCommand(command); + const textIndex = path[0] === 'message' ? path[1] === 'send' ? 1 : path[1] === 'edit' ? 2 : -1 : -1; + if (textIndex >= 0 && command.processedArgs[textIndex] === '-') request.stdin = await readRequestStdin(); + daemon = new DaemonClient(paths.socketPath); + const result = await daemon.execute(request.argv, request); + if (result.output.ok) outputSuccess(result.output.data); + else outputError(result.output.error, result.output.code); + if (result.exitCode !== 0) process.exitCode = result.exitCode; + } catch (error) { + if (error instanceof DaemonRpcError) { + if (error.code === -32601) { + outputError('Running daemon does not support execute. Restart it with the current tg binary.', ErrorCode.DAEMON_PROXY_UNAVAILABLE); + } else { + const data = error.data as { tgCode?: unknown } | undefined; + outputError(error.message, typeof data?.tgCode === 'string' ? data.tgCode : ErrorCode.DAEMON_CONNECTION_FAILED); + } + } else { + const { message, code } = formatError(error); + outputError(message, code ?? ErrorCode.DAEMON_CONNECTION_FAILED); + } + } finally { + daemon?.close(); + } + return true; +} diff --git a/cli/src/lib/daemon/server.ts b/cli/src/lib/daemon/server.ts new file mode 100644 index 0000000..c65d7af --- /dev/null +++ b/cli/src/lib/daemon/server.ts @@ -0,0 +1,483 @@ +// src/lib/daemon/server.ts +import { createServer, type Server, type Socket } from 'node:net'; +import { chmodSync } from 'node:fs'; +import type { TelegramClient } from 'teleproto'; +import { NewMessage } from 'teleproto/events/NewMessage.js'; +import { DaemonPaths } from './pid.js'; +import { cleanupStaleDaemon, daemonPidAlive, pingDaemon } from './guard.js'; +import { encodeResponse, encodeError, encodeNotification, parseMessage } from './protocol.js'; +import { resolveEntity } from '../peer.js'; +import { markedPeerId, messagePeerMarkedId, serializeMessage } from '../serialize.js'; +import { parseTopicId } from '../validate.js'; +import { messageMatchesTopic } from './topic-filter.js'; +import { SessionStore } from '../session-store.js'; +import { JsonLineDecoder, MAX_FRAME_BYTES } from './frames.js'; +import { createGramjsLogger } from '../gramjs-logger.js'; +import { installClientErrorDiagnostics } from '../transport-diagnostics.js'; +import { connectionOptions } from '../connection-options.js'; +import type { Transport } from '../types.js'; +import { connectOrThrow } from '../connect.js'; +import { createRequestClient } from './request-client.js'; +import { executeDaemonCommand } from './execute.js'; +import { TgError } from '../errors.js'; +import { ErrorCode } from '../error-codes.js'; + +const MAX_ACTIVE_REQUESTS = 16; +const MAX_EXECUTION_TIMEOUT = 120_000; + +interface ActiveRequest { + controller: AbortController; + done: Promise<void>; + socket: Socket; +} + +interface DaemonClientOpts { + apiId: number; + apiHash: string; + transport?: Transport; + /** Optional in-memory session for library callers; CLI always reads under lock. */ + sessionString?: string; +} + +interface DaemonServerOpts { + /** Idle timeout in ms before auto-shutdown. Default: 300_000 (5 min). */ + idleTimeout?: number; + /** Called after stop() from idle timeout or shutdown RPC (not from explicit stop()). */ + onIdle?: () => void; + /** Parent already `writePidExclusive(child.pid)` — wait for that file, never stale-clean it. */ + pidPreclaimed?: boolean; +} + +/** + * Daemon server that holds a persistent TelegramClient connection + * and accepts JSON-RPC 2.0 requests over a Unix domain socket. + */ +export class DaemonServer { + private readonly paths: DaemonPaths; + private readonly clientOpts: DaemonClientOpts; + private readonly idleTimeout: number; + private readonly onIdle?: () => void; + private readonly pidPreclaimed: boolean; + private server: Server | null = null; + private client: TelegramClient | null = null; + private idleTimer: ReturnType<typeof setTimeout> | null = null; + private startTime: number = 0; + private stopping: Promise<void> | null = null; + private starting: Promise<void> | null = null; + private releaseSession: (() => Promise<void>) | null = null; + private stopRequested = false; + private ownsPid = false; + private readonly sockets = new Set<Socket>(); + private readonly activeRequests = new Set<ActiveRequest>(); + + constructor(paths: DaemonPaths, clientOpts: DaemonClientOpts, opts?: DaemonServerOpts) { + this.paths = paths; + this.clientOpts = clientOpts; + this.idleTimeout = opts?.idleTimeout ?? 300_000; + if (!Number.isSafeInteger(this.idleTimeout) || this.idleTimeout < 0 || this.idleTimeout > 2_147_483_647) { + throw new Error('Daemon idle timeout must be an integer from 0 to 2147483647 milliseconds'); + } + this.onIdle = opts?.onIdle; + this.pidPreclaimed = opts?.pidPreclaimed ?? false; + } + + async start(): Promise<void> { + if (this.stopping) throw new Error('Daemon is stopping'); + if (this.starting) return this.starting; + this.starting = this.doStart(); + return this.starting; + } + + private async doStart(): Promise<void> { + this.paths.ensureDir(); + this.paths.validateSocketPath(); + + if (this.pidPreclaimed) { + const deadline = Date.now() + 2_000; + while (this.paths.readPid() !== process.pid && Date.now() < deadline) { + await new Promise((r) => setTimeout(r, 10)); + } + } + + const weOwnPid = this.paths.readPid() === process.pid; + + if (!weOwnPid) { + if (this.pidPreclaimed) { + throw new Error('Daemon already running'); + } + if (daemonPidAlive(this.paths) || await pingDaemon(this.paths)) { + throw new Error('Daemon already running'); + } + if (!cleanupStaleDaemon(this.paths)) { + throw new Error('Daemon already running'); + } + if (!this.paths.writePidExclusive(process.pid)) { + throw new Error('Daemon already running'); + } + this.ownsPid = true; + } else if (await pingDaemon(this.paths)) { + throw new Error('Daemon already running'); + } + + try { + this.throwIfStopping(); + const store = new SessionStore(this.paths.configDir); + this.releaseSession = await store.acquireLock(this.paths.profile); + // A preclaimed PID belongs to this instance only after it also owns the + // session. Another instance in this process may own the same PID already. + this.ownsPid = true; + this.throwIfStopping(); + const sessionString = this.clientOpts.sessionString ?? store.loadUnlocked(this.paths.profile); + if (!sessionString) throw new Error('Not logged in. Run: tg auth login'); + this.paths.unlinkSocket(); + + const { TelegramClient, sessions } = await import('teleproto'); + this.throwIfStopping(); + const session = new sessions.StringSession(sessionString); + const logger = createGramjsLogger([this.clientOpts.apiHash, sessionString]); + this.client = new TelegramClient(session, this.clientOpts.apiId, this.clientOpts.apiHash, { + connectionRetries: 3, + requestRetries: 1, + catchUp: true, + retryDelay: 1000, + floodSleepThreshold: 60, + baseLogger: logger, + ...connectionOptions(this.clientOpts.transport), + }); + installClientErrorDiagnostics(this.client, logger); + await connectOrThrow(this.client); + this.throwIfStopping(); + + this.server = createServer((socket) => this.handleConnection(socket)); + await new Promise<void>((resolve, reject) => { + this.server!.listen(this.paths.socketPath, () => resolve()); + this.server!.on('error', reject); + }); + + chmodSync(this.paths.socketPath, 0o600); + + this.startTime = Date.now(); + this.resetIdle(); + } catch (err) { + // Failed destruction cannot prove the session is safe for another owner. + // Retain the lease and PID if teardown itself rejects. + await this.client?.destroy(); + this.client = null; + if (this.server) { + const server = this.server; + this.server = null; + await new Promise<void>((resolve) => server.close(() => resolve())); + } + this.cleanupPid(); + await this.releaseOwnership(); + throw err; + } + } + + async stop(): Promise<void> { + if (this.stopping) return this.stopping; + this.stopRequested = true; + this.stopping = this.doStop(); + return this.stopping; + } + + private async doStop(): Promise<void> { + for (const request of this.activeRequests) { + request.controller.abort(new TgError('Daemon is stopping; the outcome of submitted Telegram operations may be unknown.', ErrorCode.DAEMON_STOPPING)); + } + // Closing transport is what interrupts an SDK connection attempt. Waiting + // for start() first would prevent SIGTERM from ever initiating that cleanup. + if (!this.server && this.client) await this.client.destroy(); + await this.starting?.catch(() => {}); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + + for (const socket of this.sockets) { + socket.destroy(); + } + this.sockets.clear(); + + const server = this.server; + this.server = null; + if (server) { + await new Promise<void>((resolve) => { + server.close(() => resolve()); + }); + } + + if (this.client) { + const started = [...this.activeRequests].map(request => request.done); + await this.client.destroy(); + // Cancelling the RPC reply does not cancel a request already sent to + // Telegram. Keep ownership until its command and all SDK work settle. + await Promise.all(started); + // A DC migration already in progress may reconnect after the first + // destroy. Tear down its late transport before handing over the lease. + if (started.length > 0) await this.client.destroy(); + this.client = null; + } + + this.cleanupPid(); + await this.releaseOwnership(); + } + + private async releaseOwnership(): Promise<void> { + const release = this.releaseSession; + this.releaseSession = null; + await release?.(); + } + + private throwIfStopping(): void { + if (this.stopRequested) throw new Error('Daemon start cancelled'); + } + + private cleanupPid(): void { + if (this.ownsPid) this.paths.cleanupOwned(process.pid); + this.ownsPid = false; + } + + getClient(): TelegramClient | null { + return this.client; + } + + private resetIdle(): void { + if (this.idleTimer) clearTimeout(this.idleTimer); + this.idleTimer = null; + if (this.stopping) return; + if (this.idleTimeout <= 0) return; + if (this.sockets.size > 0) return; + if (this.activeRequests.size > 0) return; + this.idleTimer = setTimeout(() => { + void this.stop().then(() => this.onIdle?.()).catch(() => {}); + }, this.idleTimeout); + } + + private handleConnection(socket: Socket): void { + this.sockets.add(socket); + this.resetIdle(); + socket.on('close', () => { + for (const request of this.activeRequests) { + if (request.socket === socket) request.controller.abort(new TgError( + 'Caller disconnected; the outcome of submitted Telegram operations may be unknown.', ErrorCode.DAEMON_CANCELLED, + )); + } + this.sockets.delete(socket); + this.resetIdle(); + }); + + // A peer's reset, oversized frame or failed write belongs to that peer only. + socket.on('error', () => socket.destroy()); + const decoder = new JsonLineDecoder(); + const write = (line: string) => { + if (!socket.destroyed && socket.writable) socket.write(line + '\n'); + }; + const handleLine = async (line: string) => { + if (socket.destroyed) return; + this.resetIdle(); + + let id: number | null = null; + try { + const msg = parseMessage(line); + if (msg.type !== 'request') { + write(encodeError(-32600, 'Expected request', null, null)); + return; + } + + id = msg.id; + const result = await this.dispatch(msg.method, msg.params, socket); + const response = encodeResponse(result, id); + if (Buffer.byteLength(response, 'utf-8') > MAX_FRAME_BYTES) { + throw new TgError('Command completed but its response is too large. Narrow the requested data; do not blindly repeat writes.', ErrorCode.DAEMON_RESPONSE_TOO_LARGE); + } + write(response); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err); + const code = err instanceof Error && 'code' in err ? (err as any).code : -32000; + const data = err instanceof Error && 'code' in err && typeof (err as any).code === 'string' + ? { tgCode: (err as any).code } + : undefined; + write(encodeError(typeof code === 'number' ? code : -32000, message, data, id)); + } + }; + socket.on('data', (chunk: Buffer) => { + try { + decoder.push(chunk, (line) => { + void handleLine(line).catch(() => socket.destroy()); + }); + } catch { + socket.destroy(); + } + }); + } + + private async dispatch( + method: string, + params: Record<string, unknown>, + socket: Socket, + ): Promise<unknown> { + switch (method) { + case 'ping': + return 'pong'; + + case 'status': + return { + running: true, + pid: process.pid, + uptime: Math.round((Date.now() - this.startTime) / 1000), + idleTimeout: this.idleTimeout / 1000, + connected: this.client != null && (this.client.connected ?? true), + transport: this.clientOpts.transport ?? 'tcp', + activeRequests: this.activeRequests.size, + apiVersion: 1, + capabilities: ['execute', 'subscribe'], + }; + + case 'shutdown': + setTimeout(() => { + void this.stop().then(() => this.onIdle?.()).catch(() => {}); + }, 100); + return { shuttingDown: true }; + + case 'subscribe': + return this.subscribe(params, socket); + + case 'execute': + return this.execute(params, socket); + + default: + throw Object.assign(new Error(`Unknown method: ${method}`), { code: -32601 }); + } + } + + /** Execute one allowlisted command against the already-connected client. */ + private async execute(params: Record<string, unknown>, socket: Socket): Promise<unknown> { + if (params == null || typeof params !== 'object' || Array.isArray(params)) { + throw new TgError('execute params must be an object', ErrorCode.INVALID_INPUT); + } + const timeoutMs = params.timeoutMs === undefined ? MAX_EXECUTION_TIMEOUT : params.timeoutMs; + if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_EXECUTION_TIMEOUT) { + throw new TgError('timeoutMs must be an integer from 1 to 120000', ErrorCode.INVALID_INPUT); + } + return this.runRequest(socket, timeoutMs, (client, signal) => + executeDaemonCommand(client, this.paths.profile, params, signal)); + } + + /** Bound active SDK work, while allowing the caller to stop waiting sooner. */ + private async runRequest<T>( + socket: Socket, + timeoutMs: number, + work: (client: TelegramClient, signal: AbortSignal) => Promise<T>, + ): Promise<T> { + if (this.stopRequested || !this.client) { + throw new TgError('Daemon is stopping or has no connected client', ErrorCode.DAEMON_STOPPING); + } + if (this.activeRequests.size >= MAX_ACTIVE_REQUESTS) { + throw new TgError('Daemon is busy (16 commands are still running). Wait for active work to finish.', ErrorCode.DAEMON_BUSY); + } + if (socket.destroyed) throw new TgError('Caller disconnected before execution', ErrorCode.DAEMON_CANCELLED); + + const controller = new AbortController(); + const view = createRequestClient(this.client, controller.signal); + const request: ActiveRequest = { controller, done: Promise.resolve(), socket }; + this.activeRequests.add(request); + this.resetIdle(); + const timer = setTimeout(() => controller.abort(new TgError( + 'Daemon request timed out. The outcome of submitted Telegram operations is unknown; check before repeating writes.', ErrorCode.TIMEOUT, + )), timeoutMs); + let rejectAborted!: (reason: unknown) => void; + const aborted = new Promise<never>((_resolve, reject) => { rejectAborted = reject; }); + const onAbort = () => rejectAborted(controller.signal.reason); + controller.signal.addEventListener('abort', onAbort, { once: true }); + + const operation = Promise.resolve().then(async () => { + controller.signal.throwIfAborted(); + const result = await work(view.client, controller.signal); + controller.signal.throwIfAborted(); + return result; + }); + request.done = operation.then(() => {}, () => {}).then(() => view.settled()).finally(() => { + clearTimeout(timer); + controller.signal.removeEventListener('abort', onAbort); + this.activeRequests.delete(request); + this.resetIdle(); + }); + // The caller can stop waiting before work finishes; keep cleanup handled. + void request.done.catch(() => {}); + try { + return await Promise.race([operation, aborted]); + } finally { + clearTimeout(timer); + } + } + + /** + * Ack the subscribe RPC, then push `message` notifications on this socket + * until it closes. Matching is by resolved peer id (+ optional topic). + */ + private async subscribe(params: Record<string, unknown>, socket: Socket): Promise<unknown> { + if (params == null || typeof params !== 'object' || Array.isArray(params)) { + throw new TgError('subscribe params must be an object', ErrorCode.INVALID_INPUT); + } + return this.runRequest(socket, MAX_EXECUTION_TIMEOUT, (client, signal) => + this.prepareSubscription(params, socket, client, signal)); + } + + private async prepareSubscription( + params: Record<string, unknown>, socket: Socket, client: TelegramClient, signal: AbortSignal, + ): Promise<unknown> { + const chat = String(params.chat ?? '').trim(); + if (!chat) { + throw new Error('chat is required'); + } + + let topic: number | undefined; + if (params.topic != null) { + topic = parseTopicId(String(params.topic)); + } + + const entity = await resolveEntity(client, chat); + signal.throwIfAborted(); + if (socket.destroyed || !this.client) throw new Error('Subscriber disconnected'); + const wantId = markedPeerId(entity); + if (!wantId) { + throw new Error(`Could not resolve chat id for ${chat}`); + } + + const handler = (event: any) => { + try { + const msg = event?.message ?? event; + if (!msg || msg.id == null) return; + + const chatId = messagePeerMarkedId(msg); + if (!chatId || chatId !== wantId) return; + + if (topic != null && !messageMatchesTopic(msg, topic)) return; + + const payload = serializeMessage(msg, msg._sender) as unknown as Record<string, unknown>; + if (!socket.destroyed) { + this.resetIdle(); + socket.write(encodeNotification('message', payload) + '\n'); + } + } catch { + // Never throw into gramjs _updateLoop + } + }; + + const builder = new NewMessage({}); + // After the acknowledgement, this handler belongs to the shared transport + // and socket, independent of the request view used to prepare it. + const sharedClient = this.client; + sharedClient.addEventHandler(handler, builder); + socket.once('close', () => { + try { + sharedClient.removeEventHandler(handler, builder); + } catch { + // gramjs removeEventHandler is best-effort + } + }); + + return { subscribed: true, chat, topic: topic ?? null }; + } +} diff --git a/cli/src/lib/daemon/topic-filter.ts b/cli/src/lib/daemon/topic-filter.ts new file mode 100644 index 0000000..630e395 --- /dev/null +++ b/cli/src/lib/daemon/topic-filter.ts @@ -0,0 +1,29 @@ +/** + * Forum-topic membership for `message watch --topic`. + * + * Telegram: `replyTo.forumTopic === true` means a named topic. + * The topic root is `replyToTopId`, or `replyToMsgId` when that flag is set. + * General (id 1) is everything that is not a named forum topic. + * The topic-root message itself has `id === topic`. + */ +export function messageMatchesTopic( + msg: { + id?: number; + replyTo?: { + forumTopic?: boolean; + replyToTopId?: number; + replyToMsgId?: number; + } | null; + }, + topic: number, +): boolean { + if (msg.id === topic) return true; + const reply = msg.replyTo; + const forumTopic = reply?.forumTopic === true; + const top = reply?.replyToTopId ?? (forumTopic ? reply?.replyToMsgId : undefined); + if (topic === 1) { + if (forumTopic && top != null && top !== 1) return false; + return true; + } + return top === topic; +} diff --git a/cli/src/lib/entity-map.ts b/cli/src/lib/entity-map.ts new file mode 100644 index 0000000..7864347 --- /dev/null +++ b/cli/src/lib/entity-map.ts @@ -0,0 +1,18 @@ +/** + * Build entity lookup map from API result users/chats arrays. + * Shared utility used by replies, get-by-ID, and pinned message commands. + * + * @param result - API response containing optional users[] and chats[] arrays + * @returns Map keyed by marked peer ID, keeping user/chat/channel namespaces distinct + */ +export function buildEntityMap(result: any): Map<string, any> { + const map = new Map<string, any>(); + for (const u of result.users ?? []) { + map.set(markedPeerId(u), u); + } + for (const c of result.chats ?? []) { + map.set(markedPeerId(c), c); + } + return map; +} +import { markedPeerId } from './serialize.js'; diff --git a/cli/src/lib/entity-to-markdown.ts b/cli/src/lib/entity-to-markdown.ts new file mode 100644 index 0000000..d2a86d7 --- /dev/null +++ b/cli/src/lib/entity-to-markdown.ts @@ -0,0 +1,64 @@ +import { Api } from 'teleproto'; + +/** + * Convert Telegram MessageEntity[] to Markdown-formatted text. + * + * Processes entities from end to start (descending offset) to avoid + * offset shifts when replacing substrings with longer Markdown syntax. + * + * Handles: Bold, Italic, Code, Pre, TextUrl, Strike, Blockquote, MentionName, + * Spoiler, Underline, CustomEmoji. + * Mention and Url entities are kept as-is (already readable). + */ +export function entitiesToMarkdown( + text: string, + entities: Api.TypeMessageEntity[] | undefined, +): string { + if (!entities || entities.length === 0) return text; + + // Sort by offset descending so replacements don't shift earlier offsets + const sorted = [...entities].sort((a, b) => b.offset - a.offset); + + let result = text; + + for (const entity of sorted) { + const start = entity.offset; + const end = start + entity.length; + const substr = result.substring(start, end); + let replacement = substr; + + if (entity instanceof Api.MessageEntityBold) { + replacement = `**${substr}**`; + } else if (entity instanceof Api.MessageEntityItalic) { + replacement = `_${substr}_`; + } else if (entity instanceof Api.MessageEntityCode) { + replacement = `\`${substr}\``; + } else if (entity instanceof Api.MessageEntityPre) { + const lang = (entity as any).language || ''; + replacement = `\`\`\`${lang}\n${substr}\n\`\`\``; + } else if (entity instanceof Api.MessageEntityTextUrl) { + replacement = `[${substr}](${(entity as any).url})`; + } else if (entity instanceof Api.MessageEntityStrike) { + replacement = `~~${substr}~~`; + } else if (entity instanceof Api.MessageEntityBlockquote) { + replacement = substr + .split('\n') + .map((line) => `> ${line}`) + .join('\n'); + } else if (entity instanceof Api.MessageEntityMentionName) { + replacement = `[${substr}](tg://user?id=${(entity as any).userId})`; + } else if (entity instanceof Api.MessageEntitySpoiler) { + replacement = `||${substr}||`; + } else if (entity instanceof Api.MessageEntityUnderline) { + replacement = `<u>${substr}</u>`; + } else if (entity instanceof Api.MessageEntityCustomEmoji) { + const id = (entity as any).documentId; + replacement = `![${substr}](tg://emoji?id=${id})`; + } + // Mention, Url, and other entities are kept as-is + + result = result.substring(0, start) + replacement + result.substring(end); + } + + return result; +} diff --git a/cli/src/lib/error-codes.ts b/cli/src/lib/error-codes.ts new file mode 100644 index 0000000..4b37ff7 --- /dev/null +++ b/cli/src/lib/error-codes.ts @@ -0,0 +1,107 @@ +/** + * Centralized error codes for tg-cli. + * Every outputError() call should reference these constants + * instead of string literals to prevent typos and ease refactoring. + */ +export const ErrorCode = Object.freeze({ + CONNECTION_FAILED: 'CONNECTION_FAILED', + // Auth + NOT_AUTHENTICATED: 'NOT_AUTHENTICATED', + NOT_LOGGED_IN: 'NOT_LOGGED_IN', + NOT_INTERACTIVE: 'NOT_INTERACTIVE', + + // Input validation + INVALID_INPUT: 'INVALID_INPUT', + INVALID_OPTIONS: 'INVALID_OPTIONS', + INVALID_TOPIC_ID: 'INVALID_TOPIC_ID', + INVALID_MESSAGE_ID: 'INVALID_MESSAGE_ID', + INVALID_MSG_ID: 'INVALID_MSG_ID', + INVALID_MESSAGE_IDS: 'INVALID_MESSAGE_IDS', + INVALID_REPLY_TO: 'INVALID_REPLY_TO', + INVALID_COMMENT_TO: 'INVALID_COMMENT_TO', + INVALID_INVITE: 'INVALID_INVITE', + INVALID_CHAT_TYPE: 'INVALID_CHAT_TYPE', + INVALID_ID: 'INVALID_ID', + INVALID_FILTER: 'INVALID_FILTER', + + // Message + MESSAGE_RESULT_UNAVAILABLE: 'MESSAGE_RESULT_UNAVAILABLE', + EMPTY_MESSAGE: 'EMPTY_MESSAGE', + MESSAGE_TOO_LONG: 'MESSAGE_TOO_LONG', + STDIN_REQUIRED: 'STDIN_REQUIRED', + DELETE_MODE_REQUIRED: 'DELETE_MODE_REQUIRED', + TOO_MANY_IDS: 'TOO_MANY_IDS', + MISSING_QUERY: 'MISSING_QUERY', + EMPTY_QUESTION: 'EMPTY_QUESTION', + QUESTION_TOO_LONG: 'QUESTION_TOO_LONG', + TOO_FEW_OPTIONS: 'TOO_FEW_OPTIONS', + TOO_MANY_OPTIONS: 'TOO_MANY_OPTIONS', + EMPTY_OPTION: 'EMPTY_OPTION', + OPTION_TOO_LONG: 'OPTION_TOO_LONG', + DUPLICATE_OPTION: 'DUPLICATE_OPTION', + QUIZ_MISSING_CORRECT: 'QUIZ_MISSING_CORRECT', + SOLUTION_WITHOUT_QUIZ: 'SOLUTION_WITHOUT_QUIZ', + QUIZ_MULTIPLE_CONFLICT: 'QUIZ_MULTIPLE_CONFLICT', + INVALID_CORRECT_INDEX: 'INVALID_CORRECT_INDEX', + INVALID_CLOSE_IN: 'INVALID_CLOSE_IN', + + // Entity + PEER_NOT_FOUND: 'PEER_NOT_FOUND', + NOT_A_USER: 'NOT_A_USER', + NOT_A_FORUM: 'NOT_A_FORUM', + NOT_A_MEMBER: 'NOT_A_MEMBER', + NO_USERS_FOUND: 'NO_USERS_FOUND', + + // Chat + USER_ALREADY_PARTICIPANT: 'USER_ALREADY_PARTICIPANT', + CHANNELS_TOO_MUCH: 'CHANNELS_TOO_MUCH', + UNKNOWN_INVITE_TYPE: 'UNKNOWN_INVITE_TYPE', + + // Contact + MISSING_FIRST_NAME: 'MISSING_FIRST_NAME', + PHONE_NOT_FOUND: 'PHONE_NOT_FOUND', + + INVALID_SCHEDULE: 'INVALID_SCHEDULE', + INVALID_PHOTO: 'INVALID_PHOTO', + NO_PROFILE_PHOTO: 'NO_PROFILE_PHOTO', + PHOTO_RESULT_UNAVAILABLE: 'PHOTO_RESULT_UNAVAILABLE', + + // Media + ALBUM_TOO_LARGE: 'ALBUM_TOO_LARGE', + NO_MEDIA: 'NO_MEDIA', + PATH_TRAVERSAL: 'PATH_TRAVERSAL', + FILE_NOT_FOUND: 'FILE_NOT_FOUND', + FILE_EXISTS: 'FILE_EXISTS', + + // Session & client + NO_SESSION: 'NO_SESSION', + NO_INPUT: 'NO_INPUT', + TIMEOUT: 'TIMEOUT', + TOO_MANY_USERS: 'TOO_MANY_USERS', + UNKNOWN_ERROR: 'UNKNOWN_ERROR', + TG_ERROR: 'TG_ERROR', + CREDENTIAL_ERROR: 'CREDENTIAL_ERROR', + CONFIG_ERROR: 'CONFIG_ERROR', + SESSION_ERROR: 'SESSION_ERROR', + INVALID_SESSION: 'INVALID_SESSION', + VERIFY_FAILED: 'VERIFY_FAILED', + FLOOD_WAIT: 'FLOOD_WAIT', + + // Presets + FETCH_FAILED: 'FETCH_FAILED', + UNKNOWN_PRESET: 'UNKNOWN_PRESET', + + // Daemon + DAEMON_NOT_RUNNING: 'DAEMON_NOT_RUNNING', + DAEMON_ALREADY_RUNNING: 'DAEMON_ALREADY_RUNNING', + DAEMON_START_FAILED: 'DAEMON_START_FAILED', + DAEMON_STOP_FAILED: 'DAEMON_STOP_FAILED', + DAEMON_CONNECTION_FAILED: 'DAEMON_CONNECTION_FAILED', + DAEMON_PROXY_UNAVAILABLE: 'DAEMON_PROXY_UNAVAILABLE', + DAEMON_BUSY: 'DAEMON_BUSY', + DAEMON_CANCELLED: 'DAEMON_CANCELLED', + DAEMON_STOPPING: 'DAEMON_STOPPING', + DAEMON_RESPONSE_TOO_LARGE: 'DAEMON_RESPONSE_TOO_LARGE', +} as const); + +export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode]; diff --git a/cli/src/lib/errors.ts b/cli/src/lib/errors.ts new file mode 100644 index 0000000..1b5d152 --- /dev/null +++ b/cli/src/lib/errors.ts @@ -0,0 +1,113 @@ +import { ErrorCode } from './error-codes.js'; + +/** + * Base error class for tg-cli. + * All custom errors extend this for consistent error handling. + */ +export class TgError extends Error { + readonly code: string; + + constructor(message: string, code: string = ErrorCode.TG_ERROR) { + super(message); + this.name = 'TgError'; + this.code = code; + } +} + +/** + * Thrown when API credentials are missing or invalid. + */ +export class CredentialError extends TgError { + constructor(message: string) { + super(message, ErrorCode.CREDENTIAL_ERROR); + this.name = 'CredentialError'; + } +} + +/** + * Thrown for session-related errors (corrupt, expired, locked). + */ +export class SessionError extends TgError { + constructor(message: string) { + super(message, ErrorCode.SESSION_ERROR); + this.name = 'SessionError'; + } +} + +/** + * Thrown when Telegram rate-limits a request. + * Includes the number of seconds to wait before retrying. + */ +export class FloodWaitError extends TgError { + readonly seconds: number; + + constructor(seconds: number) { + super(`Rate limited. Retry after ${seconds} seconds.`, ErrorCode.FLOOD_WAIT); + this.name = 'FloodWaitError'; + this.seconds = seconds; + } +} + +/** + * Extract a structured error message and optional code from any thrown value. + * Handles Error instances, TgError subclasses, and arbitrary thrown values. + */ +export function formatError(err: unknown): { message: string; code?: string } { + if (err instanceof TgError) { + return { message: err.message, code: err.code }; + } + if (err instanceof Error) { + if ('code' in err && err.code === 'ELOCKED') { + return { message: 'Session profile is busy. Wait for the running command or stop its daemon.', code: ErrorCode.SESSION_ERROR }; + } + return { message: err.message }; + } + return { message: String(err) }; +} + +/** + * Map of Telegram RPCError codes to human-readable messages. + * Used by translateTelegramError to produce actionable CLI output. + */ +const TELEGRAM_ERROR_MAP: Record<string, string> = { + 'MESSAGE_EDIT_TIME_EXPIRED': 'Cannot edit: 48-hour edit window has expired', + 'MESSAGE_AUTHOR_REQUIRED': 'Cannot edit: you can only edit your own messages', + 'MESSAGE_DELETE_FORBIDDEN': 'Cannot delete this message', + 'CHAT_ADMIN_REQUIRED': 'Admin privileges required', + 'MESSAGE_ID_INVALID': 'Message not found', + 'PEER_ID_INVALID': 'Peer not found', + 'MESSAGE_NOT_MODIFIED': 'Message content unchanged', + 'USER_BOT_INVALID': 'Cannot block this bot', + 'INPUT_USER_DEACTIVATED': 'User account deleted', + 'CONTACT_ID_INVALID': 'Contact not found', + 'CONTACT_NAME_EMPTY': 'First name is required', + 'CONTACT_REQ_MISSING': 'Contact request required', + 'SEARCH_QUERY_EMPTY': 'Search query cannot be empty', + 'PREMIUM_ACCOUNT_REQUIRED': 'Telegram Premium is required for this search', + 'OFFSET_PEER_ID_INVALID': 'Invalid pagination peer. Pass nextOffsetPeer from the previous page', + // Poll error codes + 'POLL_ANSWERS_INVALID': 'Invalid poll: need 2-10 answer options', + 'POLL_OPTION_DUPLICATE': 'Duplicate poll option', + 'POLL_OPTION_INVALID': 'Poll option text is invalid or too long', + 'POLL_QUESTION_INVALID': 'Poll question is invalid or too long', + 'QUIZ_CORRECT_ANSWERS_EMPTY': 'Quiz poll requires a correct answer', + 'QUIZ_CORRECT_ANSWERS_TOO_MUCH': 'Quiz poll allows only one correct answer', + 'CHAT_SEND_POLL_FORBIDDEN': 'You cannot send polls in this chat', +}; + +/** + * Translate a Telegram API error into a user-friendly message + code pair. + * + * Handles gramjs RPCError objects (which have an `errorMessage` property) + * by mapping known error codes to human-readable messages. + * Falls back to formatError for non-RPCError thrown values. + */ +export function translateTelegramError(err: unknown): { message: string; code: string } { + if (err != null && typeof err === 'object' && 'errorMessage' in err) { + const errorMessage = (err as any).errorMessage as string; + const humanMessage = TELEGRAM_ERROR_MAP[errorMessage] || errorMessage; + return { message: humanMessage, code: errorMessage }; + } + const result = formatError(err); + return { message: result.message, code: result.code ?? ErrorCode.UNKNOWN_ERROR }; +} diff --git a/cli/src/lib/fields.ts b/cli/src/lib/fields.ts new file mode 100644 index 0000000..1e4049f --- /dev/null +++ b/cli/src/lib/fields.ts @@ -0,0 +1,135 @@ +/** + * Field selection utilities for --fields CLI option. + * Supports dot-notation for nested paths (e.g., "media.filename"). + */ + +/** Known array property names for list command detection. */ +const LIST_KEYS = ['messages', 'chats', 'members', 'topics', 'files', 'profiles', 'users', 'contacts', 'results', 'posts'] as const; +const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + +/** + * Pick specific fields from an object, supporting dot-notation paths. + * Missing or invalid paths are silently omitted. + * + * @example + * pickFields({ id: 1, text: "hi", date: "2026" }, ["id", "text"]) + * // => { id: 1, text: "hi" } + * + * pickFields({ id: 1, media: { filename: "a.jpg", fileSize: 100 } }, ["id", "media.filename"]) + * // => { id: 1, media: { filename: "a.jpg" } } + */ +export function pickFields<T>(obj: T, fields: string[]): Partial<T> { + const result: Record<string, unknown> = {}; + + for (const field of fields) { + const parts = field.split('.'); + if (parts.some(part => !part || UNSAFE_KEYS.has(part))) continue; + // Walk source object to find value + let value: unknown = obj; + let valid = true; + for (const part of parts) { + if (value == null || typeof value !== 'object' || !Object.hasOwn(value, part)) { + valid = false; + break; + } + value = (value as Record<string, unknown>)[part]; + if (value === undefined) { + valid = false; + break; + } + } + if (!valid) continue; + + // Reconstruct nested path in result + let target = result; + for (let i = 0; i < parts.length - 1; i++) { + const part = parts[i]; + if (!Object.hasOwn(target, part) || typeof target[part] !== 'object' || target[part] == null) { + target[part] = {}; + } + target = target[part] as Record<string, unknown>; + } + target[parts[parts.length - 1]] = value; + } + + return result as Partial<T>; +} + +/** + * Apply field selection to a data object. + * For list data (containing arrays of objects), filters each item with pickFields + * while preserving metadata fields (total, count, etc.). + * + * @example + * applyFieldSelection({ messages: [{ id: 1, text: "hi" }], total: 5 }, ["id"]) + * // => { messages: [{ id: 1 }], total: 5 } + */ +export function applyFieldSelection(data: unknown, fields: string[]): unknown { + if (data == null || typeof data !== 'object') return data; + + const obj = data as Record<string, unknown>; + + const isNamedListKey = (key: string) => + (LIST_KEYS as readonly string[]).includes(key); + + const isListShaped = Object.entries(obj).some(([key, value]) => { + if (key === 'errors' || UNSAFE_KEYS.has(key)) return false; + if (!Array.isArray(value)) return false; + if (isNamedListKey(key)) return true; + return value.length > 0 && typeof value[0] === 'object' && value[0] !== null; + }); + + // Single-object output (e.g., MessageItem from `message send`) + if (!isListShaped) { + const selected = pickFields(obj, fields); + if (Array.isArray(obj.errors)) { + selected.errors = obj.errors; + if (typeof obj.partial === 'boolean') selected.partial = obj.partial; + } + return selected; + } + + // List-shaped data: filter each array item, preserve metadata (including empty lists) + const result: Record<string, unknown> = {}; + + for (const [key, value] of Object.entries(obj)) { + if (UNSAFE_KEYS.has(key)) continue; + // Failures are operation metadata, not successful list items. Never + // erase their error/code when selecting fields such as --fields id. + if (key === 'errors' && Array.isArray(value)) { + result[key] = value; + continue; + } + if ( + Array.isArray(value) && + (isNamedListKey(key) || (value.length > 0 && typeof value[0] === 'object' && value[0] !== null)) + ) { + result[key] = value.map((item) => + item != null && typeof item === 'object' ? pickFields(item, fields) : item, + ); + } else { + result[key] = value; + } + } + + return result; +} + +/** + * Extract the list items array from a data object, if present. + * Checks known array property names in order: messages, chats, members, topics, files. + * Returns null if no list array is found. + */ +export function extractListItems(data: unknown): unknown[] | null { + if (data == null || typeof data !== 'object') return null; + + const obj = data as Record<string, unknown>; + + for (const key of LIST_KEYS) { + if (Array.isArray(obj[key])) { + return obj[key] as unknown[]; + } + } + + return null; +} diff --git a/cli/src/lib/format.ts b/cli/src/lib/format.ts new file mode 100644 index 0000000..4f93f0f --- /dev/null +++ b/cli/src/lib/format.ts @@ -0,0 +1,614 @@ +import pc from 'picocolors'; +import type { + MessageItem, + ChatListItem, + ChatInfo, + MemberItem, + SearchResultItem, + DownloadResult, + AlbumResult, + TopicItem, + DeleteResult, + PinResult, + UserProfile, + BlockResult, + BlockedListItem, + PollData, +} from './types.js'; +import { formatBytes } from './media-utils.js'; + +/** + * Format a date string to local "YYYY-MM-DD HH:MM" display. + */ +function formatTimestamp(dateStr: string): string { + const d = new Date(dateStr); + const year = d.getFullYear(); + const month = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + const hours = String(d.getHours()).padStart(2, '0'); + const minutes = String(d.getMinutes()).padStart(2, '0'); + return `${year}-${month}-${day} ${hours}:${minutes}`; +} + +/** + * Build a rich media annotation string from a message's media metadata. + * + * With media metadata: [photo 1920x1080 240KB], [video 1280x720 0:32 1.2MB], [document report.pdf 3.4MB] + * Without metadata but with mediaType: [photo] (existing behavior for messages without full metadata) + * Neither: empty string + */ +function formatMediaAnnotation(m: MessageItem): string { + if (m.media) { + const parts: string[] = [m.mediaType ?? 'file']; + if (m.media.width != null && m.media.height != null) { + parts.push(`${m.media.width}x${m.media.height}`); + } + if (m.media.duration != null) { + const mins = Math.floor(m.media.duration / 60); + const secs = String(m.media.duration % 60).padStart(2, '0'); + parts.push(`${mins}:${secs}`); + } + if (m.media.fileSize != null) { + parts.push(formatBytes(m.media.fileSize)); + } + if (m.media.filename != null) { + parts.push(m.media.filename); + } + return `[${parts.join(' ')}]`; + } + if (m.mediaType) { + return `[${m.mediaType}]`; + } + return ''; +} + +/** + * Format poll data as expanded multi-line text. + * + * Renders question, numbered options with vote counts and correct markers, + * and config tags (Quiz, Public, Multiple, Closes in Ns, Closed, voter count). + */ +export function formatPoll(poll: PollData): string { + const lines: string[] = []; + lines.push(`\u{1F4CA} Poll: ${poll.question}`); + + poll.options.forEach((opt, i) => { + const num = i + 1; + const correct = opt.correct ? ' \u2713' : ''; + const votes = opt.voters > 0 + ? ` (${opt.voters} vote${opt.voters !== 1 ? 's' : ''})` + : ''; + lines.push(` ${num}. ${opt.text}${correct}${votes}`); + }); + + const tags: string[] = []; + if (poll.isQuiz) tags.push('Quiz'); + if (poll.isPublic) tags.push('Public'); + if (poll.isMultiple) tags.push('Multiple'); + if (poll.closePeriod) tags.push(`Closes in ${poll.closePeriod}s`); + if (poll.isClosed) { + tags.push('Closed'); + tags.push(`${poll.totalVoters} voter${poll.totalVoters !== 1 ? 's' : ''}`); + } + if (tags.length > 0) { + lines.push(` ${tags.join(' \u00B7 ')}`); + } + + return lines.join('\n'); +} + +/** + * Format a single message line in conversational style. + * [2026-03-11 12:30] Alice: Hello world + * [2026-03-11 12:31] Bob (reply to 42): Thanks! + * [2026-03-11 12:32] Alice: [photo 1920x1080 240KB] Check this out + */ +function formatSingleMessage(m: MessageItem): string { + const ts = pc.dim(`[${formatTimestamp(m.date)}]`); + const sender = pc.bold(m.senderName ?? 'Unknown'); + const reply = m.replyToMsgId != null ? pc.dim(` (reply to ${m.replyToMsgId})`) : ''; + const edited = m.editDate ? pc.dim(' (edited)') : ''; + const annotation = formatMediaAnnotation(m); + const media = annotation ? pc.yellow(annotation) + ' ' : ''; + let line = `${ts} ${sender}${reply}${edited}: ${media}${m.text}`; + if (m.poll) { + line += '\n' + formatPoll(m.poll); + } + return line; +} + +/** + * Format a list of messages in conversational style. + * Each message on its own line with timestamp, sender, optional reply/media annotations. + */ +export function formatMessages(messages: MessageItem[]): string { + if (messages.length === 0) return ''; + return messages.map(formatSingleMessage).join('\n'); +} + +/** + * Format a chat list in table format. + * [channel] My Channel @mychan + * [supergroup] Dev Group @devs (5 unread) + * [user] Alice @alice + */ +export function formatChatList(chats: ChatListItem[]): string { + if (chats.length === 0) return ''; + + // Determine max type length for alignment + const maxTypeLen = Math.max(...chats.map(c => c.type.length)); + + return chats.map(c => { + const typePad = c.type.padEnd(maxTypeLen); + const typeTag = pc.dim(`[${typePad}]`); + const title = pc.bold(c.title); + const username = c.username ? pc.dim(` @${c.username}`) : ''; + const unread = c.unreadCount > 0 ? pc.yellow(` (${c.unreadCount} unread)`) : ''; + return `${typeTag} ${title}${username}${unread}`; + }).join('\n'); +} + +/** + * Format chat info as key-value pairs. + * Title: My Channel + * Type: channel + * Username: @mychan + * Description: A test channel + * Members: 1,234 + */ +export function formatChatInfo(info: ChatInfo): string { + const pairs: [string, string][] = []; + + pairs.push(['Title', info.title]); + pairs.push(['Type', info.type]); + if (info.username != null) pairs.push(['Username', `@${info.username}`]); + if (info.description != null) pairs.push(['Description', info.description]); + if (info.memberCount != null) pairs.push(['Members', info.memberCount.toLocaleString()]); + if (info.creationDate != null) pairs.push(['Created', info.creationDate]); + if (info.linkedChatId != null) pairs.push(['Linked Chat', info.linkedChatId]); + if (info.slowmodeSeconds != null) pairs.push(['Slowmode', `${info.slowmodeSeconds}s`]); + if (info.inviteLink != null) pairs.push(['Invite Link', info.inviteLink]); + if (info.migratedFrom != null) pairs.push(['Migrated From', info.migratedFrom]); + + const maxLabelLen = Math.max(...pairs.map(([label]) => label.length)); + + return pairs.map(([label, value]) => { + const paddedLabel = label.padEnd(maxLabelLen); + return `${pc.bold(paddedLabel)} ${value}`; + }).join('\n'); +} + +/** + * Format members list with name, username, and bot tag. + * Alice @alice + * Bob @bob [bot] + */ +export function formatMembers(members: Pick<MemberItem, 'firstName' | 'lastName' | 'username' | 'isBot'>[]): string { + if (members.length === 0) return ''; + + return members.map(m => { + const name = pc.bold([m.firstName, m.lastName].filter(Boolean).join(' ') || 'Unknown'); + const username = m.username ? pc.dim(` @${m.username}`) : ''; + const bot = m.isBot ? pc.cyan(' [bot]') : ''; + return `${name}${username}${bot}`; + }).join('\n'); +} + +/** + * Format search results grouped by chat title. + * --- Dev Group --- + * [2026-03-11 12:30] Alice: found this + * --- General Chat --- + * [2026-03-11 12:35] Bob: also here + */ +export function formatSearchResults(results: SearchResultItem[]): string { + if (results.length === 0) return ''; + + // Group by chatTitle preserving order + const groups = new Map<string, SearchResultItem[]>(); + for (const r of results) { + const existing = groups.get(r.chatTitle); + if (existing) { + existing.push(r); + } else { + groups.set(r.chatTitle, [r]); + } + } + + const sections: string[] = []; + for (const [chatTitle, msgs] of groups) { + sections.push(pc.bold(`--- ${chatTitle} ---`)); + for (const m of msgs) { + sections.push(formatSingleMessage(m)); + } + } + + return sections.join('\n'); +} + +/** + * Format a download result with path, filename, size, and type. + */ +export function formatDownloadResult(result: DownloadResult): string { + const lines = [ + `${pc.bold('Downloaded:')} ${result.filename}`, + `${pc.bold('Path:')} ${pc.green(result.path)}`, + `${pc.bold('Size:')} ${formatBytes(result.size)}`, + `${pc.bold('Type:')} ${result.mediaType}`, + ]; + return lines.join('\n'); +} + +/** + * Format an upload/send result. + * Handles both single MessageItem (delegates to formatSingleMessage) and + * AlbumResult (header + each message formatted). + */ +export function formatUploadResult(result: AlbumResult | MessageItem): string { + // AlbumResult shape + if ('messages' in result && 'sent' in result) { + const album = result as AlbumResult; + const header = pc.bold(`Sent ${album.sent} files`); + const msgs = album.messages.map(formatSingleMessage).join('\n'); + return `${header}\n${msgs}`; + } + // Single MessageItem + return formatSingleMessage(result); +} + +/** + * Format forum topics as a human-readable list. + * Each topic shows its ID, title, and optional pinned/closed indicators. + * Example: + * 42 General Discussion [pinned] + * 43 Off Topic [closed] + * 44 Normal Topic + */ +export function formatTopics(topics: TopicItem[]): string { + if (topics.length === 0) return ''; + + // Determine max ID width for alignment + const maxIdLen = Math.max(...topics.map(t => String(t.id).length)); + + return topics.map(t => { + const idStr = String(t.id).padStart(maxIdLen); + const id = pc.dim(idStr); + const title = pc.bold(t.title); + const indicators: string[] = []; + if (t.isPinned) indicators.push(pc.cyan('[pinned]')); + if (t.isClosed) indicators.push(pc.yellow('[closed]')); + const suffix = indicators.length > 0 ? ' ' + indicators.join(' ') : ''; + return ` ${id} ${title}${suffix}`; + }).join('\n'); +} + +/** + * Format a get-by-ID result with messages and a not-found footer. + * Renders found messages with formatMessages, appends dim "Not found: ..." line. + */ +export function formatGetResult(data: { messages: MessageItem[]; notFound: number[] }): string { + const parts: string[] = []; + + if (data.messages.length > 0) { + parts.push(formatMessages(data.messages)); + } else { + parts.push('No messages found.'); + } + + if (data.notFound.length > 0) { + parts.push(pc.dim('Not found: ' + data.notFound.join(', '))); + } + + return parts.join('\n'); +} + +/** + * Format a delete result with count, mode, and any failed entries. + * "Deleted 3 messages (revoke)." or "Failed: 42 (permission denied)" + */ +export function formatDeleteResult(result: DeleteResult): string { + const parts: string[] = []; + if (result.deleted.length > 0) { + parts.push(`Deleted ${result.deleted.length} message${result.deleted.length > 1 ? 's' : ''} (${result.mode}).`); + } + for (const f of result.failed) { + parts.push(pc.red(`Failed: ${f.id} (${f.reason})`)); + } + if (parts.length === 0) { + parts.push('No messages deleted.'); + } + return parts.join('\n'); +} + +/** + * Format a pin/unpin result with action, message ID, chat ID, and silent indicator. + * "Pinned message 456 in @group (silent)" or "Unpinned message 456 in @group" + */ +export function formatPinResult(result: PinResult): string { + const action = result.action === 'pinned' ? 'Pinned' : 'Unpinned'; + const suffix = result.action === 'pinned' + ? (result.silent ? ' (silent)' : ' (notified)') + : ''; + return `${action} message ${result.messageId} in ${result.chatId}${suffix}`; +} + +/** + * Format user profiles as aligned key-value pairs with color-coded status. + * + * Each profile displays: Name, ID, Username, Phone, Bio, Last Seen, + * Photos, Common Chats, and conditional flags (Blocked, Premium, Verified, Bot). + * Multiple profiles separated by blank lines. + * Appends dim "Not found: ..." for any unresolved inputs. + */ +export function formatUserProfile(profiles: UserProfile[], notFound: string[]): string { + const parts: string[] = []; + + for (const p of profiles) { + const pairs: [string, string][] = []; + + const name = [p.firstName, p.lastName].filter(Boolean).join(' ') || 'Unknown'; + pairs.push(['Name', name]); + pairs.push(['ID', p.id]); + if (p.username != null) pairs.push(['Username', `@${p.username}`]); + + // Phone: restricted indicator rendered dim + if (p.phone === '[restricted]') { + pairs.push(['Phone', pc.dim('[restricted]')]); + } else if (p.phone != null) { + pairs.push(['Phone', p.phone]); + } + + if (p.bio != null) pairs.push(['Bio', p.bio]); + + // Last Seen: color-coded by status + if (p.lastSeen != null) { + let lastSeenFormatted: string; + if (p.lastSeen === 'online') { + lastSeenFormatted = pc.green('online'); + } else if (['recently', 'within_week', 'within_month', 'long_time_ago'].includes(p.lastSeen)) { + lastSeenFormatted = pc.dim(p.lastSeen.replace(/_/g, ' ')); + } else { + // ISO timestamp + lastSeenFormatted = p.lastSeen; + } + pairs.push(['Last Seen', lastSeenFormatted]); + } + + pairs.push(['Photos', String(p.photoCount)]); + pairs.push(['Common Chats', String(p.commonChatsCount)]); + + // Conditional flags + if (p.blocked) pairs.push(['Blocked', pc.red('yes')]); + if (p.premium) pairs.push(['Premium', pc.yellow('yes')]); + if (p.verified) pairs.push(['Verified', pc.cyan('yes')]); + if (p.mutualContact) pairs.push(['Mutual Contact', 'yes']); + + if (p.isBot) { + pairs.push(['Bot', pc.cyan('yes')]); + if (p.supportsInline) pairs.push(['Inline', 'yes']); + if (p.botInlinePlaceholder) pairs.push(['Placeholder', p.botInlinePlaceholder]); + } + + if (p.langCode != null) pairs.push(['Language', p.langCode]); + + const maxLabelLen = Math.max(...pairs.map(([label]) => label.length)); + + const section = pairs.map(([label, value]) => { + const paddedLabel = label.padEnd(maxLabelLen); + return `${pc.bold(paddedLabel)} ${value}`; + }).join('\n'); + + parts.push(section); + } + + if (notFound.length > 0) { + parts.push(pc.dim('Not found: ' + notFound.join(', '))); + } + + return parts.join('\n\n'); +} + +/** + * Format a blocked user list. + * Empty list returns 'No blocked users.'. + * Non-empty list delegates to formatMembers (BlockedListItem is MemberItem-compatible). + */ +export function formatBlockedList(users: BlockedListItem[]): string { + if (users.length === 0) return 'No blocked users.'; + return formatMembers(users); +} + +/** + * Format a contact list for human-readable output. + * Empty list returns 'No contacts.'. + * Delegates to formatMembers for compact name + username + bot tag display. + */ +export function formatContactList(contacts: UserProfile[]): string { + if (contacts.length === 0) return 'No contacts.'; + return formatMembers(contacts); +} + +/** + * Format contact search results for human-readable output. + * Empty list returns 'No results.'. + * Each result shows name, username, and [contact] tag for contacts. + */ +export function formatContactSearch(results: (UserProfile & { isContact: boolean })[]): string { + if (results.length === 0) return 'No results.'; + + return results.map(r => { + const name = pc.bold([r.firstName, r.lastName].filter(Boolean).join(' ') || 'Unknown'); + const username = r.username ? pc.dim(` @${r.username}`) : ''; + const bot = r.isBot ? pc.cyan(' [bot]') : ''; + const contact = r.isContact ? pc.green(' [contact]') : ''; + return `${name}${username}${bot}${contact}`; + }).join('\n'); +} + +/** + * Fallback formatter: pretty-prints any data as indented JSON. + * Used for auth status, session export/import, join/leave confirmations, etc. + */ +export function formatGeneric(data: unknown): string { + return JSON.stringify(data, null, 2); +} + +/** + * Auto-detect data shape and dispatch to the appropriate formatter. + * + * Detection order: + * 1. .messages[] with .chatTitle -> formatSearchResults + * 2. .messages[] with .text and .date -> formatMessages + * 3. .chats[] with .type and .title -> formatChatList + * 4. .title + .type + .memberCount (ChatInfo) -> formatChatInfo + * 5. .members[] with .isBot -> formatMembers + * 6. Default -> formatGeneric + */ +export function formatData(data: unknown): string { + if (data == null || typeof data !== 'object') { + return formatGeneric(data); + } + + const obj = data as Record<string, any>; + + if (typeof obj.scheduledAt === 'string' && 'text' in obj && 'date' in obj) { + return `Scheduled for ${obj.scheduledAt}\n${formatMessages([obj as MessageItem])}`; + } + + if (Array.isArray(obj.errors)) { + const { errors, partial: _partial, ...successfulData } = obj; + const formatted = formatData(successfulData); + const failures = errors.map((failure: { input: string; error: string; code: string }) => + `Failed ${failure.input}: ${failure.error} [${failure.code}]`, + ); + return [formatted, ...failures].filter(Boolean).join('\n'); + } + + // Check for UserProfileResult shape (profiles[] + notFound[]) + if (Array.isArray(obj.profiles) && Array.isArray(obj.notFound)) { + return formatUserProfile(obj.profiles as UserProfile[], obj.notFound as string[]); + } + + // Check for ContactListResult shape (contacts[] + total number) + if (Array.isArray(obj.contacts) && typeof obj.total === 'number') { + return formatContactList(obj.contacts as UserProfile[]); + } + + // Check for ContactSearchResult shape (results[] + total number) + if (Array.isArray(obj.results) && typeof obj.total === 'number') { + return formatContactSearch(obj.results as (UserProfile & { isContact: boolean })[]); + } + + // Check for ContactDeleteResult shape (userId + action === 'deleted') + if ('userId' in obj && 'action' in obj && obj.action === 'deleted') { + const name = obj.firstName || obj.username || obj.userId; + return `Deleted contact ${name}`; + } + + // Check for BlockedListResult shape (users[] + total number, first item has isBot) + if (Array.isArray(obj.users) && typeof obj.total === 'number') { + if (obj.users.length === 0) return 'No blocked users.'; + if ('isBot' in obj.users[0]) { + return formatMembers(obj.users as BlockedListItem[]); + } + } + + // Check for BlockResult shape (userId + action blocked/unblocked) + if ('userId' in obj && 'action' in obj && (obj.action === 'blocked' || obj.action === 'unblocked')) { + const name = (obj as any).firstName || (obj as any).username || (obj as any).userId; + return `${obj.action === 'blocked' ? 'Blocked' : 'Unblocked'} ${name}`; + } + + if (obj.personal === true && 'photoId' in obj && 'userId' in obj) { + return `Set personal photo ${obj.photoId} for ${obj.userId} (visible only to you)`; + } + if (obj.profilePhoto === true && 'path' in obj && 'userId' in obj) { + return `Downloaded profile photo for ${obj.userId}: ${obj.path} (${obj.size} bytes)`; + } + + // Check for DownloadResult shape (has path + filename + size + mediaType + messageId) + if ('path' in obj && 'filename' in obj && 'size' in obj && 'mediaType' in obj && 'messageId' in obj) { + return formatDownloadResult(obj as DownloadResult); + } + + // Check for batch download shape (has files[] + downloaded count) + if (Array.isArray(obj.files) && 'downloaded' in obj) { + const header = pc.bold(`Downloaded ${obj.downloaded} files`); + const items = (obj.files as DownloadResult[]).map(f => formatDownloadResult(f)).join('\n\n'); + return `${header}\n\n${items}`; + } + + // Check for AlbumResult shape (messages[] + sent number) - before generic messages check + if (Array.isArray(obj.messages) && typeof obj.sent === 'number') { + return formatUploadResult(obj as AlbumResult); + } + + // Check for single MessageItem at top level (e.g. from send command) + if ('id' in obj && 'text' in obj && 'date' in obj && 'type' in obj && !('messages' in obj) && !('chats' in obj)) { + return formatMessages([obj as MessageItem]); + } + + // Check for get-by-ID result shape (messages[] + notFound[]) — BEFORE generic messages check + // to avoid notFound being silently dropped + if (Array.isArray(obj.messages) && Array.isArray(obj.notFound)) { + return formatGetResult(obj as { messages: MessageItem[]; notFound: number[] }); + } + + // Check for messages array + if (Array.isArray(obj.messages)) { + if (obj.messages.length === 0) return 'No messages.'; + const first = obj.messages[0]; + if ('chatTitle' in first) { + return formatSearchResults(obj.messages as SearchResultItem[]); + } + if ('text' in first && 'date' in first) { + return formatMessages(obj.messages as MessageItem[]); + } + } + + // Check for chats array + if (Array.isArray(obj.chats)) { + if (obj.chats.length === 0) return 'No chats.'; + const first = obj.chats[0]; + if ('type' in first && 'title' in first) { + return formatChatList(obj.chats as ChatListItem[]); + } + } + + // Check for ChatInfo shape (has title + type + memberCount at top level) + if ('title' in obj && 'type' in obj && 'memberCount' in obj) { + return formatChatInfo(obj as ChatInfo); + } + + // Check for topics array (forum topics) + if (Array.isArray(obj.topics)) { + if (obj.topics.length === 0) return 'No topics.'; + const first = obj.topics[0]; + if ('title' in first && 'isClosed' in first) { + return formatTopics(obj.topics as TopicItem[]); + } + } + + // Check for members array + if (Array.isArray(obj.members)) { + if (obj.members.length === 0) return 'No members.'; + const first = obj.members[0]; + if ('isBot' in first) { + return formatMembers(obj.members as MemberItem[]); + } + } + + // Check for DeleteResult shape (has deleted[] + mode) + if (Array.isArray(obj.deleted) && 'mode' in obj) { + return formatDeleteResult(obj as DeleteResult); + } + + // Check for PinResult shape (has action pinned/unpinned + messageId, but NOT emoji to avoid react conflict) + if ('action' in obj && 'messageId' in obj && !('emoji' in obj) && + (obj.action === 'pinned' || obj.action === 'unpinned')) { + return formatPinResult(obj as PinResult); + } + + // Fallback + return formatGeneric(data); +} diff --git a/cli/src/lib/gramjs-logger.ts b/cli/src/lib/gramjs-logger.ts new file mode 100644 index 0000000..df3dfce --- /dev/null +++ b/cli/src/lib/gramjs-logger.ts @@ -0,0 +1,32 @@ +import { Logger, LogLevel } from 'teleproto/extensions/Logger.js'; +import { isQuietMode, isVerboseMode } from './cli-mode.js'; + +/** Keep gramjs diagnostics on stderr, including its constructor banner. */ +class GramjsLogger extends Logger { + constructor(private readonly sensitiveValues: readonly string[]) { + super(LogLevel.DEBUG); + } + + override canSend(level: LogLevel): boolean { + if (isQuietMode() || level === LogLevel.NONE) return false; + if (!isVerboseMode() && level !== LogLevel.WARN && level !== LogLevel.ERROR) return false; + return super.canSend(level); + } + + override log(level: LogLevel, message: string, _color: string): void { + if (!this.canSend(level)) return; + // These SDK diagnostics include raw response bytes, which can contain + // account data. A protocol failure does not require dumping its payload. + let safeMessage = String(message) + .replace(/(remaining data|Received response without parent request:)[\s\S]*/i, '$1 [redacted]'); + for (const secret of this.sensitiveValues) { + if (secret) safeMessage = safeMessage.split(secret).join('[redacted]'); + } + process.stderr.write(`[gramjs ${level}] ${safeMessage}\n`); + } +} + +/** Pass as baseLogger when constructing every TelegramClient. */ +export function createGramjsLogger(sensitiveValues: readonly string[] = []): Logger { + return new GramjsLogger(sensitiveValues); +} diff --git a/cli/src/lib/media-utils.ts b/cli/src/lib/media-utils.ts new file mode 100644 index 0000000..c287f58 --- /dev/null +++ b/cli/src/lib/media-utils.ts @@ -0,0 +1,99 @@ +import { Api } from 'teleproto'; + +/** + * Map of user-facing filter names to factory functions that create + * gramjs InputMessagesFilter instances for search filtering. + * + * Factory functions ensure a fresh instance per call (gramjs mutates filter objects). + */ +export const FILTER_MAP: Record<string, () => InstanceType<any>> = { + photos: () => new Api.InputMessagesFilterPhotos(), + videos: () => new Api.InputMessagesFilterVideo(), + photo_video: () => new Api.InputMessagesFilterPhotoVideo(), + documents: () => new Api.InputMessagesFilterDocument(), + urls: () => new Api.InputMessagesFilterUrl(), + gifs: () => new Api.InputMessagesFilterGif(), + voice: () => new Api.InputMessagesFilterVoice(), + music: () => new Api.InputMessagesFilterMusic(), + round: () => new Api.InputMessagesFilterRoundVideo(), + round_voice: () => new Api.InputMessagesFilterRoundVoice(), + chat_photos: () => new Api.InputMessagesFilterChatPhotos(), + phone_calls: () => new Api.InputMessagesFilterPhoneCalls({ missed: false }), + mentions: () => new Api.InputMessagesFilterMyMentions(), + geo: () => new Api.InputMessagesFilterGeo(), + contacts: () => new Api.InputMessagesFilterContacts(), + pinned: () => new Api.InputMessagesFilterPinned(), +}; + +/** + * Array of valid filter names for validation and help text. + */ +export const VALID_FILTERS: string[] = Object.keys(FILTER_MAP); + +/** + * MIME type to file extension map for auto-naming downloaded files. + */ +const MIME_EXT_MAP: Record<string, string> = { + 'image/jpeg': '.jpg', + 'image/png': '.png', + 'image/gif': '.gif', + 'image/webp': '.webp', + 'image/bmp': '.bmp', + 'video/mp4': '.mp4', + 'video/quicktime': '.mov', + 'video/x-msvideo': '.avi', + 'video/x-matroska': '.mkv', + 'video/webm': '.webm', + 'audio/ogg': '.ogg', + 'audio/mpeg': '.mp3', + 'audio/opus': '.opus', +}; + +/** + * Generate an auto-name for a downloaded media file. + * + * Format: {mediaType}_{msgId}{ext} + * Extension derived from MIME type; falls back to .bin. + */ +export function generateFilename( + mediaType: string, + msgId: number, + mimeType: string | null, +): string { + const ext = mimeType ? (MIME_EXT_MAP[mimeType] ?? '.bin') : '.bin'; + return `${mediaType}_${msgId}${ext}`; +} + +/** + * Extension sets for file type classification. + */ +const PHOTO_EXTS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']); +const VIDEO_EXTS = new Set(['.mp4', '.mov', '.avi', '.mkv', '.webm']); +const VOICE_EXTS = new Set(['.ogg', '.opus']); + +/** + * Classify a file by its extension for upload type detection. + */ +export function detectFileType( + ext: string, +): 'photo' | 'video' | 'voice' | 'document' { + const lower = ext.toLowerCase(); + if (PHOTO_EXTS.has(lower)) return 'photo'; + if (VIDEO_EXTS.has(lower)) return 'video'; + if (VOICE_EXTS.has(lower)) return 'voice'; + return 'document'; +} + +/** + * Format a byte count as a human-readable string. + * + * <1024 -> NB, <1MB -> NKB (rounded), <1GB -> N.NMB, else N.NGB + */ +export function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes}B`; + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)}KB`; + if (bytes < 1024 * 1024 * 1024) { + return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; + } + return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`; +} diff --git a/cli/src/lib/output.ts b/cli/src/lib/output.ts new file mode 100644 index 0000000..f6c5cd4 --- /dev/null +++ b/cli/src/lib/output.ts @@ -0,0 +1,233 @@ +import pc from 'picocolors'; +import type { SuccessEnvelope, ErrorEnvelope, BatchItemError } from './types.js'; +import { formatData } from './format.js'; +import { pickFields, applyFieldSelection, extractListItems } from './fields.js'; +import { encodeToon } from './toon.js'; +import { isQuietMode, isVerboseMode, setQuietMode, setVerboseMode } from './cli-mode.js'; +import { captureDaemonOutput, getDaemonContext, markExitFailure } from './daemon/execution-context.js'; + +export { setQuietMode, setVerboseMode, isQuietMode, isVerboseMode }; + +/** Current output mode: false = JSON (default), true = human-readable. */ +let _humanMode = false; + +/** JSONL streaming mode: one JSON object per line, no envelope. */ +let _jsonlMode = false; + +/** TOON output mode: token-efficient LLM-optimized format. */ +let _toonMode = false; + +/** Field selection: comma-separated field names parsed into array. */ +let _fieldSelection: string[] | null = null; + +/** + * Set the output mode for all subsequent output calls. + * Called by the preAction hook in tg.ts based on --human / --no-json flags. + */ +export function setOutputMode(human: boolean): void { + _humanMode = human; +} + +/** + * Get the current output mode. + */ +export function getOutputMode(): boolean { + return _humanMode; +} + +/** + * Enable or disable JSONL streaming mode. + * In JSONL mode, list commands output one JSON object per line without envelope. + */ +export function setJsonlMode(enabled: boolean): void { + _jsonlMode = enabled; +} + +/** + * Enable or disable TOON output mode. + * In TOON mode, output is encoded as Token-Oriented Object Notation + * for optimal LLM context window usage. + */ +export function setToonMode(enabled: boolean): void { + _toonMode = enabled; +} + +/** + * Set the field selection filter. + * Fields are applied to output data to reduce noise. + */ +export function setFieldSelection(fields: string[] | null): void { + _fieldSelection = fields; +} + +/** + * Write a success response to stdout. + * Priority: TOON > JSONL > human > JSON. + * + * - TOON mode: encodes the full `{ ok, data }` envelope. + * - JSONL mode: extracts list items, writes one JSON object per line (no envelope). + * Composes with field selection. Falls through to JSON for non-list data. + * - Human mode: writes formatted text. --fields silently ignored. + * - JSON mode: writes envelope, applying field selection if set. + */ +export function outputSuccess<T>(data: T): void { + if (captureDaemonOutput({ ok: true, data })) return; + + // TOON mode: encode full envelope through TOON (highest priority) + if (_toonMode) { + const filteredData = _fieldSelection + ? applyFieldSelection(data, _fieldSelection) as T + : data; + const envelope = { ok: true, data: filteredData }; + process.stdout.write(encodeToon(envelope) + '\n'); + return; + } + + // JSONL mode: one object per line, no envelope + if (_jsonlMode) { + // Special case: shapes with notFound array ({ messages, notFound } or { profiles, notFound }) + // Stream list items to stdout, report notFound to stderr + const obj = data as Record<string, unknown>; + // Partial batch results must keep machine-readable failures even with + // --quiet or --fields. Field selection applies only to successful data. + if (obj != null && typeof obj === 'object' && Array.isArray(obj.errors)) { + const items = extractListItems(obj); + if (items !== null) { + for (const item of items) { + process.stdout.write(JSON.stringify(_fieldSelection ? pickFields(item, _fieldSelection) : item) + '\n'); + } + for (const failure of obj.errors as BatchItemError[]) { + process.stdout.write(JSON.stringify({ status: 'failed', ...failure }) + '\n'); + } + if (Array.isArray(obj.notFound) && obj.notFound.length > 0) { + logStatus(`Not found: ${obj.notFound.join(', ')}`); + } + return; + } + } + if (obj != null && typeof obj === 'object' && Array.isArray(obj.notFound)) { + // Find the list key (messages, profiles, etc.) + const listKey = Object.keys(obj).find(k => k !== 'notFound' && Array.isArray(obj[k])); + if (listKey) { + for (const item of obj[listKey] as unknown[]) { + const filtered = _fieldSelection ? pickFields(item, _fieldSelection) : item; + process.stdout.write(JSON.stringify(filtered) + '\n'); + } + if ((obj.notFound as unknown[]).length > 0) { + logStatus(`Not found: ${(obj.notFound as unknown[]).join(', ')}`); + } + return; + } + } + + // Batch download: { files[], downloaded, failed[] } + if ( + obj != null && typeof obj === 'object' + && Array.isArray(obj.files) && Array.isArray(obj.failed) && 'downloaded' in obj + ) { + for (const file of obj.files as unknown[]) { + const entry = _fieldSelection + ? pickFields({ ...(file as object), status: 'downloaded' }, _fieldSelection) + : { ...(file as object), status: 'downloaded' }; + process.stdout.write(JSON.stringify(entry) + '\n'); + } + for (const f of obj.failed as { messageId: number; error: string; code: string }[]) { + const entry = _fieldSelection + ? pickFields({ messageId: f.messageId, status: 'failed', error: f.error, code: f.code }, _fieldSelection) + : { messageId: f.messageId, status: 'failed', error: f.error, code: f.code }; + process.stdout.write(JSON.stringify(entry) + '\n'); + } + return; + } + + // Special case: DeleteResult shape { deleted[], failed[], mode } + // Stream each deleted/failed ID as a separate JSONL line + if (obj != null && typeof obj === 'object' && Array.isArray(obj.deleted) && Array.isArray(obj.failed) && 'mode' in obj) { + for (const id of obj.deleted as number[]) { + const entry = _fieldSelection ? pickFields({ id, status: 'deleted' }, _fieldSelection) : { id, status: 'deleted' }; + process.stdout.write(JSON.stringify(entry) + '\n'); + } + for (const f of obj.failed as { id: number; reason: string }[]) { + const entry = _fieldSelection ? pickFields({ id: f.id, status: 'failed', reason: f.reason }, _fieldSelection) : { id: f.id, status: 'failed', reason: f.reason }; + process.stdout.write(JSON.stringify(entry) + '\n'); + } + return; + } + + const items = extractListItems(data); + if (items !== null) { + for (const item of items) { + const filtered = _fieldSelection ? pickFields(item, _fieldSelection) : item; + process.stdout.write(JSON.stringify(filtered) + '\n'); + } + return; + } + // Non-list data in JSONL mode: fall through to normal JSON output + } + + if (_humanMode) { + // Human mode: --fields silently ignored per design decision + const formatted = formatData(data); + process.stdout.write(formatted + '\n'); + } else { + // JSON mode: apply field selection if set, preserve envelope + const filteredData = _fieldSelection + ? applyFieldSelection(data, _fieldSelection) as T + : data; + const envelope: SuccessEnvelope<T> = { ok: true, data: filteredData }; + process.stdout.write(JSON.stringify(envelope) + '\n'); + } +} + +/** + * Write an error response and set process.exitCode = 1. + * In JSON mode (default): writes JSON envelope { ok: false, error: ... } to stdout. + * In human mode: writes colored error text to stderr. + * In JSONL mode: errors always go to stderr (no envelope). + */ +export function outputError(error: string, code?: string): void { + // Commander treats a resolved action as success (exit 0). Set the + // code instead of process.exit() so withClient/withAuth finally + // still runs destroy(). + markExitFailure(); + if (captureDaemonOutput({ ok: false, error, ...(code && { code }) })) return; + + // TOON mode: encode error as TOON to stdout (highest priority) + if (_toonMode) { + const envelope = { ok: false, error, ...(code && { code }) }; + process.stdout.write(encodeToon(envelope) + '\n'); + return; + } + + if (_jsonlMode) { + // JSONL mode: errors to stderr only, no envelope + const suffix = code ? ` [${code}]` : ''; + process.stderr.write(`Error: ${error}${suffix}\n`); + return; + } + if (_humanMode) { + const prefix = pc.red('Error: '); + const suffix = code ? pc.dim(` [${code}]`) : ''; + process.stderr.write(prefix + error + suffix + '\n'); + } else { + const envelope: ErrorEnvelope = { ok: false, error, ...(code && { code }) }; + process.stdout.write(JSON.stringify(envelope) + '\n'); + } +} + +/** + * Write a status/progress message to stderr. + * Suppressed when quiet mode is enabled. + * NEVER writes to stdout -- stdout is reserved for data output only. + */ +export function logStatus(message: string, quiet?: boolean): void { + if (getDaemonContext()) return; + if (quiet ?? isQuietMode()) return; + process.stderr.write(message + '\n'); +} + +/** Extra stderr for --verbose. Suppressed when quiet. */ +export function logVerbose(message: string): void { + if (!isVerboseMode() || isQuietMode()) return; + process.stderr.write(message + '\n'); +} diff --git a/cli/src/lib/peer.ts b/cli/src/lib/peer.ts new file mode 100644 index 0000000..51321df --- /dev/null +++ b/cli/src/lib/peer.ts @@ -0,0 +1,152 @@ +import { TelegramClient, Api } from 'teleproto'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** + * Assert that an entity is a forum-enabled supergroup when topicId is provided. + * Used by commands that support --topic flag to reject non-forum chats early. + * + * @throws TgError with NOT_A_FORUM if entity is not a forum Channel + */ +export async function assertForum(entity: any, topicId: number | undefined): Promise<void> { + if (topicId === undefined) return; + if (entity?.className !== 'Channel' || entity.forum !== true) { + throw new TgError('Chat is not a forum-enabled supergroup', ErrorCode.NOT_A_FORUM); + } +} + +/** + * Regex to extract invite hash from Telegram invite link URLs. + * Handles: t.me/+HASH, t.me/joinchat/HASH, telegram.me/+HASH, telegram.me/joinchat/HASH + * With or without https:// prefix. + */ +const INVITE_LINK_RE = /(?:t\.me|telegram\.me)\/(?:joinchat\/|\+)([a-zA-Z0-9_-]+)/; + +/** + * Check if input looks like an invite link (contains t.me/+ or joinchat/). + */ +function isInviteLink(input: string): boolean { + return INVITE_LINK_RE.test(input); +} + +/** + * Check if input looks like a phone number (+digits). + */ +export function isPhoneNumber(input: string): boolean { + return /^\+\d+$/.test(input); +} + +/** + * Check if input is a valid integer (including negative). + */ +function isNumericId(input: string): boolean { + return /^-?\d+$/.test(input); +} + +/** Preserve transport/RPC failures; only known absence errors mean not found. */ +function throwResolutionError(err: unknown, invite = false): never { + if (err instanceof TgError) throw err; + const rpcCode = err != null && typeof err === 'object' && 'errorMessage' in err + ? String(err.errorMessage) : undefined; + const missingRpc = invite + ? ['INVITE_HASH_EMPTY', 'INVITE_HASH_INVALID', 'INVITE_HASH_EXPIRED'] + : ['USERNAME_INVALID', 'USERNAME_NOT_OCCUPIED', 'PHONE_NOT_OCCUPIED', 'USER_ID_INVALID', 'PEER_ID_INVALID']; + const message = err instanceof Error ? err.message : String(err); + const missing = rpcCode ? missingRpc.includes(rpcCode) : invite + ? /^invite hash (?:invalid|expired)$/i.test(message) + : /^(?:(?:entity|phone|id|peer) not found|Could not find the input entity for |Cannot find any entity corresponding to |No user has .+ as username)/i.test(message); + if (!missing) throw err; + throw new TgError( + `${invite ? 'Failed to resolve invite link' : 'Peer not found'}: ${message}`, + invite ? ErrorCode.INVALID_INVITE : ErrorCode.PEER_NOT_FOUND, + ); +} + +/** + * Extract the invite hash from a Telegram invite link. + * + * Supported formats: + * - https://t.me/+HASH + * - https://t.me/joinchat/HASH + * - https://telegram.me/+HASH + * - t.me/+HASH (without https://) + * + * @throws TgError with INVALID_INVITE code if format is not recognized + */ +export function extractInviteHash(link: string): string { + const match = link.match(INVITE_LINK_RE); + if (!match) { + throw new TgError('Invalid invite link format', 'INVALID_INVITE'); + } + return match[1]; +} + +/** + * Resolve a user input string to a gramjs entity. + * + * Accepts: + * - Username: "username" or "@username" + * - Numeric ID: "12345" or "-1001234567" + * - Phone number: "+15551234567" + * - Invite link: "https://t.me/+HASH" or "https://t.me/joinchat/HASH" + * + * @returns The resolved entity (User, Chat, or Channel) + * @throws TgError with PEER_NOT_FOUND for resolution failures + * @throws TgError with INVALID_INVITE for invite link failures + */ +export async function resolveEntity( + client: TelegramClient, + input: string, +): Promise<Api.User | Api.Chat | Api.Channel> { + // Invite link: extract hash and use CheckChatInvite + if (isInviteLink(input)) { + const hash = extractInviteHash(input); + try { + const result = await client.invoke( + new Api.messages.CheckChatInvite({ hash }), + ); + // Return the chat from the result (ChatInviteAlready has .chat, + // ChatInvite has the invite info, ChatInvitePeek has .chat) + const chat = (result as any).chat; + if (!chat) { + throw new TgError( + 'Not a member of this invite. Join first with: tg chat join <link>', + ErrorCode.NOT_A_MEMBER, + ); + } + return chat; + } catch (err) { + throwResolutionError(err, true); + } + } + + // Phone number: pass as-is to getEntity + if (isPhoneNumber(input)) { + try { + return (await client.getEntity(input)) as Api.User | Api.Chat | Api.Channel; + } catch (err) { + throwResolutionError(err); + } + } + + // Numeric ID: parse to number + if (isNumericId(input)) { + const numId = Number(input); + if (!Number.isSafeInteger(numId)) { + throw new TgError('Peer ID must be a safe integer', ErrorCode.INVALID_ID); + } + try { + return (await client.getEntity(numId)) as Api.User | Api.Chat | Api.Channel; + } catch (err) { + throwResolutionError(err); + } + } + + // Username: strip leading @ if present + const username = input.startsWith('@') ? input.slice(1) : input; + try { + return (await client.getEntity(username)) as Api.User | Api.Chat | Api.Channel; + } catch (err) { + throwResolutionError(err); + } +} diff --git a/cli/src/lib/presets.ts b/cli/src/lib/presets.ts new file mode 100644 index 0000000..7dd7c53 --- /dev/null +++ b/cli/src/lib/presets.ts @@ -0,0 +1,170 @@ +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; +import { logStatus } from './output.js'; + +// Pinned to specific commit SHA for supply-chain safety. +// Update this SHA when upgrading to a newer opentele version. +const OPENTELE_COMMIT = '1a6f0816eac47ff3cb907af72ed9f8cbbbe8fba0'; +const OPENTELE_URL = `https://raw.githubusercontent.com/thedemons/opentele/${OPENTELE_COMMIT}/src/api.py`; + +/** Cache TTL: 30 days in milliseconds. */ +const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; + +/** Known test API IDs that must never be used in production. */ +export const TEST_API_IDS = new Set([17349]); + +/** Map opentele Python class names to user-friendly preset names. */ +export const PRESET_NAME_MAP: Record<string, string> = { + TelegramDesktop: 'desktop', + TelegramAndroid: 'android', + TelegramAndroidX: 'android-x', + TelegramIOS: 'ios', + TelegramMacOS: 'macos', + TelegramWeb_Z: 'web-z', + TelegramWeb_K: 'web-k', + Webogram: 'webogram', +}; + +export interface PresetCredentials { + apiId: number; + apiHash: string; +} + +interface CachedPreset extends PresetCredentials { + fetchedAt: string; +} + +/** + * Parse opentele's api.py content and extract API credentials. + * Filters out known test API IDs. + * + * @returns Map of preset name to credentials + */ +export function parseApiPy(content: string): Map<string, PresetCredentials> { + const result = new Map<string, PresetCredentials>(); + + // Match: class ClassName(APIData): ... api_id = N ... api_hash = "..." + const classRegex = /class\s+(\w+)\(APIData\):[^]*?api_id\s*=\s*(\d+)[^]*?api_hash\s*=\s*"([a-f0-9]+)"/g; + + let match; + while ((match = classRegex.exec(content)) !== null) { + const [, className, apiIdStr, apiHash] = match; + const apiId = parseInt(apiIdStr, 10); + + // Filter test keys and invalid ranges + if (TEST_API_IDS.has(apiId)) continue; + if (apiId <= 0 || apiId > 1_000_000) continue; + + const presetName = PRESET_NAME_MAP[className] ?? className.toLowerCase(); + result.set(presetName, { apiId, apiHash }); + } + + return result; +} + +/** + * Fetch presets from opentele GitHub and cache them in config. + * + * @param config - Conf instance to store cached presets + * @returns Map of preset name to credentials + * @throws TgError with FETCH_FAILED if network request fails and no cache exists + */ +export async function fetchAndCachePresets( + config: { get: (key: string) => unknown; set: (key: string, value: unknown) => void }, +): Promise<Map<string, PresetCredentials>> { + let content: string; + + try { + const response = await fetch(OPENTELE_URL); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + content = await response.text(); + } catch (err) { + // Try stale cache as fallback + const cached = config.get('presets') as Record<string, CachedPreset> | undefined; + if (cached && Object.keys(cached).length > 0) { + logStatus('Warning: Failed to fetch fresh presets, using cached values'); + const map = new Map<string, PresetCredentials>(); + for (const [name, data] of Object.entries(cached)) { + map.set(name, { apiId: data.apiId, apiHash: data.apiHash }); + } + return map; + } + + throw new TgError( + `Failed to fetch client presets. Check internet connection: ${(err as Error).message}`, + ErrorCode.FETCH_FAILED, + ); + } + + const presets = parseApiPy(content); + + // Cache with timestamp + const cacheObj: Record<string, CachedPreset> = {}; + for (const [name, creds] of presets) { + cacheObj[name] = { ...creds, fetchedAt: new Date().toISOString() }; + } + config.set('presets', cacheObj); + + return presets; +} + +/** + * Get credentials for a specific client preset. + * Uses cache if fresh, fetches otherwise. + * + * @throws TgError with UNKNOWN_PRESET if preset name is not found + * @throws TgError with FETCH_FAILED if fetch fails and no cache + */ +export async function getPreset( + config: { get: (key: string) => unknown; set: (key: string, value: unknown) => void }, + name: string, +): Promise<PresetCredentials> { + // Check cache first + const cached = config.get('presets') as Record<string, CachedPreset> | undefined; + if (cached && cached[name]) { + const entry = cached[name]; + const age = Date.now() - new Date(entry.fetchedAt).getTime(); + if (age < CACHE_TTL_MS) { + return { apiId: entry.apiId, apiHash: entry.apiHash }; + } + } + + // Fetch fresh + const presets = await fetchAndCachePresets(config); + const preset = presets.get(name); + + if (!preset) { + const available = [...presets.keys()].join(', '); + throw new TgError( + `Unknown client "${name}". Available: ${available}`, + ErrorCode.UNKNOWN_PRESET, + ); + } + + return preset; +} + +/** + * List all available presets. + * Uses cache if fresh, fetches otherwise. + */ +export async function listPresets( + config: { get: (key: string) => unknown; set: (key: string, value: unknown) => void }, +): Promise<Map<string, PresetCredentials>> { + const cached = config.get('presets') as Record<string, CachedPreset> | undefined; + if (cached && Object.keys(cached).length > 0) { + const first = Object.values(cached)[0]; + const age = Date.now() - new Date(first.fetchedAt).getTime(); + if (age < CACHE_TTL_MS) { + const map = new Map<string, PresetCredentials>(); + for (const [name, data] of Object.entries(cached)) { + map.set(name, { apiId: data.apiId, apiHash: data.apiHash }); + } + return map; + } + } + + return fetchAndCachePresets(config); +} diff --git a/cli/src/lib/prompt.ts b/cli/src/lib/prompt.ts new file mode 100644 index 0000000..f33f02a --- /dev/null +++ b/cli/src/lib/prompt.ts @@ -0,0 +1,47 @@ +import { createInterface, type Interface } from 'node:readline/promises'; +import { Writable } from 'node:stream'; + +/** + * Create a prompt wrapper using Node.js readline/promises. + * Prompts are written to stderr (not stdout) to keep stdout clean for data output. + * + * The output goes through a mutable proxy so that askSecret() can suppress + * character echoing for password/secret input. + * + * @returns Object with `ask`, `askSecret`, and `close` functions. + */ +export function createPrompt(): { + ask: (question: string) => Promise<string>; + askSecret: (question: string) => Promise<string>; + close: () => void; +} { + let muted = false; + const output = new Writable({ + write(chunk, encoding, callback) { + if (!muted) process.stderr.write(chunk, encoding as BufferEncoding); + callback(); + }, + }); + + const rl: Interface = createInterface({ + input: process.stdin, + output, + terminal: true, + }); + + return { + ask: (question: string): Promise<string> => rl.question(question), + askSecret: async (question: string): Promise<string> => { + process.stderr.write(question); + muted = true; + try { + const answer = await rl.question(''); + return answer; + } finally { + muted = false; + process.stderr.write('\n'); + } + }, + close: (): void => rl.close(), + }; +} diff --git a/cli/src/lib/schedule.ts b/cli/src/lib/schedule.ts new file mode 100644 index 0000000..cdd696f --- /dev/null +++ b/cli/src/lib/schedule.ts @@ -0,0 +1,15 @@ +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** Parse an explicit zoned ISO timestamp; never silently schedule immediately. */ +export function parseSchedule(value: string, now = Date.now()): number { + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/.exec(value); + const invalid = () => new TgError('--schedule requires a valid ISO timestamp with timezone, at least 10 seconds in the future', ErrorCode.INVALID_SCHEDULE); + if (!match) throw invalid(); + const [, y, mo, d, h, mi, s] = match; + const days = new Date(Date.UTC(Number(y), Number(mo), 0)).getUTCDate(); + if (+mo < 1 || +mo > 12 || +d < 1 || +d > days || +h > 23 || +mi > 59 || +s > 59) throw invalid(); + const seconds = Math.floor(Date.parse(value) / 1000); + if (!Number.isFinite(seconds) || seconds * 1000 < now + 10_000 || seconds > 2_147_483_646) throw invalid(); + return seconds; +} diff --git a/cli/src/lib/serialize.ts b/cli/src/lib/serialize.ts new file mode 100644 index 0000000..0092150 --- /dev/null +++ b/cli/src/lib/serialize.ts @@ -0,0 +1,457 @@ +import { Api } from 'teleproto'; +import type { Dialog } from 'teleproto/tl/custom/dialog.js'; +import { entitiesToMarkdown } from './entity-to-markdown.js'; +import type { + ChatListItem, + MediaInfo, + MessageItem, + PollData, + PollOption, + ReactionCount, + SearchResultItem, + MemberItem, + TopicItem, +} from './types.js'; + +/** + * Safely convert a BigInteger, number, or null value to a string. + * gramjs uses big-integer library for IDs -- JSON.stringify would produce {}. + */ +export function bigIntToString(val: any): string { + if (val == null) return ''; + return val.toString(); +} + +/** + * Stable peer id matching `dialog.id` / `utils.getPeerId`: + * users unmarked, basic chats `-{id}`, channels `-100{id}`. + */ +export function markedPeerId(entity: any): string { + const raw = bigIntToString(entity?.id); + if (!raw) return ''; + if (raw.startsWith('-')) return raw; + const cls = entity?.className ?? entity?.constructor?.name ?? ''; + if ( + cls === 'Channel' || cls === 'ChannelForbidden' + || entity?.megagroup || entity?.broadcast + ) { + return `-100${raw}`; + } + if (cls === 'Chat' || cls === 'ChatForbidden') { + return `-${raw}`; + } + return raw; +} + +/** + * Marked peer id from a gramjs message / update (users unmarked, + * basic chats `-{id}`, channels `-100{id}`). Empty if unknown. + */ +export function messagePeerMarkedId(msg: any): string { + const peer = msg?.peerId; + if (peer) { + if (peer.channelId != null) { + const raw = bigIntToString(peer.channelId); + return raw.startsWith('-') ? raw : `-100${raw}`; + } + if (peer.chatId != null) { + const raw = bigIntToString(peer.chatId); + return raw.startsWith('-') ? raw : `-${raw}`; + } + if (peer.userId != null) return bigIntToString(peer.userId); + } + if (msg?.chatId != null) return bigIntToString(msg.chatId); + return ''; +} + +export function serializeChatPhoto(photo: any): { hasPhoto: boolean } | null { + if (!photo) return null; + const name = photo.className ?? photo.constructor?.name ?? ''; + if (name.includes('Empty')) return null; + return { hasPhoto: true }; +} + +export function serializeBannedRights(rights: any): Record<string, boolean> | null { + if (!rights || typeof rights !== 'object') return null; + const out: Record<string, boolean> = {}; + for (const [key, value] of Object.entries(rights)) { + if (typeof value === 'boolean') out[key] = value; + } + return Object.keys(out).length > 0 ? out : null; +} + +/** + * Extract username from a dialog entity (User, Chat, or Channel). + */ +function entityUsername(entity: any): string | null { + return entity?.username ?? null; +} + +/** + * Determine the chat type from a Dialog's helper properties. + */ +function dialogType(dialog: Dialog): ChatListItem['type'] { + if (dialog.isUser) return 'user'; + if (dialog.isChannel) { + const entity = dialog.entity as any; + if (entity?.megagroup) return 'supergroup'; + return 'channel'; + } + return 'group'; // isGroup for basic Chat +} + +/** + * Serialize a gramjs Dialog to a lean ChatListItem for list output. + */ +export function serializeDialog(dialog: Dialog): ChatListItem { + return { + id: bigIntToString(dialog.id) || markedPeerId((dialog as any).entity), + title: dialog.title ?? dialog.name ?? '', + type: dialogType(dialog), + username: entityUsername(dialog.entity), + unreadCount: dialog.unreadCount, + }; +} + +/** + * Detect media type from a message's media object. + * Returns the media type string and optional emoji for stickers. + */ +export function detectMedia(media: any): { mediaType: string | null; emoji?: string } { + if (!media) return { mediaType: null }; + + if (media instanceof Api.MessageMediaPhoto) { + return { mediaType: 'photo' }; + } + + if (media instanceof Api.MessageMediaDocument) { + const doc = media.document as any; + if (doc && doc.attributes) { + for (const attr of doc.attributes) { + if (attr instanceof Api.DocumentAttributeSticker) { + return { mediaType: 'sticker', emoji: attr.alt || undefined }; + } + if (attr instanceof Api.DocumentAttributeVideo) { + return { mediaType: 'video' }; + } + if (attr instanceof Api.DocumentAttributeAudio) { + if ((attr as any).voice) { + return { mediaType: 'voice' }; + } + return { mediaType: 'audio' }; + } + } + // Document without recognized attributes + return { mediaType: 'document' }; + } + return { mediaType: 'document' }; + } + + if (media instanceof Api.MessageMediaPoll) { + return { mediaType: 'poll' }; + } + + // Fallback for other media types + return { mediaType: 'other' }; +} + +/** + * Safely convert a gramjs numeric value (possibly BigInteger) to a JS number. + * gramjs uses big-integer for some fields like file sizes. + */ +function toSafeNumber(val: any): number | null { + if (val == null) return null; + if (typeof val === 'number') return val; + if (typeof val.toJSNumber === 'function') return val.toJSNumber(); + const n = Number(val); + return isNaN(n) ? null : n; +} + +/** + * Extract detailed media metadata from a message's media object. + * + * Supports MessageMediaPhoto (extracts largest PhotoSize dimensions/size) + * and MessageMediaDocument (extracts doc attributes for filename, dimensions, duration). + * Returns null for unsupported media types or null/undefined input. + */ +export function extractMediaInfo(media: any): MediaInfo | null { + if (!media) return null; + + if (media instanceof Api.MessageMediaPhoto) { + const photo = media.photo as any; + if (!photo || !photo.sizes) return null; + + // Find largest PhotoSize with dimensions + let bestSize: any = null; + for (const s of photo.sizes) { + if (s.w != null && s.h != null) { + if (!bestSize || (s.w * s.h > bestSize.w * bestSize.h)) { + bestSize = s; + } + } + } + + return { + filename: null, + fileSize: toSafeNumber(bestSize?.size), + mimeType: 'image/jpeg', + width: bestSize?.w ?? null, + height: bestSize?.h ?? null, + duration: null, + }; + } + + if (media instanceof Api.MessageMediaDocument) { + const doc = media.document as any; + if (!doc) return null; + + let filename: string | null = null; + let width: number | null = null; + let height: number | null = null; + let duration: number | null = null; + + if (doc.attributes) { + for (const attr of doc.attributes) { + if (attr instanceof Api.DocumentAttributeFilename) { + filename = attr.fileName; + } + if (attr instanceof Api.DocumentAttributeVideo) { + width = attr.w ?? null; + height = attr.h ?? null; + duration = attr.duration ?? null; + } + if (attr instanceof Api.DocumentAttributeAudio) { + duration = attr.duration ?? null; + } + if (attr instanceof Api.DocumentAttributeImageSize) { + width = attr.w ?? null; + height = attr.h ?? null; + } + } + } + + return { + filename, + fileSize: toSafeNumber(doc.size), + mimeType: doc.mimeType ?? null, + width, + height, + duration, + }; + } + + return null; +} + +/** + * Extract structured poll data from a MessageMediaPoll. + * + * Returns null if the media is not a MessageMediaPoll. + * Maps poll answers to PollOption[] with vote counts matched via Buffer.equals + * on option bytes. Derives correctOption as 1-based index from the first + * option where correct === true. + */ +export function extractPollData(media: any): PollData | null { + if (!media || !(media instanceof Api.MessageMediaPoll)) return null; + + const poll = media.poll; + const results = (media as any).results; + + const options: PollOption[] = (poll as any).answers.map((answer: any) => { + const optionBytes = Buffer.from(answer.option); + // Find matching voter result + const voterResult = results?.results?.find( + (r: any) => Buffer.from(r.option).equals(optionBytes), + ); + return { + text: answer.text?.text ?? answer.text ?? '', + voters: voterResult?.voters ?? 0, + chosen: voterResult?.chosen ?? false, + correct: voterResult?.correct ?? false, + }; + }); + + // Derive correctOption: 1-based index of first correct option + let correctOption: number | null = null; + for (let i = 0; i < options.length; i++) { + if (options[i].correct) { + correctOption = i + 1; + break; + } + } + + return { + question: (poll as any).question?.text ?? '', + options, + isQuiz: !!(poll as any).quiz, + isPublic: !!(poll as any).publicVoters, + isMultiple: !!(poll as any).multipleChoice, + isClosed: !!(poll as any).closed, + closePeriod: (poll as any).closePeriod ?? null, + closeDate: (poll as any).closeDate + ? new Date((poll as any).closeDate * 1000).toISOString() + : null, + totalVoters: results?.totalVoters ?? 0, + correctOption, + solution: results?.solution ?? null, + }; +} + +/** + * Extract reaction counts from a message's reactions object. + */ +function extractReactions(reactions: any): ReactionCount[] { + if (!reactions?.results) return []; + return reactions.results + .filter((r: any) => r.count > 0) + .map((r: any) => ({ + emoji: r.reaction?.emoticon ?? r.reaction?.documentId?.toString() ?? '?', + count: r.count, + })); +} + +/** + * Build sender display name from a User/Chat/Channel entity. + */ +function senderName(entity: any): string | null { + if (!entity) return null; + const first = entity.firstName ?? entity.title ?? ''; + const last = entity.lastName ?? ''; + const full = last ? `${first} ${last}` : first; + return full || null; +} + +/** + * Extract forward-from information from a message's fwdFrom field. + */ +function forwardFromName(fwdFrom: any): string | null { + if (!fwdFrom) return null; + return fwdFrom.fromName ?? null; +} + +/** + * Serialize a gramjs Api.Message to a MessageItem for JSON output. + * + * Handles: text messages, media messages (photo, video, voice, sticker, document), + * service messages (action), entity-to-markdown conversion, date conversion, + * BigInt ID serialization. + */ +export function serializeMessage( + msg: Api.Message, + senderEntity?: Api.User | Api.Chat | Api.Channel, +): MessageItem { + const isService = !!(msg as any).action; + const { mediaType, emoji } = detectMedia((msg as any).media); + + const text = entitiesToMarkdown( + (msg as any).message ?? '', + (msg as any).entities, + ); + + // Extract reaction counts + const reactions = extractReactions((msg as any).reactions); + + const item: MessageItem = { + id: msg.id, + text, + date: msg.date ? new Date(msg.date * 1000).toISOString() : new Date().toISOString(), + senderId: (msg as any).senderId ? bigIntToString((msg as any).senderId) : null, + senderName: senderName(senderEntity ?? (msg as any)._sender), + replyToMsgId: (msg as any).replyTo?.replyToMsgId ?? null, + forwardFrom: forwardFromName((msg as any).fwdFrom), + mediaType, + type: isService ? 'service' : 'message', + views: (msg as any).views ?? null, + forwards: (msg as any).forwards ?? null, + ...(reactions.length > 0 && { reactions }), + }; + + if (isService) { + const action = (msg as any).action; + // Use the constructor name as actionText, stripping "MessageAction" prefix + const className = action?.constructor?.name ?? action?.className ?? 'Unknown'; + item.actionText = className.replace(/^MessageAction/, ''); + } + + if (emoji) { + item.emoji = emoji; + } + + // Populate editDate when message has been edited (gramjs stores as Unix timestamp) + if ((msg as any).editDate) { + item.editDate = new Date((msg as any).editDate * 1000).toISOString(); + } + + // Populate media metadata when message has media + if (mediaType) { + const mediaInfo = extractMediaInfo((msg as any).media); + if (mediaInfo) { + item.media = mediaInfo; + } + } + + // Populate poll data when message contains a poll + const pollData = extractPollData((msg as any).media); + if (pollData) { + item.poll = pollData; + } + + return item; +} + +/** + * Serialize a message as a search result with chat context. + */ +export function serializeSearchResult( + msg: Api.Message, + chatId: string, + chatTitle: string, + senderEntity?: Api.User | Api.Chat | Api.Channel, +): SearchResultItem { + return { + ...serializeMessage(msg, senderEntity), + chatId, + chatTitle, + }; +} + +/** + * Extract the peer ID from a gramjs fromId peer object. + * Handles PeerUser (userId), PeerChannel (channelId), and PeerChat (chatId). + */ +function extractPeerId(fromId: any): string { + if (!fromId) return ''; + return bigIntToString(fromId.userId ?? fromId.channelId ?? fromId.chatId ?? ''); +} + +/** + * Serialize a gramjs ForumTopic to a TopicItem for JSON output. + * + * Maps gramjs fields: topMessage -> topMessageId, closed -> isClosed, pinned -> isPinned. + */ +export function serializeTopic(topic: any): TopicItem { + return { + id: topic.id, + title: topic.title ?? '', + iconEmoji: topic.iconEmojiId != null ? topic.iconEmojiId.toString() : null, + creationDate: topic.date ? new Date(topic.date * 1000).toISOString() : new Date().toISOString(), + creatorId: extractPeerId(topic.fromId), + topMessageId: topic.topMessage ?? 0, + isClosed: !!topic.closed, + isPinned: !!topic.pinned, + }; +} + +/** + * Serialize a gramjs Api.User to a MemberItem. + */ +export function serializeMember(user: Api.User): MemberItem { + return { + id: bigIntToString((user as any).id), + username: (user as any).username ?? null, + firstName: (user as any).firstName ?? null, + lastName: (user as any).lastName ?? null, + isBot: !!(user as any).bot, + status: (user as any).status?.className ?? null, + }; +} diff --git a/cli/src/lib/session-store.ts b/cli/src/lib/session-store.ts new file mode 100644 index 0000000..ce7d641 --- /dev/null +++ b/cli/src/lib/session-store.ts @@ -0,0 +1,125 @@ +import { lock } from 'proper-lockfile'; +import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, chmodSync, realpathSync } from 'node:fs'; +import { join, basename } from 'node:path'; + +const DIR_MODE = 0o700; +const FILE_MODE = 0o600; + +/** Register successful teardown that must finish before releasing ownership. */ +export type SessionHoldUntil = (cleanup: Promise<unknown>) => void; + +/** chmod after create: write/mkdir mode is still masked by umask. */ +function chmodPrivate(path: string, mode: number): void { + try { + chmodSync(path, mode); + } catch { + // Windows and some FS ignore POSIX modes + } +} + +/** + * Manages session persistence and exclusive ownership for each profile. + * Every reader, writer and connected client shares `<profile>.session.lock`, + * including when the session has not been created or was deleted under lock. + */ +export class SessionStore { + private readonly dir: string; + private readonly lockDir: string; + + constructor(configDir: string) { + const dir = join(configDir, 'sessions'); + mkdirSync(dir, { recursive: true, mode: DIR_MODE }); + chmodPrivate(dir, DIR_MODE); + // Resolve directory aliases without requiring a session file to exist. + this.dir = dir; + this.lockDir = realpathSync(dir); + } + + /** Acquire profile ownership. Release only after the connected client is destroyed. */ + async acquireLock(profile: string): Promise<() => Promise<void>> { + return lock(join(this.lockDir, `${basename(profile)}.session`), { + realpath: false, + retries: { retries: 3, minTimeout: 100 }, + }); + } + + /** Load a session while holding exclusive profile ownership. */ + async load(profile: string): Promise<string> { + return this.withLock(profile, async (session) => session); + } + + /** Persist a session while holding exclusive profile ownership. */ + async save(profile: string, sessionString: string): Promise<void> { + await this.withLock(profile, async () => this.saveUnlocked(profile, sessionString)); + } + + /** Delete a session before releasing profile ownership. */ + async delete(profile: string): Promise<void> { + await this.withLock(profile, async () => this.deleteUnlocked(profile)); + } + + /** Read without re-locking. Caller must already own the profile lock. */ + loadUnlocked(profile: string): string { + const file = this.filePath(profile); + if (!existsSync(file)) return ''; + chmodPrivate(file, FILE_MODE); + return readFileSync(file, 'utf-8').trim(); + } + + /** Save without re-locking. ONLY use inside withLock or after acquireLock. */ + saveUnlocked(profile: string, sessionString: string): void { + const file = this.filePath(profile); + writeFileSync(file, sessionString, { encoding: 'utf-8', mode: FILE_MODE }); + chmodPrivate(file, FILE_MODE); + } + + /** Delete without re-locking. ONLY use inside withLock or after acquireLock. */ + deleteUnlocked(profile: string): void { + const file = this.filePath(profile); + if (existsSync(file)) unlinkSync(file); + } + + /** + * Hold ownership for the callback, even for an absent session. A callback may + * register asynchronous teardown with holdUntil before returning. Its result + * still settles promptly, but ownership remains until every teardown succeeds. + * Rejected teardown keeps the lock until process exit: a failed cleanup does + * not prove the transport is closed. Cleanup rejections are always handled. + */ + async withLock<T>(profile: string, fn: (sessionString: string, holdUntil: SessionHoldUntil) => Promise<T>): Promise<T> { + const release = await this.acquireLock(profile); + const pending = new Set<Promise<void>>(); + let cleanupFailed = false; + let callbackDone = false; + const holdUntil: SessionHoldUntil = (cleanup) => { + if (callbackDone) throw new Error('Register session cleanup before the callback completes'); + // Attach the rejection handler immediately, including when a caller gives + // us an already rejected promise. The tracking promise never rejects. + const tracked = Promise.resolve(cleanup).then( + () => {}, + () => { cleanupFailed = true; }, + ).then(() => { pending.delete(tracked); }); + pending.add(tracked); + }; + try { + return await fn(this.loadUnlocked(profile), holdUntil); + } finally { + callbackDone = true; + if (pending.size === 0) { + if (!cleanupFailed) await release(); + } else { + // A timed-out operation can return while its SDK transport is still + // settling. Never release early and never create an unhandled rejection + // (or a second CLI output envelope) from background teardown/release. + void Promise.all(pending).then(async () => { + if (!cleanupFailed) await release(); + }).catch(() => {}); + } + } + } + + /** Get the file path for a profile's session file. */ + filePath(profile: string): string { + return join(this.dir, `${basename(profile)}.session`); + } +} diff --git a/cli/src/lib/toon.ts b/cli/src/lib/toon.ts new file mode 100644 index 0000000..ef1bbc4 --- /dev/null +++ b/cli/src/lib/toon.ts @@ -0,0 +1,16 @@ +import { encode } from '@toon-format/toon'; + +/** Fixed TOON encode options per project decisions. */ +const TOON_OPTIONS = { + indent: 2, + delimiter: '\t' as const, + keyFolding: 'safe' as const, +} as const; + +/** + * Encode any JSON-serializable value to TOON format. + * Uses tab delimiter and safe key folding for optimal token efficiency. + */ +export function encodeToon(value: unknown): string { + return encode(value, TOON_OPTIONS); +} diff --git a/cli/src/lib/transport-diagnostics.ts b/cli/src/lib/transport-diagnostics.ts new file mode 100644 index 0000000..f68427f --- /dev/null +++ b/cli/src/lib/transport-diagnostics.ts @@ -0,0 +1,87 @@ +import type { TelegramClient } from 'teleproto'; +import { Socket } from 'node:net'; +import type { Logger } from 'teleproto/extensions/Logger.js'; +import { ConnectionTCPFull } from 'teleproto/network/index.js'; +import { InvalidBufferError, InvalidChecksumError, TypeNotFoundError, SecurityError } from 'teleproto/errors/Common.js'; + +const NETWORK_CODES = new Set([ + 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', + 'EPIPE', 'ENOTFOUND', 'EAI_AGAIN', 'ERR_SOCKET_CLOSED', +]); + +/** Read data properties only; diagnostics must not invoke SDK object getters. */ +function ownValue(error: object, key: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(error, key); + return descriptor && 'value' in descriptor ? descriptor.value : undefined; +} + +/** Fixed labels and bounded codes only: never interpolate messages or payloads. */ +export function describeTransportError(error: unknown): string { + try { + if (!error || typeof error !== 'object') return 'UNKNOWN_ERROR'; + if (error instanceof InvalidBufferError) { + const code = ownValue(error, 'code'); + return typeof code === 'number' && Number.isInteger(code) && code >= 100 && code <= 599 + ? `INVALID_BUFFER (code=${code})` : 'INVALID_BUFFER'; + } + if (error instanceof InvalidChecksumError) return 'INVALID_CHECKSUM'; + if (error instanceof TypeNotFoundError) return 'UNKNOWN_CONSTRUCTOR'; + if (error instanceof SecurityError) return 'SECURITY_CHECK_FAILED'; + const code = ownValue(error, 'code'); + if (typeof code === 'string' && NETWORK_CODES.has(code)) return code; + const message = ownValue(error, 'message'); + if (message === 'Socket was closed' || message === 'No data received' || message === 'NetSocket was closed' || message === 'WebSocket was closed' || message === 'Not connected' || message === 'no data received') { + return 'CONNECTION_CLOSED'; + } + if (message === 'TIMEOUT' || message === 'Timeout') return 'TIMEOUT'; + } catch { /* Even unusual error objects must not break transport cleanup. */ } + return 'UNKNOWN_ERROR'; +} + +/** Capture the receive failure before gramjs replaces it with "Not connected". */ +export class DiagnosticTCPFull extends ConnectionTCPFull { + private socketFailure?: string; + + override async connect(): Promise<void> { + this.socketFailure = undefined; + try { + await super.connect(); + // gramjs can reduce a socket error to its generic closed-read error. + // Keep only the safe category, not the Error or its attached objects. + const socket = ownValue(this.socket, 'client'); + if (socket instanceof Socket) { + socket.once('error', error => { + if (ownValue(this.socket, 'client') === socket) { + this.socketFailure = describeTransportError(error); + } + }); + } + } + catch (error) { + this.log.error(`Transport connect failed: ${describeTransportError(error)}`); + throw error; + } + } + + override async recv(): Promise<Buffer> { + try { return await super.recv(); } + catch (error) { + // Intentional shutdown closes the socket after clearing this flag. + if (this.isConnected()) { + this.log.error(`Transport receive failed: ${this.socketFailure ?? describeTransportError(error)}`); + } + throw error; + } + } + + override toString(): string { + return `${this.ip}:${this.port}/TCPFull`; + } +} + +/** SDK errors outside the receive loop also get a safe stderr diagnostic. */ +export function installClientErrorDiagnostics(client: TelegramClient, logger: Logger): void { + client.onError = async error => { + logger.error(`Telegram client failed: ${describeTransportError(error)}`); + }; +} diff --git a/cli/src/lib/transport.ts b/cli/src/lib/transport.ts new file mode 100644 index 0000000..e65271a --- /dev/null +++ b/cli/src/lib/transport.ts @@ -0,0 +1,15 @@ +import type Conf from 'conf'; +import type { TgConfig, Transport } from './types.js'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** Validate transport names without reflecting arbitrary config values. */ +export function validateTransport(value: unknown): Transport { + if (value === 'tcp' || value === 'wss') return value; + throw new TgError('Transport must be tcp or wss', ErrorCode.INVALID_OPTIONS); +} + +/** Explicit CLI choice overrides the profile; existing profiles default to TCP. */ +export function resolveTransport(config: Conf<TgConfig>, profile: string, explicit?: Transport): Transport { + return validateTransport(explicit ?? config.get(`profiles.${profile}.transport`) ?? 'tcp'); +} diff --git a/cli/src/lib/types.ts b/cli/src/lib/types.ts new file mode 100644 index 0000000..ae2a199 --- /dev/null +++ b/cli/src/lib/types.ts @@ -0,0 +1,461 @@ +/** Telegram network transport; independent of the daemon's local Unix socket. */ +export type Transport = 'tcp' | 'wss'; + +/** + * Global CLI options available on all commands via optsWithGlobals(). + */ +export interface GlobalOptions { + json: boolean; + human: boolean; + verbose: boolean; + quiet: boolean; + profile: string; + config?: string; + fields?: string; + jsonl?: boolean; + toon?: boolean; + daemon?: boolean; + transport?: Transport; +} + +/** + * Stored metadata for a named profile. Session data lives in SessionStore. + */ +export interface ProfileData { + /** Legacy config metadata; never write session material into config. */ + session?: string; + phone?: string; + created?: string; + client?: string; + transport?: Transport; +} + +/** Failure associated with one input of a batch operation. */ +export interface BatchItemError { + input: string; + error: string; + code: string; +} + +/** Additive metadata for a batch that could not complete every input. */ +export interface PartialResultMetadata { + partial: boolean; + errors: BatchItemError[]; +} + +/** + * Configuration schema for the tg-cli config file. + */ +export interface TgConfig { + apiId?: number; + apiHash?: string; + profiles: Record<string, ProfileData>; +} + +/** + * JSON output envelope for successful responses. + */ +export interface SuccessEnvelope<T> { + ok: true; + data: T; +} + +/** + * JSON output envelope for error responses. + */ +export interface ErrorEnvelope { + ok: false; + error: string; + code?: string; +} + +/** + * Union type for all JSON output envelopes. + */ +export type OutputEnvelope<T> = SuccessEnvelope<T> | ErrorEnvelope; + +// ---- Phase 2: Chat Discovery & Message Reading types ---- + +/** + * Serialized chat/dialog item for list output. + */ +export interface ChatListItem { + id: string; + title: string; + type: 'user' | 'group' | 'channel' | 'supergroup'; + username: string | null; + unreadCount: number; +} + +/** + * Detailed chat information (kitchen sink per user decision). + */ +export interface ChatInfo { + id: string; + title: string; + type: string; + username: string | null; + description: string | null; + memberCount: number | null; + creationDate: string | null; + photo: { hasPhoto: boolean } | null; + linkedChatId: string | null; + slowmodeSeconds: number | null; + permissions: Record<string, boolean> | null; + inviteLink: string | null; + migratedFrom: string | null; +} + +/** + * Serialized group/channel member. + */ +export interface MemberItem { + id: string; + username: string | null; + firstName: string | null; + lastName: string | null; + isBot: boolean; + status: string | null; +} + +/** + * Serialized message for history and search output. + */ +export interface MessageItem { + id: number; + text: string; + date: string; + senderId: string | null; + senderName: string | null; + replyToMsgId: number | null; + forwardFrom: string | null; + mediaType: string | null; + type: 'message' | 'service'; + views?: number | null; + forwards?: number | null; + reactions?: ReactionCount[]; + actionText?: string; + emoji?: string; + media?: MediaInfo; // Only present when mediaType is not null + editDate?: string; // ISO string when message has been edited + poll?: PollData; // Present when message contains a poll +} + +/** Reaction count for a message. */ +export interface ReactionCount { + emoji: string; + count: number; +} + +/** + * Search result extends MessageItem with chat context for global search. + */ +export interface SearchResultItem extends MessageItem { + chatId: string; + chatTitle: string; +} + +/** Pagination + quota for `tg message search --public`. */ +export interface PublicPostSearchFlood { + remains: number | null; + totalDaily: number | null; + waitTill: number | null; + starsAmount: string | null; + queryIsFree: boolean; +} + +export interface PublicPostSearchResult { + messages: SearchResultItem[]; + total: number; + hasMore: boolean; + nextRate: number | null; + nextOffsetId: number | null; + nextOffsetPeer: string | null; + flood?: PublicPostSearchFlood; +} + +/** + * Options for the chat list command. + */ +export interface ChatListOptions { + type?: 'user' | 'group' | 'channel' | 'supergroup'; + limit: number; + offset: number; +} + +/** + * Options for the chat info command. + */ +export interface ChatInfoOptions { + chat: string; +} + +/** + * Options for the chat members command. + */ +export interface ChatMembersOptions { + chat: string; + limit: number; + offset: number; + search?: string; +} + +/** + * Options for the message history command. + */ +export interface MessageHistoryOptions { + chat: string; + limit: number; + offset: number; + since?: string; + until?: string; +} + +/** + * Options for the message search command. + */ +export interface MessageSearchOptions { + query?: string; // Now optional (required when no --filter) + filter?: string; + chat?: string; + limit: number; + offset: number; + since?: string; + until?: string; +} + +// ---- Phase 4: Media & Files types ---- + +/** Metadata extracted from a message's media attachment. */ +export interface MediaInfo { + filename: string | null; + fileSize: number | null; + mimeType: string | null; + width: number | null; + height: number | null; + duration: number | null; +} + +/** Result of downloading a single media file. */ +export interface DownloadResult { + path: string; + filename: string; + size: number; + mediaType: string; + messageId: number; +} + +/** Result of uploading/sending a single file. */ +export interface UploadResult extends MessageItem {} + +/** Result of sending an album (multiple files). */ +export interface AlbumResult { + messages: MessageItem[]; + sent: number; +} + +/** Options for the media download command. */ +export interface MediaDownloadOptions { + chat: string; + messageIds: number[]; + output?: string; +} + +/** Options for the media send command. */ +export interface MediaSendOptions { + chat: string; + files: string[]; + caption?: string; + replyTo?: number; +} + +// ---- Phase 5: Advanced Features types ---- + +/** + * Serialized forum topic item for topic listing output. + */ +export interface TopicItem { + id: number; + title: string; + iconEmoji: string | null; + creationDate: string; + creatorId: string; + /** Latest message id in the topic (gramjs topMessage). */ + topMessageId: number; + isClosed: boolean; + isPinned: boolean; +} + +/** + * Options for the chat topics command. + */ +export interface TopicListOptions { + chat: string; + limit: number; + offset: number; +} + +// ---- Phase 3: Messaging & Interaction types ---- + +export interface SendOptions { + chat: string; + text: string; + replyTo?: number; +} + +export interface ForwardOptions { + fromChat: string; + messageIds: number[]; + toChat: string; +} + +export interface ReactOptions { + chat: string; + messageId: number; + emoji: string; + remove: boolean; +} + +// ---- Phase 7: Message Write Operations types ---- + +/** Result of deleting messages. */ +export interface DeleteResult { + deleted: number[]; + failed: { id: number; reason: string }[]; + mode: 'revoke' | 'for-me'; +} + +/** Result of pinning or unpinning a message. */ +export interface PinResult { + messageId: number; + chatId: string; + action: 'pinned' | 'unpinned'; + silent?: boolean; +} + +// ---- Phase 8: User Profiles & Block/Unblock types ---- + +/** Detailed user profile information. */ +export interface UserProfile { + id: string; + firstName: string | null; + lastName: string | null; + username: string | null; + phone: string | null | '[restricted]'; + bio: string | null; + photoCount: number | null; + lastSeen: string | null; + isBot: boolean; + blocked: boolean; + commonChatsCount: number; + premium: boolean; + verified: boolean; + mutualContact: boolean; + langCode: string | null; + /** Bot-only: inline query placeholder text. */ + botInlinePlaceholder?: string; + /** Bot-only: whether the bot supports inline queries. */ + supportsInline?: boolean; +} + +/** Result of a multi-user profile lookup. */ +export interface UserProfileResult extends Partial<PartialResultMetadata> { + profiles: UserProfile[]; + notFound: string[]; +} + +/** Result of blocking or unblocking a user. */ +export interface BlockResult { + userId: string; + username: string | null; + firstName: string | null; + action: 'blocked' | 'unblocked'; +} + +/** Summary of a blocked user for list output. */ +export interface BlockedListItem { + id: string; + firstName: string | null; + lastName: string | null; + username: string | null; + isBot: boolean; +} + +/** Result of listing blocked users. */ +export interface BlockedListResult { + users: BlockedListItem[]; + total: number; +} + +// ---- Phase 10: Polls types ---- + +/** Single poll option with vote data. */ +export interface PollOption { + text: string; + voters: number; + chosen: boolean; + correct: boolean; +} + +/** Structured poll data extracted from MessageMediaPoll. */ +export interface PollData { + question: string; + options: PollOption[]; + isQuiz: boolean; + isPublic: boolean; + isMultiple: boolean; + isClosed: boolean; + closePeriod: number | null; + closeDate: string | null; + totalVoters: number; + correctOption: number | null; + solution: string | null; +} + +// ---- Phase 9: Contacts CRUD types ---- + +/** Result of deleting a contact. */ +export interface ContactDeleteResult { + userId: string; + username: string | null; + firstName: string | null; + action: 'deleted'; +} + +/** Result of listing contacts. */ +export interface ContactListResult extends Partial<PartialResultMetadata> { + contacts: UserProfile[]; + total: number; +} + +/** A search result item with contact status. */ +export interface ContactSearchItem extends UserProfile { + isContact: boolean; +} + +/** Result of searching contacts. */ +export interface ContactSearchResult extends Partial<PartialResultMetadata> { + results: ContactSearchItem[]; + total: number; +} + +/** Result of setting an account-local personal contact photo. */ +export interface ContactPhotoResult { + userId: string; + photoId: string; + personal: true; + size: number; +} + +/** Result of downloading the currently visible profile photo. */ +export interface UserPhotoDownloadResult { + userId: string; + path: string; + size: number; + profilePhoto: true; +} + +/** Scheduled send acknowledgement; scheduledAt is the requested delivery time. */ +export interface ScheduledMessageResult extends MessageItem { + scheduledAt: string; +} diff --git a/cli/src/lib/user-profile.ts b/cli/src/lib/user-profile.ts new file mode 100644 index 0000000..5731a16 --- /dev/null +++ b/cli/src/lib/user-profile.ts @@ -0,0 +1,103 @@ +import { Api } from 'teleproto'; +import { bigIntToString } from './serialize.js'; +import type { UserProfile } from './types.js'; + +/** + * Map a gramjs user status object to a lastSeen string. + * + * Returns: + * - "online" for UserStatusOnline + * - ISO timestamp for UserStatusOffline (from wasOnline) + * - "recently" for UserStatusRecently + * - "within_week" for UserStatusLastWeek + * - "within_month" for UserStatusLastMonth + * - "long_time_ago" for UserStatusEmpty + * - null for unknown/missing status + */ +export function mapUserStatus(status: any): string | null { + if (!status || !status.className) return null; + + switch (status.className) { + case 'UserStatusOnline': + return 'online'; + case 'UserStatusOffline': + return status.wasOnline != null + ? new Date(status.wasOnline * 1000).toISOString() + : null; + case 'UserStatusRecently': + return 'recently'; + case 'UserStatusLastWeek': + return 'within_week'; + case 'UserStatusLastMonth': + return 'within_month'; + case 'UserStatusEmpty': + return 'long_time_ago'; + default: + return null; + } +} + +/** + * Build a full UserProfile from a GetFullUser result. + * + * Fetches photo count, maps user status, and assembles all UserProfile fields + * including bot-specific fields when applicable. + */ +export async function buildUserProfile( + client: any, + user: Api.User, + fullUser: any, + userFromResult: Api.User, + onPhotoError?: (err: unknown) => void, +): Promise<UserProfile> { + // Fetch photo count + let photoCount: number | null = null; + try { + const photosResult = await client.invoke( + new Api.photos.GetUserPhotos({ + userId: user, + offset: 0, + maxId: BigInt(0) as any, + limit: 1, + }), + ); + photoCount = (photosResult as any).count + ?? (photosResult as any).photos?.length + ?? 0; + } catch (err: unknown) { + // The presence of a profile picture does not reveal the photo count. + onPhotoError?.(err); + } + + const isBot = !!userFromResult.bot; + const lastSeen = isBot ? null : mapUserStatus(userFromResult.status); + const phone = userFromResult.phone ?? (isBot ? null : '[restricted]'); + + const profileData: UserProfile = { + id: bigIntToString(userFromResult.id), + firstName: userFromResult.firstName ?? null, + lastName: userFromResult.lastName ?? null, + username: userFromResult.username ?? null, + phone, + bio: fullUser.about ?? null, + photoCount, + lastSeen, + isBot, + blocked: !!fullUser.blocked, + commonChatsCount: fullUser.commonChatsCount ?? 0, + premium: !!userFromResult.premium, + verified: !!userFromResult.verified, + mutualContact: !!userFromResult.mutualContact, + langCode: userFromResult.langCode ?? null, + }; + + // Bot-specific fields + if (isBot) { + profileData.botInlinePlaceholder = + userFromResult.botInlinePlaceholder ?? undefined; + profileData.supportsInline = + !!userFromResult.botInlinePlaceholder; + } + + return profileData; +} diff --git a/cli/src/lib/validate.ts b/cli/src/lib/validate.ts new file mode 100644 index 0000000..2dd6d99 --- /dev/null +++ b/cli/src/lib/validate.ts @@ -0,0 +1,134 @@ +import { z } from 'zod/v4'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +/** Largest positive signed TL int (message IDs, offsets, and counts). */ +export const MAX_TL_INT = 2_147_483_647; + +/** Parse a decimal CLI integer without truncation, coercion, or overflow. */ +export function parseIntegerOption( + input: string, + label: string, + options: { min?: number; max?: number; code?: string } = {}, +): number { + const { min = 0, max = MAX_TL_INT, code = ErrorCode.INVALID_INPUT } = options; + const trimmed = input.trim(); + const value = Number(trimmed); + if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(value) || value < min || value > max) { + throw new TgError(`${label} must be an integer from ${min} to ${max}`, code); + } + return value; +} + +const profileSchema = z.string() + .min(1, 'Profile name cannot be empty') + .max(64, 'Profile name too long (max 64)') + .regex(/^[a-zA-Z0-9_-]+$/, 'Profile name: only letters, digits, _ and -'); + +/** + * Validate and return a sanitized profile name. + * Rejects path traversal, special chars, and empty strings. + * + * @throws TgError with INVALID_INPUT + */ +export function validateProfile(profile: string): string { + const result = profileSchema.safeParse(profile); + if (!result.success) { + throw new TgError(result.error.issues[0].message, ErrorCode.INVALID_INPUT); + } + return result.data; +} + +/** Normalize readable international phone numbers without echoing input errors. */ +export function validatePhone(input: string): string { + const phone = input.trim().replace(/[\s()-]/g, ''); + if (!/^\+[1-9]\d{6,14}$/.test(phone)) { + throw new TgError('Phone number must start with + and contain 7–15 digits including the country code', ErrorCode.INVALID_INPUT); + } + return phone; +} + +/** + * Validate and parse pagination options with defaults. + * + * @throws TgError with INVALID_INPUT + */ +export function validatePagination( + opts: { limit?: string; offset?: string }, + defaultLimit = 50, +): { limit: number; offset: number } { + try { + return { + limit: parseIntegerOption(opts.limit ?? String(defaultLimit), 'limit', { min: 1 }), + offset: parseIntegerOption(opts.offset ?? '0', 'offset'), + }; + } catch (err) { + throw new TgError(`Invalid pagination: ${(err as Error).message}`, ErrorCode.INVALID_INPUT); + } +} + +/** + * Parse comma-separated message IDs: digits only, each > 0, max `max` entries. + * + * @throws TgError INVALID_MESSAGE_ID or TOO_MANY_IDS + */ +export function parseMessageIds(input: string, max = 100): number[] { + const parts = input.split(',').map((s) => s.trim()).filter((s) => s.length > 0); + if (parts.length === 0) { + throw new TgError('No message IDs provided', ErrorCode.INVALID_MESSAGE_ID); + } + + const ids: number[] = []; + const invalid: string[] = []; + for (const part of parts) { + if (!/^\d+$/.test(part)) { + invalid.push(part); + continue; + } + const num = parseInt(part, 10); + if (!Number.isSafeInteger(num) || num <= 0 || num > MAX_TL_INT) invalid.push(part); + else ids.push(num); + } + + if (invalid.length > 0) { + throw new TgError(`Invalid message IDs: ${invalid.join(', ')}`, ErrorCode.INVALID_MESSAGE_ID); + } + if (ids.length > max) { + throw new TgError( + `Maximum ${max} IDs per request (got ${ids.length})`, + ErrorCode.TOO_MANY_IDS, + ); + } + return ids; +} + +/** Parse a single positive message ID. */ +export function parseMessageId(input: string): number { + try { + return parseIntegerOption(input, 'Message ID', { min: 1, code: ErrorCode.INVALID_MESSAGE_ID }); + } catch { + throw new TgError(`Invalid message ID: expected an integer from 1 to ${MAX_TL_INT}`, ErrorCode.INVALID_MESSAGE_ID); + } +} + +/** Parse a forum topic id. Rejects `12x` (no parseInt truncation). */ +export function parseTopicId(input: string): number { + const trimmed = input.trim(); + if (!/^\d+$/.test(trimmed)) { + throw new TgError('Invalid topic ID: must be a number', ErrorCode.INVALID_TOPIC_ID); + } + const n = Number.parseInt(trimmed, 10); + if (!Number.isSafeInteger(n) || n <= 0 || n > MAX_TL_INT) { + throw new TgError('Invalid topic ID: must be a number', ErrorCode.INVALID_TOPIC_ID); + } + return n; +} + +/** Parse an ISO 8601 (or Date.parse-able) timestamp. */ +export function parseIsoDate(value: string, label: string): Date { + const ms = Date.parse(value); + if (Number.isNaN(ms)) { + throw new TgError(`Invalid ${label}: must be ISO 8601`, ErrorCode.INVALID_INPUT); + } + return new Date(ms); +} diff --git a/cli/src/lib/with-auth.ts b/cli/src/lib/with-auth.ts new file mode 100644 index 0000000..aad615b --- /dev/null +++ b/cli/src/lib/with-auth.ts @@ -0,0 +1,137 @@ +import type { TelegramClient } from 'teleproto'; +import { createConfig, getCredentialsOrThrow } from './config.js'; +import type { Transport } from './types.js'; +import { resolveTransport } from './transport.js'; +import { withClient } from './client.js'; +import { SessionStore } from './session-store.js'; +import { outputError, logVerbose } from './output.js'; +import { isVerboseMode } from './cli-mode.js'; +import { formatError, translateTelegramError, TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; +import { validateProfile } from './validate.js'; +import { DaemonPaths } from './daemon/pid.js'; +import { DaemonClient } from './daemon/client.js'; +import { blockIfDaemonRunning, cleanupStaleDaemon, daemonPidAlive, rejectDaemonProxy } from './daemon/guard.js'; +import { getDaemonContext } from './daemon/execution-context.js'; + +/** + * Minimal options required by withAuth. + * Compatible with GlobalOptions but doesn't force the full interface. + */ +export interface WithAuthOptions { + profile: string; + config?: string; + daemon?: boolean; + transport?: Transport; +} + +/** + * Execute an authenticated Telegram operation with full boilerplate: + * config → session store → lock → auth check → credentials → client → callback. + * + * Most authenticated commands. Excluded: auth/{login,logout,status}, + * session/{export,import}, daemon/*, message/watch, completion. + * + * @param opts - Must include `profile` and optional `config` + * @param fn - Receives a connected TelegramClient + */ +export async function withAuth( + opts: WithAuthOptions, + fn: (client: TelegramClient) => Promise<void>, +): Promise<void> { + const context = getDaemonContext(); + if (context) { + try { + validateProfile(opts.profile); + if (opts.profile !== context.profile) { + throw new TgError('Command profile does not match the daemon profile', ErrorCode.INVALID_OPTIONS); + } + context.signal.throwIfAborted(); + await fn(context.client); + context.signal.throwIfAborted(); + } catch (err: unknown) { + const { message, code } = translateTelegramError(err); + outputError(message, code); + } + return; + } + + try { + validateProfile(opts.profile); + } catch (err: unknown) { + const { message, code } = formatError(err); + outputError(message, code); + return; + } + + const config = createConfig(opts.config); + const configDir = config.path.replace(/[/\\][^/\\]+$/, ''); + const paths = new DaemonPaths(configDir, opts.profile); + + // CLI command routing happens before its action. An arbitrary library callback + // cannot be serialized: reject it rather than opening a second MTProto client. + if (opts.daemon) { + + if (paths.socketExists()) { + try { + const daemon = new DaemonClient(paths.socketPath); + const pong = await daemon.call('ping', {}); + daemon.close(); + if (pong === 'pong') { + rejectDaemonProxy({ daemon: true }); + return; + } + } catch { + if (!cleanupStaleDaemon(paths)) { + outputError( + 'Daemon is not responding. Try: tg daemon stop && tg daemon start', + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + return; + } + } + } + + if (daemonPidAlive(paths)) { + outputError( + 'Daemon is not responding. Try: tg daemon stop && tg daemon start', + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + return; + } + + outputError('Daemon is not running. Start one with: tg daemon start', ErrorCode.DAEMON_NOT_RUNNING); + return; + } + + if (await blockIfDaemonRunning(paths)) return; + + // Direct connection (current behavior) + const store = new SessionStore(configDir); + + try { + await store.withLock(opts.profile, async (sessionString, holdUntil) => { + if (!sessionString) { + outputError('Not logged in. Run: tg auth login', ErrorCode.NOT_AUTHENTICATED); + return; + } + + const { apiId, apiHash } = await getCredentialsOrThrow(config, undefined, opts.profile); + + await withClient({ apiId, apiHash, sessionString, transport: resolveTransport(config, opts.profile, opts.transport) }, async (client) => { + await fn(client); + }, { holdUntil }); + }); + } catch (err: unknown) { + if (isVerboseMode()) { + const raw = err instanceof Error + ? (err.stack ?? err.message) + : typeof err === 'object' && err && 'errorMessage' in err + ? String((err as { errorMessage: unknown }).errorMessage) + : String(err); + logVerbose(raw); + } + const { message, code } = translateTelegramError(err); + outputError(message, code); + } +} diff --git a/cli/src/lib/wss.ts b/cli/src/lib/wss.ts new file mode 100644 index 0000000..ebae616 --- /dev/null +++ b/cli/src/lib/wss.ts @@ -0,0 +1,115 @@ +import WebSocket from 'ws'; +import { ConnectionTCPObfuscated } from 'teleproto/network/index.js'; +import { PromisedWebSockets } from 'teleproto/extensions/PromisedWebSockets.js'; +import { describeTransportError } from './transport-diagnostics.js'; +import { TgError } from './errors.js'; +import { ErrorCode } from './error-codes.js'; + +// Node 20 has no built-in WebSocket; keep the documented Node floor. +class NodeWebSocket extends PromisedWebSockets { + static override webSocketImpl = WebSocket as unknown as typeof PromisedWebSockets.webSocketImpl; +} + +const DC_NAMES = ['pluto', 'venus', 'aurora', 'vesta', 'flora'] as const; + +/** Official Telegram WSS endpoints require a hostname for TLS and routing. */ +export function wssHost(dcId: number): string { + const media = dcId < 0; + dcId = Math.abs(dcId); + if (!Number.isInteger(dcId) || dcId < 1 || dcId > DC_NAMES.length) { + throw new TgError('This Telegram data center does not support the WSS transport', ErrorCode.CONNECTION_FAILED); + } + return `${DC_NAMES[dcId - 1]}${media ? '-1' : ''}.web.telegram.org`; +} + +/** Bound TLS/upgrade waits and cancel an upgrade when the client is destroyed. */ +export class WssSocket extends PromisedWebSockets { + constructor(options?: number | ConstructorParameters<typeof PromisedWebSockets>[0]) { + super(); + if (options && typeof options !== 'number') throw new TgError('WSS transport does not support an explicit proxy', ErrorCode.INVALID_OPTIONS); + } + + override get lastDataAt(): number { return this.current?.lastDataAt ?? 0; } + + private current?: PromisedWebSockets; + private cancelConnect?: () => void; + private generation = 0; + + override async connect(port: number, ip: string, testServers = false): Promise<void> { + const closing = this.close(); + const generation = this.generation; + await closing; + if (generation !== this.generation) throw new Error('WebSocket was closed'); + // The SDK's close/message handlers mutate their socket wrapper. Isolate + // each attempt so a late callback cannot mark a new connection as closed. + const socket = new NodeWebSocket(); + this.current = socket; + let timer: ReturnType<typeof setTimeout> | undefined; + const interrupted = new Promise<never>((_resolve, reject) => { + this.cancelConnect = () => reject(new Error('WebSocket was closed')); + timer = setTimeout(() => reject(new Error('TIMEOUT')), 10_000); + }); + try { + return await Promise.race([socket.connect(port, ip, testServers), interrupted]); + } catch (error) { + await socket.close().catch(() => {}); + throw error; + } finally { + clearTimeout(timer); + if (this.current === socket) this.cancelConnect = undefined; + } + } + + override async close(): Promise<void> { + this.generation++; + this.cancelConnect?.(); + await this.current?.close(); + } + + private activeSocket(): PromisedWebSockets { + if (!this.current) throw new Error('WebSocket was closed'); + return this.current; + } + + override readExactly(length: number): Promise<Buffer> { return this.activeSocket().readExactly(length); } + override read(length: number): Promise<Buffer> { return this.activeSocket().read(length); } + override readAll(): Promise<Buffer> { return this.activeSocket().readAll(); } + override write(data: Buffer): void { this.activeSocket().write(data); } +} + +/** Map every connection by DC, including migration and borrowed media senders. */ +export class DiagnosticWSS extends ConnectionTCPObfuscated { + constructor(params: ConstructorParameters<typeof ConnectionTCPObfuscated>[0]) { + if ('proxy' in params && params.proxy) { + throw new TgError('WSS transport does not support an explicit proxy', ErrorCode.INVALID_OPTIONS); + } + super({ ...params, ip: wssHost(params.dcId), port: 443, socket: WssSocket }); + } + + override async connect(): Promise<void> { + try { await super.connect(); } + catch (error) { + this.log.error(`Transport connect failed: ${describeTransportError(error)}`); + await this.socket.close().catch(() => {}); + throw error; + } + } + + override async recv(): Promise<Buffer> { + try { return await super.recv(); } + catch (error) { + if (this.isConnected()) this.log.error(`Transport receive failed: ${describeTransportError(error)}`); + throw error; + } + } + + override async disconnect(): Promise<void> { + // gramjs's base implementation skips an in-progress TLS/WS connection. + try { await super.disconnect(); } + finally { await this.socket.close(); } + } + + override toString(): string { + return `${this.ip}:443/WSS`; + } +} diff --git a/cli/tests/fixtures/daemon-api-telegram.ts b/cli/tests/fixtures/daemon-api-telegram.ts new file mode 100644 index 0000000..ff621a1 --- /dev/null +++ b/cli/tests/fixtures/daemon-api-telegram.ts @@ -0,0 +1,97 @@ +import { appendFileSync } from 'node:fs'; +import bigInt from 'big-integer'; +import { Api } from 'teleproto/tl/api.js'; + +export { Api }; + +/** Only the MTProto boundary is fake; commands, IPC, output and process lifetime are real. */ +function record(event: string, details: Record<string, unknown> = {}): void { + const path = process.env.TG_DAEMON_API_TEST_JOURNAL; + if (!path) throw new Error('Offline daemon fixture requires its isolated journal'); + appendFileSync(path, JSON.stringify({ event, pid: process.pid, ...details }) + '\n'); +} + +export const sessions = { + StringSession: class { + constructor(private readonly value: string) {} + save(): string { return this.value; } + }, +}; + +const me = new Api.User({ + id: bigInt(7), accessHash: bigInt(20), self: true, + firstName: 'Offline', lastName: 'Fixture', username: 'fixture', +}); +const forum = new Api.Channel({ + id: bigInt(1234567890), accessHash: bigInt(10), title: 'Offline forum', + photo: new Api.ChatPhotoEmpty(), date: 1_700_000_000, + megagroup: true, forum: true, +}); + +function message(id: number, text: string, entity: Api.User | Api.Channel = me): Api.Message { + const result = new Api.Message({ + id, date: 1_700_000_000 + id, message: text, + peerId: entity instanceof Api.Channel + ? new Api.PeerChannel({ channelId: entity.id }) + : new Api.PeerUser({ userId: entity.id }), + fromId: new Api.PeerUser({ userId: me.id }), + }); + (result as any)._sender = me; + return result; +} + +export class TelegramClient { + private readonly handlers = new Set<(event: { message: Api.Message }) => void>(); + private readonly messages = [message(30, 'seed newest'), message(20, 'seed middle'), message(10, 'seed oldest')]; + private nextId = 100; + + constructor(..._args: unknown[]) { record('constructor'); } + async connect(): Promise<void> { record('connect'); } + async destroy(): Promise<void> { record('destroy'); } + + async getEntity(input: string | number): Promise<Api.User | Api.Channel> { + record('getEntity', { input }); + if (['me', 'fixture', '7'].includes(String(input))) return me; + if (['forum', '-1001234567890'].includes(String(input))) return forum; + throw Object.assign(new Error('No such offline fixture peer'), { errorMessage: 'USERNAME_NOT_OCCUPIED' }); + } + + async getDialogs(options: { limit: number }): Promise<unknown[]> { + record('getDialogs'); + const dialogs = [ + { id: me.id, title: 'Saved Messages', isUser: true, entity: me, unreadCount: 0 }, + { id: bigInt('-1001234567890'), title: forum.title, isChannel: true, entity: forum, unreadCount: 2 }, + ]; + return Object.assign(dialogs.slice(0, options.limit), { total: dialogs.length }); + } + + async getMessages(_entity: unknown, options: { limit: number; addOffset?: number }): Promise<Api.Message[]> { + record('getMessages'); + const offset = options.addOffset ?? 0; + return Object.assign(this.messages.slice(offset, offset + options.limit), { total: this.messages.length }); + } + + async sendMessage(entity: Api.User | Api.Channel, options: { message: string }): Promise<Api.Message> { + record('sendMessage:start', { text: options.message }); + if (options.message.startsWith('fixture:slow')) await new Promise((resolve) => setTimeout(resolve, 150)); + if (options.message === 'fixture:fail') { + record('sendMessage:failure'); + throw Object.assign(new Error('Offline chat is read-only'), { errorMessage: 'CHAT_WRITE_FORBIDDEN' }); + } + const sent = message(this.nextId++, options.message, entity); + this.messages.unshift(sent); + for (const handler of this.handlers) handler({ message: sent }); + record('sendMessage:done', { id: sent.id }); + return sent; + } + + addEventHandler(handler: (event: { message: Api.Message }) => void, _builder: unknown): void { + this.handlers.add(handler); + record('subscribe'); + } + + removeEventHandler(handler: (event: { message: Api.Message }) => void, _builder: unknown): void { + this.handlers.delete(handler); + record('unsubscribe'); + } +} diff --git a/cli/tests/fixtures/daemon-telegram.ts b/cli/tests/fixtures/daemon-telegram.ts new file mode 100644 index 0000000..0b99e19 --- /dev/null +++ b/cli/tests/fixtures/daemon-telegram.ts @@ -0,0 +1,28 @@ +/** Offline transport for the multi-process ownership regression suite. */ +export { Api } from 'teleproto/tl/api.js'; + +export const sessions = { + StringSession: class StringSession { + constructor(private readonly value: string) {} + save(): string { return this.value || 'synthetic-new-session'; } + }, +}; + +export class TelegramClient { + connected = false; + private destroyCount = 0; + constructor(readonly session: { save(): string }) {} + async connect(): Promise<void> { + await (globalThis as any).ownershipBarrier('connecting'); + this.connected = true; + process.send?.({ event: 'connected' }); + } + async start(): Promise<void> { if (!this.connected) await this.connect(); } + async checkAuthorization(): Promise<boolean> { return true; } + async destroy(): Promise<void> { + this.connected = false; + const suffix = (globalThis as any).ownershipTimeoutRole ? `-${++this.destroyCount}` : ''; + await (globalThis as any).ownershipBarrier(`destroying${suffix}`); + process.send?.({ event: `destroyed${suffix}` }); + } +} diff --git a/cli/tests/fixtures/session-ownership.ts b/cli/tests/fixtures/session-ownership.ts new file mode 100644 index 0000000..c3d947c --- /dev/null +++ b/cli/tests/fixtures/session-ownership.ts @@ -0,0 +1,100 @@ +import { SessionStore } from '../../src/lib/session-store.js'; +import { withAuth } from '../../src/lib/with-auth.js'; +import { daemonStartAction } from '../../src/commands/daemon/start.js'; +import { importAction } from '../../src/commands/session/import.js'; +import { loginAction } from '../../src/commands/auth/login.js'; +import { join } from 'node:path'; + +const [role, configDir, profile = 'test'] = process.argv.slice(2); +const messages: string[] = []; +const listeners = new Map<string, () => void>(); +process.on('message', (message: unknown) => { + const command = String(message); + const listener = listeners.get(command); + if (listener) { listeners.delete(command); listener(); } + else messages.push(command); +}); +function receive(command: string): Promise<void> { + const index = messages.indexOf(command); + if (index !== -1) { messages.splice(index, 1); return Promise.resolve(); } + return new Promise((resolve) => listeners.set(command, resolve)); +} +(globalThis as any).ownershipBarrier = async (event: string) => { + process.send?.({ event }); + await receive(event); +}; +const config = join(configDir, 'config.json'); +const opts = { profile, quiet: true, json: true, config }; +const context = { optsWithGlobals: () => ({ ...opts, foreground: true, idleTimeout: '0' }) } as any; + +async function main() { + process.send?.({ event: 'ready' }); + await receive('run'); + if (role === 'direct-timeout') { + (globalThis as any).ownershipTimeoutRole = true; + // Exercise the production withAuth timeout path without spending 120s. + // Session heartbeat/retry timers retain their real durations. + const originalTimeout = globalThis.setTimeout; + globalThis.setTimeout = ((callback: any, ms?: number, ...args: any[]) => + originalTimeout(callback, ms === 120_000 ? 30 : ms, ...args)) as typeof setTimeout; + } + if (role === 'direct-race') { + const acquire = SessionStore.prototype.acquireLock; + SessionStore.prototype.acquireLock = async function (...args) { + await (globalThis as any).ownershipBarrier('before-lock'); + return acquire.apply(this, args); + }; + } + if (role.startsWith('direct')) { + await withAuth(opts, async () => { + await (globalThis as any).ownershipBarrier('operation'); + }); + if (role === 'direct-timeout') { + process.send?.({ event: 'timed-out' }); + await receive('finish'); + } + } else if (role === 'foreground') { + await daemonStartAction.call(context); + } else if (role === 'background') { + process.env.TG_DAEMON_CONFIG_DIR = configDir; + process.env.TG_DAEMON_PROFILE = profile; + process.env.TG_DAEMON_CONFIG = config; + process.env.TG_DAEMON_IDLE_TIMEOUT = '0'; + process.env.TG_DAEMON_PID_PRECLAIMED = '1'; + await import('../../src/lib/daemon/entry.js'); + return; + } else if (role === 'import') { + await importAction.call(context, 'synthetic-imported-session'); + } else if (role === 'login') { + Object.defineProperty(process.stdin, 'isTTY', { value: true }); + await loginAction.call({ optsWithGlobals: () => ({ ...context.optsWithGlobals(), phone: '+10000000000' }) } as any); + } else if (role === 'probe') { + const store = new SessionStore(configDir); + try { + await store.withLock(profile, async () => { process.send?.({ event: 'acquired' }); }); + } catch (err) { + process.send?.({ event: 'blocked', code: (err as any).code }); + } + } else if (role === 'delete-recreate') { + const store = new SessionStore(configDir); + await store.withLock(profile, async () => { + store.deleteUnlocked(profile); + await (globalThis as any).ownershipBarrier('deleted'); + store.saveUnlocked(profile, 'synthetic-recreated-session'); + await (globalThis as any).ownershipBarrier('saved'); + }); + } else if (role === 'hold-reject') { + await new SessionStore(configDir).withLock(profile, async (_session, holdUntil) => { + holdUntil(Promise.reject(new Error('Synthetic cleanup failure'))); + }); + process.send?.({ event: 'cleanup-rejected' }); + await receive('finish'); + } + process.send?.({ event: 'done' }); + process.disconnect(); +} +main().catch((err) => { + process.send?.({ event: 'failed', message: err.message, code: err.code }); + process.exitCode = 1; + process.disconnect(); +}); diff --git a/cli/tests/fixtures/toon-benchmark/chat-list-50.json b/cli/tests/fixtures/toon-benchmark/chat-list-50.json new file mode 100644 index 0000000..80f6dd7 --- /dev/null +++ b/cli/tests/fixtures/toon-benchmark/chat-list-50.json @@ -0,0 +1,390 @@ +{ + "chats": [ + { + "id": "200000", + "title": "Alice Johnson", + "type": "user", + "username": null, + "unreadCount": 0 + }, + { + "id": "200001", + "title": "Bob Williams", + "type": "user", + "username": "bob_williams1", + "unreadCount": 7 + }, + { + "id": "200002", + "title": "Charlie Brown", + "type": "user", + "username": "charlie_brown2", + "unreadCount": 0 + }, + { + "id": "200003", + "title": "Diana Prince", + "type": "user", + "username": null, + "unreadCount": 3 + }, + { + "id": "200004", + "title": "QA and Testing", + "type": "group", + "username": null, + "unreadCount": 3 + }, + { + "id": "200005", + "title": "DevOps Guild", + "type": "group", + "username": null, + "unreadCount": 90 + }, + { + "id": "200006", + "title": "Data Science Hub", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200007", + "title": "Open Source Weekly", + "type": "channel", + "username": "open_source_weekly", + "unreadCount": 57 + }, + { + "id": "200008", + "title": "Product Hunt", + "type": "channel", + "username": "product_hunt", + "unreadCount": 0 + }, + { + "id": "200009", + "title": "Dev Community", + "type": "channel", + "username": "dev_community", + "unreadCount": 0 + }, + { + "id": "200010", + "title": "Go Programmers", + "type": "supergroup", + "username": "go_programmers", + "unreadCount": 0 + }, + { + "id": "200011", + "title": "TypeScript Fans", + "type": "supergroup", + "username": "typescript_fans", + "unreadCount": 0 + }, + { + "id": "200012", + "title": "Mia Thompson", + "type": "user", + "username": "mia_thompson12", + "unreadCount": 0 + }, + { + "id": "200013", + "title": "Noah Garcia", + "type": "user", + "username": null, + "unreadCount": 0 + }, + { + "id": "200014", + "title": "Olivia Robinson", + "type": "user", + "username": "olivia_robinson14", + "unreadCount": 0 + }, + { + "id": "200015", + "title": "Alice Johnson", + "type": "user", + "username": null, + "unreadCount": 7 + }, + { + "id": "200016", + "title": "Design Workshop", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200017", + "title": "QA and Testing", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200018", + "title": "DevOps Guild", + "type": "group", + "username": null, + "unreadCount": 87 + }, + { + "id": "200019", + "title": "Dev Community", + "type": "channel", + "username": "dev_community", + "unreadCount": 9 + }, + { + "id": "200020", + "title": "Tech News Daily", + "type": "channel", + "username": "tech_news_daily", + "unreadCount": 6 + }, + { + "id": "200021", + "title": "Crypto Updates", + "type": "channel", + "username": "crypto_updates", + "unreadCount": 5 + }, + { + "id": "200022", + "title": "Python Developers", + "type": "supergroup", + "username": null, + "unreadCount": 0 + }, + { + "id": "200023", + "title": "JavaScript Universe", + "type": "supergroup", + "username": "javascript_universe", + "unreadCount": 0 + }, + { + "id": "200024", + "title": "Jack Taylor", + "type": "user", + "username": "jack_taylor24", + "unreadCount": 64 + }, + { + "id": "200025", + "title": "Kate Anderson", + "type": "user", + "username": "kate_anderson25", + "unreadCount": 0 + }, + { + "id": "200026", + "title": "Leo Martin", + "type": "user", + "username": "leo_martin26", + "unreadCount": 89 + }, + { + "id": "200027", + "title": "Mia Thompson", + "type": "user", + "username": null, + "unreadCount": 3 + }, + { + "id": "200028", + "title": "Marketing Crew", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200029", + "title": "Design Workshop", + "type": "group", + "username": null, + "unreadCount": 6 + }, + { + "id": "200030", + "title": "QA and Testing", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200031", + "title": "Crypto Updates", + "type": "channel", + "username": null, + "unreadCount": 0 + }, + { + "id": "200032", + "title": "World Events", + "type": "channel", + "username": "world_events", + "unreadCount": 0 + }, + { + "id": "200033", + "title": "Startup Insider", + "type": "channel", + "username": "startup_insider", + "unreadCount": 6 + }, + { + "id": "200034", + "title": "Docker Enthusiasts", + "type": "supergroup", + "username": "docker_enthusiasts", + "unreadCount": 0 + }, + { + "id": "200035", + "title": "Rust Community", + "type": "supergroup", + "username": "rust_community", + "unreadCount": 0 + }, + { + "id": "200036", + "title": "Grace Lee", + "type": "user", + "username": "grace_lee36", + "unreadCount": 0 + }, + { + "id": "200037", + "title": "Henry Wilson", + "type": "user", + "username": "henry_wilson37", + "unreadCount": 94 + }, + { + "id": "200038", + "title": "Iris Zhang", + "type": "user", + "username": null, + "unreadCount": 6 + }, + { + "id": "200039", + "title": "Jack Taylor", + "type": "user", + "username": null, + "unreadCount": 0 + }, + { + "id": "200040", + "title": "Backend Devs", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200041", + "title": "Marketing Crew", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200042", + "title": "Design Workshop", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200043", + "title": "Startup Insider", + "type": "channel", + "username": "startup_insider", + "unreadCount": 9 + }, + { + "id": "200044", + "title": "Science Today", + "type": "channel", + "username": "science_today", + "unreadCount": 0 + }, + { + "id": "200045", + "title": "AI Research Feed", + "type": "channel", + "username": "ai_research_feed", + "unreadCount": 0 + }, + { + "id": "200046", + "title": "TypeScript Fans", + "type": "supergroup", + "username": null, + "unreadCount": 0 + }, + { + "id": "200047", + "title": "Kubernetes Users", + "type": "supergroup", + "username": "kubernetes_users", + "unreadCount": 46 + }, + { + "id": "200048", + "title": "Diana Prince", + "type": "user", + "username": "diana_prince48", + "unreadCount": 0 + }, + { + "id": "200049", + "title": "Eve Davis", + "type": "user", + "username": "eve_davis49", + "unreadCount": 1 + }, + { + "id": "200050", + "title": "Frank Miller", + "type": "user", + "username": "frank_miller50", + "unreadCount": 0 + }, + { + "id": "200051", + "title": "Grace Lee", + "type": "user", + "username": "grace_lee51", + "unreadCount": 0 + }, + { + "id": "200052", + "title": "Project Alpha Team", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200053", + "title": "Backend Devs", + "type": "group", + "username": null, + "unreadCount": 0 + }, + { + "id": "200054", + "title": "Marketing Crew", + "type": "group", + "username": null, + "unreadCount": 0 + } + ], + "total": 55 +} \ No newline at end of file diff --git a/cli/tests/fixtures/toon-benchmark/messages-100.json b/cli/tests/fixtures/toon-benchmark/messages-100.json new file mode 100644 index 0000000..467a053 --- /dev/null +++ b/cli/tests/fixtures/toon-benchmark/messages-100.json @@ -0,0 +1,1370 @@ +{ + "messages": [ + { + "id": 10001, + "text": "be right back", + "date": "2026-03-01T04:40:17.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10002, + "text": "will do", + "date": "2026-03-01T13:09:06.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10003, + "text": "nice!", + "date": "2026-03-01T19:36:43.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10004, + "text": "Happy birthday! Hope you have an amazing day ahead!", + "date": "2026-03-01T12:13:25.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10005, + "text": "nice!", + "date": "2026-03-01T09:01:55.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10006, + "text": "brb", + "date": "2026-03-01T09:41:43.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10007, + "text": "agreed", + "date": "2026-03-01T09:03:59.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10008, + "text": "I found a bug in the payment processing flow. Filing now.", + "date": "2026-03-01T04:59:19.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 4935, + "forwards": null + }, + { + "id": 10009, + "text": "be right back", + "date": "2026-03-02T05:04:33.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10010, + "text": "nice!", + "date": "2026-03-02T08:55:29.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10007, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10011, + "text": "sounds good", + "date": "2026-03-02T12:36:08.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10012, + "text": "The meeting has been rescheduled to Friday at 3 PM.", + "date": "2026-03-02T01:46:15.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": "News Channel", + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10013, + "text": "good morning", + "date": "2026-03-02T20:53:30.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10014, + "text": "ok", + "date": "2026-03-02T23:41:32.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "document", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10015, + "text": "For the upcoming hackathon I am thinking we should focus on building an AI-powered code review assistant. It would analyze pull requests and provide suggestions for improvements including potential bugs security issues and performance optimizations.", + "date": "2026-03-02T22:18:31.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10012, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": 5 + }, + { + "id": 10016, + "text": "Can someone review the pull request I just opened?", + "date": "2026-03-02T12:37:54.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 2383, + "forwards": null + }, + { + "id": 10017, + "text": "let me check", + "date": "2026-03-02T12:57:14.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10018, + "text": "lol", + "date": "2026-03-03T19:13:10.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10019, + "text": "perfect", + "date": "2026-03-03T15:33:31.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10020, + "text": "", + "date": "2026-03-03T23:24:50.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10017, + "forwardFrom": null, + "mediaType": null, + "type": "service", + "views": null, + "forwards": null + }, + { + "id": 10021, + "text": "hi there", + "date": "2026-03-03T02:05:43.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10022, + "text": "yes", + "date": "2026-03-03T06:37:32.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10023, + "text": "hi there", + "date": "2026-03-03T06:18:30.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10024, + "text": "Just finished the migration script. Running tests now.", + "date": "2026-03-03T12:22:19.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": "Tech Updates", + "mediaType": null, + "type": "message", + "views": 440, + "forwards": null + }, + { + "id": 10025, + "text": "good morning", + "date": "2026-03-03T02:54:44.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10022, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10026, + "text": "yes", + "date": "2026-03-03T10:43:45.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10027, + "text": "brb", + "date": "2026-03-04T08:26:22.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10028, + "text": "Lunch at the new Italian place today? Around 12:30?", + "date": "2026-03-04T21:55:37.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10029, + "text": "hi there", + "date": "2026-03-04T01:20:34.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10030, + "text": "I have been researching alternative approaches to the caching problem and found that using a two-level cache with Redis for hot data and memcached for warm data provides the best balance of performance and cost. The implementation is straightforward.", + "date": "2026-03-04T15:10:13.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10027, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": 42 + }, + { + "id": 10031, + "text": "on my way", + "date": "2026-03-04T10:00:13.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10032, + "text": "Lunch at the new Italian place today? Around 12:30?", + "date": "2026-03-04T21:58:35.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 983, + "forwards": null + }, + { + "id": 10033, + "text": "on my way", + "date": "2026-03-04T07:51:34.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10034, + "text": "thanks", + "date": "2026-03-04T21:32:36.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10035, + "text": "perfect", + "date": "2026-03-05T23:54:38.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10032, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10036, + "text": "Reminder: quarterly review is tomorrow at 10 AM sharp.", + "date": "2026-03-05T04:36:13.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": "News Channel", + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10037, + "text": "later", + "date": "2026-03-05T01:57:05.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10038, + "text": "thanks", + "date": "2026-03-05T15:20:27.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10039, + "text": "be right back", + "date": "2026-03-05T23:36:21.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10040, + "text": "", + "date": "2026-03-05T13:04:01.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10037, + "forwardFrom": null, + "mediaType": null, + "type": "service", + "views": null, + "forwards": null + }, + { + "id": 10041, + "text": "hi there", + "date": "2026-03-05T22:46:10.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10042, + "text": "perfect", + "date": "2026-03-05T02:24:44.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10043, + "text": "nice!", + "date": "2026-03-05T06:00:51.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10044, + "text": "Reminder: quarterly review is tomorrow at 10 AM sharp.", + "date": "2026-03-06T15:06:47.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10045, + "text": "I have been researching alternative approaches to the caching problem and found that using a two-level cache with Redis for hot data and memcached for warm data provides the best balance of performance and cost. The implementation is straightforward.", + "date": "2026-03-06T16:52:13.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10042, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": 16 + }, + { + "id": 10046, + "text": "sounds good", + "date": "2026-03-06T12:32:45.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10047, + "text": "be right back", + "date": "2026-03-06T01:44:50.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10048, + "text": "Lunch at the new Italian place today? Around 12:30?", + "date": "2026-03-06T11:26:19.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": "Tech Updates", + "mediaType": null, + "type": "message", + "views": 104, + "forwards": null + }, + { + "id": 10049, + "text": "one sec", + "date": "2026-03-06T04:03:36.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10050, + "text": "will do", + "date": "2026-03-06T03:38:42.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10047, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10051, + "text": "brb", + "date": "2026-03-06T02:36:25.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10052, + "text": "The new dashboard looks great, excellent work everyone!", + "date": "2026-03-06T03:54:42.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10053, + "text": "yes", + "date": "2026-03-07T09:17:38.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10054, + "text": "thanks", + "date": "2026-03-07T16:52:42.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10055, + "text": "good morning", + "date": "2026-03-07T23:38:44.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10052, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10056, + "text": "I will check the latest deployment and get back to you soon.", + "date": "2026-03-07T18:06:39.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "video", + "type": "message", + "views": 1001, + "forwards": null + }, + { + "id": 10057, + "text": "sounds good", + "date": "2026-03-07T21:49:24.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10058, + "text": "yes", + "date": "2026-03-07T06:36:01.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10059, + "text": "be right back", + "date": "2026-03-07T20:03:37.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10060, + "text": "", + "date": "2026-03-07T00:47:25.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10057, + "forwardFrom": "News Channel", + "mediaType": null, + "type": "service", + "views": null, + "forwards": null + }, + { + "id": 10061, + "text": "perfect", + "date": "2026-03-07T14:15:29.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10062, + "text": "good morning", + "date": "2026-03-08T21:57:16.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10063, + "text": "good morning", + "date": "2026-03-08T11:37:18.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "document", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10064, + "text": "Has anyone tried the new version of the API? Seems faster.", + "date": "2026-03-08T13:21:44.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 3899, + "forwards": null + }, + { + "id": 10065, + "text": "agreed", + "date": "2026-03-08T07:33:11.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10062, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10066, + "text": "no", + "date": "2026-03-08T08:47:46.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10067, + "text": "got it", + "date": "2026-03-08T10:19:52.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10068, + "text": "Has anyone tried the new version of the API? Seems faster.", + "date": "2026-03-08T19:35:13.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10069, + "text": "got it", + "date": "2026-03-08T23:36:49.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10070, + "text": "later", + "date": "2026-03-09T01:12:29.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10067, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10071, + "text": "agreed", + "date": "2026-03-09T19:16:01.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10072, + "text": "I will check the latest deployment and get back to you soon.", + "date": "2026-03-09T21:31:08.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": "Daily Digest", + "mediaType": null, + "type": "message", + "views": 3703, + "forwards": null + }, + { + "id": 10073, + "text": "one sec", + "date": "2026-03-09T06:27:38.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10074, + "text": "brb", + "date": "2026-03-09T04:21:46.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10075, + "text": "I have been researching alternative approaches to the caching problem and found that using a two-level cache with Redis for hot data and memcached for warm data provides the best balance of performance and cost. The implementation is straightforward.", + "date": "2026-03-09T18:40:29.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10072, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": 56 + }, + { + "id": 10076, + "text": "Happy birthday! Hope you have an amazing day ahead!", + "date": "2026-03-09T11:31:04.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10077, + "text": "lol", + "date": "2026-03-09T20:10:43.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10078, + "text": "one sec", + "date": "2026-03-09T23:52:23.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10079, + "text": "perfect", + "date": "2026-03-10T02:38:11.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10080, + "text": "", + "date": "2026-03-10T22:56:47.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10077, + "forwardFrom": null, + "mediaType": null, + "type": "service", + "views": null, + "forwards": null + }, + { + "id": 10081, + "text": "brb", + "date": "2026-03-10T13:45:04.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10082, + "text": "no", + "date": "2026-03-10T19:55:19.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10083, + "text": "sure", + "date": "2026-03-10T19:26:33.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10084, + "text": "The new dashboard looks great, excellent work everyone!", + "date": "2026-03-10T16:16:31.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": "Tech Updates", + "mediaType": "video", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10085, + "text": "be right back", + "date": "2026-03-10T02:47:40.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10082, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10086, + "text": "later", + "date": "2026-03-10T14:04:02.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10087, + "text": "hi there", + "date": "2026-03-10T08:07:19.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10088, + "text": "Happy birthday! Hope you have an amazing day ahead!", + "date": "2026-03-11T18:11:00.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 3953, + "forwards": null + }, + { + "id": 10089, + "text": "later", + "date": "2026-03-11T13:20:39.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10090, + "text": "For the upcoming hackathon I am thinking we should focus on building an AI-powered code review assistant. It would analyze pull requests and provide suggestions for improvements including potential bugs security issues and performance optimizations.", + "date": "2026-03-11T13:36:31.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10087, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": 28 + }, + { + "id": 10091, + "text": "on my way", + "date": "2026-03-11T16:54:28.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10092, + "text": "The new dashboard looks great, excellent work everyone!", + "date": "2026-03-11T19:47:37.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10093, + "text": "thanks", + "date": "2026-03-11T21:26:06.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10094, + "text": "no", + "date": "2026-03-11T13:11:05.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10095, + "text": "one sec", + "date": "2026-03-11T11:22:46.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10092, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10096, + "text": "I will check the latest deployment and get back to you soon.", + "date": "2026-03-11T20:31:48.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": "News Channel", + "mediaType": null, + "type": "message", + "views": 4802, + "forwards": null + }, + { + "id": 10097, + "text": "hi there", + "date": "2026-03-12T01:19:40.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10098, + "text": "be right back", + "date": "2026-03-12T01:37:07.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "document", + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10099, + "text": "got it", + "date": "2026-03-12T17:22:20.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10100, + "text": "", + "date": "2026-03-12T06:33:23.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": 10097, + "forwardFrom": null, + "mediaType": null, + "type": "service", + "views": null, + "forwards": null + }, + { + "id": 10101, + "text": "will do", + "date": "2026-03-12T15:31:45.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10102, + "text": "let me check", + "date": "2026-03-12T06:32:06.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10103, + "text": "let me check", + "date": "2026-03-12T14:26:09.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null + }, + { + "id": 10104, + "text": "The meeting has been rescheduled to Friday at 3 PM.", + "date": "2026-03-12T21:43:06.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 336, + "forwards": null + }, + { + "id": 10105, + "text": "So I have been looking into the performance issues we discussed last week and it turns out the problem is in the database query layer. The ORM is generating N+1 queries for the user profile endpoint which causes significant latency under load. I have prepared a fix using eager loading and batch queries that reduces response time by approximately 60 percent.", + "date": "2026-03-13T23:39:30.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": 10102, + "forwardFrom": null, + "mediaType": "video", + "type": "message", + "views": null, + "forwards": 83 + } + ], + "total": 105 +} \ No newline at end of file diff --git a/cli/tests/fixtures/toon-benchmark/mixed-shapes.json b/cli/tests/fixtures/toon-benchmark/mixed-shapes.json new file mode 100644 index 0000000..79a93ae --- /dev/null +++ b/cli/tests/fixtures/toon-benchmark/mixed-shapes.json @@ -0,0 +1,233 @@ +{ + "chatInfo": { + "id": "500001", + "title": "Engineering All-Hands", + "type": "supergroup", + "username": "eng_all_hands", + "description": "Weekly engineering sync for all teams. Agenda posted Monday mornings.", + "memberCount": 342, + "creationDate": "2024-06-15T09:00:00.000Z", + "photo": { + "hasPhoto": true + }, + "linkedChatId": "500002", + "slowmodeSeconds": 0, + "permissions": { + "sendMessages": true, + "sendMedia": true, + "sendPolls": true, + "inviteUsers": false + }, + "inviteLink": "https://t.me/+abc123def456", + "migratedFrom": null + }, + "deleteResult": { + "deleted": [ + 10001, + 10002, + 10003, + 10005, + 10008 + ], + "failed": [ + { + "id": 10004, + "reason": "Message not found" + }, + { + "id": 10006, + "reason": "No permission to delete" + } + ], + "mode": "revoke" + }, + "blockedList": { + "users": [ + { + "id": "600001", + "firstName": "Spammer", + "lastName": "Bot", + "username": "spam_bot_x", + "isBot": true + }, + { + "id": "600002", + "firstName": "Annoying", + "lastName": "User", + "username": null, + "isBot": false + }, + { + "id": "600003", + "firstName": "Crypto", + "lastName": "Scammer", + "username": "crypto_moon_99", + "isBot": false + }, + { + "id": "600004", + "firstName": "Fake", + "lastName": "Account", + "username": "totally_legit", + "isBot": false + }, + { + "id": "600005", + "firstName": "Troll", + "lastName": null, + "username": "bridge_troll", + "isBot": false + } + ], + "total": 5 + }, + "contactSearch": { + "results": [ + { + "id": "700001", + "firstName": "Alex", + "lastName": "Petrov", + "username": "alex_petrov", + "phone": "+79161234567", + "bio": "Senior software engineer", + "photoCount": 12, + "lastSeen": "2026-03-13T10:30:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 5, + "premium": true, + "verified": false, + "mutualContact": true, + "langCode": "ru", + "isContact": true + }, + { + "id": "700002", + "firstName": "Alexandra", + "lastName": "Petrova", + "username": "alexa_p", + "phone": null, + "bio": null, + "photoCount": 3, + "lastSeen": "2026-03-12T15:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 1, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "ru", + "isContact": false + }, + { + "id": "700003", + "firstName": "Alexei", + "lastName": "Popov", + "username": null, + "phone": null, + "bio": "Photographer", + "photoCount": 67, + "lastSeen": "2026-03-11T20:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 0, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": null, + "isContact": false + }, + { + "id": "700004", + "firstName": "Alex", + "lastName": "Turner", + "username": "alex_turner", + "phone": "+447911123456", + "bio": "Music producer and DJ", + "photoCount": 22, + "lastSeen": "2026-03-13T08:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 2, + "premium": true, + "verified": false, + "mutualContact": true, + "langCode": "en", + "isContact": true + }, + { + "id": "700005", + "firstName": "Aleksandr", + "lastName": "Volkov", + "username": "a_volkov", + "phone": null, + "bio": "Blockchain developer", + "photoCount": 1, + "lastSeen": "2026-03-10T12:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 0, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "ru", + "isContact": false + }, + { + "id": "700006", + "firstName": "Alexis", + "lastName": "Chen", + "username": "alexis_c", + "phone": "+8613912345678", + "bio": "UX researcher at Google", + "photoCount": 8, + "lastSeen": "2026-03-13T03:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 1, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "en", + "isContact": false + }, + { + "id": "700007", + "firstName": "Alex", + "lastName": "Kim", + "username": null, + "phone": null, + "bio": null, + "photoCount": 0, + "lastSeen": null, + "isBot": false, + "blocked": false, + "commonChatsCount": 0, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": null, + "isContact": false + }, + { + "id": "700008", + "firstName": "Alexander", + "lastName": "Bell", + "username": "alex_bell", + "phone": "+12025551234", + "bio": "History buff and amateur inventor", + "photoCount": 15, + "lastSeen": "2026-03-12T11:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 3, + "premium": false, + "verified": false, + "mutualContact": true, + "langCode": "en", + "isContact": true + } + ], + "total": 8 + } +} \ No newline at end of file diff --git a/cli/tests/fixtures/toon-benchmark/search-results-30.json b/cli/tests/fixtures/toon-benchmark/search-results-30.json new file mode 100644 index 0000000..608b2e2 --- /dev/null +++ b/cli/tests/fixtures/toon-benchmark/search-results-30.json @@ -0,0 +1,455 @@ +{ + "results": [ + { + "id": 50001, + "text": "yes", + "date": "2026-03-01T20:04:36.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400002", + "chatTitle": "Backend Devs" + }, + { + "id": 50002, + "text": "on my way", + "date": "2026-03-01T20:00:07.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400003", + "chatTitle": "Tech News Daily" + }, + { + "id": 50003, + "text": "let me check", + "date": "2026-03-02T11:32:45.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400004", + "chatTitle": "Design Workshop" + }, + { + "id": 50004, + "text": "Lunch at the new Italian place today? Around 12:30?", + "date": "2026-03-02T13:50:20.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400005", + "chatTitle": "QA and Testing" + }, + { + "id": 50005, + "text": "on my way", + "date": "2026-03-03T07:20:18.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 1856, + "forwards": null, + "chatId": "400006", + "chatTitle": "DevOps Guild" + }, + { + "id": 50006, + "text": "yes", + "date": "2026-03-03T20:33:35.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400007", + "chatTitle": "AI Research Feed" + }, + { + "id": 50007, + "text": "be right back", + "date": "2026-03-03T08:39:26.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": 50005, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400001", + "chatTitle": "Project Alpha Team" + }, + { + "id": 50008, + "text": "Just finished the migration script. Running tests now.", + "date": "2026-03-04T00:32:19.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "photo", + "type": "message", + "views": null, + "forwards": null, + "chatId": "400002", + "chatTitle": "Backend Devs" + }, + { + "id": 50009, + "text": "hi there", + "date": "2026-03-04T16:02:44.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400003", + "chatTitle": "Tech News Daily" + }, + { + "id": 50010, + "text": "perfect", + "date": "2026-03-05T18:30:15.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 2547, + "forwards": null, + "chatId": "400004", + "chatTitle": "Design Workshop" + }, + { + "id": 50011, + "text": "lol", + "date": "2026-03-05T09:43:50.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": null, + "forwardFrom": "Shared Post", + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400005", + "chatTitle": "QA and Testing" + }, + { + "id": 50012, + "text": "I found a bug in the payment processing flow. Filing now.", + "date": "2026-03-05T19:23:34.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400006", + "chatTitle": "DevOps Guild" + }, + { + "id": 50013, + "text": "on my way", + "date": "2026-03-06T23:25:03.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400007", + "chatTitle": "AI Research Feed" + }, + { + "id": 50014, + "text": "lol", + "date": "2026-03-06T21:50:52.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": 50012, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400001", + "chatTitle": "Project Alpha Team" + }, + { + "id": 50015, + "text": "I have been researching alternative approaches to the caching problem and found that using a two-level cache with Redis for hot data and memcached for warm data provides the best balance of performance and cost. The implementation is straightforward.", + "date": "2026-03-07T04:28:48.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 1173, + "forwards": null, + "chatId": "400002", + "chatTitle": "Backend Devs" + }, + { + "id": 50016, + "text": "Happy birthday! Hope you have an amazing day ahead!", + "date": "2026-03-07T11:15:39.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "document", + "type": "message", + "views": null, + "forwards": null, + "chatId": "400003", + "chatTitle": "Tech News Daily" + }, + { + "id": 50017, + "text": "yes", + "date": "2026-03-07T17:29:24.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400004", + "chatTitle": "Design Workshop" + }, + { + "id": 50018, + "text": "hi there", + "date": "2026-03-08T23:34:33.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400005", + "chatTitle": "QA and Testing" + }, + { + "id": 50019, + "text": "on my way", + "date": "2026-03-08T18:56:50.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400006", + "chatTitle": "DevOps Guild" + }, + { + "id": 50020, + "text": "Just finished the migration script. Running tests now.", + "date": "2026-03-09T10:15:11.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 1711, + "forwards": null, + "chatId": "400007", + "chatTitle": "AI Research Feed" + }, + { + "id": 50021, + "text": "no", + "date": "2026-03-09T03:15:10.000Z", + "senderId": "100002", + "senderName": "Maria Ivanova", + "replyToMsgId": 50019, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400001", + "chatTitle": "Project Alpha Team" + }, + { + "id": 50022, + "text": "sure", + "date": "2026-03-09T10:21:23.000Z", + "senderId": "100003", + "senderName": "John Smith", + "replyToMsgId": null, + "forwardFrom": "Shared Post", + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400002", + "chatTitle": "Backend Devs" + }, + { + "id": 50023, + "text": "brb", + "date": "2026-03-10T19:08:58.000Z", + "senderId": "100004", + "senderName": "Elena Kuznetsova", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400003", + "chatTitle": "Tech News Daily" + }, + { + "id": 50024, + "text": "Just finished the migration script. Running tests now.", + "date": "2026-03-10T04:43:20.000Z", + "senderId": "100005", + "senderName": "David Chen", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": "document", + "type": "message", + "views": null, + "forwards": null, + "chatId": "400004", + "chatTitle": "Design Workshop" + }, + { + "id": 50025, + "text": "no", + "date": "2026-03-11T11:48:35.000Z", + "senderId": "100006", + "senderName": "Ольга Смирнова", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 1322, + "forwards": null, + "chatId": "400005", + "chatTitle": "QA and Testing" + }, + { + "id": 50026, + "text": "on my way", + "date": "2026-03-11T09:53:14.000Z", + "senderId": "100007", + "senderName": "Максим Волков", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400006", + "chatTitle": "DevOps Guild" + }, + { + "id": 50027, + "text": "got it", + "date": "2026-03-11T12:46:19.000Z", + "senderId": "100008", + "senderName": "Anna Mueller", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400007", + "chatTitle": "AI Research Feed" + }, + { + "id": 50028, + "text": "Just finished the migration script. Running tests now.", + "date": "2026-03-12T22:04:28.000Z", + "senderId": "100009", + "senderName": "Дмитрий Козлов", + "replyToMsgId": 50026, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400001", + "chatTitle": "Project Alpha Team" + }, + { + "id": 50029, + "text": "thanks", + "date": "2026-03-12T15:29:25.000Z", + "senderId": "100010", + "senderName": "Sophie Laurent", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": null, + "forwards": null, + "chatId": "400002", + "chatTitle": "Backend Devs" + }, + { + "id": 50030, + "text": "After thorough analysis of our deployment pipeline I recommend we switch from the current manual process to a fully automated CI/CD setup. This would include automated testing on every push, staged rollouts with canary deployments, and automatic rollback on failure. The initial setup will take about two weeks.", + "date": "2026-03-13T07:24:46.000Z", + "senderId": "100001", + "senderName": "Alex Petrov", + "replyToMsgId": null, + "forwardFrom": null, + "mediaType": null, + "type": "message", + "views": 108, + "forwards": null, + "chatId": "400003", + "chatTitle": "Tech News Daily" + } + ], + "total": 30 +} \ No newline at end of file diff --git a/cli/tests/fixtures/toon-benchmark/user-profiles-10.json b/cli/tests/fixtures/toon-benchmark/user-profiles-10.json new file mode 100644 index 0000000..31c6c98 --- /dev/null +++ b/cli/tests/fixtures/toon-benchmark/user-profiles-10.json @@ -0,0 +1,175 @@ +{ + "profiles": [ + { + "id": "300001", + "firstName": "Alexander", + "lastName": "Petrov", + "username": "alex_petrov", + "phone": "+79161234567", + "bio": "Senior software engineer at Yandex. Open source enthusiast.", + "photoCount": 12, + "lastSeen": "2026-03-13T10:30:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 5, + "premium": true, + "verified": false, + "mutualContact": true, + "langCode": "ru" + }, + { + "id": "300002", + "firstName": "Sarah", + "lastName": "Connor", + "username": "sarah_c", + "phone": "+14155551234", + "bio": "Product manager by day, photographer by night.", + "photoCount": 34, + "lastSeen": "2026-03-12T22:15:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 3, + "premium": true, + "verified": false, + "mutualContact": true, + "langCode": "en" + }, + { + "id": "300003", + "firstName": "BotFather", + "lastName": null, + "username": "BotFather", + "phone": null, + "bio": "I am the one bot to rule them all.", + "photoCount": 1, + "lastSeen": null, + "isBot": true, + "blocked": false, + "commonChatsCount": 0, + "premium": false, + "verified": true, + "mutualContact": false, + "langCode": null + }, + { + "id": "300004", + "firstName": "Hans", + "lastName": "Mueller", + "username": null, + "phone": "[restricted]", + "bio": null, + "photoCount": 0, + "lastSeen": "2026-03-10T08:00:00.000Z", + "isBot": false, + "blocked": true, + "commonChatsCount": 1, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "de" + }, + { + "id": "300005", + "firstName": "Елена", + "lastName": "Кузнецова", + "username": "elena_kuz", + "phone": "+79031112233", + "bio": "Люблю путешествия и фотографию. Currently in Bali.", + "photoCount": 89, + "lastSeen": "2026-03-13T14:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 8, + "premium": true, + "verified": false, + "mutualContact": true, + "langCode": "ru" + }, + { + "id": "300006", + "firstName": "NewsBot", + "lastName": null, + "username": "daily_news_bot", + "phone": null, + "bio": "Your daily news aggregator. Send /help to get started.", + "photoCount": 1, + "lastSeen": null, + "isBot": true, + "blocked": false, + "commonChatsCount": 0, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "en" + }, + { + "id": "300007", + "firstName": "Chen", + "lastName": "Wei", + "username": "chenwei88", + "phone": "+8613800138000", + "bio": "Tech lead at ByteDance. Distributed systems. Rust.", + "photoCount": 5, + "lastSeen": "2026-03-13T06:45:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 2, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": "en" + }, + { + "id": "300008", + "firstName": "Olivia", + "lastName": "Martin", + "username": "olivia_m", + "phone": "[restricted]", + "bio": "Freelance designer and illustrator based in Paris.", + "photoCount": 42, + "lastSeen": "2026-03-11T18:30:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 4, + "premium": false, + "verified": false, + "mutualContact": true, + "langCode": "en" + }, + { + "id": "300009", + "firstName": "Дмитрий", + "lastName": "Козлов", + "username": null, + "phone": "+79267778899", + "bio": "DevOps инженер. Kubernetes, Terraform, Ansible.", + "photoCount": 3, + "lastSeen": "2026-03-13T12:00:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 6, + "premium": false, + "verified": false, + "mutualContact": true, + "langCode": "ru" + }, + { + "id": "300010", + "firstName": "Sophie", + "lastName": "Laurent", + "username": "sophie_l", + "phone": "+33612345678", + "bio": "Data scientist at CNRS. Machine learning and NLP researcher.", + "photoCount": 15, + "lastSeen": "2026-03-13T09:20:00.000Z", + "isBot": false, + "blocked": false, + "commonChatsCount": 3, + "premium": false, + "verified": false, + "mutualContact": false, + "langCode": null + } + ], + "notFound": [] +} \ No newline at end of file diff --git a/cli/tests/integration/cli-entry.test.ts b/cli/tests/integration/cli-entry.test.ts new file mode 100644 index 0000000..47b1a52 --- /dev/null +++ b/cli/tests/integration/cli-entry.test.ts @@ -0,0 +1,470 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { execSync, execFileSync, spawnSync } from 'node:child_process'; +import { existsSync, readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; + +const ROOT = join(import.meta.dirname, '..', '..'); +const BINARY = join(ROOT, 'dist', 'bin', 'tg.js'); + +describe('CLI entry point (built binary)', () => { + let fixtureDir: string; + let fixtureConfig: string; + beforeAll(() => { + // Build the project before running integration tests + execSync('npx tsup', { cwd: ROOT, stdio: 'pipe' }); + expect(existsSync(BINARY)).toBe(true); + fixtureDir = mkdtempSync(join(tmpdir(), 'tg-cli-entry-')); + fixtureConfig = join(fixtureDir, 'config.json'); + writeFileSync(fixtureConfig, JSON.stringify({ profiles: { review: { phone: '+10000000000', created: '2026-09-06T00:00:00Z' } } })); + mkdirSync(join(fixtureDir, 'sessions')); + writeFileSync(join(fixtureDir, 'sessions', 'review.session'), 'synthetic-not-a-real-session'); + }); + + afterAll(() => { + if (fixtureDir) rmSync(fixtureDir, { recursive: true, force: true }); + }); + + function runFixture(args: string[]) { + return spawnSync(process.execPath, [BINARY, '--config', fixtureConfig, '--profile', 'review', ...args], { + cwd: ROOT, encoding: 'utf-8', timeout: 5000, + }); + } + + it.each([ + ['--transport', 'https', 'auth', 'login'], + ['--transport', 'wss', '--daemon', 'chat', 'list'], + ['message', 'watch', '--transport', 'wss'], + ])('rejects invalid transport usage before network access: %s', (...args) => { + const result = runFixture(args); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_OPTIONS' }); + }); + + it('exposes scheduled send and photo command options in help', () => { + expect(runFixture(['message', 'send', '--help']).stdout).toContain('--schedule'); + expect(runFixture(['contact', 'set-photo', '--help']).stdout).toContain('visible only to you'); + expect(runFixture(['user', 'download-photo', '--help']).stdout).toContain('--force'); + }); + + it('returns a structured invalid schedule before authenticating', () => { + const result = runFixture(['message', 'send', 'me', 'Synthetic', '--schedule', '2030-01-01T01:00:00']); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_SCHEDULE' }); + }); + + it('retains schedule errors with TOON and field selection', () => { + const result = runFixture(['--toon', '--fields', 'id', 'message', 'send', 'me', 'Synthetic', '--schedule', 'invalid']); + expect(result.status).toBe(1); + expect(result.stdout).toContain('ok: false'); + expect(result.stdout).toContain('INVALID_SCHEDULE'); + }); + + function runTerminal(args: string[], env: NodeJS.ProcessEnv = {}) { + // Model a terminal in an isolated child while capturing its two streams separately. + const bootstrap = ` + for (const stream of [process.stdin, process.stdout, process.stderr]) { + Object.defineProperty(stream, 'isTTY', { value: true }); + } + `; + return spawnSync(process.execPath, ['--import', `data:text/javascript,${encodeURIComponent(bootstrap)}`, BINARY, ...args], { + cwd: ROOT, encoding: 'utf-8', timeout: 5000, + env: { ...process.env, TERM: 'xterm-256color', NO_COLOR: '1', FORCE_COLOR: '0', ...env }, + }); + } + + it.each([ + { args: ['--help'], banner: true }, + { args: ['help'], banner: true }, + { args: ['--quiet', '--help'], banner: false }, + { args: ['--help', '--quiet'], banner: false }, + { args: ['help', '--quiet'], banner: false }, + { args: ['auth', '--help'], banner: false }, + { args: ['help', 'message'], banner: false }, + { args: ['--version'], banner: false }, + ])('terminal branding for $args: $banner', ({ args, banner }) => { + const result = runTerminal(args); + expect(result.status).toBe(0); + expect(result.stdout.includes('(. .)')).toBe(banner); + expect(result.stderr).toBe(''); + }); + + it('keeps the piped help output undecorated', () => { + const result = runFixture(['--help']); + expect(result.status).toBe(0); + expect(result.stdout).toMatch(/^Usage: tg /); + expect(result.stdout).not.toContain('(. .)'); + expect(result.stderr).toBe(''); + }); + + it('honors NO_COLOR even when FORCE_COLOR is set', () => { + const result = runTerminal(['--help'], { NO_COLOR: '', FORCE_COLOR: '1' }); + expect(result.status).toBe(0); + expect(result.stdout).toContain('(. .)'); + expect(result.stdout).not.toContain('\x1b['); + }); + + it('omits branding in a dumb terminal', () => { + const result = runTerminal(['--help'], { TERM: 'dumb' }); + expect(result.status).toBe(0); + expect(result.stdout).toMatch(/^Usage: tg /); + }); + + it('keeps terminal command results as JSON without a mascot', () => { + const result = runTerminal(['--config', fixtureConfig, '--profile', 'review', '--json', 'session', 'export']); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: true }); + expect(result.stdout + result.stderr).not.toContain('(. .)'); + expect(result.stdout + result.stderr).not.toContain('.------.'); + }); + + it('--help exits 0 and shows Auth and Session group headings', () => { + const output = execFileSync(process.execPath, [BINARY, "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('Auth'); + expect(output).toContain('Session'); + expect(output).toContain('auth'); + expect(output).toContain('session'); + }); + + it('--version exits 0 and shows package version + teleproto version', () => { + const output = execFileSync(process.execPath, [BINARY, "--version"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + // Format: "X.Y.Z (teleproto A.B.C)" + expect(output.trim()).toMatch(/\d+\.\d+\.\d+(?:-[\w.]+)? \(teleproto \d+\.\d+\.\d+\)/); + }); + + it('auth --help shows login, status, logout subcommands', () => { + const output = execFileSync(process.execPath, [BINARY, "auth", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('login'); + expect(output).toContain('status'); + expect(output).toContain('logout'); + }); + + it('login help documents --phone', () => { + expect(runFixture(['auth', 'login', '--help']).stdout).toContain('--phone <number>'); + }); + + it('rejects invalid --phone in a terminal before connecting', () => { + const result = runTerminal(['--config', fixtureConfig, '--profile', 'review', 'auth', 'login', '--phone', '@username']); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_INPUT' }); + expect(result.stderr).not.toContain('Starting authentication'); + expect(result.stderr).not.toContain('Phone number (international format):'); + }); + + it('session --help shows export, import subcommands', () => { + const output = execFileSync(process.execPath, [BINARY, "session", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('export'); + expect(output).toContain('import'); + }); + + it('session import --help shows --skip-verify option', () => { + const output = execFileSync(process.execPath, [BINARY, "session", "import", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('--skip-verify'); + }); + + it('chat --help shows list, info, join, leave, resolve, invite-info, members subcommands', () => { + const output = execFileSync(process.execPath, [BINARY, "chat", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('list'); + expect(output).toContain('info'); + expect(output).toContain('join'); + expect(output).toContain('leave'); + expect(output).toContain('resolve'); + expect(output).toContain('invite-info'); + expect(output).toContain('members'); + }); + + it('message search --help shows --public', () => { + const output = execFileSync(process.execPath, [BINARY, "message", "search", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + expect(output).toContain('--public'); + expect(output).toContain('--peer'); + expect(output).toContain('--after'); + }); + + it('message --help shows all subcommands including edit, delete, pin, unpin', () => { + const output = execFileSync(process.execPath, [BINARY, "message", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('history'); + expect(output).toContain('search'); + expect(output).toContain('send'); + expect(output).toContain('forward'); + expect(output).toContain('react'); + expect(output).toContain('edit'); + expect(output).toContain('delete'); + expect(output).toContain('pin'); + expect(output).toContain('unpin'); + }); + + it('message delete --help shows --revoke and --for-me flags', () => { + const output = execFileSync(process.execPath, [BINARY, "message", "delete", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('--revoke'); + expect(output).toContain('--for-me'); + }); + + it('message pin --help shows --notify flag', () => { + const output = execFileSync(process.execPath, [BINARY, "message", "pin", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('--notify'); + }); + + it('--help shows all 7 command groups: Auth, Session, Chat, Message, Media, User, Contact', () => { + const output = execFileSync(process.execPath, [BINARY, "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('Auth'); + expect(output).toContain('Session'); + expect(output).toContain('Chat'); + expect(output).toContain('Message'); + expect(output).toContain('Media'); + expect(output).toContain('User'); + expect(output).toContain('user'); + expect(output).toContain('Contact'); + expect(output).toContain('contact'); + }); + + it('--help shows --no-json and --human global options', () => { + const output = execFileSync(process.execPath, [BINARY, "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('--no-json'); + expect(output).toContain('--human'); + }); + + it('media --help exits 0 and shows download subcommand', () => { + const output = execFileSync(process.execPath, [BINARY, "media", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('download'); + }); + + it('media download --help exits 0 and shows msg-ids argument', () => { + const output = execFileSync(process.execPath, [BINARY, "media", "download", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('msg-ids'); + }); + + it('user --help shows profile, block, unblock, blocked subcommands', () => { + const output = execFileSync(process.execPath, [BINARY, "user", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('profile'); + expect(output).toContain('block'); + expect(output).toContain('unblock'); + expect(output).toContain('blocked'); + expect(output).toContain('User profiles'); + }); + + it('contact --help shows list, add, delete, search subcommands', () => { + const output = execFileSync(process.execPath, [BINARY, "contact", "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('list'); + expect(output).toContain('add'); + expect(output).toContain('delete'); + expect(output).toContain('search'); + expect(output).toContain('Contact'); + }); + + it('--help shows --toon global option', () => { + const output = execFileSync(process.execPath, [BINARY, "--help"], { + cwd: ROOT, + encoding: 'utf-8', + }); + + expect(output).toContain('--toon'); + }); + + it('unknown command exits non-zero', () => { + const result = spawnSync(process.execPath, [BINARY, 'not-a-real-command'], { + cwd: ROOT, + encoding: 'utf-8', + }); + expect(result.status).not.toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_OPTIONS' }); + expect(result.stderr).toBe(''); + }); + + it.each([ + ['--json', 'session', 'export'], + ['session', '--json', 'export'], + ['session', 'export', '--json'], + ])('session export honors explicit --json via real Commander: %j', (...args) => { + const result = runFixture(args); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + ok: true, + data: { session: 'synthetic-not-a-real-session', phone: '+10000000000', created: '2026-09-06T00:00:00Z' }, + }); + }); + + it('session export retains raw piping output when --json is not explicit', () => { + const result = runFixture(['session', 'export', '--quiet']); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe('synthetic-not-a-real-session\n'); + expect(result.stderr).toBe(''); + }); + + it.each([ + ['chat', 'list', '--bogus'], + ['message', 'get'], + ['session', 'unknown'], + ['chat', 'list', '--limit'], + ])('returns one structured Commander error for %j', (...args) => { + const result = runFixture(args); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_OPTIONS' }); + expect(result.stdout.trim().split('\n')).toHaveLength(1); + expect(result.stderr).toBe(''); + }); + + it('honors human mode even for a Commander parse failure', () => { + const result = runFixture(['chat', 'list', '--human', '--bogus']); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('INVALID_OPTIONS'); + expect(result.stderr).not.toContain(' at '); + }); + + it.each([ + { mode: [], stdout: true }, + { mode: ['--quiet'], stdout: true }, + { mode: ['--toon'], stdout: true }, + { mode: ['--human'], stdout: false }, + { mode: ['--jsonl'], stdout: false }, + ])('catches asynchronous malformed-config failures in $mode', ({ mode, stdout }) => { + const corruptConfig = join(fixtureDir, 'corrupt.json'); + writeFileSync(corruptConfig, '{"secret-token": invalid json'); + const result = runFixture(['--config', corruptConfig, ...mode, 'chat', 'list']); + expect(result.status).toBe(1); + expect(stdout ? result.stdout : result.stderr).toContain('CONFIG_ERROR'); + expect(stdout ? result.stderr : result.stdout).toBe(''); + expect(result.stdout + result.stderr).not.toContain('secret-token'); + expect(result.stdout + result.stderr).not.toContain(' at '); + if (!mode.includes('--toon') && stdout) { + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'CONFIG_ERROR' }); + expect(result.stdout.trim().split('\n')).toHaveLength(1); + } + }); + + it('catches an async session-file read error without an unhandled rejection', () => { + mkdirSync(join(fixtureDir, 'sessions', 'broken.session')); + const result = runFixture(['--profile', 'broken', 'session', 'export', '--json']); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'UNKNOWN_ERROR' }); + expect(result.stderr).toBe(''); + }); + + it('keeps invalid-profile failures in the selected human format', () => { + const result = runFixture(['--human', '--profile', '../invalid', 'session', 'export']); + expect(result.status).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toContain('INVALID_INPUT'); + }); + + it.each([['auth', 'status'], ['session', 'export']])('rejects an explicit empty profile before %j', (...args) => { + const result = runFixture(['--profile', '', '--config', join(fixtureDir, 'missing-parent', 'bad.json'), ...args]); + expect(result.status).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ ok: false, code: 'INVALID_INPUT' }); + expect(existsSync(join(fixtureDir, 'missing-parent'))).toBe(false); + expect(result.stderr).toBe(''); + }); + + it('session import --skip-verify with empty stdin exits non-zero with NO_INPUT', () => { + const result = spawnSync( + process.execPath, + [BINARY, 'session', 'import', '--skip-verify', '--json'], + { + cwd: ROOT, + encoding: 'utf-8', + input: '\n', + env: { ...process.env, HOME: '/tmp/tg-cli-test-home' }, + }, + ); + expect(result.status).not.toBe(0); + const parsed = JSON.parse((result.stdout ?? '').trim()); + expect(parsed.ok).toBe(false); + expect(parsed.code).toBe('NO_INPUT'); + }); + + it('completion powershell exits non-zero with a JSON error envelope', () => { + const result = spawnSync(process.execPath, [BINARY, 'completion', 'powershell', '--json'], { + cwd: ROOT, + encoding: 'utf-8', + }); + expect(result.status).not.toBe(0); + const parsed = JSON.parse((result.stdout ?? '').trim()); + expect(parsed.ok).toBe(false); + expect(parsed.code).toBe('INVALID_INPUT'); + }); + + it('publishes a library entry that can be imported', async () => { + const lib = join(ROOT, 'dist', 'index.js'); + const dts = join(ROOT, 'dist', 'index.d.ts'); + expect(existsSync(lib)).toBe(true); + expect(existsSync(dts)).toBe(true); + + const result = spawnSync( + process.execPath, + ['--input-type=module', '-e', "import { ErrorCode, withAuth, resolveEntity } from './dist/index.js'; if (!ErrorCode.NOT_AUTHENTICATED || typeof withAuth !== 'function' || typeof resolveEntity !== 'function') process.exit(2); console.log('library-console-unmodified');"], + { cwd: ROOT, encoding: 'utf-8' }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe('library-console-unmodified\n'); + }); + + it('puts a shebang only on the CLI binary, not the daemon entry', () => { + const bin = readFileSync(BINARY, 'utf-8'); + const daemon = readFileSync(join(ROOT, 'dist', 'lib', 'daemon', 'entry.js'), 'utf-8'); + expect(bin.startsWith('#!/usr/bin/env node')).toBe(true); + expect(daemon.startsWith('#!/usr/bin/env node')).toBe(false); + }); +}); diff --git a/cli/tests/unit/auth-preset.test.ts b/cli/tests/unit/auth-preset.test.ts new file mode 100644 index 0000000..ab1b2f7 --- /dev/null +++ b/cli/tests/unit/auth-preset.test.ts @@ -0,0 +1,112 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createConfig, getCredentialsOrThrow } from '../../src/lib/config.js'; +import { SessionStore } from '../../src/lib/session-store.js'; + +const mocks = vi.hoisted(() => ({ + start: vi.fn(), destroy: vi.fn().mockResolvedValue(undefined), + success: vi.fn(), error: vi.fn(), +})); +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts, fn) => fn({})), + createClientForAuth: vi.fn(async () => ({ + connect: vi.fn().mockResolvedValue(true), + start: mocks.start, destroy: mocks.destroy, + session: { save: () => 'synthetic-test-session' }, + })), +})); +vi.mock('../../src/lib/prompt.js', () => ({ + createPrompt: () => ({ ask: vi.fn().mockResolvedValue('+10000000000'), askSecret: vi.fn(), close: vi.fn() }), +})); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: mocks.success, outputError: mocks.error, logStatus: vi.fn(), +})); + +import { loginAction } from '../../src/commands/auth/login.js'; +import { createClientForAuth, withClient } from '../../src/lib/client.js'; +import { withAuth } from '../../src/lib/with-auth.js'; + +describe('login preset persistence and session ownership', () => { + let dir: string; + const originalTTY = process.stdin.isTTY; + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv('TG_API_ID', undefined); + vi.stubEnv('TG_API_HASH', undefined); + dir = mkdtempSync(join(tmpdir(), 'tg-preset-login-')); + Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true }); + }); + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: originalTTY }); + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); + }); + + it('persists --client desktop and resolves it on the next invocation', async () => { + const configPath = join(dir, 'config.json'); + createConfig(configPath).set('presets', { + desktop: { apiId: 1, apiHash: 'synthetic-api-hash', fetchedAt: new Date().toISOString() }, + }); + const store = new SessionStore(dir); + // A second owner cannot connect while login or its teardown is running. + mocks.start.mockImplementationOnce(async () => { + await expect(store.acquireLock('work')).rejects.toMatchObject({ code: 'ELOCKED' }); + }); + mocks.destroy.mockImplementationOnce(async () => { + await expect(store.acquireLock('work')).rejects.toMatchObject({ code: 'ELOCKED' }); + }); + await loginAction.call({ optsWithGlobals: () => ({ profile: 'work', config: configPath, client: 'desktop' }) } as any); + expect(mocks.error).not.toHaveBeenCalled(); + expect(mocks.success).toHaveBeenCalledWith({ loggedIn: true, profile: 'work', phone: '+10000000000' }); + const fresh = createConfig(configPath); + expect(fresh.get('profiles.work.client')).toBe('desktop'); + await expect(getCredentialsOrThrow(fresh, undefined, 'work')).resolves.toEqual({ apiId: 1, apiHash: 'synthetic-api-hash' }); + await expect(store.load('work')).resolves.toBe('synthetic-test-session'); + }); + + it('releases the lock and destroys the client when authentication fails', async () => { + const configPath = join(dir, 'config.json'); + const config = createConfig(configPath); + config.set('apiId', 1); + config.set('apiHash', 'synthetic-api-hash'); + mocks.start.mockRejectedValueOnce(new Error('offline failure')); + await loginAction.call({ optsWithGlobals: () => ({ profile: 'work', config: configPath }) } as any); + expect(mocks.destroy).toHaveBeenCalledOnce(); + expect(mocks.error).toHaveBeenCalledWith('offline failure', 'UNKNOWN_ERROR'); + expect(mocks.success).not.toHaveBeenCalled(); + const release = await new SessionStore(dir).acquireLock('work'); + await release(); + }); + + it('persists WSS on successful login and uses it on the next direct command', async () => { + const configPath = join(dir, 'config.json'); + const config = createConfig(configPath); + config.set('apiId', 1); + config.set('apiHash', 'synthetic-api-hash'); + await loginAction.call({ optsWithGlobals: () => ({ profile: 'work', config: configPath, transport: 'wss' }) } as any); + expect(mocks.error).not.toHaveBeenCalled(); + expect(createClientForAuth).toHaveBeenCalledWith(1, 'synthetic-api-hash', 'wss'); + expect(createConfig(configPath).get('profiles.work.transport')).toBe('wss'); + await withAuth({ profile: 'work', config: configPath }, async () => {}); + expect(withClient).toHaveBeenLastCalledWith(expect.objectContaining({ transport: 'wss' }), expect.any(Function), expect.any(Object)); + await withAuth({ profile: 'work', config: configPath, transport: 'tcp' }, async () => {}); + expect(withClient).toHaveBeenLastCalledWith(expect.objectContaining({ transport: 'tcp' }), expect.any(Function), expect.any(Object)); + expect(createConfig(configPath).get('profiles.work.transport')).toBe('wss'); + }); + + it('keeps the saved transport and session when a new login fails', async () => { + const configPath = join(dir, 'config.json'); + const config = createConfig(configPath); + config.set('apiId', 1); + config.set('apiHash', 'synthetic-api-hash'); + config.set('profiles.work', { transport: 'tcp' }); + const store = new SessionStore(dir); + await store.withLock('work', async () => store.saveUnlocked('work', 'previous-session')); + mocks.start.mockRejectedValueOnce(new Error('offline failure')); + await loginAction.call({ optsWithGlobals: () => ({ profile: 'work', config: configPath, transport: 'wss' }) } as any); + expect(createConfig(configPath).get('profiles.work.transport')).toBe('tcp'); + expect(await store.load('work')).toBe('previous-session'); + }); +}); diff --git a/cli/tests/unit/auth-status-envelope.test.ts b/cli/tests/unit/auth-status-envelope.test.ts new file mode 100644 index 0000000..9c6c957 --- /dev/null +++ b/cli/tests/unit/auth-status-envelope.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const mockWithLock = vi.fn(); +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: (...args: any[]) => mockWithLock(...args), + })), +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockGetMe = vi.fn(); +const mockCheckAuthorization = vi.fn(); +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => + fn({ + checkAuthorization: mockCheckAuthorization, + getMe: mockGetMe, + }, new AbortController().signal), + ), +})); + +import { statusAction } from '../../src/commands/auth/status.js'; + +describe('auth status envelope (no output/serialize mock)', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + vi.clearAllMocks(); + process.exitCode = 0; + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + mockWithLock.mockImplementation(async (_p: string, fn: (s: string) => Promise<any>) => fn('session')); + mockCheckAuthorization.mockResolvedValue(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + process.exitCode = 0; + }); + + it('serializes user.id as a string even when gramjs id toJSON is {}', async () => { + const weirdId = { + toString: () => '12345', + toJSON: () => ({}), + }; + mockGetMe.mockResolvedValue({ + id: weirdId, + phone: '+15551234567', + username: 'testuser', + firstName: 'Test', + }); + + await statusAction.call({ + optsWithGlobals: () => ({ profile: 'default', quiet: true, json: true }), + } as any); + + expect(stdoutSpy).toHaveBeenCalled(); + const parsed = JSON.parse(stdoutSpy.mock.calls[0][0] as string); + expect(parsed.ok).toBe(true); + expect(parsed.data.authorized).toBe(true); + expect(parsed.data.user.id).toBe('12345'); + expect(JSON.stringify(parsed.data.user.id)).toBe('"12345"'); + }); +}); diff --git a/cli/tests/unit/auth.test.ts b/cli/tests/unit/auth.test.ts new file mode 100644 index 0000000..3b7bd9d --- /dev/null +++ b/cli/tests/unit/auth.test.ts @@ -0,0 +1,493 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { existsSync, rmSync, mkdirSync, writeFileSync } from 'node:fs'; + +// ---- Mocks ---- + +// Mock prompt +const mockAsk = vi.fn(); +const mockAskSecret = vi.fn(); +const mockClose = vi.fn(); +vi.mock('../../src/lib/prompt.js', () => ({ + createPrompt: vi.fn(() => ({ ask: mockAsk, askSecret: mockAskSecret, close: mockClose })), +})); + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockStart, + mockConnect, + mockDestroy, + mockCheckAuthorization, + mockGetMe, + mockInvoke, + mockSessionSave, +} = vi.hoisted(() => ({ + mockStart: vi.fn().mockResolvedValue(undefined), + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockCheckAuthorization: vi.fn().mockResolvedValue(true), + mockGetMe: vi.fn().mockResolvedValue({ id: 123, phone: '+15551234567', username: 'testuser', firstName: 'Test' }), + mockInvoke: vi.fn().mockResolvedValue(true), + mockSessionSave: vi.fn().mockReturnValue('saved-session-string'), +})); + +const mockClientInstance = { + start: mockStart, + connect: mockConnect, + destroy: mockDestroy, + checkAuthorization: mockCheckAuthorization, + getMe: mockGetMe, + invoke: mockInvoke, + session: { save: mockSessionSave }, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + auth: { + LogOut: vi.fn().mockImplementation(() => ({ className: 'auth.LogOut' })), + }, + }, +})); + +// Mock config +const mockConfigGet = vi.fn(); +const mockConfigSet = vi.fn(); +const mockConfigDelete = vi.fn(); +const mockConfigObj = { + get: mockConfigGet, + set: mockConfigSet, + delete: mockConfigDelete, + path: '/tmp/mock-config.json', +}; + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => mockConfigObj), + resolveCredentials: vi.fn(), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// We need to mock SessionStore at the module level +const mockStoreSave = vi.fn().mockResolvedValue(undefined); +const mockStoreLoad = vi.fn().mockResolvedValue(''); +const mockStoreDelete = vi.fn().mockResolvedValue(undefined); +const mockStoreDeleteUnlocked = vi.fn(); +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + const session = await mockStoreLoad(); + return fn(session); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + save: vi.fn(), + saveUnlocked: mockStoreSave, + load: mockStoreLoad, + delete: mockStoreDelete, + deleteUnlocked: mockStoreDeleteUnlocked, + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + createClientForAuth: vi.fn(async () => mockClientInstance), + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance, new AbortController().signal)), +})); + +// Import after mocks +import { loginAction } from '../../src/commands/auth/login.js'; +import { statusAction } from '../../src/commands/auth/status.js'; +import { logoutAction } from '../../src/commands/auth/logout.js'; +import { createAuthCommand } from '../../src/commands/auth/index.js'; + +// Create a mock Command context for action handlers +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('auth --daemon', () => { + it('status refuses --daemon instead of opening a second client', async () => { + const ctx = createMockCommandContext({ daemon: true }); + await statusAction.call(ctx as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + 'DAEMON_PROXY_UNAVAILABLE', + ); + expect(mockStoreWithLock).not.toHaveBeenCalled(); + }); + + it('login refuses --daemon', async () => { + const ctx = createMockCommandContext({ daemon: true }); + await loginAction.call(ctx as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + 'DAEMON_PROXY_UNAVAILABLE', + ); + }); + + it('logout refuses --daemon', async () => { + const ctx = createMockCommandContext({ daemon: true }); + await logoutAction.call(ctx as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + 'DAEMON_PROXY_UNAVAILABLE', + ); + }); +}); + +describe('loginAction', () => { + const originalIsTTY = process.stdin.isTTY; + + async function captureLoginBanner(opts: Record<string, unknown> = {}, tty = { stdout: true, stderr: true }) { + const stdoutTTY = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY'); + const stderrTTY = Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'); + Object.defineProperty(process.stdout, 'isTTY', { configurable: true, value: tty.stdout }); + Object.defineProperty(process.stderr, 'isTTY', { configurable: true, value: tty.stderr }); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + try { + await loginAction.call(createMockCommandContext(opts) as any); + return { + stdout: stdout.mock.calls.map(([chunk]) => String(chunk)).join(''), + stderr: stderr.mock.calls.map(([chunk]) => String(chunk)).join(''), + }; + } finally { + stdout.mockRestore(); + stderr.mockRestore(); + if (stdoutTTY) Object.defineProperty(process.stdout, 'isTTY', stdoutTTY); + else Reflect.deleteProperty(process.stdout, 'isTTY'); + if (stderrTTY) Object.defineProperty(process.stderr, 'isTTY', stderrTTY); + else Reflect.deleteProperty(process.stderr, 'isTTY'); + } + } + + beforeEach(() => { + vi.clearAllMocks(); + mockAsk.mockResolvedValue('+15551234567'); + mockAskSecret.mockResolvedValue('secret123'); + // Default: simulate interactive TTY + Object.defineProperty(process.stdin, 'isTTY', { value: true, writable: true, configurable: true }); + }); + + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, writable: true, configurable: true }); + vi.unstubAllEnvs(); + }); + + it('writes the login mascot only to terminal stderr', async () => { + vi.stubEnv('TERM', 'xterm-256color'); + vi.stubEnv('NO_COLOR', '1'); + const captured = await captureLoginBanner(); + expect(captured.stdout).toBe(''); + expect(captured.stderr).toContain('.------.'); + expect(captured.stderr).toContain('Telegram, from your terminal.'); + expect(captured.stderr).not.toContain('\x1b['); + expect(mockOutputSuccess).toHaveBeenCalledWith(expect.objectContaining({ loggedIn: true })); + }); + + it.each([ + { label: 'quiet', opts: { quiet: true }, tty: { stdout: true, stderr: true }, term: 'xterm-256color' }, + { label: 'redirected stdout', opts: {}, tty: { stdout: false, stderr: true }, term: 'xterm-256color' }, + { label: 'redirected stderr', opts: {}, tty: { stdout: true, stderr: false }, term: 'xterm-256color' }, + { label: 'dumb terminal', opts: {}, tty: { stdout: true, stderr: true }, term: 'dumb' }, + ])('omits the login mascot for $label', async ({ opts, tty, term }) => { + vi.stubEnv('TERM', term); + const captured = await captureLoginBanner(opts, tty); + expect(captured).toEqual({ stdout: '', stderr: '' }); + expect(mockStart).toHaveBeenCalledOnce(); + }); + + it('calls client.start() with phone, code, and password callbacks', async () => { + const ctx = createMockCommandContext(); + await loginAction.call(ctx as any); + + expect(mockStart).toHaveBeenCalledOnce(); + const startArgs = mockStart.mock.calls[0][0]; + expect(startArgs).toHaveProperty('phoneNumber'); + expect(startArgs).toHaveProperty('phoneCode'); + expect(startArgs).toHaveProperty('password'); + expect(startArgs).toHaveProperty('onError'); + expect(typeof startArgs.phoneNumber).toBe('function'); + expect(typeof startArgs.phoneCode).toBe('function'); + expect(typeof startArgs.password).toBe('function'); + }); + + it('saves session string after successful login', async () => { + const ctx = createMockCommandContext(); + await loginAction.call(ctx as any); + + expect(mockStoreSave).toHaveBeenCalledWith('default', 'saved-session-string'); + }); + + it('asks for the phone before fetching credentials or opening a connection', async () => { + await loginAction.call(createMockCommandContext() as any); + const { getCredentialsOrThrow } = await import('../../src/lib/config.js'); + expect(mockAsk.mock.calls[0][0]).toBe('Phone number (international format): '); + expect(mockAsk.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getCredentialsOrThrow).mock.invocationCallOrder[0]); + expect(mockAsk.mock.invocationCallOrder[0]).toBeLessThan(mockConnect.mock.invocationCallOrder[0]); + const params = mockStart.mock.calls[0][0]; + expect(await params.phoneNumber()).toBe('+15551234567'); + expect(mockAsk).toHaveBeenCalledOnce(); + }); + + it('passes a normalized --phone literally to gramjs without asking for it', async () => { + await loginAction.call(createMockCommandContext({ phone: '+1 (555) 123-4567' }) as any); + expect(mockAsk).not.toHaveBeenCalled(); + expect(mockStart.mock.calls[0][0].phoneNumber).toBe('+15551234567'); + expect(mockConfigSet).toHaveBeenCalledWith('profiles.default', expect.objectContaining({ phone: '+15551234567' })); + }); + + it.each(['', '@username', '+012345678', '+123', '+1234567890123456'])('rejects invalid --phone %s before connecting', async phone => { + await loginAction.call(createMockCommandContext({ phone }) as any); + expect(mockConnect).not.toHaveBeenCalled(); + expect(mockStart).not.toHaveBeenCalled(); + expect(mockStoreSave).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith(expect.stringContaining('Phone number must'), 'INVALID_INPUT'); + expect(mockClose).toHaveBeenCalledOnce(); + }); + + it('asks for a corrected phone when the interactive SDK flow retries it', async () => { + mockAsk.mockResolvedValueOnce('+15551234567').mockResolvedValueOnce('+15557654321'); + mockStart.mockImplementationOnce(async params => { + expect(await params.phoneNumber()).toBe('+15551234567'); + expect(await params.phoneNumber()).toBe('+15557654321'); + }); + await loginAction.call(createMockCommandContext() as any); + expect(mockConfigSet).toHaveBeenCalledWith('profiles.default', expect.objectContaining({ phone: '+15557654321' })); + }); + + it.each([false, true])('pauses SDK diagnostics during code/2FA input and restores them (reject=%s)', async reject => { + const { createGramjsLogger } = await import('../../src/lib/gramjs-logger.js'); + const { setVerboseMode } = await import('../../src/lib/cli-mode.js'); + const logger = createGramjsLogger(); + (mockClientInstance as any).logger = logger; + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + setVerboseMode(true); + const answer = async () => { + logger.debug('hidden ping during input'); + logger.error('hidden diagnostic during input'); + if (reject) throw new Error('prompt cancelled'); + return 'synthetic-code'; + }; + mockAsk.mockImplementationOnce(answer); + mockAskSecret.mockImplementationOnce(answer); + mockStart.mockImplementationOnce(async params => { + await params.phoneCode(true); + await params.password(); + }); + try { + await loginAction.call(createMockCommandContext({ phone: '+15551234567' }) as any); + logger.debug('diagnostics restored'); + const output = stderr.mock.calls.map(([chunk]) => String(chunk)).join(''); + expect(output).not.toContain('hidden ping'); + expect(output).not.toContain('hidden diagnostic'); + expect(output).toContain('diagnostics restored'); + } finally { + delete (mockClientInstance as any).logger; + setVerboseMode(false); + stderr.mockRestore(); + mockAsk.mockReset(); + mockAskSecret.mockReset(); + } + }); + + it('stops after exhausted connection retries without starting auth or saving a session', async () => { + mockConnect.mockResolvedValueOnce(false); + await loginAction.call(createMockCommandContext() as any); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), 'CONNECTION_FAILED'); + expect(mockStart).not.toHaveBeenCalled(); + expect(mockStoreSave).not.toHaveBeenCalled(); + expect(mockConfigSet).not.toHaveBeenCalled(); + expect(mockDestroy).toHaveBeenCalledOnce(); + expect(mockClose).toHaveBeenCalledOnce(); + }); + + it('outputs login metadata without disclosing the session string', async () => { + const ctx = createMockCommandContext(); + await loginAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data).toMatchObject({ loggedIn: true, profile: 'default' }); + expect(data).not.toHaveProperty('session'); + expect(JSON.stringify(data)).not.toContain('saved-session'); + expect(data).toHaveProperty('phone'); + }); + + it('destroys client and closes prompt on completion', async () => { + const ctx = createMockCommandContext(); + await loginAction.call(ctx as any); + + expect(mockDestroy).toHaveBeenCalled(); + expect(mockClose).toHaveBeenCalled(); + }); + + it('destroys client and closes prompt even on error', async () => { + mockStart.mockRejectedValueOnce(new Error('auth failed')); + const ctx = createMockCommandContext(); + + // Should not throw (error is handled gracefully) + await loginAction.call(ctx as any); + + expect(mockDestroy).toHaveBeenCalled(); + expect(mockClose).toHaveBeenCalled(); + }); + + it('outputs NOT_INTERACTIVE error when stdin is not a TTY', async () => { + Object.defineProperty(process.stdin, 'isTTY', { value: false, writable: true, configurable: true }); + const ctx = createMockCommandContext(); + + await loginAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Interactive login requires a terminal'), + 'NOT_INTERACTIVE', + ); + // Should NOT have tried to start auth + expect(mockStart).not.toHaveBeenCalled(); + }); + + it('uses askSecret for 2FA password callback (not ask)', async () => { + // Make client.start call the password callback + mockStart.mockImplementationOnce(async (opts: any) => { + await opts.phoneNumber(); + await opts.phoneCode(true); + await opts.password('my hint'); + }); + + const ctx = createMockCommandContext(); + await loginAction.call(ctx as any); + + // Phone and code should use ask() + expect(mockAsk).toHaveBeenCalledWith('Phone number (international format): '); + expect(mockAsk).toHaveBeenCalledWith('Code (from Telegram app): '); + // Password should use askSecret() for masked input + expect(mockAskSecret).toHaveBeenCalledWith('2FA password (hint: my hint): '); + }); +}); + +describe('statusAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('outputs authorized: false when no session file exists', async () => { + mockStoreLoad.mockResolvedValueOnce(''); + const ctx = createMockCommandContext(); + await statusAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.authorized).toBe(false); + }); + + it('checks authorization with existing session', async () => { + mockStoreLoad.mockResolvedValueOnce('existing-session'); + mockCheckAuthorization.mockResolvedValueOnce(true); + const ctx = createMockCommandContext(); + await statusAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.authorized).toBe(true); + }); + + it('serializes gramjs user.id as a string, not a BigInteger object', async () => { + mockStoreLoad.mockResolvedValueOnce('existing-session'); + mockCheckAuthorization.mockResolvedValueOnce(true); + // gramjs big-integer: JSON.stringify produces {} unless converted via toString() + const gramjsId = { + toString: () => '123456789012345', + toJSON: () => ({}), + }; + mockGetMe.mockResolvedValueOnce({ + id: gramjsId, + phone: '+15551234567', + username: 'testuser', + firstName: 'Test', + }); + const ctx = createMockCommandContext(); + await statusAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.authorized).toBe(true); + expect(data.user.id).toBe('123456789012345'); + expect(JSON.parse(JSON.stringify(data.user)).id).toBe('123456789012345'); + }); +}); + +describe('logoutAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('outputs error when not logged in', async () => { + mockStoreLoad.mockResolvedValueOnce(''); + const ctx = createMockCommandContext(); + await logoutAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledOnce(); + }); + + it('invokes auth.LogOut and deletes session file (without re-locking)', async () => { + mockStoreLoad.mockResolvedValueOnce('existing-session'); + const ctx = createMockCommandContext(); + await logoutAction.call(ctx as any); + + expect(mockInvoke).toHaveBeenCalled(); + // Must use deleteUnlocked (not delete) to avoid deadlock inside withLock + expect(mockStoreDeleteUnlocked).toHaveBeenCalledWith('default'); + expect(mockStoreDelete).not.toHaveBeenCalled(); + }); + + it('outputs loggedOut: true on success', async () => { + mockStoreLoad.mockResolvedValueOnce('existing-session'); + const ctx = createMockCommandContext(); + await logoutAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.loggedOut).toBe(true); + }); +}); + +describe('createAuthCommand', () => { + it('returns a Command with auth name', () => { + const cmd = createAuthCommand(); + expect(cmd.name()).toBe('auth'); + }); + + it('has login, status, and logout subcommands', () => { + const cmd = createAuthCommand(); + const subcommands = cmd.commands.map((c: any) => c.name()); + expect(subcommands).toContain('login'); + expect(subcommands).toContain('status'); + expect(subcommands).toContain('logout'); + }); +}); diff --git a/cli/tests/unit/chat-create.test.ts b/cli/tests/unit/chat-create.test.ts new file mode 100644 index 0000000..15741ef --- /dev/null +++ b/cli/tests/unit/chat-create.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + MockCreateChannel, + MockCreateChat, +} = vi.hoisted(() => { + const _MockCreateChannel = vi.fn().mockImplementation((args: any) => ({ className: 'channels.CreateChannel', ...args })); + const _MockCreateChat = vi.fn().mockImplementation((args: any) => ({ className: 'messages.CreateChat', ...args })); + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({ chats: [{ id: BigInt(999), title: 'New Chat' }] }), + MockCreateChannel: _MockCreateChannel, + MockCreateChat: _MockCreateChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + channels: { + CreateChannel: MockCreateChannel, + }, + messages: { + CreateChat: MockCreateChat, + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Import after mocks +import { chatCreateAction } from '../../src/commands/chat/create.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatCreateAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue({ chats: [{ id: BigInt(999), title: 'New Chat' }] }); + }); + + it('creates a supergroup by default (calls CreateChannel with megagroup=true)', async () => { + const ctx = createMockCommandContext(); + await chatCreateAction.call(ctx as any, 'My Supergroup'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(MockCreateChannel).toHaveBeenCalledWith( + expect.objectContaining({ title: 'My Supergroup', megagroup: true, broadcast: false }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.title).toBe('My Supergroup'); + expect(data.type).toBe('supergroup'); + expect(data.id).toBe('-100999'); + }); + + it('creates a channel when --type channel is passed (broadcast=true)', async () => { + const ctx = createMockCommandContext({ type: 'channel' }); + await chatCreateAction.call(ctx as any, 'My Channel'); + + expect(MockCreateChannel).toHaveBeenCalledWith( + expect.objectContaining({ title: 'My Channel', broadcast: true, megagroup: false }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.type).toBe('channel'); + }); + + it('creates a basic group when --type group and --members are passed', async () => { + const user = { id: BigInt(7), className: 'User' }; + mockResolveEntity.mockResolvedValueOnce(user); + const ctx = createMockCommandContext({ type: 'group', members: '@alice' }); + await chatCreateAction.call(ctx as any, 'My Group'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@alice'); + expect(MockCreateChat).toHaveBeenCalledWith( + expect.objectContaining({ title: 'My Group', users: [user] }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-999'); + expect(data.type).toBe('group'); + }); + + it('errors when --type group is passed without --members', async () => { + const ctx = createMockCommandContext({ type: 'group' }); + await chatCreateAction.call(ctx as any, 'My Group'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--members'), + 'INVALID_OPTIONS', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('errors on unknown --type before connecting', async () => { + const ctx = createMockCommandContext({ type: 'banana' }); + await chatCreateAction.call(ctx as any, 'Nope'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('banana'), + 'INVALID_CHAT_TYPE', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('passes description as about when provided', async () => { + const ctx = createMockCommandContext({ description: 'A test description' }); + await chatCreateAction.call(ctx as any, 'Described Chat'); + + expect(MockCreateChannel).toHaveBeenCalledWith( + expect.objectContaining({ about: 'A test description' }), + ); + }); + + it('errors on empty title', async () => { + const ctx = createMockCommandContext(); + await chatCreateAction.call(ctx as any, ''); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('INVALID_INPUT'); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('outputs null id when result has no chats', async () => { + mockInvoke.mockResolvedValueOnce({}); + const ctx = createMockCommandContext(); + await chatCreateAction.call(ctx as any, 'Empty Result'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBeNull(); + }); +}); diff --git a/cli/tests/unit/chat-edit.test.ts b/cli/tests/unit/chat-edit.test.ts new file mode 100644 index 0000000..5cfea56 --- /dev/null +++ b/cli/tests/unit/chat-edit.test.ts @@ -0,0 +1,216 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChannel, + MockChat, + MockUser, + MockEditTitle, + MockEditAbout, + MockEditChatTitle, + MockEditChatAbout, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; } + }; + const _MockChat = class Chat { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(200); this.title = args.title ?? 'Test Group'; } + }; + const _MockUser = class User { + id: any; + constructor(args: any = {}) { this.id = args.id ?? BigInt(1); } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + MockChannel: _MockChannel, + MockChat: _MockChat, + MockUser: _MockUser, + MockEditTitle: vi.fn().mockImplementation((args: any) => ({ className: 'channels.EditTitle', ...args })), + MockEditAbout: vi.fn().mockImplementation((args: any) => ({ className: 'channels.EditAbout', ...args })), + MockEditChatTitle: vi.fn().mockImplementation((args: any) => ({ className: 'messages.EditChatTitle', ...args })), + MockEditChatAbout: vi.fn().mockImplementation((args: any) => ({ className: 'messages.EditChatAbout', ...args })), + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + Chat: MockChat, + User: MockUser, + channels: { + EditTitle: MockEditTitle, + EditAbout: MockEditAbout, + }, + messages: { + EditChatTitle: MockEditChatTitle, + EditChatAbout: MockEditChatAbout, + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Import after mocks +import { chatEditAction } from '../../src/commands/chat/edit.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatEditAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue({}); + }); + + it('errors when neither --title nor --description provided', async () => { + const ctx = createMockCommandContext(); + await chatEditAction.call(ctx as any, '@mychat'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('INVALID_INPUT'); + expect(mockResolveEntity).not.toHaveBeenCalled(); + }); + + it('calls EditTitle for Channel entity when --title provided', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'Old Title' }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ title: 'New Title' }); + await chatEditAction.call(ctx as any, '@mychannel'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@mychannel'); + expect(MockEditTitle).toHaveBeenCalledWith( + expect.objectContaining({ channel: entity, title: 'New Title' }), + ); + expect(MockEditChatAbout).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.updated).toBe(true); + expect(data.title).toBe('New Title'); + expect(data.description).toBeNull(); + }); + + it('calls EditChatAbout for Channel entity when --description provided', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ description: 'New about text' }); + await chatEditAction.call(ctx as any, '@mychannel'); + + expect(MockEditChatAbout).toHaveBeenCalledWith( + expect.objectContaining({ peer: entity, about: 'New about text' }), + ); + expect(MockEditTitle).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.description).toBe('New about text'); + expect(data.title).toBeNull(); + }); + + it('calls both EditTitle and EditChatAbout for Channel when both options provided', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ title: 'New Title', description: 'New Desc' }); + await chatEditAction.call(ctx as any, '@mychannel'); + + expect(MockEditTitle).toHaveBeenCalledOnce(); + expect(MockEditChatAbout).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('calls EditChatTitle for basic Chat entity', async () => { + const entity = new MockChat({ id: BigInt(200), title: 'My Group' }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ title: 'Renamed Group' }); + await chatEditAction.call(ctx as any, '200'); + + expect(MockEditChatTitle).toHaveBeenCalledWith( + expect.objectContaining({ chatId: entity.id, title: 'Renamed Group' }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chatId).toBe('-200'); + }); + + it('calls EditChatAbout for basic Chat entity', async () => { + const entity = new MockChat({ id: BigInt(200) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ description: 'Group about' }); + await chatEditAction.call(ctx as any, '200'); + + expect(MockEditChatAbout).toHaveBeenCalledWith( + expect.objectContaining({ peer: entity, about: 'Group about' }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('errors when entity is a User (cannot edit user chat)', async () => { + const entity = new MockUser({ id: BigInt(1) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext({ title: 'New Title' }); + await chatEditAction.call(ctx as any, 'someuser'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('INVALID_CHAT_TYPE'); + expect(mockOutputSuccess).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/chat-info.test.ts b/cli/tests/unit/chat-info.test.ts new file mode 100644 index 0000000..41373b8 --- /dev/null +++ b/cli/tests/unit/chat-info.test.ts @@ -0,0 +1,279 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state for telegram client + Api classes +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChannel, + MockChat, + MockUser, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; username: string | null; megagroup: boolean; date: number; photo: any; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; + this.username = args.username ?? null; this.megagroup = args.megagroup ?? false; + this.date = args.date ?? 1700000000; this.photo = args.photo ?? null; + } + }; + const _MockChat = class Chat { + id: any; title: string; date: number; photo: any; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(200); this.title = args.title ?? 'Test Group'; + this.date = args.date ?? 1700000000; this.photo = args.photo ?? null; + } + }; + const _MockUser = class User { + id: any; firstName: string; lastName: string | null; username: string | null; phone: string | null; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(300); this.firstName = args.firstName ?? 'Test'; + this.lastName = args.lastName ?? null; this.username = args.username ?? null; + this.phone = args.phone ?? null; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + MockChannel: _MockChannel, + MockChat: _MockChat, + MockUser: _MockUser, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + Chat: MockChat, + User: MockUser, + channels: { + GetFullChannel: vi.fn().mockImplementation((args: any) => ({ className: 'channels.GetFullChannel', ...args })), + }, + messages: { + GetFullChat: vi.fn().mockImplementation((args: any) => ({ className: 'messages.GetFullChat', ...args })), + }, + users: { + GetFullUser: vi.fn().mockImplementation((args: any) => ({ className: 'users.GetFullUser', ...args })), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Import after mocks +import { chatInfoAction } from '../../src/commands/chat/info.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('chatInfoAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns channel info via GetFullChannel', async () => { + const channelEntity = new MockChannel({ + id: BigInt(100), title: 'My Channel', username: 'mychan', + megagroup: false, date: 1700000000, + }); + mockResolveEntity.mockResolvedValueOnce(channelEntity); + mockInvoke.mockResolvedValueOnce({ + fullChat: { + about: 'Channel description', + participantsCount: 5000, + adminsCount: 10, + linkedChatId: BigInt(999), + slowmodeSeconds: 0, + exportedInvite: { link: 'https://t.me/+abc123' }, + migratedFromChatId: null, + }, + }); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, 'mychan'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'mychan'); + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-100100'); + expect(data.title).toBe('My Channel'); + expect(data.type).toBe('channel'); + expect(data.username).toBe('mychan'); + expect(data.description).toBe('Channel description'); + expect(data.memberCount).toBe(5000); + expect(data.inviteLink).toBe('https://t.me/+abc123'); + }); + + it('returns supergroup info with megagroup flag', async () => { + const sgEntity = new MockChannel({ + id: BigInt(101), title: 'Supergroup', username: 'sg1', + megagroup: true, date: 1700000000, + }); + mockResolveEntity.mockResolvedValueOnce(sgEntity); + mockInvoke.mockResolvedValueOnce({ + fullChat: { + about: 'SG description', + participantsCount: 200, + adminsCount: 5, + linkedChatId: null, + slowmodeSeconds: 30, + exportedInvite: null, + migratedFromChatId: BigInt(50), + }, + }); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, 'sg1'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.type).toBe('supergroup'); + expect(data.slowmodeSeconds).toBe(30); + expect(data.migratedFrom).toBe('-50'); + }); + + it('returns basic group info via GetFullChat', async () => { + const groupEntity = new MockChat({ + id: BigInt(200), title: 'My Group', date: 1700000000, + }); + mockResolveEntity.mockResolvedValueOnce(groupEntity); + mockInvoke.mockResolvedValueOnce({ + fullChat: { + about: 'Group description', + participants: { participants: [{}, {}, {}] }, + exportedInvite: { link: 'https://t.me/+grouphash' }, + }, + }); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, '200'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-200'); + expect(data.title).toBe('My Group'); + expect(data.type).toBe('group'); + expect(data.description).toBe('Group description'); + expect(data.memberCount).toBe(3); + expect(data.inviteLink).toBe('https://t.me/+grouphash'); + }); + + it('returns user info without GetFull call', async () => { + const userEntity = new MockUser({ + id: BigInt(300), firstName: 'Alice', lastName: 'Smith', username: 'alice', + }); + mockResolveEntity.mockResolvedValueOnce(userEntity); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, 'alice'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('300'); + expect(data.title).toBe('Alice Smith'); + expect(data.type).toBe('user'); + expect(data.username).toBe('alice'); + // Users have null for group-specific fields + expect(data.memberCount).toBeNull(); + expect(data.slowmodeSeconds).toBeNull(); + }); + + it('handles null/missing fields gracefully', async () => { + const channelEntity = new MockChannel({ + id: BigInt(105), title: 'Sparse Channel', username: null, + megagroup: false, date: 1700000000, photo: null, + }); + mockResolveEntity.mockResolvedValueOnce(channelEntity); + mockInvoke.mockResolvedValueOnce({ + fullChat: { + about: null, + participantsCount: null, + adminsCount: null, + linkedChatId: null, + slowmodeSeconds: null, + exportedInvite: null, + migratedFromChatId: null, + }, + }); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, '105'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.description).toBeNull(); + expect(data.memberCount).toBeNull(); + expect(data.linkedChatId).toBeNull(); + expect(data.inviteLink).toBeNull(); + }); + + it('outputs error on resolve failure', async () => { + mockResolveEntity.mockRejectedValueOnce(new Error('Peer not found')); + + const ctx = createMockCommandContext(); + await chatInfoAction.call(ctx as any, 'nonexistent'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError).toHaveBeenCalledWith('Peer not found', 'UNKNOWN_ERROR'); + }); +}); diff --git a/cli/tests/unit/chat-invite-info.test.ts b/cli/tests/unit/chat-invite-info.test.ts new file mode 100644 index 0000000..e0f91fe --- /dev/null +++ b/cli/tests/unit/chat-invite-info.test.ts @@ -0,0 +1,192 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChatInviteAlready, + MockChatInvitePeek, + MockChatInvite, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn(), + MockChatInviteAlready: class ChatInviteAlready {}, + MockChatInvitePeek: class ChatInvitePeek {}, + MockChatInvite: class ChatInvite {}, +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + ChatInviteAlready: MockChatInviteAlready, + ChatInvitePeek: MockChatInvitePeek, + ChatInvite: MockChatInvite, + messages: { + CheckChatInvite: vi.fn().mockImplementation((opts: any) => opts), + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +const mockExtractInviteHash = vi.fn().mockReturnValue('abc123'); +vi.mock('../../src/lib/peer.js', () => ({ + extractInviteHash: (...args: any[]) => mockExtractInviteHash(...args), +})); + +const mockBigIntToString = vi.fn((val: any) => val?.toString() ?? ''); +vi.mock('../../src/lib/serialize.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/serialize.js')>(); + return { ...actual, bigIntToString: (val: any) => mockBigIntToString(val) }; +}); + +import { chatInviteInfoAction } from '../../src/commands/chat/invite-info.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + ...opts, + })), + }; +} + +describe('chatInviteInfoAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('ChatInviteAlready → alreadyMember: true with chat info', async () => { + const result = Object.create(MockChatInviteAlready.prototype); + result.chat = { id: { toString: () => '100' }, title: 'Existing Group' }; + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+abc123'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(true); + expect(data.chat.id).toBe('100'); + expect(data.chat.title).toBe('Existing Group'); + }); + + it('ChatInvitePeek → alreadyMember: false with chat and expires', async () => { + const result = Object.create(MockChatInvitePeek.prototype); + result.chat = { id: { toString: () => '200' }, title: 'Peek Group' }; + result.expires = 1710150900; // 2024-03-11T09:55:00Z + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+xyz789'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(false); + expect(data.chat.id).toBe('200'); + expect(data.chat.title).toBe('Peek Group'); + expect(data.expires).toBe(new Date(1710150900 * 1000).toISOString()); + }); + + it('ChatInvite → preview info with title, about, participantsCount', async () => { + const result = Object.create(MockChatInvite.prototype); + Object.assign(result, { + title: 'New Group', + about: 'A cool group', + participantsCount: 42, + channel: true, + broadcast: false, + }); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+invite'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(false); + expect(data.title).toBe('New Group'); + expect(data.about).toBe('A cool group'); + expect(data.participantsCount).toBe(42); + expect(data.channel).toBe(true); + expect(data.broadcast).toBe(false); + }); + + it('unknown result type → outputs error', async () => { + // Some unknown object that doesn't match any known class + mockInvoke.mockResolvedValueOnce({ unknownField: true }); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+unknown'); + + expect(mockOutputError).toHaveBeenCalledWith('Unknown invite result type', 'UNKNOWN_INVITE_TYPE'); + }); + + it('invalid invite link → error from extractInviteHash', async () => { + const { TgError } = await import('../../src/lib/errors.js'); + mockExtractInviteHash.mockImplementationOnce(() => { + throw new TgError('Invalid invite link format', 'INVALID_INVITE'); + }); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'not-a-link'); + + expect(mockOutputError).toHaveBeenCalledWith('Invalid invite link format', 'INVALID_INVITE'); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+abc'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/chat-invite.test.ts b/cli/tests/unit/chat-invite.test.ts new file mode 100644 index 0000000..b252c31 --- /dev/null +++ b/cli/tests/unit/chat-invite.test.ts @@ -0,0 +1,182 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const mockExtractInviteHash = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + extractInviteHash: (...args: any[]) => mockExtractInviteHash(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChatInviteAlready, + MockChatInvite, + MockChatInvitePeek, +} = vi.hoisted(() => { + const _MockChatInviteAlready = class ChatInviteAlready { + chat: any; + constructor(args: any = {}) { this.chat = args.chat ?? { id: BigInt(100), title: 'Already Joined' }; } + }; + const _MockChatInvite = class ChatInvite { + title: string; about: string | null; participantsCount: number; channel: boolean; broadcast: boolean; + constructor(args: any = {}) { + this.title = args.title ?? 'Invite Group'; + this.about = args.about ?? null; + this.participantsCount = args.participantsCount ?? 100; + this.channel = args.channel ?? false; + this.broadcast = args.broadcast ?? false; + } + }; + const _MockChatInvitePeek = class ChatInvitePeek { + chat: any; expires: number; + constructor(args: any = {}) { + this.chat = args.chat ?? { id: BigInt(200), title: 'Peek Group' }; + this.expires = args.expires ?? 1700000000; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + MockChatInviteAlready: _MockChatInviteAlready, + MockChatInvite: _MockChatInvite, + MockChatInvitePeek: _MockChatInvitePeek, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + ChatInviteAlready: MockChatInviteAlready, + ChatInvite: MockChatInvite, + ChatInvitePeek: MockChatInvitePeek, + messages: { + CheckChatInvite: vi.fn().mockImplementation((args: any) => ({ className: 'messages.CheckChatInvite', ...args })), + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +import { chatInviteInfoAction } from '../../src/commands/chat/invite-info.js'; +import { TgError } from '../../src/lib/errors.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatInviteInfoAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('handles already-member invite result', async () => { + mockExtractInviteHash.mockReturnValueOnce('abc123'); + const result = new MockChatInviteAlready({ + chat: { id: BigInt(100), title: 'Already Group' }, + }); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+abc123'); + + expect(mockExtractInviteHash).toHaveBeenCalledWith('https://t.me/+abc123'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(true); + expect(data.chat.title).toBe('Already Group'); + }); + + it('handles invite preview result', async () => { + mockExtractInviteHash.mockReturnValueOnce('def456'); + const result = new MockChatInvite({ + title: 'Preview Group', + about: 'Some description', + participantsCount: 500, + channel: false, + broadcast: false, + }); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+def456'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(false); + expect(data.title).toBe('Preview Group'); + expect(data.about).toBe('Some description'); + expect(data.participantsCount).toBe(500); + }); + + it('handles peek result with expiry', async () => { + mockExtractInviteHash.mockReturnValueOnce('ghi789'); + const result = new MockChatInvitePeek({ + chat: { id: BigInt(200), title: 'Peek Group' }, + expires: 1700000000, + }); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'https://t.me/+ghi789'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.alreadyMember).toBe(false); + expect(data.chat.title).toBe('Peek Group'); + expect(data.expires).toBeDefined(); + }); + + it('outputs error for invalid link', async () => { + mockExtractInviteHash.mockImplementationOnce(() => { + throw new TgError('Invalid invite link format', 'INVALID_INVITE'); + }); + + const ctx = createMockCommandContext(); + await chatInviteInfoAction.call(ctx as any, 'not-a-link'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toContain('Invalid invite link'); + expect(mockOutputError.mock.calls[0][1]).toBe('INVALID_INVITE'); + }); +}); diff --git a/cli/tests/unit/chat-join.test.ts b/cli/tests/unit/chat-join.test.ts new file mode 100644 index 0000000..2dc8e9c --- /dev/null +++ b/cli/tests/unit/chat-join.test.ts @@ -0,0 +1,165 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +const mockExtractInviteHash = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + extractInviteHash: (...args: any[]) => mockExtractInviteHash(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + mockGetInputEntity, + MockChannel, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; username: string | null; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; + this.username = args.username ?? null; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + mockGetInputEntity: vi.fn().mockResolvedValue({ className: 'InputPeerChannel' }), + MockChannel: _MockChannel, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, + getInputEntity: mockGetInputEntity, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + channels: { + JoinChannel: vi.fn().mockImplementation((args: any) => ({ className: 'channels.JoinChannel', ...args })), + }, + messages: { + ImportChatInvite: vi.fn().mockImplementation((args: any) => ({ className: 'messages.ImportChatInvite', ...args })), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Import after mocks +import { chatJoinAction } from '../../src/commands/chat/join.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatJoinAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('joins by username via JoinChannel', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'My Group', username: 'mygroup' }); + mockResolveEntity.mockResolvedValueOnce(entity); + mockInvoke.mockResolvedValueOnce({}); + + const ctx = createMockCommandContext(); + await chatJoinAction.call(ctx as any, '@mygroup'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@mygroup'); + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.joined).toBe(true); + expect(data.chat.title).toBe('My Group'); + }); + + it('joins by invite link via ImportChatInvite', async () => { + mockExtractInviteHash.mockReturnValueOnce('abc123hash'); + mockInvoke.mockResolvedValueOnce({ + chats: [{ id: BigInt(200), title: 'Invite Group' }], + }); + + const ctx = createMockCommandContext(); + await chatJoinAction.call(ctx as any, 'https://t.me/+abc123hash'); + + expect(mockExtractInviteHash).toHaveBeenCalledWith('https://t.me/+abc123hash'); + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.joined).toBe(true); + }); + + it('handles USER_ALREADY_PARTICIPANT error', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'Group' }); + mockResolveEntity.mockResolvedValueOnce(entity); + mockInvoke.mockRejectedValueOnce(new Error('USER_ALREADY_PARTICIPANT')); + + const ctx = createMockCommandContext(); + await chatJoinAction.call(ctx as any, '@group'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toContain('already'); + }); + + it('handles CHANNELS_TOO_MUCH error', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'Group' }); + mockResolveEntity.mockResolvedValueOnce(entity); + mockInvoke.mockRejectedValueOnce(new Error('CHANNELS_TOO_MUCH')); + + const ctx = createMockCommandContext(); + await chatJoinAction.call(ctx as any, '@group'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toContain('limit'); + }); +}); diff --git a/cli/tests/unit/chat-kick.test.ts b/cli/tests/unit/chat-kick.test.ts new file mode 100644 index 0000000..b95d3ce --- /dev/null +++ b/cli/tests/unit/chat-kick.test.ts @@ -0,0 +1,194 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChannel, + MockChat, + MockUser, + MockEditBanned, + MockChatBannedRights, + MockDeleteChatUser, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; } + }; + const _MockChat = class Chat { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(200); this.title = args.title ?? 'Test Group'; } + }; + const _MockUser = class User { + id: any; username: string | null; + constructor(args: any = {}) { this.id = args.id ?? BigInt(1); this.username = args.username ?? null; } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + MockChannel: _MockChannel, + MockChat: _MockChat, + MockUser: _MockUser, + MockEditBanned: vi.fn().mockImplementation((args: any) => ({ className: 'channels.EditBanned', ...args })), + MockChatBannedRights: vi.fn().mockImplementation((args: any) => ({ className: 'ChatBannedRights', ...args })), + MockDeleteChatUser: vi.fn().mockImplementation((args: any) => ({ className: 'messages.DeleteChatUser', ...args })), + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + Chat: MockChat, + User: MockUser, + ChatBannedRights: MockChatBannedRights, + channels: { + EditBanned: MockEditBanned, + }, + messages: { + DeleteChatUser: MockDeleteChatUser, + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Import after mocks +import { chatKickAction } from '../../src/commands/chat/kick.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatKickAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue({}); + }); + + it('calls EditBanned for Channel entity with viewMessages=true', async () => { + const chatEntity = new MockChannel({ id: BigInt(100), title: 'My Channel' }); + const userEntity = new MockUser({ id: BigInt(42), username: 'target_user' }); + mockResolveEntity + .mockResolvedValueOnce(chatEntity) + .mockResolvedValueOnce(userEntity); + + const ctx = createMockCommandContext(); + await chatKickAction.call(ctx as any, '@mychannel', '@target_user'); + + expect(mockResolveEntity).toHaveBeenCalledTimes(2); + expect(mockResolveEntity).toHaveBeenNthCalledWith(1, mockClientInstance, '@mychannel'); + expect(mockResolveEntity).toHaveBeenNthCalledWith(2, mockClientInstance, '@target_user'); + + expect(MockChatBannedRights).toHaveBeenCalledWith( + expect.objectContaining({ viewMessages: true }), + ); + expect(MockEditBanned).toHaveBeenCalledWith( + expect.objectContaining({ channel: chatEntity, participant: userEntity }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.kicked).toBe(true); + expect(data.chatId).toBe('-100100'); + expect(data.userId).toBe('42'); + }); + + it('calls DeleteChatUser for basic Chat entity', async () => { + const chatEntity = new MockChat({ id: BigInt(200), title: 'My Group' }); + const userEntity = new MockUser({ id: BigInt(55) }); + mockResolveEntity + .mockResolvedValueOnce(chatEntity) + .mockResolvedValueOnce(userEntity); + + const ctx = createMockCommandContext(); + await chatKickAction.call(ctx as any, '200', '55'); + + expect(MockDeleteChatUser).toHaveBeenCalledWith( + expect.objectContaining({ chatId: chatEntity.id, userId: userEntity }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.kicked).toBe(true); + expect(data.chatId).toBe('-200'); + }); + + it('errors when target entity is not a User', async () => { + const chatEntity = new MockChannel({ id: BigInt(100) }); + // Return a Channel as the "user" — not a User instance + const notAUser = new MockChannel({ id: BigInt(999) }); + mockResolveEntity + .mockResolvedValueOnce(chatEntity) + .mockResolvedValueOnce(notAUser); + + const ctx = createMockCommandContext(); + await chatKickAction.call(ctx as any, '@mychannel', '@notauser'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('NOT_A_USER'); + expect(mockOutputSuccess).not.toHaveBeenCalled(); + }); + + it('errors when chat entity is not a Channel or Chat', async () => { + // Return a User as the chat entity + const notAChat = new MockUser({ id: BigInt(1) }); + const userEntity = new MockUser({ id: BigInt(2) }); + mockResolveEntity + .mockResolvedValueOnce(notAChat) + .mockResolvedValueOnce(userEntity); + + const ctx = createMockCommandContext(); + await chatKickAction.call(ctx as any, 'someuser', '@target'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('INVALID_CHAT_TYPE'); + expect(mockOutputSuccess).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/chat-leave.test.ts b/cli/tests/unit/chat-leave.test.ts new file mode 100644 index 0000000..47b0ea4 --- /dev/null +++ b/cli/tests/unit/chat-leave.test.ts @@ -0,0 +1,144 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + mockInvoke, + mockGetMe, + MockChannel, + MockChat, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; } + }; + const _MockChat = class Chat { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(200); this.title = args.title ?? 'Test Group'; } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + mockGetMe: vi.fn().mockResolvedValue({ id: BigInt(999) }), + MockChannel: _MockChannel, + MockChat: _MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, + getMe: mockGetMe, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + Chat: MockChat, + channels: { + LeaveChannel: vi.fn().mockImplementation((args: any) => ({ className: 'channels.LeaveChannel', ...args })), + }, + messages: { + DeleteChatUser: vi.fn().mockImplementation((args: any) => ({ className: 'messages.DeleteChatUser', ...args })), + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +import { chatLeaveAction } from '../../src/commands/chat/leave.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatLeaveAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('leaves a channel via LeaveChannel', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'My Channel' }); + mockResolveEntity.mockResolvedValueOnce(entity); + mockInvoke.mockResolvedValueOnce({}); + + const ctx = createMockCommandContext(); + await chatLeaveAction.call(ctx as any, '@mychannel'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@mychannel'); + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.left).toBe(true); + expect(data.chat.title).toBe('My Channel'); + }); + + it('leaves a basic group via DeleteChatUser', async () => { + const entity = new MockChat({ id: BigInt(200), title: 'My Group' }); + mockResolveEntity.mockResolvedValueOnce(entity); + mockInvoke.mockResolvedValueOnce({}); + + const ctx = createMockCommandContext(); + await chatLeaveAction.call(ctx as any, '200'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockGetMe).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.left).toBe(true); + expect(data.chat.title).toBe('My Group'); + }); + + it('outputs error on failure', async () => { + mockResolveEntity.mockRejectedValueOnce(new Error('Peer not found')); + + const ctx = createMockCommandContext(); + await chatLeaveAction.call(ctx as any, 'unknown'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + }); +}); diff --git a/cli/tests/unit/chat-list.test.ts b/cli/tests/unit/chat-list.test.ts new file mode 100644 index 0000000..9c49c29 --- /dev/null +++ b/cli/tests/unit/chat-list.test.ts @@ -0,0 +1,295 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetDialogs, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetDialogs: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getDialogs: mockGetDialogs, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Helper to create mock dialog objects matching gramjs Dialog shape +function createMockDialog(overrides: Record<string, any> = {}) { + const id = overrides.id ?? BigInt(123); + const defaults = { + id, + title: 'Test Chat', + name: 'Test Chat', + isUser: false, + isChannel: false, + isGroup: true, + unreadCount: 0, + date: 1_700_000_000, + message: { id: Number(id), date: 1_700_000_000 }, + inputEntity: { className: 'InputPeerChat', chatId: id }, + entity: { username: null, megagroup: false }, + }; + return { ...defaults, ...overrides }; +} + +// Import after mocks +import { chatListAction } from '../../src/commands/chat/list.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('chatListAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('lists dialogs and outputs serialized chats', async () => { + const dialogs = [ + createMockDialog({ id: BigInt(1), title: 'Group One', isGroup: true }), + createMockDialog({ id: BigInt(2), title: 'Channel Two', isChannel: true, isGroup: false, entity: { username: 'chan2', megagroup: false } }), + ]; + (dialogs as any).total = 100; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext(); + await chatListAction.call(ctx as any); + + expect(mockGetDialogs).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(2); + expect(data.total).toBe(100); + expect(data.chats[0].title).toBe('Group One'); + expect(data.chats[0].type).toBe('group'); + expect(data.chats[1].title).toBe('Channel Two'); + expect(data.chats[1].type).toBe('channel'); + }); + + it('filters by --type group', async () => { + const dialogs = [ + createMockDialog({ id: BigInt(1), title: 'Group One', isGroup: true }), + createMockDialog({ id: BigInt(2), title: 'Channel Two', isChannel: true, isGroup: false }), + createMockDialog({ id: BigInt(3), title: 'User Three', isUser: true, isGroup: false }), + ]; + (dialogs as any).total = 50; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext({ type: 'group' }); + await chatListAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(1); + expect(data.chats[0].type).toBe('group'); + expect(data.chats[0].title).toBe('Group One'); + expect(data.total).toBe(1); + }); + + it('keeps fetching until --type page is full', async () => { + const first = Array.from({ length: 100 }, (_, i) => { + if (i === 0) { + return createMockDialog({ id: BigInt(1), title: 'Group One', isGroup: true }); + } + return createMockDialog({ + id: BigInt(i + 1), + title: `User ${i + 1}`, + isUser: true, + isGroup: false, + }); + }); + const second = [ + createMockDialog({ id: BigInt(201), title: 'Group Two', isGroup: true }), + createMockDialog({ id: BigInt(202), title: 'Group Three', isGroup: true }), + createMockDialog({ id: BigInt(203), title: 'User Extra', isUser: true, isGroup: false }), + ]; + mockGetDialogs + .mockResolvedValueOnce(first) + .mockResolvedValueOnce(second); + + const ctx = createMockCommandContext({ type: 'group', limit: '2' }); + await chatListAction.call(ctx as any); + + expect(mockGetDialogs).toHaveBeenCalledTimes(2); + expect(mockGetDialogs).toHaveBeenNthCalledWith(1, expect.objectContaining({ limit: 100 })); + expect(mockGetDialogs).toHaveBeenNthCalledWith( + 2, + expect.objectContaining({ + limit: 100, + offsetId: first[99].message.id, + offsetPeer: first[99].inputEntity, + }), + ); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.hasMore).toBe(true); + expect(data.chats).toHaveLength(2); + expect(data.chats.map((c: { title: string }) => c.title)).toEqual(['Group One', 'Group Two']); + expect(data.chats.every((c: { type: string }) => c.type === 'group')).toBe(true); + }); + + it('hasMore is false when MAX_DIALOGS is hit without filling the typed page', async () => { + let n = 0; + mockGetDialogs.mockImplementation(async () => { + return Array.from({ length: 100 }, () => { + n += 1; + return createMockDialog({ + id: BigInt(n), + title: `User ${n}`, + isUser: true, + isGroup: false, + }); + }); + }); + + const ctx = createMockCommandContext({ type: 'group', limit: '2' }); + await chatListAction.call(ctx as any); + + expect(mockGetDialogs).toHaveBeenCalledTimes(50); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toEqual([]); + expect(data.hasMore).toBe(false); + }); + + it('filters by --type channel', async () => { + const dialogs = [ + createMockDialog({ id: BigInt(1), title: 'Group One', isGroup: true }), + createMockDialog({ id: BigInt(2), title: 'Channel Two', isChannel: true, isGroup: false }), + ]; + (dialogs as any).total = 50; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext({ type: 'channel' }); + await chatListAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(1); + expect(data.chats[0].type).toBe('channel'); + }); + + it('applies --limit and --offset pagination', async () => { + const dialogs = Array.from({ length: 15 }, (_, i) => + createMockDialog({ id: BigInt(i + 1), title: `Chat ${i + 1}` }), + ); + (dialogs as any).total = 100; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await chatListAction.call(ctx as any); + + // Should fetch offset+limit=15 dialogs + expect(mockGetDialogs).toHaveBeenCalledWith( + expect.objectContaining({ limit: 15 }), + ); + + const data = mockOutputSuccess.mock.calls[0][0]; + // Sliced from offset 5, take 10 items -> items 5-14 (indices 5 through 14) + expect(data.chats).toHaveLength(10); + expect(data.chats[0].title).toBe('Chat 6'); + expect(data.chats[9].title).toBe('Chat 15'); + }); + + it('handles empty dialog list', async () => { + const dialogs: any[] = []; + (dialogs as any).total = 0; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext(); + await chatListAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(0); + expect(data.total).toBe(0); + }); + + it('includes total count in output', async () => { + const dialogs = [ + createMockDialog({ id: BigInt(1), title: 'One' }), + ]; + (dialogs as any).total = 500; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext({ limit: '1', offset: '0' }); + await chatListAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.total).toBe(500); + }); + + it('detects supergroup type via megagroup flag', async () => { + const dialogs = [ + createMockDialog({ id: BigInt(1), title: 'Supergroup', isChannel: true, isGroup: false, entity: { username: 'sg1', megagroup: true } }), + ]; + (dialogs as any).total = 1; + mockGetDialogs.mockResolvedValueOnce(dialogs); + + const ctx = createMockCommandContext(); + await chatListAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats[0].type).toBe('supergroup'); + }); +}); diff --git a/cli/tests/unit/chat-members.test.ts b/cli/tests/unit/chat-members.test.ts new file mode 100644 index 0000000..0a930b2 --- /dev/null +++ b/cli/tests/unit/chat-members.test.ts @@ -0,0 +1,223 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state for telegram client + Api classes +const { + mockConnect, + mockDestroy, + mockGetParticipants, + MockChannel, + MockUser, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; } + }; + const _MockUser = class User { + id: any; username: string | null; firstName: string | null; lastName: string | null; bot: boolean; status: any; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(1); this.username = args.username ?? null; + this.firstName = args.firstName ?? null; this.lastName = args.lastName ?? null; + this.bot = args.bot ?? false; this.status = args.status ?? null; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetParticipants: vi.fn().mockResolvedValue([]), + MockChannel: _MockChannel, + MockUser: _MockUser, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getParticipants: mockGetParticipants, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + User: MockUser, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Helper to create mock user participants +function createMockUser(overrides: Record<string, any> = {}) { + return { + id: BigInt(1), + username: null, + firstName: null, + lastName: null, + bot: false, + status: null, + ...overrides, + }; +} + +// Import after mocks +import { chatMembersAction } from '../../src/commands/chat/members.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('chatMembersAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('lists members with serialized output', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'Test Group' }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const participants = [ + createMockUser({ id: BigInt(1), username: 'alice', firstName: 'Alice', lastName: 'Smith' }), + createMockUser({ id: BigInt(2), username: 'bob', firstName: 'Bob', bot: true, status: { className: 'UserStatusOnline' } }), + ]; + (participants as any).total = 2; + mockGetParticipants.mockResolvedValueOnce(participants); + + const ctx = createMockCommandContext(); + await chatMembersAction.call(ctx as any, 'testgroup'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testgroup'); + expect(mockGetParticipants).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.members).toHaveLength(2); + expect(data.total).toBe(2); + expect(data.members[0].username).toBe('alice'); + expect(data.members[0].firstName).toBe('Alice'); + expect(data.members[0].lastName).toBe('Smith'); + expect(data.members[0].isBot).toBe(false); + expect(data.members[1].username).toBe('bob'); + expect(data.members[1].isBot).toBe(true); + expect(data.members[1].status).toBe('UserStatusOnline'); + }); + + it('applies limit and offset pagination', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const participants = [ + createMockUser({ id: BigInt(10), firstName: 'User10' }), + ]; + (participants as any).total = 50; + mockGetParticipants.mockResolvedValueOnce(participants); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await chatMembersAction.call(ctx as any, 'group'); + + expect(mockGetParticipants).toHaveBeenCalledWith( + entity, + expect.objectContaining({ limit: 10, offset: 5 }), + ); + }); + + it('applies search filter', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const participants: any[] = []; + (participants as any).total = 0; + mockGetParticipants.mockResolvedValueOnce(participants); + + const ctx = createMockCommandContext({ search: 'alice' }); + await chatMembersAction.call(ctx as any, 'group'); + + expect(mockGetParticipants).toHaveBeenCalledWith( + entity, + expect.objectContaining({ search: 'alice' }), + ); + }); + + it('handles CHAT_ADMIN_REQUIRED error gracefully', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + // gramjs throws an Error instance with message containing the RPC code + const rpcErr = new Error('CHAT_ADMIN_REQUIRED'); + mockGetParticipants.mockRejectedValueOnce(rpcErr); + + const ctx = createMockCommandContext(); + await chatMembersAction.call(ctx as any, 'group'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toBe('CHAT_ADMIN_REQUIRED'); + }); + + it('handles empty member list', async () => { + const entity = new MockChannel({ id: BigInt(100) }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const participants: any[] = []; + (participants as any).total = 0; + mockGetParticipants.mockResolvedValueOnce(participants); + + const ctx = createMockCommandContext(); + await chatMembersAction.call(ctx as any, 'group'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.members).toHaveLength(0); + expect(data.total).toBe(0); + }); +}); diff --git a/cli/tests/unit/chat-resolve.test.ts b/cli/tests/unit/chat-resolve.test.ts new file mode 100644 index 0000000..00df512 --- /dev/null +++ b/cli/tests/unit/chat-resolve.test.ts @@ -0,0 +1,208 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const { mockConnect, mockDestroy, MockUser, MockChat, MockChannel } = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + MockUser: class User { static className = 'User'; }, + MockChat: class Chat { static className = 'Chat'; }, + MockChannel: class Channel { static className = 'Channel'; }, +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Chat: MockChat, + Channel: MockChannel, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +vi.mock('../../src/lib/serialize.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/serialize.js')>(); + return actual; +}); + +import { chatResolveAction } from '../../src/commands/chat/resolve.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + ...opts, + })), + }; +} + +describe('chatResolveAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('resolves a username and outputs id, type, title, username', async () => { + const entity = Object.create(MockUser.prototype); + Object.assign(entity, { + id: { toString: () => '123' }, + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '@alice'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@alice'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('123'); + expect(data.type).toBe('user'); + expect(data.title).toBe('Alice Smith'); + expect(data.username).toBe('alice'); + }); + + it('resolves a Channel as channel type', async () => { + const entity = Object.create(MockChannel.prototype); + Object.assign(entity, { + id: { toString: () => '456' }, + title: 'My Channel', + username: 'mychan', + megagroup: false, + }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '@mychan'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-100456'); + expect(data.type).toBe('channel'); + expect(data.title).toBe('My Channel'); + }); + + it('resolves a Channel with megagroup as supergroup type', async () => { + const entity = Object.create(MockChannel.prototype); + Object.assign(entity, { + id: { toString: () => '789' }, + title: 'Supergroup', + username: 'sg', + megagroup: true, + }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '@sg'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-100789'); + expect(data.type).toBe('supergroup'); + }); + + it('resolves a Chat as group type', async () => { + const entity = Object.create(MockChat.prototype); + Object.assign(entity, { + id: { toString: () => '111' }, + title: 'Old Group', + username: null, + }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '111'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-111'); + expect(data.type).toBe('group'); + expect(data.title).toBe('Old Group'); + expect(data.username).toBeNull(); + }); + + it('outputs user title as firstName + lastName', async () => { + const entity = Object.create(MockUser.prototype); + Object.assign(entity, { + id: { toString: () => '1' }, + firstName: 'John', + lastName: undefined, + username: 'john', + }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, 'john'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.title).toBe('John'); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '@test'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + it('outputs error when resolveEntity throws', async () => { + const { TgError } = await import('../../src/lib/errors.js'); + mockResolveEntity.mockRejectedValueOnce(new TgError('Peer not found: test', 'PEER_NOT_FOUND')); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, 'nonexistent'); + + expect(mockOutputError).toHaveBeenCalledWith('Peer not found: test', 'PEER_NOT_FOUND'); + }); +}); diff --git a/cli/tests/unit/chat-search.test.ts b/cli/tests/unit/chat-search.test.ts new file mode 100644 index 0000000..4a2a565 --- /dev/null +++ b/cli/tests/unit/chat-search.test.ts @@ -0,0 +1,161 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const { mockConnect, mockDestroy, mockInvoke } = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn(), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + contacts: { + Search: vi.fn().mockImplementation((opts: any) => opts), + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +vi.mock('../../src/lib/serialize.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/serialize.js')>(); + return { ...actual, bigIntToString: (val: any) => val?.toString() ?? '' }; +}); + +import { chatSearchAction } from '../../src/commands/chat/search.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + limit: '20', + ...opts, + })), + }; +} + +describe('chatSearchAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns channels and groups from contacts.Search', async () => { + mockInvoke.mockResolvedValueOnce({ + chats: [ + { className: 'Channel', id: { toString: () => '100' }, title: 'AI News', username: 'ainews', megagroup: false, participantsCount: 5000 }, + { className: 'Channel', id: { toString: () => '200' }, title: 'ML Community', username: 'mlchat', megagroup: true, participantsCount: 1200 }, + { className: 'Chat', id: { toString: () => '300' }, title: 'Dev Group', username: null, participantsCount: 50 }, + ], + users: [], + }); + + const ctx = createMockCommandContext(); + await chatSearchAction.call(ctx as any, 'AI'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(3); + expect(data.chats[0]).toEqual({ + id: '-100100', title: 'AI News', type: 'channel', username: 'ainews', membersCount: 5000, + }); + expect(data.chats[1].type).toBe('supergroup'); + expect(data.chats[2].type).toBe('group'); + expect(data.total).toBe(3); + }); + + it('filters out non-Chat/Channel entities', async () => { + mockInvoke.mockResolvedValueOnce({ + chats: [ + { className: 'Channel', id: { toString: () => '100' }, title: 'Good', username: 'good', megagroup: false, participantsCount: 100 }, + { className: 'ChatEmpty', id: { toString: () => '999' } }, + ], + users: [], + }); + + const ctx = createMockCommandContext(); + await chatSearchAction.call(ctx as any, 'test'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(1); + expect(data.chats[0].title).toBe('Good'); + }); + + it('returns empty results when no chats found', async () => { + mockInvoke.mockResolvedValueOnce({ chats: [], users: [] }); + + const ctx = createMockCommandContext(); + await chatSearchAction.call(ctx as any, 'nonexistent'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.chats).toHaveLength(0); + expect(data.total).toBe(0); + }); + + it('passes limit to API call', async () => { + mockInvoke.mockResolvedValueOnce({ chats: [], users: [] }); + + const ctx = createMockCommandContext({ limit: '10' }); + await chatSearchAction.call(ctx as any, 'query'); + + const invokeArg = mockInvoke.mock.calls[0][0]; + expect(invokeArg.limit).toBe(10); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await chatSearchAction.call(ctx as any, 'AI'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/chat-topics.test.ts b/cli/tests/unit/chat-topics.test.ts new file mode 100644 index 0000000..47d702f --- /dev/null +++ b/cli/tests/unit/chat-topics.test.ts @@ -0,0 +1,518 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Serialization & Format Tests (Task 1) ---- +// These use dynamic imports to avoid mock interference. + +describe('serializeTopic', () => { + let serializeTopic: typeof import('../../src/lib/serialize.js').serializeTopic; + + beforeEach(async () => { + const mod = await import('../../src/lib/serialize.js'); + serializeTopic = mod.serializeTopic; + }); + + it('converts a full gramjs ForumTopic to TopicItem', () => { + const topic = { + id: 42, + title: 'General Discussion', + iconEmojiId: BigInt('12345678901234'), + date: 1700000000, // Unix timestamp + fromId: { userId: BigInt(999) }, + topMessage: 150, + closed: false, + pinned: true, + }; + + const result = serializeTopic(topic); + + expect(result.id).toBe(42); + expect(result.title).toBe('General Discussion'); + expect(result.iconEmoji).toBe('12345678901234'); + expect(result.creationDate).toBe(new Date(1700000000 * 1000).toISOString()); + expect(result.creatorId).toBe('999'); + expect(result.topMessageId).toBe(150); + expect(result.isClosed).toBe(false); + expect(result.isPinned).toBe(true); + }); + + it('handles null iconEmojiId gracefully', () => { + const topic = { + id: 10, + title: 'No Icon', + iconEmojiId: null, + date: 1700000000, + fromId: { userId: BigInt(1) }, + topMessage: 5, + closed: false, + pinned: false, + }; + + const result = serializeTopic(topic); + expect(result.iconEmoji).toBeNull(); + }); + + it('handles undefined iconEmojiId gracefully', () => { + const topic = { + id: 11, + title: 'Undefined Icon', + date: 1700000000, + fromId: { userId: BigInt(1) }, + topMessage: 5, + closed: false, + pinned: false, + }; + + const result = serializeTopic(topic); + expect(result.iconEmoji).toBeNull(); + }); + + it('handles fromId with channelId', () => { + const topic = { + id: 20, + title: 'Channel Topic', + iconEmojiId: null, + date: 1700000000, + fromId: { channelId: BigInt(500) }, + topMessage: 10, + closed: true, + pinned: false, + }; + + const result = serializeTopic(topic); + expect(result.creatorId).toBe('500'); + expect(result.isClosed).toBe(true); + }); + + it('handles fromId with chatId', () => { + const topic = { + id: 30, + title: 'Chat Topic', + iconEmojiId: null, + date: 1700000000, + fromId: { chatId: BigInt(300) }, + topMessage: 8, + closed: false, + pinned: true, + }; + + const result = serializeTopic(topic); + expect(result.creatorId).toBe('300'); + }); + + it('handles missing fromId', () => { + const topic = { + id: 40, + title: 'No Creator', + iconEmojiId: null, + date: 1700000000, + fromId: null, + topMessage: 1, + closed: false, + pinned: false, + }; + + const result = serializeTopic(topic); + expect(result.creatorId).toBe(''); + }); +}); + +describe('formatTopics', () => { + let formatTopics: typeof import('../../src/lib/format.js').formatTopics; + + beforeEach(async () => { + const mod = await import('../../src/lib/format.js'); + formatTopics = mod.formatTopics; + }); + + it('renders topics with pinned and closed indicators', () => { + const topics = [ + { id: 42, title: 'General', iconEmoji: null, creationDate: '2023-11-14T22:13:20.000Z', creatorId: '1', topMessageId: 100, isClosed: false, isPinned: true }, + { id: 43, title: 'Off Topic', iconEmoji: null, creationDate: '2023-11-14T22:13:20.000Z', creatorId: '2', topMessageId: 50, isClosed: true, isPinned: false }, + { id: 44, title: 'Normal Topic', iconEmoji: null, creationDate: '2023-11-14T22:13:20.000Z', creatorId: '3', topMessageId: 10, isClosed: false, isPinned: false }, + ]; + + const result = formatTopics(topics); + + expect(result).toContain('42'); + expect(result).toContain('General'); + expect(result).toContain('[pinned]'); + expect(result).toContain('43'); + expect(result).toContain('Off Topic'); + expect(result).toContain('[closed]'); + expect(result).toContain('44'); + expect(result).toContain('Normal Topic'); + }); + + it('returns empty string for empty topics array', () => { + const result = formatTopics([]); + expect(result).toBe(''); + }); +}); + +describe('formatData topics dispatch', () => { + let formatData: typeof import('../../src/lib/format.js').formatData; + + beforeEach(async () => { + const mod = await import('../../src/lib/format.js'); + formatData = mod.formatData; + }); + + it('dispatches topics[] array to formatTopics', () => { + const data = { + topics: [ + { id: 1, title: 'Topic 1', iconEmoji: null, creationDate: '2023-11-14T22:13:20.000Z', creatorId: '1', topMessageId: 5, isClosed: false, isPinned: false }, + ], + total: 1, + }; + + const result = formatData(data); + // Should contain topic data, not JSON + expect(result).toContain('Topic 1'); + expect(result).not.toContain('"ok"'); + }); + + it('returns "No topics." for empty topics array', () => { + const data = { topics: [], total: 0 }; + const result = formatData(data); + expect(result).toBe('No topics.'); + }); +}); + +// ---- Handler Tests (Task 2) ---- +// These use vi.mock for full isolation of the command handler. + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state for telegram client + Api classes +const { + mockConnect, + mockDestroy, + mockInvoke, + MockChannel, + MockForumTopic, + MockForumTopicDeleted, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + className = 'Channel'; + id: any; + title: string; + forum: boolean; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(100); + this.title = args.title ?? 'Test Forum'; + this.forum = args.forum ?? true; + } + }; + const _MockForumTopic = class ForumTopic { + className = 'ForumTopic'; + id: number; + title: string; + iconEmojiId: any; + date: number; + fromId: any; + topMessage: number; + closed: boolean; + pinned: boolean; + constructor(args: any = {}) { + this.id = args.id ?? 1; + this.title = args.title ?? 'Test Topic'; + this.iconEmojiId = args.iconEmojiId ?? null; + this.date = args.date ?? 1700000000; + this.fromId = args.fromId ?? { userId: BigInt(1) }; + this.topMessage = args.topMessage ?? 10; + this.closed = args.closed ?? false; + this.pinned = args.pinned ?? false; + } + }; + const _MockForumTopicDeleted = class ForumTopicDeleted { + className = 'ForumTopicDeleted'; + id: number; + constructor(args: any = {}) { + this.id = args.id ?? 99; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({ topics: [], count: 0 }), + MockChannel: _MockChannel, + MockForumTopic: _MockForumTopic, + MockForumTopicDeleted: _MockForumTopicDeleted, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + messages: { + GetForumTopics: vi.fn().mockImplementation((args: any) => args), + }, + ForumTopic: MockForumTopic, + ForumTopicDeleted: MockForumTopicDeleted, + Channel: MockChannel, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Import after mocks +import { chatTopicsAction } from '../../src/commands/chat/topics.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('chatTopicsAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('throws NOT_A_FORUM for non-Channel entity', async () => { + const userEntity = { className: 'User', id: BigInt(1) }; + mockResolveEntity.mockResolvedValueOnce(userEntity); + + const ctx = createMockCommandContext(); + await chatTopicsAction.call(ctx as any, 'someuser'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toContain('forum'); + expect(mockOutputError.mock.calls[0][1]).toBe('NOT_A_FORUM'); + }); + + it('throws NOT_A_FORUM for Channel with forum=false', async () => { + const entity = new MockChannel({ forum: false }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatTopicsAction.call(ctx as any, 'nonforum'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][1]).toBe('NOT_A_FORUM'); + }); + + it('throws NOT_A_FORUM for Channel with forum unset', async () => { + const entity = new MockChannel({ forum: true }); + (entity as any).forum = undefined; + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatTopicsAction.call(ctx as any, 'nonforum'); + + expect(mockOutputError.mock.calls[0][1]).toBe('NOT_A_FORUM'); + }); + + it('filters ForumTopicDeleted items from results', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const forumTopic = new MockForumTopic({ id: 1, title: 'Keep Me' }); + const deletedTopic = new MockForumTopicDeleted({ id: 2 }); + + mockInvoke.mockResolvedValueOnce({ + topics: [forumTopic, deletedTopic], + count: 2, + }); + + const ctx = createMockCommandContext(); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(1); + expect(data.topics[0].title).toBe('Keep Me'); + }); + + it('applies client-side offset slicing', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const topics = Array.from({ length: 5 }, (_, i) => + new MockForumTopic({ id: i + 1, title: `Topic ${i + 1}` }), + ); + + mockInvoke.mockResolvedValueOnce({ + topics, + count: 5, + }); + + const ctx = createMockCommandContext({ offset: '2' }); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(3); + expect(data.topics[0].title).toBe('Topic 3'); + }); + + it('fetches offset+limit topics for correct second-page pagination', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + // Simulate 20 topics available; request page 2 with limit=10, offset=10 + const topics = Array.from({ length: 20 }, (_, i) => + new MockForumTopic({ id: i + 1, title: `Topic ${i + 1}` }), + ); + + mockInvoke.mockResolvedValueOnce({ + topics, + count: 20, + }); + + const ctx = createMockCommandContext({ limit: '10', offset: '10' }); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockInvoke).toHaveBeenCalledWith( + expect.objectContaining({ limit: 100, offsetTopic: 0 }), + ); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(10); + expect(data.topics[0].title).toBe('Topic 11'); + expect(data.topics[9].title).toBe('Topic 20'); + }); + + it('keeps paging when a full batch contains ForumTopicDeleted', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const first = [ + ...Array.from({ length: 95 }, (_, i) => + new MockForumTopic({ id: i + 1, title: `Topic ${i + 1}`, topMessage: i + 1, date: 1 }), + ), + new MockForumTopicDeleted({ id: 96 }), + new MockForumTopicDeleted({ id: 97 }), + new MockForumTopicDeleted({ id: 98 }), + new MockForumTopicDeleted({ id: 99 }), + new MockForumTopicDeleted({ id: 100 }), + ]; + const second = [new MockForumTopic({ id: 101, title: 'Topic 101', topMessage: 101, date: 2 })]; + mockInvoke + .mockResolvedValueOnce({ topics: first, count: 101 }) + .mockResolvedValueOnce({ topics: second, count: 101 }); + + const ctx = createMockCommandContext({ limit: '1', offset: '95' }); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockInvoke).toHaveBeenCalledTimes(2); + expect(mockInvoke.mock.calls[1][0]).toEqual( + expect.objectContaining({ offsetTopic: 100 }), + ); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(1); + expect(data.topics[0].title).toBe('Topic 101'); + }); + + it('pages GetForumTopics with offsetTopic when the first batch is full', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const first = Array.from({ length: 100 }, (_, i) => + new MockForumTopic({ id: i + 1, title: `Topic ${i + 1}`, topMessage: i + 1, date: 1_700_000_000 + i }), + ); + const second = [new MockForumTopic({ id: 101, title: 'Topic 101', topMessage: 101, date: 1_700_000_100 })]; + mockInvoke + .mockResolvedValueOnce({ topics: first, count: 101 }) + .mockResolvedValueOnce({ topics: second, count: 101 }); + + const ctx = createMockCommandContext({ limit: '1', offset: '100' }); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockInvoke).toHaveBeenCalledTimes(2); + expect(mockInvoke.mock.calls[1][0]).toEqual( + expect.objectContaining({ offsetTopic: 100, offsetId: 100 }), + ); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(1); + expect(data.topics[0].title).toBe('Topic 101'); + }); + + it('lists topics with serialized output', async () => { + const entity = new MockChannel({ forum: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const forumTopic = new MockForumTopic({ + id: 42, + title: 'General', + topMessage: 100, + pinned: true, + closed: false, + fromId: { userId: BigInt(999) }, + }); + + mockInvoke.mockResolvedValueOnce({ + topics: [forumTopic], + count: 1, + }); + + const ctx = createMockCommandContext(); + await chatTopicsAction.call(ctx as any, 'testforum'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.topics).toHaveLength(1); + expect(data.topics[0].id).toBe(42); + expect(data.topics[0].title).toBe('General'); + expect(data.topics[0].topMessageId).toBe(100); + expect(data.topics[0].isPinned).toBe(true); + expect(data.topics[0].creatorId).toBe('999'); + expect(data.total).toBe(1); + }); +}); diff --git a/cli/tests/unit/cli-console.test.ts b/cli/tests/unit/cli-console.test.ts new file mode 100644 index 0000000..a972a71 --- /dev/null +++ b/cli/tests/unit/cli-console.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { inspect } from 'node:util'; +import { installCliConsoleGuard } from '../../src/lib/cli-console.js'; +import { createClientForAuth } from '../../src/lib/client.js'; +import { setQuietMode, setVerboseMode } from '../../src/lib/cli-mode.js'; + +afterEach(() => { + setQuietMode(false); + setVerboseMode(false); + vi.restoreAllMocks(); +}); + +describe('CLI dependency console guard', () => { + it.each([false, true])('prevents raw console data or secret payloads (quiet=%s)', quiet => { + setQuietMode(quiet); + setVerboseMode(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const payload = { apiHash: 'synthetic-secret', [inspect.custom]: () => { throw new Error('must not format secret objects'); } }; + const restore = installCliConsoleGuard(); + try { + console.log(payload); + console.info(payload); + console.debug(payload); + console.warn(payload); + console.error(payload); + console.dir(payload); + console.table(payload); + console.trace(payload); + console.assert(false, payload); + } finally { restore(); } + expect(stdout).not.toHaveBeenCalled(); + if (quiet) expect(stderr).not.toHaveBeenCalled(); + else { + expect(stderr).toHaveBeenCalledTimes(9); + expect(stderr.mock.calls.flat().join('')).not.toContain('synthetic-secret'); + } + }); + + it.each([false, true])('contains the real SDK dialog initialization failure branch (quiet=%s)', async quiet => { + setQuietMode(quiet); + setVerboseMode(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const client = await createClientForAuth(1, 'synthetic-api-hash'); + const message = new Api.Message({ + id: 42, date: 1700000000, message: 'synthetic-message-content', + peerId: new Api.PeerUser({ userId: bigInt(7) }), + }); + const finish = vi.spyOn(message, '_finishInit').mockImplementation(() => { + throw new Error('synthetic-error-payload'); + }); + vi.spyOn(client, 'invoke').mockResolvedValue(new Api.messages.Dialogs({ + dialogs: [], messages: [message], users: [], chats: [], + })); + const restore = installCliConsoleGuard(); + try { + await expect(client.getDialogs({ limit: 1 })).resolves.toHaveLength(0); + await client.destroy(); + } finally { restore(); } + expect(finish).toHaveBeenCalledOnce(); + expect(stdout).not.toHaveBeenCalled(); + const diagnostics = stderr.mock.calls.flat().join(''); + expect(diagnostics).not.toContain('synthetic-'); + if (quiet) expect(stderr).not.toHaveBeenCalled(); + // Teleproto silently discards this initialization failure; payload must stay private. + }); + + it('leaves console untouched until explicitly installed and restores it', () => { + const original = console.log; + const restore = installCliConsoleGuard(); + expect(console.log).not.toBe(original); + restore(); + expect(console.log).toBe(original); + }); +}); diff --git a/cli/tests/unit/client.test.ts b/cli/tests/unit/client.test.ts new file mode 100644 index 0000000..c18a4e8 --- /dev/null +++ b/cli/tests/unit/client.test.ts @@ -0,0 +1,348 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// Mock the telegram module before importing our code +// vi.hoisted lets us define variables that are accessible inside vi.mock factories +const { mockConnect, mockDestroy, mockClient } = vi.hoisted(() => { + const mockConnect = vi.fn().mockResolvedValue(undefined); + const mockDestroy = vi.fn().mockResolvedValue(undefined); + const mockClient = { + connect: mockConnect, + destroy: mockDestroy, + }; + return { mockConnect, mockDestroy, mockClient }; +}); + +vi.mock('teleproto', async () => ({ + ...await vi.importActual('teleproto'), + TelegramClient: vi.fn().mockImplementation(() => mockClient), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, +})); + +vi.mock('../../src/lib/errors.js', async () => { + const actual = await vi.importActual<typeof import('../../src/lib/errors.js')>('../../src/lib/errors.js'); + return actual; +}); + +import { withClient, createClientForAuth } from '../../src/lib/client.js'; +import { TgError } from '../../src/lib/errors.js'; + +describe('withClient', () => { + const opts = { apiId: 123, apiHash: 'abc', sessionString: 'sess' }; + + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.useRealTimers(); + mockConnect.mockResolvedValue(undefined); + }); + + it('calls connect then runs callback then destroys', async () => { + const fn = vi.fn().mockResolvedValue('result'); + const result = await withClient(opts, fn); + + expect(mockConnect).toHaveBeenCalledOnce(); + expect(fn).toHaveBeenCalledWith(mockClient, expect.any(AbortSignal)); + expect(mockDestroy).toHaveBeenCalledOnce(); + expect(result).toBe('result'); + }); + + it('calls destroy even when callback throws', async () => { + const fn = vi.fn().mockRejectedValue(new Error('oops')); + + await expect(withClient(opts, fn)).rejects.toThrow('oops'); + expect(mockDestroy).toHaveBeenCalledOnce(); + }); + + it('does not execute the action when the SDK exhausts connection retries', async () => { + mockConnect.mockResolvedValueOnce(false); + const action = vi.fn(); + await expect(withClient(opts, action)).rejects.toMatchObject({ code: 'CONNECTION_FAILED' }); + expect(action).not.toHaveBeenCalled(); + expect(mockDestroy).toHaveBeenCalledOnce(); + }); + + it('sets a safety timeout that defaults to 120_000 and is cleared on success', async () => { + const setTimeoutSpy = vi.spyOn(global, 'setTimeout'); + const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout'); + const fn = vi.fn().mockResolvedValue('ok'); + + await withClient(opts, fn); + + // setTimeout should have been called with 120_000 (default timeout) + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 120_000); + // clearTimeout should have been called + expect(clearTimeoutSpy).toHaveBeenCalled(); + + setTimeoutSpy.mockRestore(); + clearTimeoutSpy.mockRestore(); + }); + + it('accepts custom timeout via options parameter', async () => { + const setTimeoutSpy = vi.spyOn(global, 'setTimeout'); + const fn = vi.fn().mockResolvedValue('ok'); + + await withClient(opts, fn, { timeout: 60_000 }); + + expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 60_000); + + setTimeoutSpy.mockRestore(); + }); + + it('rejects with TgError TIMEOUT instead of calling process.exit', async () => { + vi.useFakeTimers(); + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + + // fn that never resolves (simulates a hung operation) + const fn = vi.fn().mockReturnValue(new Promise(() => {})); + + // Attach catch handler before advancing timers to prevent unhandled rejection + let caughtError: unknown; + const promise = withClient(opts, fn).catch((err) => { caughtError = err; }); + + // Advance past the 120s default timeout + await vi.advanceTimersByTimeAsync(120_000); + await promise; + + expect(caughtError).toBeInstanceOf(TgError); + expect((caughtError as TgError).message).toBe('Client operation timed out after 120 seconds'); + expect((caughtError as TgError).code).toBe('TIMEOUT'); + + // Must NOT call process.exit + expect(exitSpy).not.toHaveBeenCalled(); + + exitSpy.mockRestore(); + vi.useRealTimers(); + }); + + it('rejects with TIMEOUT when connect() hangs', async () => { + vi.useFakeTimers(); + + // connect() that never resolves + mockConnect.mockReturnValue(new Promise(() => {})); + + const fn = vi.fn().mockResolvedValue('should not reach'); + + let caughtError: unknown; + const promise = withClient(opts, fn).catch((err) => { caughtError = err; }); + + await vi.advanceTimersByTimeAsync(120_000); + await promise; + + expect(caughtError).toBeInstanceOf(TgError); + expect((caughtError as TgError).code).toBe('TIMEOUT'); + // The callback should never have been called since connect hung + expect(fn).not.toHaveBeenCalled(); + + mockConnect.mockResolvedValue(undefined); + vi.useRealTimers(); + }); + + it('uses custom timeout value in error message', async () => { + vi.useFakeTimers(); + + const fn = vi.fn().mockReturnValue(new Promise(() => {})); + + let caughtError: unknown; + const promise = withClient(opts, fn, { timeout: 30_000 }).catch((err) => { caughtError = err; }); + + await vi.advanceTimersByTimeAsync(30_000); + await promise; + + expect(caughtError).toBeInstanceOf(TgError); + expect((caughtError as TgError).message).toBe('Client operation timed out after 30 seconds'); + + vi.useRealTimers(); + }); + + it('retries on network error up to configured retries', async () => { + const networkErr = new Error('ECONNRESET'); + (networkErr as any).code = 'ECONNRESET'; + let callCount = 0; + const fn = vi.fn().mockImplementation(async () => { + callCount++; + if (callCount < 3) throw networkErr; + return 'success'; + }); + + const result = await withClient(opts, fn, { retries: 3, retryDelay: 10 }); + expect(result).toBe('success'); + expect(fn).toHaveBeenCalledTimes(3); + }); + + it('does not retry non-retryable errors', async () => { + const { TgError: ActualTgError } = await import('../../src/lib/errors.js'); + const tgErr = new ActualTgError('Peer not found', 'PEER_NOT_FOUND'); + const fn = vi.fn().mockRejectedValue(tgErr); + + await expect(withClient(opts, fn, { retries: 3, retryDelay: 10 })).rejects.toThrow('Peer not found'); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('throws after exhausting all retries', async () => { + const networkErr = new Error('ECONNRESET'); + (networkErr as any).code = 'ECONNRESET'; + const fn = vi.fn().mockRejectedValue(networkErr); + + await expect(withClient(opts, fn, { retries: 2, retryDelay: 10 })).rejects.toThrow('ECONNRESET'); + expect(fn).toHaveBeenCalledTimes(3); + }); + + it('defaults to no retries when retries option is not set', async () => { + const networkErr = new Error('ECONNRESET'); + (networkErr as any).code = 'ECONNRESET'; + const fn = vi.fn().mockRejectedValue(networkErr); + + await expect(withClient(opts, fn)).rejects.toThrow('ECONNRESET'); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('does not retry FloodWait errors', async () => { + const flood = new Error('A wait of 120 seconds is required'); + (flood as any).seconds = 120; + const fn = vi.fn().mockRejectedValue(flood); + + await expect(withClient(opts, fn, { retries: 3, retryDelay: 10 })).rejects.toThrow( + 'A wait of 120 seconds is required', + ); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('retries exactly once when retries is 1', async () => { + const failure = Object.assign(new Error('connection reset'), { code: 'ECONNRESET' }); + const fn = vi.fn().mockRejectedValueOnce(failure).mockResolvedValue('recovered'); + await expect(withClient(opts, fn, { retries: 1, retryDelay: 0 })).resolves.toBe('recovered'); + expect(fn).toHaveBeenCalledTimes(2); + }); + + it('cancels a pending backoff at timeout and never invokes a later retry', async () => { + vi.useFakeTimers(); + const fn = vi.fn().mockRejectedValue(Object.assign(new Error('reset'), { code: 'ECONNRESET' })); + const result = withClient(opts, fn, { timeout: 10, retries: 2, retryDelay: 80 }); + const rejected = expect(result).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + expect(mockDestroy).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(1000); + expect(fn).toHaveBeenCalledOnce(); + }); + + it('does not call the callback when connect resolves after the deadline', async () => { + vi.useFakeTimers(); + let finishConnect!: () => void; + mockConnect.mockImplementationOnce(() => new Promise<void>((resolve) => { finishConnect = resolve; })); + const fn = vi.fn().mockResolvedValue('too late'); + const rejected = expect(withClient(opts, fn, { timeout: 10 })).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + finishConnect(); + await vi.advanceTimersByTimeAsync(0); + expect(fn).not.toHaveBeenCalled(); + expect(mockDestroy).toHaveBeenCalledTimes(2); + }); + + it('signals an in-flight callback so it can avoid work after the deadline', async () => { + vi.useFakeTimers(); + const write = vi.fn(); + let resume!: () => void; + let callbackSignal!: AbortSignal; + const fn = vi.fn(async (_client, signal: AbortSignal) => { + callbackSignal = signal; + await new Promise<void>((resolve) => { resume = resolve; }); + signal.throwIfAborted(); + write(); + }); + const rejected = expect(withClient(opts, fn, { timeout: 10, retries: 2 })).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + expect(callbackSignal.aborted).toBe(true); + resume(); + await vi.advanceTimersByTimeAsync(1000); + expect(write).not.toHaveBeenCalled(); + expect(fn).toHaveBeenCalledOnce(); + }); + + it('does not retry a late in-flight network rejection', async () => { + vi.useFakeTimers(); + let fail!: (err: Error) => void; + const fn = vi.fn(() => new Promise((_resolve, reject) => { fail = reject; })); + const rejected = expect(withClient(opts, fn, { timeout: 10, retries: 2 })).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + fail(Object.assign(new Error('reset'), { code: 'ECONNRESET' })); + await vi.advanceTimersByTimeAsync(10000); + expect(fn).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([{ retries: -1 }, { retries: 0.5 }, { timeout: Infinity }, { timeout: 0 }, { retryDelay: -1 }])( + 'rejects invalid timeout/retry options before connecting: %j', async (options) => { + await expect(withClient(opts, vi.fn(), options)).rejects.toMatchObject({ code: 'INVALID_OPTIONS' }); + expect(mockConnect).not.toHaveBeenCalled(); + }, + ); + + it('registers ownership cleanup before starting connect and resolves it after teardown', async () => { + const holdUntil = vi.fn(); + mockConnect.mockImplementationOnce(async () => { + expect(holdUntil).toHaveBeenCalledOnce(); + }); + await expect(withClient(opts, async () => 'ok', { holdUntil })).resolves.toBe('ok'); + await expect(holdUntil.mock.calls[0][0]).resolves.toBeUndefined(); + expect(mockDestroy).toHaveBeenCalledOnce(); + }); + + it('returns TIMEOUT promptly while ownership cleanup waits for in-flight work and final destroy', async () => { + vi.useFakeTimers(); + let finishWork!: () => void; + let cleanupFinished = false; + let cleanup!: Promise<unknown>; + const holdUntil = vi.fn((pending: Promise<unknown>) => { + cleanup = pending; + pending.then(() => { cleanupFinished = true; }); + }); + const fn = vi.fn(() => new Promise<void>(resolve => { finishWork = resolve; })); + const rejected = expect(withClient(opts, fn, { timeout: 10, holdUntil })).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + expect(cleanupFinished).toBe(false); + expect(mockDestroy).toHaveBeenCalledOnce(); + finishWork(); + await cleanup; + expect(cleanupFinished).toBe(true); + expect(mockDestroy).toHaveBeenCalledTimes(2); + expect(fn).toHaveBeenCalledOnce(); + }); + + it('resolves ownership cleanup even when the operation rejects normally', async () => { + const holdUntil = vi.fn(); + await expect(withClient(opts, async () => { throw new Error('operation failed'); }, { holdUntil })).rejects.toThrow('operation failed'); + await expect(holdUntil.mock.calls[0][0]).resolves.toBeUndefined(); + expect(mockDestroy).toHaveBeenCalledOnce(); + }); + + it('reports failed destruction to the ownership hook', async () => { + mockDestroy.mockRejectedValueOnce(new Error('teardown failed')); + const holdUntil = vi.fn(); + await withClient(opts, async () => 'ok', { holdUntil }); + await expect(holdUntil.mock.calls[0][0]).rejects.toThrow('teardown failed'); + }); +}); + +describe('createClientForAuth', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns a client instance without connecting', async () => { + const client = await createClientForAuth(123, 'abc'); + + expect(client).toBeDefined(); + // Should NOT have called connect + expect(mockConnect).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/commands-cross-review.test.ts b/cli/tests/unit/commands-cross-review.test.ts new file mode 100644 index 0000000..3d6696b --- /dev/null +++ b/cli/tests/unit/commands-cross-review.test.ts @@ -0,0 +1,111 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Api, TelegramClient } from 'teleproto'; +import { StringSession } from 'teleproto/sessions/index.js'; +import { Logger, LogLevel } from 'teleproto/extensions/Logger.js'; +import { getInputPeer } from 'teleproto/Utils.js'; +import bigInt from 'big-integer'; + +const state = vi.hoisted(() => ({ client: undefined as any, success: vi.fn(), error: vi.fn() })); +vi.mock('../../src/lib/with-auth.js', () => ({ withAuth: async (_opts, fn) => fn(state.client) })); +vi.mock('../../src/lib/output.js', () => ({ outputSuccess: state.success, outputError: state.error, logStatus: vi.fn() })); + +import { messageSearchAction } from '../../src/commands/message/search.js'; +import { mediaSendAction } from '../../src/commands/media/send.js'; +import { messageRepliesAction } from '../../src/commands/message/replies.js'; +import { userProfileAction } from '../../src/commands/user/profile.js'; + +const channel = (id = 7) => new Api.Channel({ + id: bigInt(id), accessHash: bigInt(10), title: 'Channel title', megagroup: true, + forum: true, photo: new Api.ChatPhotoEmpty(), date: 1700000000, +}); +const user = (id = 7) => new Api.User({ id: bigInt(id), accessHash: bigInt(11), firstName: 'Actual sender' }); +const message = (id: number) => new Api.Message({ + id, date: 1700000000, message: 'needle', fromId: new Api.PeerUser({ userId: bigInt(7) }), + peerId: new Api.PeerChannel({ channelId: bigInt(7) }), +}); +const context = (opts: Record<string, unknown> = {}, args: string[] = []) => ({ + optsWithGlobals: () => ({ profile: 'offline', limit: '50', offset: '0', ...opts }), args, +}) as any; + +describe('independent command review against actual gramjs shapes', () => { + let client: TelegramClient; + let fixtureDir: string | undefined; + const originalExitCode = process.exitCode; + beforeEach(() => { + vi.clearAllMocks(); + process.exitCode = 0; + client = new TelegramClient(new StringSession(''), 1, 'synthetic', { baseLogger: new Logger(LogLevel.NONE) }); + state.client = client; + vi.spyOn(client, 'getEntity').mockResolvedValue(channel()); + vi.spyOn(client, 'getInputEntity').mockImplementation(async entity => getInputPeer(entity as any)); + vi.spyOn(client, 'invoke').mockRejectedValue(new Error('Unplanned offline RPC')); + }); + afterEach(async () => { + await client.destroy(); + vi.restoreAllMocks(); + process.exitCode = originalExitCode; + if (fixtureDir) await rm(fixtureDir, { recursive: true, force: true }); + fixtureDir = undefined; + }); + + it('distinguishes a user from a channel with the same raw ID in topic search', async () => { + vi.mocked(client.invoke).mockResolvedValue(new Api.messages.MessagesSlice({ + count: 1, messages: [message(42)], users: [user()], chats: [channel()], + })); + await messageSearchAction.call(context({ chat: '@fixture', topic: '20', query: 'needle' })); + const data = state.success.mock.calls[0][0]; + expect(data.messages[0]).toMatchObject({ id: 42, senderId: '7', senderName: 'Actual sender' }); + }); + + it('reports an incomplete SDK album mapping without throwing after the send', async () => { + fixtureDir = await mkdtemp(join(tmpdir(), 'tg-album-cross-review-')); + const files = [join(fixtureDir, 'a.jpg'), join(fixtureDir, 'b.jpg')]; + await Promise.all(files.map(file => writeFile(file, 'synthetic'))); + const updates = new Api.Updates({ + updates: [ + new Api.UpdateMessageID({ id: 42, randomId: bigInt(100) }), + new Api.UpdateNewChannelMessage({ message: message(42), pts: 1, ptsCount: 1 }), + ], + users: [user()], chats: [channel()], date: 1700000000, seq: 1, + }); + // Invoke the same SDK response conversion used by _sendAlbum. The missing + // second mapping produces undefined, despite the successful write response. + const sdkResult = client._getResponseMessage([bigInt(100), bigInt(101)], updates, getInputPeer(channel())); + expect(sdkResult).toHaveLength(2); + expect(sdkResult[1]).toBeUndefined(); + const send = vi.spyOn(client, 'sendFile').mockResolvedValue(sdkResult as any); + const reread = vi.spyOn(client, 'getMessages'); + await expect(mediaSendAction.call(context({}, ['@fixture', ...files]))).resolves.toBeUndefined(); + expect(send).toHaveBeenCalledOnce(); + expect(reread).not.toHaveBeenCalled(); + expect(state.success.mock.calls[0][0]).toMatchObject({ messages: [expect.objectContaining({ id: 42 })] }); + expect(state.success.mock.calls[0][0].warning).toEqual(expect.any(String)); + }); + + it('preserves one reply result and a separate network error without inventing an empty post', async () => { + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request.msgId === 42) return new Api.messages.MessagesSlice({ count: 1, messages: [message(61)], users: [user()], chats: [channel()] }) as any; + throw Object.assign(new Error('temporary socket failure'), { code: 'ECONNRESET' }); + }); + await messageRepliesAction.call(context(), '@fixture', '42,43'); + expect(state.success.mock.calls[0][0]).toMatchObject({ + posts: [{ postId: 42, total: 1, messages: [expect.objectContaining({ id: 61 })] }], + partial: true, + errors: [{ input: '43', error: 'temporary socket failure', code: 'ECONNRESET' }], + }); + expect(process.exitCode).toBe(1); + }); + + it('does not turn an entity-resolution transport failure into notFound', async () => { + vi.mocked(client.getEntity).mockRejectedValue(Object.assign(new Error('temporary socket failure'), { code: 'ECONNRESET' })); + await userProfileAction.call(context(), '@fixture'); + expect(state.success).toHaveBeenCalledWith({ profiles: [], notFound: [], partial: true, errors: [ + { input: '@fixture', error: 'temporary socket failure', code: 'ECONNRESET' }, + ] }); + expect(client.invoke).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/cli/tests/unit/commands-sdk-boundary.test.ts b/cli/tests/unit/commands-sdk-boundary.test.ts new file mode 100644 index 0000000..c3fb810 --- /dev/null +++ b/cli/tests/unit/commands-sdk-boundary.test.ts @@ -0,0 +1,441 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Api, TelegramClient } from 'teleproto'; +import { StringSession } from 'teleproto/sessions/index.js'; +import { Logger, LogLevel } from 'teleproto/extensions/Logger.js'; +import bigInt from 'big-integer'; +import { getInputPeer } from 'teleproto/Utils.js'; + +// Keep actual Api constructors, serialization, entity resolution and gramjs message +// iteration/deletion. Only authentication and the network transport are replaced. +const state = vi.hoisted(() => ({ client: undefined as any, success: vi.fn(), error: vi.fn() })); +vi.mock('../../src/lib/with-auth.js', () => ({ withAuth: async (_opts: any, fn: any) => fn(state.client) })); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => state.success(...args), + outputError: (...args: any[]) => state.error(...args), + logStatus: vi.fn(), +})); + +import { messageDeleteAction } from '../../src/commands/message/delete.js'; +import { messageSearchAction } from '../../src/commands/message/search.js'; +import { messageRepliesAction } from '../../src/commands/message/replies.js'; +import { mediaSendAction } from '../../src/commands/media/send.js'; +import { chatCreateAction } from '../../src/commands/chat/create.js'; +import { contactListAction } from '../../src/commands/contact/list.js'; +import { contactAddAction } from '../../src/commands/contact/add.js'; +import { contactSearchAction } from '../../src/commands/contact/search.js'; +import { userProfileAction } from '../../src/commands/user/profile.js'; + +const channel = (id = 1234567890) => new Api.Channel({ + id: bigInt(id), accessHash: bigInt(10), title: `Channel ${id}`, + forum: true, megagroup: true, photo: new Api.ChatPhotoEmpty(), date: 1700000000, +}); +const user = (id = 7) => new Api.User({ id: bigInt(id), accessHash: bigInt(20), firstName: `User ${id}` }); +const message = (id: number, chat = channel(), text = 'needle') => new Api.Message({ + id, date: 1700000000 + id, message: text, + peerId: new Api.PeerChannel({ channelId: chat.id }), + fromId: new Api.PeerUser({ userId: bigInt(7) }), +}); +const context = (opts: Record<string, unknown> = {}, args: string[] = []) => ({ + optsWithGlobals: () => ({ profile: 'fixture', limit: '50', offset: '0', ...opts }), args, +}) as any; +const rpcError = (code: string) => Object.assign(new Error(code), { errorMessage: code }); + +describe('command boundaries against installed gramjs (offline transport)', () => { + let client: TelegramClient; + const originalExitCode = process.exitCode; + let fixtures: string | undefined; + + beforeEach(() => { + vi.clearAllMocks(); + client = new TelegramClient(new StringSession(''), 1, 'synthetic', { + baseLogger: new Logger(LogLevel.NONE), + }); + state.client = client; + vi.spyOn(client, 'getEntity').mockResolvedValue(channel()); + vi.spyOn(client, 'getInputEntity').mockImplementation(async entity => getInputPeer(entity as any)); + vi.spyOn(client, 'invoke').mockRejectedValue(new Error('Unexpected offline RPC')); + }); + + afterEach(async () => { + process.exitCode = originalExitCode; + vi.restoreAllMocks(); + await client.destroy(); + if (fixtures) await rm(fixtures, { recursive: true, force: true }); + fixtures = undefined; + }); + + it.each([false, true])('blocks --for-me on channel megagroup=%s before delete RPC', async megagroup => { + const entity = channel(); + entity.megagroup = megagroup; + vi.mocked(client.getEntity).mockResolvedValue(entity); + await messageDeleteAction.call(context({ forMe: true }), '@fixture', '42'); + expect(client.invoke).not.toHaveBeenCalled(); + expect(state.success).not.toHaveBeenCalled(); + expect(state.error).toHaveBeenCalledWith(expect.stringContaining('not supported'), 'INVALID_OPTIONS'); + }); + + it('retains explicit revoke on a channel in the actual delete request', async () => { + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + expect(request).toBeInstanceOf(Api.channels.DeleteMessages); + expect(request.id).toEqual([42, 47]); + expect(request.getBytes().length).toBeGreaterThan(0); + return new Api.messages.AffectedMessages({ pts: 1, ptsCount: 2 }) as any; + }); + await messageDeleteAction.call(context({ revoke: true }), '@fixture', '42,47'); + expect(client.invoke).toHaveBeenCalledOnce(); + expect(state.success).toHaveBeenCalledWith({ deleted: [42, 47], failed: [], mode: 'revoke' }); + }); + + it.each(['user', 'group'])('retains for-me for a supported %s', async kind => { + const entity = kind === 'user' ? user() : new Api.Chat({ + id: bigInt(99), title: 'Group', photo: new Api.ChatPhotoEmpty(), participantsCount: 2, date: 0, version: 1, + }); + vi.mocked(client.getEntity).mockResolvedValue(entity); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + expect(request).toBeInstanceOf(Api.messages.DeleteMessages); + expect(request.revoke).toBe(false); + expect(request.getBytes().length).toBeGreaterThan(0); + return new Api.messages.AffectedMessages({ pts: 1, ptsCount: 1 }) as any; + }); + await messageDeleteAction.call(context({ forMe: true }), '@fixture', '42'); + expect(client.invoke).toHaveBeenCalledOnce(); + expect(state.success.mock.calls[0][0].mode).toBe('for-me'); + }); + + it.each([ + { query: 'needle', filter: 'photos' }, { query: 'needle' }, { filter: 'photos' }, + ])('topic search preserves query/filter in real Search RPC: %j', async options => { + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + expect(request).toBeInstanceOf(Api.messages.Search); + expect(request.topMsgId).toBe(42); + expect(request.q).toBe(options.query ?? ''); + expect(request.filter).toBeInstanceOf(options.filter ? Api.InputMessagesFilterPhotos : Api.InputMessagesFilterEmpty); + expect(request.addOffset).toBe(3); + expect(request.getBytes().length).toBeGreaterThan(0); + return new Api.messages.MessagesSlice({ count: 1, messages: [message(56)], users: [user()], chats: [channel()] }) as any; + }); + await messageSearchAction.call(context({ chat: '@fixture', topic: '42', limit: '5', offset: '3', ...options })); + expect(client.invoke).toHaveBeenCalledOnce(); + expect(state.success.mock.calls[0][0].messages[0]).toMatchObject({ id: 56, text: 'needle', senderName: 'User 7' }); + }); + + it('topic search advances offsetId in chunks while keeping topMsgId, query and filter', async () => { + const source = Array.from({ length: 145 }, (_, i) => message(300 - i)); + const requests: any[] = []; + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + requests.push({ offsetId: request.offsetId, addOffset: request.addOffset, limit: request.limit }); + expect(request.topMsgId).toBe(42); + expect(request.q).toBe('needle'); + expect(request.filter).toBeInstanceOf(Api.InputMessagesFilterPhotos); + const start = (request.offsetId ? source.findIndex(m => m.id === request.offsetId) + 1 : 0) + request.addOffset; + return new Api.messages.MessagesSlice({ count: source.length, messages: source.slice(start, start + request.limit), users: [user()], chats: [channel()] }) as any; + }); + await messageSearchAction.call(context({ chat: '@fixture', topic: '42', query: 'needle', filter: 'photos', limit: '120', offset: '5' })); + const result = state.success.mock.calls[0][0]; + expect(result.messages.map((m: any) => m.id)).toEqual(source.slice(5, 125).map(m => m.id)); + expect(result.total).toBe(145); + expect(requests).toEqual([{ offsetId: 0, addOffset: 5, limit: 100 }, { offsetId: 196, addOffset: 0, limit: 20 }]); + }); + + it('global offset follows SearchGlobal peer/rate/id cursor beyond 100 results without duplicates', async () => { + const chats = [channel(1234567890), channel(2234567890)]; + // invoke normally populates this cache from every response before the + // iterator hydrates Message.inputChat for the next SearchGlobal cursor. + (client as any)._entityCache.add({ chats, users: [user()] }); + const source = Array.from({ length: 137 }, (_, i) => message(300 - Math.floor(i / 2), chats[i % 2])); + const requests: any[] = []; + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + expect(request).toBeInstanceOf(Api.messages.SearchGlobal); + expect(request.q).toBe('needle'); + const previous = request.offsetId ? source.findIndex(m => m.id === request.offsetId && + (m.peerId as Api.PeerChannel).channelId.equals(request.offsetPeer.channelId)) : -1; + if (request.offsetId) { + expect(previous).toBeGreaterThanOrEqual(0); + expect(request.offsetRate).toBe(700 + previous + 1); + } + const start = previous + 1; + requests.push({ bytes: request.getBytes(), offsetId: request.offsetId, offsetRate: request.offsetRate, limit: request.limit }); + const messages = source.slice(start, start + request.limit); + return new Api.messages.MessagesSlice({ count: source.length, messages, users: [user()], chats, nextRate: 700 + start + messages.length }) as any; + }); + await messageSearchAction.call(context({ query: 'needle', offset: '105', limit: '7' })); + const result = state.success.mock.calls[0][0]; + expect(result.total).toBe(137); + expect(result.messages.map((m: any) => [m.id, m.chatId])).toEqual(source.slice(105, 112).map(m => [m.id, `-100${(m.peerId as Api.PeerChannel).channelId}`])); + expect(requests).toHaveLength(2); + expect(requests[0].limit).toBe(100); + expect(requests[1].limit).toBe(12); + expect(requests[0].bytes.equals(requests[1].bytes)).toBe(false); + }); + + it('global offset past the end returns an empty page and retains server total', async () => { + vi.mocked(client.invoke).mockResolvedValue(new Api.messages.MessagesSlice({ count: 1, messages: [message(7)], users: [], chats: [channel()] })); + await messageSearchAction.call(context({ query: 'needle', offset: '4', limit: '2' })); + expect(state.success).toHaveBeenCalledWith({ messages: [], total: 1 }); + }); + + it('albums serialize actual nonconsecutive Message[] IDs without a second read', async () => { + fixtures = await mkdtemp(join(tmpdir(), 'tg-sdk-album-')); + const paths = [join(fixtures, 'a.jpg'), join(fixtures, 'b.jpg')]; + await Promise.all(paths.map(path => writeFile(path, 'fixture'))); + vi.spyOn(client, 'sendFile').mockResolvedValue([message(50), message(54)] as any); + const getMessages = vi.spyOn(client, 'getMessages'); + await mediaSendAction.call(context({}, ['@fixture', ...paths])); + expect(getMessages).not.toHaveBeenCalled(); + expect(client.invoke).not.toHaveBeenCalled(); + const result = state.success.mock.calls[0][0]; + expect(result.sent).toBe(2); + expect(result.messages.map((m: any) => m.id)).toEqual([50, 54]); + expect(result.warning).toBeUndefined(); + }); + + it('single media send reports unavailable SDK mapping without re-uploading or reading guessed IDs', async () => { + fixtures = await mkdtemp(join(tmpdir(), 'tg-sdk-single-')); + const path = join(fixtures, 'a.jpg'); + await writeFile(path, 'fixture'); + const request = new Api.messages.SendMedia({ peer: getInputPeer(channel()), media: new Api.InputMediaEmpty(), randomId: bigInt.one, message: '' }); + const updates = new Api.Updates({ updates: [], users: [], chats: [], date: 0, seq: 0 }); + const missing = (client as any)._getResponseMessage(request, updates, getInputPeer(channel())); + expect(missing).toBeUndefined(); + const send = vi.spyOn(client, 'sendFile').mockResolvedValue(missing); + await mediaSendAction.call(context({}, ['@fixture', path])); + expect(send).toHaveBeenCalledOnce(); + expect(client.invoke).not.toHaveBeenCalled(); + expect(state.success).not.toHaveBeenCalled(); + expect(state.error).toHaveBeenCalledWith(expect.stringContaining('retrying may create a duplicate'), 'MESSAGE_RESULT_UNAVAILABLE'); + }); + + it('CreateChat unwraps the installed InvitedUsers response and marks the created ID', async () => { + vi.mocked(client.getEntity).mockResolvedValue(user()); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + expect(request).toBeInstanceOf(Api.messages.CreateChat); + return new Api.messages.InvitedUsers({ + updates: new Api.Updates({ updates: [], users: [user()], chats: [new Api.Chat({ + id: bigInt(99), title: 'Fixture', photo: new Api.ChatPhotoEmpty(), participantsCount: 2, date: 0, version: 1, + })], date: 0, seq: 1 }), missingInvitees: [], + }) as any; + }); + await chatCreateAction.call(context({ type: 'group', members: '@fixture' }), 'Fixture'); + expect(state.success).toHaveBeenCalledWith({ id: '-99', title: 'Fixture', type: 'group' }); + expect(client.invoke).toHaveBeenCalledOnce(); + }); + + it.each([false, true])('contact limit applies before enrichment with global=%s and deduplicates contacts first', async global => { + const users = [user(1), user(2), user(3)]; + const enriched: string[] = []; + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.GetContacts) return new Api.contacts.Contacts({ users, savedCount: 2, + contacts: [new Api.Contact({ userId: bigInt(1), mutual: true }), new Api.Contact({ userId: bigInt(1), mutual: true }), new Api.Contact({ userId: bigInt(2), mutual: true })], + }) as any; + if (request instanceof Api.contacts.Search) return new Api.contacts.Found({ + users, chats: [], myResults: [new Api.PeerUser({ userId: bigInt(1) }), new Api.PeerUser({ userId: bigInt(1) }), new Api.PeerUser({ userId: bigInt(2) })], + results: [new Api.PeerUser({ userId: bigInt(2) }), new Api.PeerUser({ userId: bigInt(3) })], + }) as any; + if (request instanceof Api.users.GetFullUser) { + enriched.push(String(request.id.id)); + return { fullUser: {}, users: [request.id] } as any; + } + if (request instanceof Api.photos.GetUserPhotos) return { photos: [], count: 0 } as any; + throw new Error('Unexpected RPC'); + }); + await contactSearchAction.call(context({ global, limit: '1' }), 'User'); + expect(enriched).toEqual(['1']); + expect(state.success.mock.calls[0][0].results).toHaveLength(1); + expect(state.success.mock.calls[0][0].results[0].isContact).toBe(true); + }); + + it('all failed replies produce no fake empty posts and retain individual RPC errors', async () => { + vi.mocked(client.invoke).mockRejectedValue(rpcError('CHAT_ADMIN_REQUIRED')); + await messageRepliesAction.call(context(), '@fixture', '42,43'); + expect(state.success).toHaveBeenCalledWith({ posts: [], partial: true, errors: [ + { input: '42', error: 'Admin privileges required', code: 'CHAT_ADMIN_REQUIRED' }, + { input: '43', error: 'Admin privileges required', code: 'CHAT_ADMIN_REQUIRED' }, + ] }); + expect(state.error).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); + + it('profile transport errors are reported without pretending users are absent', async () => { + vi.mocked(client.getEntity).mockResolvedValue(user()); + vi.mocked(client.invoke).mockRejectedValue(rpcError('FLOOD_WAIT_17')); + await userProfileAction.call(context(), '@first,@second'); + expect(state.success).toHaveBeenCalledWith({ profiles: [], notFound: [], partial: true, errors: [ + { input: '@first', error: 'FLOOD_WAIT_17', code: 'FLOOD_WAIT_17' }, + { input: '@second', error: 'FLOOD_WAIT_17', code: 'FLOOD_WAIT_17' }, + ] }); + expect(process.exitCode).toBe(1); + }); + it('topic search terminates a repeated server page without returning duplicates', async () => { + const messages = Array.from({ length: 100 }, (_, i) => message(300 - i)); + vi.mocked(client.invoke).mockResolvedValue(new Api.messages.MessagesSlice({ count: 500, messages, users: [], chats: [channel()] })); + await messageSearchAction.call(context({ chat: '@fixture', topic: '42', query: 'needle', limit: '250' })); + expect(client.invoke).toHaveBeenCalledTimes(2); + expect(state.success.mock.calls[0][0].messages.map((m: any) => m.id)).toEqual(messages.map(m => m.id)); + }); + + it.each(['12junk', '1.2', '0', '-1', '2147483648', '9007199254740993', '', '1,'])('media rejects reply-to %j before any client request', async replyTo => { + fixtures = await mkdtemp(join(tmpdir(), 'tg-sdk-validation-')); + const path = join(fixtures, 'a.jpg'); + await writeFile(path, 'fixture'); + const sendFile = vi.spyOn(client, 'sendFile'); + await mediaSendAction.call(context({ replyTo }, ['@fixture', path])); + expect(client.getEntity).not.toHaveBeenCalled(); + expect(sendFile).not.toHaveBeenCalled(); + expect(state.error).toHaveBeenCalledWith(expect.any(String), 'INVALID_REPLY_TO'); + }); + + it.each([false, true])('multi-chat search retains per-chat errors when allFail=%s, including quiet mode', async allFail => { + vi.mocked(client.getEntity).mockImplementation(async input => { + if (input === 'bad' || allFail) throw rpcError('CHANNEL_PRIVATE'); + return channel(); + }); + vi.mocked(client.invoke).mockResolvedValue(new Api.messages.MessagesSlice({ count: 1, messages: [message(5)], users: [], chats: [channel()] })); + await messageSearchAction.call(context({ chat: '@bad,@good', query: 'needle', quiet: true })); + const result = state.success.mock.calls[0][0]; + expect(result.messages).toHaveLength(allFail ? 0 : 1); + if (!allFail) expect(result.messages[0].chatId).toBe('-1001234567890'); + expect(result.errors.map((error: any) => [error.input, error.code])).toEqual(allFail ? + [['@bad', 'CHANNEL_PRIVATE'], ['@good', 'CHANNEL_PRIVATE']] : [['@bad', 'CHANNEL_PRIVATE']]); + expect(result.partial).toBe(true); + expect(process.exitCode).toBe(1); + }); + + it('a successful empty reply result remains distinguishable from a failed post', async () => { + vi.mocked(client.invoke).mockResolvedValueOnce(new Api.messages.MessagesSlice({ count: 0, messages: [], users: [], chats: [] })) + .mockRejectedValueOnce(rpcError('MSG_ID_INVALID')); + await messageRepliesAction.call(context(), '@fixture', '42,43'); + const result = state.success.mock.calls[0][0]; + expect(result.posts).toEqual([{ postId: 42, messages: [], total: 0 }]); + expect(result.errors).toEqual([{ input: '43', error: 'MSG_ID_INVALID', code: 'MSG_ID_INVALID' }]); + expect(result.partial).toBe(true); + }); + + it.each([false, true])('contact enrichment exposes failures with allFail=%s', async allFail => { + const users = [user(1), user(2)]; + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.GetContacts) return new Api.contacts.Contacts({ users, savedCount: users.length, + contacts: users.map(u => new Api.Contact({ userId: u.id, mutual: true })), + }) as any; + if (request instanceof Api.users.GetFullUser) { + if (String(request.id.id) === '2' || allFail) throw rpcError('FLOOD_WAIT_3'); + return { fullUser: {}, users: [request.id] } as any; + } + return { photos: [], count: 0 } as any; + }); + await contactSearchAction.call(context({ limit: '2' }), 'User'); + const result = state.success.mock.calls[0][0]; + expect(result.results).toHaveLength(allFail ? 0 : 1); + expect(result.partial).toBe(true); + expect(result.errors.map((error: any) => [error.input, error.code])).toEqual(allFail ? [['1', 'FLOOD_WAIT_3'], ['2', 'FLOOD_WAIT_3']] : [['2', 'FLOOD_WAIT_3']]); + expect(process.exitCode).toBe(1); + }); + + it('profile missing users, transport errors, and successful users remain distinct', async () => { + vi.mocked(client.getEntity).mockImplementation(async input => { + if (input === 'missing') throw rpcError('USERNAME_NOT_OCCUPIED'); + if (input === 'offline') throw Object.assign(new Error('Connection reset'), { code: 'ECONNRESET' }); + return user(); + }); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.users.GetFullUser) return { fullUser: {}, users: [user()] } as any; + return { photos: [], count: 0 } as any; + }); + await userProfileAction.call(context(), '@missing,@offline,@ok'); + const result = state.success.mock.calls[0][0]; + expect(result.profiles).toHaveLength(1); + expect(result.notFound).toEqual(['@missing']); + expect(result.errors.map((error: any) => [error.input, error.code])).toEqual([['@missing', 'PEER_NOT_FOUND'], ['@offline', 'ECONNRESET']]); + expect(result.partial).toBe(true); + }); + + it.each(['profile', 'contact', 'list', 'add'])('photo enrichment failure retains the %s with an unknown count and an error', async kind => { + vi.mocked(client.getEntity).mockResolvedValue(user()); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.Search) return new Api.contacts.Found({ users: [user()], chats: [], results: [], + myResults: [new Api.PeerUser({ userId: bigInt(7) })], + }) as any; + if (request instanceof Api.contacts.GetContacts) return new Api.contacts.Contacts({ users: [user()], savedCount: 1, + contacts: [new Api.Contact({ userId: bigInt(7), mutual: true })], + }) as any; + if (request instanceof Api.contacts.AddContact) return new Api.Updates({ updates: [], users: [], chats: [], date: 0, seq: 0 }) as any; + if (request instanceof Api.users.GetFullUser) return { fullUser: {}, users: [user()] } as any; + throw rpcError('FLOOD_WAIT_5'); + }); + if (kind === 'profile') await userProfileAction.call(context(), '@fixture'); + else if (kind === 'list') await contactListAction.call(context()); + else if (kind === 'add') await contactAddAction.call(context(), '@fixture'); + else await contactSearchAction.call(context(), 'User'); + const result = state.success.mock.calls[0][0]; + expect(kind === 'add' ? result.photoCount : (result.profiles ?? result.results ?? result.contacts)[0].photoCount).toBeNull(); + expect(result.partial).toBe(true); + expect(result.errors).toEqual([{ input: kind === 'profile' || kind === 'add' ? '@fixture' : '7', error: 'Could not fetch profile photos: FLOOD_WAIT_5', code: 'FLOOD_WAIT_5' }]); + expect(process.exitCode).toBe(1); + }); + + it('contact list retains total and reports enrichment failures instead of dropping them silently', async () => { + const users = [user(1), user(2)]; + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.GetContacts) return new Api.contacts.Contacts({ users, savedCount: 2, + contacts: users.map(u => new Api.Contact({ userId: u.id, mutual: true })), + }) as any; + if (request instanceof Api.users.GetFullUser) { + if (String(request.id.id) === '2') throw rpcError('USER_ID_INVALID'); + return { fullUser: {}, users: [request.id] } as any; + } + return { photos: [], count: 0 } as any; + }); + await contactListAction.call(context()); + const result = state.success.mock.calls[0][0]; + expect(result.contacts).toHaveLength(1); + expect(result.total).toBe(2); + expect(result.partial).toBe(true); + expect(result.errors.map((error: any) => [error.input, error.code])).toEqual([['2', 'USER_ID_INVALID']]); + expect(process.exitCode).toBe(1); + }); + + it('contact add preserves confirmed mutation success if its profile read fails', async () => { + vi.mocked(client.getEntity).mockResolvedValue(user()); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.AddContact) return new Api.Updates({ updates: [], users: [], chats: [], date: 0, seq: 0 }) as any; + throw rpcError('FLOOD_WAIT_5'); + }); + await contactAddAction.call(context(), '@fixture'); + expect(client.invoke).toHaveBeenCalledTimes(2); + expect(state.error).not.toHaveBeenCalled(); + expect(state.success).toHaveBeenCalledWith({ added: true, id: '7', firstName: 'User 7', lastName: null, username: null, + partial: true, errors: [{ input: '@fixture', error: 'Could not fetch added contact profile: FLOOD_WAIT_5', code: 'FLOOD_WAIT_5' }], + }); + expect(process.exitCode).toBe(1); + }); + + it.each(['profile', 'contact', 'list', 'add'])('the %s profile is selected by requested ID, not vector position', async kind => { + const target = user(7); + const related = user(99); + vi.mocked(client.getEntity).mockResolvedValue(target); + vi.mocked(client.invoke).mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.Search) return new Api.contacts.Found({ users: [target], chats: [], results: [], + myResults: [new Api.PeerUser({ userId: target.id })], + }) as any; + if (request instanceof Api.contacts.GetContacts) return new Api.contacts.Contacts({ users: [target], savedCount: 1, + contacts: [new Api.Contact({ userId: target.id, mutual: true })], + }) as any; + if (request instanceof Api.contacts.AddContact) return new Api.Updates({ updates: [], users: [], chats: [], date: 0, seq: 0 }) as any; + if (request instanceof Api.users.GetFullUser) return { fullUser: { id: target.id }, users: [related, target] } as any; + return { photos: [], count: 0 } as any; + }); + if (kind === 'profile') await userProfileAction.call(context(), '@fixture'); + else if (kind === 'list') await contactListAction.call(context()); + else if (kind === 'add') await contactAddAction.call(context(), '@fixture'); + else await contactSearchAction.call(context(), 'User'); + const result = state.success.mock.calls[0][0]; + const profile = kind === 'add' ? result : (result.profiles ?? result.results ?? result.contacts)[0]; + expect(profile.id).toBe('7'); + expect(profile.firstName).toBe('User 7'); + expect(result.partial).toBe(false); + expect(result.errors).toEqual([]); + }); + +}); diff --git a/cli/tests/unit/completion.test.ts b/cli/tests/unit/completion.test.ts new file mode 100644 index 0000000..756ca49 --- /dev/null +++ b/cli/tests/unit/completion.test.ts @@ -0,0 +1,72 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { createCompletionCommand } from '../../src/commands/completion/index.js'; +import { outputError } from '../../src/lib/output.js'; + +describe('completion command', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + process.exitCode = 0; + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + stderrSpy.mockRestore(); + process.exitCode = 0; + }); + + it('writes a bash completion script to stdout', async () => { + const cmd = createCompletionCommand(); + cmd.exitOverride(); + await cmd.parseAsync(['node', 'completion', 'bash']); + expect(stdoutSpy).toHaveBeenCalled(); + const written = stdoutSpy.mock.calls.map((c) => c[0]).join(''); + expect(written).toContain('_tg_completions'); + expect(written).toContain('login status logout'); + expect(process.exitCode ?? 0).toBe(0); + }); + + it('lists subcommands in zsh and fish scripts', async () => { + const cmd = createCompletionCommand(); + cmd.exitOverride(); + await cmd.parseAsync(['node', 'completion', 'zsh']); + const zsh = stdoutSpy.mock.calls.map((c) => c[0]).join(''); + expect(zsh).toContain('login:Log in'); + expect(zsh).toContain('case $words[1]'); + + stdoutSpy.mockClear(); + await cmd.parseAsync(['node', 'completion', 'fish']); + const fish = stdoutSpy.mock.calls.map((c) => c[0]).join(''); + expect(fish).toContain("__fish_seen_subcommand_from auth"); + expect(fish).toContain('login status logout'); + }); + + it('outputs a JSON error envelope for an unknown shell', async () => { + const cmd = createCompletionCommand(); + cmd.exitOverride(); + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + try { + await cmd.parseAsync(['node', 'completion', 'powershell']); + expect(exitSpy).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + } finally { + exitSpy.mockRestore(); + } + const written = stdoutSpy.mock.calls.map((c) => c[0]).join(''); + const parsed = JSON.parse(written.trim()); + expect(parsed).toEqual({ + ok: false, + error: 'Unknown shell: powershell. Use: bash, zsh, or fish', + code: 'INVALID_INPUT', + }); + }); +}); + +describe('outputError used by completion', () => { + it('is the same helper as other commands', () => { + expect(typeof outputError).toBe('function'); + }); +}); diff --git a/cli/tests/unit/config.test.ts b/cli/tests/unit/config.test.ts new file mode 100644 index 0000000..2875d7f --- /dev/null +++ b/cli/tests/unit/config.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { resolveCredentials, createConfig, getCredentialsOrThrow } from '../../src/lib/config.js'; + +describe('createConfig', () => { + it('returns a Conf instance', () => { + const config = createConfig(); + expect(config).toBeDefined(); + expect(typeof config.get).toBe('function'); + expect(typeof config.set).toBe('function'); + }); + + it('default config path uses telegram-cli project name', () => { + const config = createConfig(); + expect(config.path).toContain('telegram-cli'); + }); + + it('uses custom config path when provided', () => { + const tmpDir = join(tmpdir(), `tg-cfg-test-${randomUUID()}`); + const customPath = join(tmpDir, 'custom.json'); + + const config = createConfig(customPath); + expect(config.path).toBe(customPath); + + // Clean up + config.clear(); + try { rmSync(tmpDir, { recursive: true, force: true }); } catch {} + }); +}); + +describe('resolveCredentials', () => { + let configDir: string; + beforeEach(() => { configDir = mkdtempSync(join(tmpdir(), 'tg-creds-test-')); }); + const originalEnv = { ...process.env }; + + afterEach(() => { + process.env = { ...originalEnv }; + rmSync(configDir, { recursive: true, force: true }); + }); + + it('returns credentials from env vars when set', () => { + process.env.TG_API_ID = '12345'; + process.env.TG_API_HASH = 'abc123hash'; + + const config = createConfig(join(configDir, 'config.json')); + const creds = resolveCredentials(config); + + expect(creds).toEqual({ apiId: 12345, apiHash: 'abc123hash' }); + }); + + it('returns credentials from config when env vars are not set', () => { + delete process.env.TG_API_ID; + delete process.env.TG_API_HASH; + + const config = createConfig(join(configDir, 'config.json')); + config.set('apiId', 99999); + config.set('apiHash', 'config_hash_value'); + + const creds = resolveCredentials(config); + + expect(creds).toEqual({ apiId: 99999, apiHash: 'config_hash_value' }); + + // Clean up config + config.clear(); + }); + + it('returns null when neither env vars nor config have credentials', () => { + delete process.env.TG_API_ID; + delete process.env.TG_API_HASH; + + const config = createConfig(join(configDir, 'config.json')); + config.clear(); + + const creds = resolveCredentials(config); + + expect(creds).toBeNull(); + }); + + it('getCredentialsOrThrow rejects non-numeric TG_API_ID', async () => { + process.env.TG_API_ID = 'foo'; + process.env.TG_API_HASH = 'abc'; + const config = createConfig(join(configDir, 'config.json')); + await expect(getCredentialsOrThrow(config)).rejects.toThrow(/positive integer/); + }); + + it('getCredentialsOrThrow does not mention tg config set', async () => { + delete process.env.TG_API_ID; + delete process.env.TG_API_HASH; + const config = createConfig(join(configDir, 'config.json')); + config.clear(); + try { + await getCredentialsOrThrow(config); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.message).toContain('config file'); + expect(err.message).not.toContain('tg config set'); + } + }); + + it('prioritizes env vars over config file values', () => { + process.env.TG_API_ID = '11111'; + process.env.TG_API_HASH = 'env_hash'; + + const config = createConfig(join(configDir, 'config.json')); + config.set('apiId', 22222); + config.set('apiHash', 'config_hash'); + + const creds = resolveCredentials(config); + + expect(creds).toEqual({ apiId: 11111, apiHash: 'env_hash' }); + + // Clean up config + config.clear(); + }); + + it('loads each saved profile preset after a new config instance is created', async () => { + delete process.env.TG_API_ID; + delete process.env.TG_API_HASH; + const path = join(configDir, 'config.json'); + const config = createConfig(path); + config.set('presets', { + desktop: { apiId: 1, apiHash: 'desktop-synthetic', fetchedAt: new Date().toISOString() }, + android: { apiId: 2, apiHash: 'android-synthetic', fetchedAt: new Date().toISOString() }, + }); + config.set('profiles', { + work: { client: 'desktop', created: '2026-09-06T00:00:00Z' }, + personal: { client: 'android', created: '2026-09-06T00:00:00Z' }, + }); + const reloaded = createConfig(path); + await expect(getCredentialsOrThrow(reloaded, undefined, 'work')).resolves.toEqual({ apiId: 1, apiHash: 'desktop-synthetic' }); + await expect(getCredentialsOrThrow(reloaded, undefined, 'personal')).resolves.toEqual({ apiId: 2, apiHash: 'android-synthetic' }); + await expect(getCredentialsOrThrow(reloaded, undefined, 'missing')).rejects.toMatchObject({ code: 'CREDENTIAL_ERROR' }); + await expect(getCredentialsOrThrow(reloaded, 'android', 'work')).resolves.toMatchObject({ apiId: 2 }); + process.env.TG_API_ID = '3'; + process.env.TG_API_HASH = 'environment-synthetic'; + await expect(getCredentialsOrThrow(reloaded, 'android', 'work')).resolves.toEqual({ apiId: 3, apiHash: 'environment-synthetic' }); + }); + + it('keeps config credentials usable for older profiles without a preset', async () => { + delete process.env.TG_API_ID; + delete process.env.TG_API_HASH; + const config = createConfig(join(configDir, 'config.json')); + config.set('apiId', 123); + config.set('apiHash', 'synthetic'); + config.set('profiles', { default: { created: '2026-09-06T00:00:00Z' } }); + await expect(getCredentialsOrThrow(config, undefined, 'default')).resolves.toEqual({ apiId: 123, apiHash: 'synthetic' }); + }); + + it.each(['12junk', '1.5', '-2', '0', '9007199254740992'])('rejects malformed TG_API_ID=%s', async (value) => { + process.env.TG_API_ID = value; + process.env.TG_API_HASH = 'synthetic'; + await expect(getCredentialsOrThrow(createConfig(join(configDir, 'config.json')))).rejects.toMatchObject({ code: 'CREDENTIAL_ERROR' }); + }); +}); diff --git a/cli/tests/unit/contact-add.test.ts b/cli/tests/unit/contact-add.test.ts new file mode 100644 index 0000000..dbac310 --- /dev/null +++ b/cli/tests/unit/contact-add.test.ts @@ -0,0 +1,296 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(undefined), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + AddContact: vi.fn(), + ImportContacts: vi.fn(), + DeleteContacts: vi.fn(), + }, + InputPhoneContact: vi.fn(), + users: { + GetFullUser: vi.fn(), + }, + photos: { + GetUserPhotos: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + isPhoneNumber: (input: string) => /^\+\d+$/.test(input), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { contactAddAction } from '../../src/commands/contact/add.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +// Helper to create a mock user entity returned by resolveEntity +function createMockUserEntity(overrides: Record<string, any> = {}) { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + phone: '+1234567890', + bot: false, + status: { className: 'UserStatusRecently' }, + premium: false, + verified: false, + mutualContact: true, + langCode: 'en', + photo: null, + ...overrides, + }); + return user; +} + +// Helper to create a mock GetFullUser response +function createMockFullUserResult(user: any, overrides: Record<string, any> = {}) { + return { + fullUser: { + about: 'Hello world', + blocked: false, + commonChatsCount: 3, + botInfo: null, + ...overrides, + }, + users: [user], + }; +} + +describe('contactAddAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(undefined); + }); + + it('adds by username successfully via resolveEntity + AddContact + GetFullUser', async () => { + const user = createMockUserEntity(); + mockResolveEntity.mockResolvedValueOnce(user); + + // AddContact returns updates + mockInvoke.mockResolvedValueOnce({ updates: [] }); + // GetFullUser returns full profile + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + // GetUserPhotos returns count + mockInvoke.mockResolvedValueOnce({ count: 2, photos: [] }); + + const ctx = createMockCommandContext(); + await contactAddAction.call(ctx as any, '@alice'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '@alice'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.id).toBe('100'); + expect(result.firstName).toBe('Alice'); + expect(result.lastName).toBe('Smith'); + expect(result.username).toBe('alice'); + expect(result.bio).toBe('Hello world'); + expect(result.photoCount).toBe(2); + }); + + it('adds by phone (+1234567890) with --first-name via ImportContacts', async () => { + const importedUser = createMockUserEntity({ id: BigInt(200), username: 'bob', firstName: 'Bob' }); + + // ImportContacts returns the imported user + mockInvoke.mockResolvedValueOnce({ + users: [importedUser], + imported: [{ userId: BigInt(200) }], + retryContacts: [], + }); + // GetFullUser returns full profile + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(importedUser, { about: 'Hi' })); + // GetUserPhotos + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext({ firstName: 'Bob' }); + await contactAddAction.call(ctx as any, '+1234567890'); + + // Should NOT call resolveEntity for phone input + expect(mockResolveEntity).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.id).toBe('200'); + expect(result.firstName).toBe('Bob'); + }); + + it('phone without --first-name produces MISSING_FIRST_NAME error', async () => { + const ctx = createMockCommandContext(); // no firstName + await contactAddAction.call(ctx as any, '+1234567890'); + + expect(mockOutputError).toHaveBeenCalledWith( + '--first-name is required when adding by phone number', + 'MISSING_FIRST_NAME', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('phone not on Telegram (empty users) produces PHONE_NOT_FOUND error', async () => { + // ImportContacts returns empty users + mockInvoke.mockResolvedValueOnce({ + users: [], + imported: [], + retryContacts: [BigInt(123)], + }); + + const ctx = createMockCommandContext({ firstName: 'Unknown' }); + await contactAddAction.call(ctx as any, '+9999999999'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Phone number not found on Telegram', + 'PHONE_NOT_FOUND', + ); + }); + + it('non-user entity produces NOT_A_USER error', async () => { + const channel = new MockChannel({}); + Object.assign(channel, { id: BigInt(300) }); + + mockResolveEntity.mockResolvedValueOnce(channel); + + const ctx = createMockCommandContext(); + await contactAddAction.call(ctx as any, '@somechannel'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not a user: this is a group/channel', + 'NOT_A_USER', + ); + }); + + it('all-digit input is a user id, not a phone', async () => { + const user = createMockUserEntity({ id: BigInt(300), firstName: 'Charlie' }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce({ updates: [] }); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext({ firstName: 'Charlie' }); + await contactAddAction.call(ctx as any, '1234567890'); + + expect(mockResolveEntity).toHaveBeenCalledWith(expect.anything(), '1234567890'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('handles RPCError via translateTelegramError', async () => { + const user = createMockUserEntity(); + mockResolveEntity.mockResolvedValueOnce(user); + + // AddContact throws RPCError + mockInvoke.mockRejectedValueOnce({ errorMessage: 'CONTACT_ID_INVALID' }); + + const ctx = createMockCommandContext(); + await contactAddAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Contact not found', + 'CONTACT_ID_INVALID', + ); + }); +}); diff --git a/cli/tests/unit/contact-delete.test.ts b/cli/tests/unit/contact-delete.test.ts new file mode 100644 index 0000000..d01843b --- /dev/null +++ b/cli/tests/unit/contact-delete.test.ts @@ -0,0 +1,194 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(true), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + DeleteContacts: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { contactDeleteAction } from '../../src/commands/contact/delete.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('contactDeleteAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(true); + }); + + it('deletes a user contact successfully', async () => { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + username: 'alice', + }); + + mockResolveEntity.mockResolvedValueOnce(user); + + const ctx = createMockCommandContext(); + await contactDeleteAction.call(ctx as any, '@alice'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledWith({ + userId: '100', + username: 'alice', + firstName: 'Alice', + action: 'deleted', + }); + }); + + it('rejects channel entity with NOT_A_USER', async () => { + const channel = new MockChannel({}); + Object.assign(channel, { id: BigInt(300) }); + + mockResolveEntity.mockResolvedValueOnce(channel); + + const ctx = createMockCommandContext(); + await contactDeleteAction.call(ctx as any, '@somechannel'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not a user: this is a group/channel', + 'NOT_A_USER', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('translates RPCError via translateTelegramError', async () => { + const user = new MockUser({}); + Object.assign(user, { id: BigInt(100), firstName: 'Alice', username: 'alice' }); + mockResolveEntity.mockResolvedValueOnce(user); + + mockInvoke.mockRejectedValueOnce({ errorMessage: 'CONTACT_ID_INVALID' }); + + const ctx = createMockCommandContext(); + await contactDeleteAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Contact not found', + 'CONTACT_ID_INVALID', + ); + }); + + it('handles not-logged-in with NOT_AUTHENTICATED', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null as any); + }); + + const ctx = createMockCommandContext(); + await contactDeleteAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not logged in. Run: tg auth login', + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/contact-list.test.ts b/cli/tests/unit/contact-list.test.ts new file mode 100644 index 0000000..cfa128d --- /dev/null +++ b/cli/tests/unit/contact-list.test.ts @@ -0,0 +1,302 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(undefined), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + GetContacts: vi.fn(), + DeleteContacts: vi.fn(), + }, + users: { + GetFullUser: vi.fn(), + }, + photos: { + GetUserPhotos: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { contactListAction } from '../../src/commands/contact/list.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +// Helper to create a mock user for GetContacts result +function createMockContactUser(overrides: Record<string, any> = {}) { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + phone: '+1234567890', + bot: false, + status: { className: 'UserStatusRecently' }, + premium: false, + verified: false, + mutualContact: true, + langCode: 'en', + photo: null, + ...overrides, + }); + return user; +} + +// Helper to create a mock GetFullUser response +function createMockFullUserResult(user: any, overrides: Record<string, any> = {}) { + return { + fullUser: { + about: 'Hello world', + blocked: false, + commonChatsCount: 3, + botInfo: null, + ...overrides, + }, + users: [user], + }; +} + +describe('contactListAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(undefined); + }); + + it('lists contacts successfully with GetContacts + GetFullUser enrichment', async () => { + const user1 = createMockContactUser({ id: BigInt(100), firstName: 'Alice', lastName: 'Smith', username: 'alice' }); + const user2 = createMockContactUser({ id: BigInt(200), firstName: 'Bob', lastName: 'Jones', username: 'bob' }); + + // GetContacts result + mockInvoke.mockResolvedValueOnce({ + className: 'contacts.Contacts', + contacts: [ + { userId: BigInt(100), mutual: true }, + { userId: BigInt(200), mutual: false }, + ], + users: [user1, user2], + }); + + // In batch of 5, both GetFullUser calls happen concurrently (map starts both), + // then both GetUserPhotos calls happen after each GetFullUser resolves. + // Mock order: GetFullUser(Alice), GetFullUser(Bob), GetUserPhotos(Alice), GetUserPhotos(Bob) + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user1)); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user2, { about: 'Hi there' })); + mockInvoke.mockResolvedValueOnce({ count: 2, photos: [] }); + mockInvoke.mockResolvedValueOnce({ count: 1, photos: [] }); + + const ctx = createMockCommandContext(); + await contactListAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.contacts).toHaveLength(2); + expect(result.total).toBe(2); + // Sorted alphabetically: Alice before Bob + expect(result.contacts[0].firstName).toBe('Alice'); + expect(result.contacts[1].firstName).toBe('Bob'); + }); + + it('handles ContactsNotModified with empty contacts', async () => { + // ContactsNotModified response + mockInvoke.mockResolvedValueOnce({ + className: 'contacts.ContactsNotModified', + }); + + const ctx = createMockCommandContext(); + await contactListAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ contacts: [], total: 0, partial: false, errors: [] }); + }); + + it('applies limit/offset pagination correctly', async () => { + const users = []; + const contacts = []; + for (let i = 0; i < 5; i++) { + const user = createMockContactUser({ + id: BigInt(100 + i), + firstName: `User${String.fromCharCode(65 + i)}`, // UserA, UserB, UserC, UserD, UserE + lastName: '', + username: `user${i}`, + }); + users.push(user); + contacts.push({ userId: BigInt(100 + i), mutual: true }); + } + + // GetContacts + mockInvoke.mockResolvedValueOnce({ + className: 'contacts.Contacts', + contacts, + users, + }); + + // Batch of 5: GetFullUser calls first, then GetUserPhotos calls + // After sort: UserA(0), UserB(1), UserC(2), UserD(3), UserE(4) -> offset=1 limit=2 -> UserB, UserC + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(users[1])); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(users[2])); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext({ limit: '2', offset: '1' }); + await contactListAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.contacts).toHaveLength(2); + expect(result.total).toBe(5); // Total before pagination + expect(result.contacts[0].firstName).toBe('UserB'); + expect(result.contacts[1].firstName).toBe('UserC'); + }); + + it('sorts contacts alphabetically by firstName + lastName', async () => { + const charlie = createMockContactUser({ id: BigInt(100), firstName: 'Charlie', lastName: 'Z', username: 'charlie' }); + const alice = createMockContactUser({ id: BigInt(200), firstName: 'Alice', lastName: 'B', username: 'alice' }); + const bob = createMockContactUser({ id: BigInt(300), firstName: 'Bob', lastName: 'A', username: 'bob' }); + + mockInvoke.mockResolvedValueOnce({ + className: 'contacts.Contacts', + contacts: [ + { userId: BigInt(100), mutual: true }, + { userId: BigInt(200), mutual: true }, + { userId: BigInt(300), mutual: true }, + ], + users: [charlie, alice, bob], + }); + + // Batch of 5: all GetFullUser calls first, then all GetUserPhotos calls (sorted: Alice, Bob, Charlie) + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(alice)); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(bob)); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(charlie)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await contactListAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.contacts[0].firstName).toBe('Alice'); + expect(result.contacts[1].firstName).toBe('Bob'); + expect(result.contacts[2].firstName).toBe('Charlie'); + }); + + it('handles not-logged-in with NOT_AUTHENTICATED', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null as any); + }); + + const ctx = createMockCommandContext(); + await contactListAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not logged in. Run: tg auth login', + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/contact-search-local.test.ts b/cli/tests/unit/contact-search-local.test.ts new file mode 100644 index 0000000..2e38ea0 --- /dev/null +++ b/cli/tests/unit/contact-search-local.test.ts @@ -0,0 +1,147 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; + +const state = vi.hoisted(() => ({ invoke: vi.fn(), success: vi.fn(), error: vi.fn() })); +vi.mock('../../src/lib/with-auth.js', () => ({ withAuth: async (_opts, fn) => fn({ invoke: state.invoke }) })); +vi.mock('../../src/lib/output.js', () => ({ outputSuccess: state.success, outputError: state.error, logStatus: vi.fn() })); +import { contactSearchAction } from '../../src/commands/contact/search.js'; + +const user = (id: number, firstName: string, username?: string, lastName?: string) => new Api.User({ + id: bigInt(id), firstName, username, lastName, accessHash: bigInt(id + 1000), +}); +const contact = (id: number) => new Api.Contact({ userId: bigInt(id), mutual: false }); +const peer = (id: number) => new Api.PeerUser({ userId: bigInt(id) }); +const context = (opts: Record<string, unknown> = {}) => ({ + optsWithGlobals: () => ({ profile: 'offline', limit: '20', ...opts }), +}) as any; +const alice = () => user(100, 'Alice', 'alice_handle', 'Smith'); +const found = () => new Api.contacts.Found({ users: [], chats: [], myResults: [], results: [] }); +const rpcError = (code: string) => Object.assign(new Error(code), { errorMessage: code }); + +function mockTransport(contacts: Api.User[], remote = found()) { + state.invoke.mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.GetContacts) { + expect(request.getBytes().length).toBeGreaterThan(0); + return new Api.contacts.Contacts({ users: contacts, savedCount: contacts.length, contacts: contacts.map(u => contact(u.id.toJSNumber())) }); + } + if (request instanceof Api.contacts.Search) return remote; + if (request instanceof Api.users.GetFullUser) return { fullUser: {}, users: [request.id] }; + if (request instanceof Api.photos.GetUserPhotos) return new Api.photos.Photos({ photos: [], users: [] }); + throw new Error(`Unexpected offline RPC ${request.className}`); + }); +} + +describe('contact search searches the actual address book locally', () => { + const exitCode = process.exitCode; + beforeEach(() => { vi.clearAllMocks(); process.exitCode = 0; }); + afterEach(() => { process.exitCode = exitCode; }); + + it.each(['ali', 'ALI', 'Alice Smith', 'SMITH', '@ALICE_HANDLE'])('finds an existing contact for %s without contacts.Search', async query => { + mockTransport([alice()]); + await contactSearchAction.call(context({ limit: '1' }), query); + expect(state.success.mock.calls[0][0]).toMatchObject({ results: [{ id: '100', isContact: true }], total: 1, partial: false, errors: [] }); + expect(state.invoke.mock.calls.some(([request]) => request instanceof Api.contacts.GetContacts)).toBe(true); + expect(state.invoke.mock.calls.some(([request]) => request instanceof Api.contacts.Search)).toBe(false); + }); + + it('matches Unicode case and ignores users not present in the contact list', async () => { + const saved = user(100, 'Сергей', 'sergey'); + const unrelated = user(200, 'Сергей'); + mockTransport([saved]); + state.invoke.mockImplementationOnce(async () => new Api.contacts.Contacts({ users: [unrelated, saved], contacts: [contact(100)], savedCount: 1 })); + await contactSearchAction.call(context(), 'СЕРГ'); + expect(state.success.mock.calls[0][0].results.map((u: any) => u.id)).toEqual(['100']); + }); + + it('merges local contacts with remote users, deduplicates, and limits before enrichment', async () => { + const known = alice(); + const remoteOne = user(200, 'Alicia', 'alicia'); + const remoteTwo = user(300, 'Alina', 'alina'); + mockTransport([known], new Api.contacts.Found({ + users: [known, remoteOne, remoteTwo], chats: [], + myResults: [peer(200)], results: [peer(100), peer(200), new Api.PeerChannel({ channelId: bigInt(400) }), peer(300)], + })); + await contactSearchAction.call(context({ global: true, limit: '2' }), 'ali'); + const data = state.success.mock.calls[0][0]; + expect(data.results.map((u: any) => [u.id, u.isContact])).toEqual([['100', true], ['200', false]]); + expect(state.invoke.mock.calls.filter(([r]) => r instanceof Api.users.GetFullUser).map(([r]) => String(r.id.id))).toEqual(['100', '200']); + expect(data).toMatchObject({ total: 2, partial: false, errors: [] }); + }); + + it('applies the limit after matching and does not enrich unmatched or duplicate contacts', async () => { + const bob = user(50, 'Bob'); + const known = alice(); + const other = user(200, 'Alicia'); + mockTransport([bob, known, other]); + state.invoke.mockImplementationOnce(async () => new Api.contacts.Contacts({ users: [bob, known, other], contacts: [contact(50), contact(100), contact(100), contact(200)], savedCount: 3 })); + await contactSearchAction.call(context({ limit: '1' }), 'ali'); + expect(state.success.mock.calls[0][0].results.map((u: any) => u.id)).toEqual(['100']); + expect(state.invoke.mock.calls.filter(([r]) => r instanceof Api.users.GetFullUser)).toHaveLength(1); + }); + + it('retains local matches and reports a remote search error as partial', async () => { + mockTransport([alice()]); + const implementation = state.invoke.getMockImplementation()!; + state.invoke.mockImplementation(async (request: any) => { + if (request instanceof Api.contacts.Search) throw rpcError('QUERY_TOO_SHORT'); + return implementation(request); + }); + await contactSearchAction.call(context({ global: true }), 'al'); + const data = state.success.mock.calls[0][0]; + expect(data.results).toMatchObject([{ id: '100', isContact: true }]); + expect(data).toMatchObject({ partial: true, errors: [expect.objectContaining({ code: 'QUERY_TOO_SHORT' })] }); + expect(process.exitCode).toBe(1); + }); + + it('retains remote matches and reports failure to read contacts as partial', async () => { + const remote = user(200, 'Alicia'); + mockTransport([], new Api.contacts.Found({ users: [remote], chats: [], myResults: [], results: [peer(200)] })); + state.invoke.mockImplementationOnce(async () => { throw Object.assign(new Error('offline reset'), { code: 'ECONNRESET' }); }); + await contactSearchAction.call(context({ global: true }), 'ali'); + expect(state.success.mock.calls[0][0]).toMatchObject({ + results: [{ id: '200', isContact: false }], partial: true, + errors: [expect.objectContaining({ code: 'ECONNRESET' })], + }); + expect(process.exitCode).toBe(1); + }); + + it('uses the returned contact flag when the address book could not be read', async () => { + const remote = user(200, 'Alicia'); + remote.contact = true; + mockTransport([], new Api.contacts.Found({ users: [remote], chats: [], myResults: [], results: [peer(200)] })); + state.invoke.mockImplementationOnce(async () => { throw Object.assign(new Error('offline reset'), { code: 'ECONNRESET' }); }); + await contactSearchAction.call(context({ global: true }), 'ali'); + expect(state.success.mock.calls[0][0]).toMatchObject({ results: [{ id: '200', isContact: true }], partial: true }); + }); + + it('returns an empty successful local search without invoking remote search or enrichment', async () => { + mockTransport([alice()]); + await contactSearchAction.call(context(), 'missing'); + expect(state.success).toHaveBeenCalledWith({ results: [], total: 0, partial: false, errors: [] }); + expect(state.invoke).toHaveBeenCalledOnce(); + expect(state.invoke.mock.calls[0][0]).toBeInstanceOf(Api.contacts.GetContacts); + }); + + it('skips the remote lookup when local matches already fill a global page', async () => { + mockTransport([alice()]); + await contactSearchAction.call(context({ global: true, limit: '1' }), 'al'); + expect(state.success.mock.calls[0][0]).toMatchObject({ results: [{ id: '100', isContact: true }], partial: false }); + expect(state.invoke.mock.calls.some(([request]) => request instanceof Api.contacts.Search)).toBe(false); + }); + + it.each(['', ' ', '@'])('rejects an empty query %j before reading contacts', async query => { + await contactSearchAction.call(context(), query); + expect(state.error).toHaveBeenCalledWith('Search query cannot be empty', 'INVALID_INPUT'); + expect(state.invoke).not.toHaveBeenCalled(); + }); + + it('exposes a failed local read in default mode instead of reporting no matches', async () => { + state.invoke.mockRejectedValueOnce(rpcError('AUTH_KEY_UNREGISTERED')); + await contactSearchAction.call(context(), 'alice'); + expect(state.success.mock.calls[0][0]).toMatchObject({ results: [], total: 0, partial: true, errors: [ + expect.objectContaining({ input: 'contacts', code: 'AUTH_KEY_UNREGISTERED' }), + ] }); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/cli/tests/unit/contact-search.test.ts b/cli/tests/unit/contact-search.test.ts new file mode 100644 index 0000000..a40206f --- /dev/null +++ b/cli/tests/unit/contact-search.test.ts @@ -0,0 +1,271 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(undefined), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + Search: vi.fn(), + GetContacts: vi.fn(), + }, + users: { + GetFullUser: vi.fn(), + }, + photos: { + GetUserPhotos: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { contactSearchAction } from '../../src/commands/contact/search.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '20', + global: false, + ...opts, + })), + }; +} + +// Helper to create a mock user for search results +function createMockSearchUser(overrides: Record<string, any> = {}) { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + phone: '+1234567890', + bot: false, + status: { className: 'UserStatusRecently' }, + premium: false, + verified: false, + mutualContact: true, + langCode: 'en', + photo: null, + ...overrides, + }); + return user; +} + +// Helper to create a mock GetFullUser response +function createMockFullUserResult(user: any, overrides: Record<string, any> = {}) { + return { + fullUser: { + about: 'Hello world', + blocked: false, + commonChatsCount: 3, + botInfo: null, + ...overrides, + }, + users: [user], + }; +} + +describe('contactSearchAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(undefined); + }); + + it('searches the address book locally and ignores unrelated users', async () => { + const user1 = createMockSearchUser({ id: BigInt(100), firstName: 'Alice', username: 'alice' }); + + // GetContacts may include entity metadata for unrelated users. + mockInvoke.mockResolvedValueOnce({ + contacts: [{ userId: BigInt(100), mutual: true }], + myResults: [{ className: 'PeerUser', userId: BigInt(100) }], + results: [ + { className: 'PeerUser', userId: BigInt(100) }, + { className: 'PeerUser', userId: BigInt(200) }, + ], + users: [ + user1, + createMockSearchUser({ id: BigInt(200), firstName: 'Alicia', username: 'alicia' }), + ], + chats: [], + }); + + // GetFullUser for the matching saved contact Alice + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user1)); + // GetUserPhotos + mockInvoke.mockResolvedValueOnce({ count: 1, photos: [] }); + + const ctx = createMockCommandContext(); + await contactSearchAction.call(ctx as any, 'ali'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + // Default mode: only saved contacts (1 user) + expect(result.results).toHaveLength(1); + expect(result.results[0].firstName).toBe('Alice'); + expect(result.results[0].isContact).toBe(true); + expect(result.total).toBe(1); + }); + + it('searches with --global using local contacts plus remote results', async () => { + const user1 = createMockSearchUser({ id: BigInt(100), firstName: 'Alice', username: 'alice' }); + const user2 = createMockSearchUser({ id: BigInt(200), firstName: 'Alicia', username: 'alicia', mutualContact: false }); + + // Read local contacts, then append remote username results. + mockInvoke.mockResolvedValueOnce({ contacts: [{ userId: BigInt(100), mutual: true }], users: [user1] }); + mockInvoke.mockResolvedValueOnce({ + myResults: [{ className: 'PeerUser', userId: BigInt(100) }], + results: [ + { className: 'PeerUser', userId: BigInt(200) }, + ], + users: [user1, user2], + chats: [], + }); + + // Batch of 5: all GetFullUser calls first, then all GetUserPhotos calls + // GetFullUser for Alice, then GetFullUser for Alicia, then GetUserPhotos for each + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user1)); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user2, { about: 'Hi' })); + mockInvoke.mockResolvedValueOnce({ count: 1, photos: [] }); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext({ global: true }); + await contactSearchAction.call(ctx as any, 'ali'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + // Global mode: local contact plus remote match (2 users) + expect(result.results).toHaveLength(2); + // Alice is in the address book -> isContact: true + expect(result.results[0].isContact).toBe(true); + // Alicia is absent from the address book -> isContact: false + expect(result.results[1].isContact).toBe(false); + expect(result.total).toBe(2); + }); + + it('handles empty results', async () => { + // GetContacts with an empty address book. + mockInvoke.mockResolvedValueOnce({ + contacts: [], + myResults: [], + results: [], + users: [], + chats: [], + }); + + const ctx = createMockCommandContext(); + await contactSearchAction.call(ctx as any, 'nonexistent'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ results: [], total: 0, partial: false, errors: [] }); + }); + + it('handles not-logged-in with NOT_AUTHENTICATED', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null as any); + }); + + const ctx = createMockCommandContext(); + await contactSearchAction.call(ctx as any, 'alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not logged in. Run: tg auth login', + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/core-cross-review.test.ts b/cli/tests/unit/core-cross-review.test.ts new file mode 100644 index 0000000..34be5a6 --- /dev/null +++ b/cli/tests/unit/core-cross-review.test.ts @@ -0,0 +1,131 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { TelegramClient, sessions } from 'teleproto'; +import { AuthKey } from 'teleproto/crypto/AuthKey.js'; +import { withClient } from '../../src/lib/client.js'; +import { createConfig, getCredentialsOrThrow } from '../../src/lib/config.js'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { importAction } from '../../src/commands/session/import.js'; +import { setQuietMode, setVerboseMode } from '../../src/lib/cli-mode.js'; + +/** Independent checks using the real SDK/config/store, with transport kept offline. */ +describe('core fixes: independent boundary review', () => { + let dir: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'tg-core-review-')); + vi.stubEnv('TG_API_ID', undefined); + vi.stubEnv('TG_API_HASH', undefined); + vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('Network forbidden in regression test')))); + setQuietMode(true); + setVerboseMode(false); + }); + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + setQuietMode(false); + setVerboseMode(false); + process.exitCode = 0; + rmSync(dir, { recursive: true, force: true }); + }); + + it('destroys a sender created by the real SDK connect after the deadline', async () => { + vi.useFakeTimers(); + let resume!: () => void; + let connected = false; + let disconnects = 0; + const originalInit = (TelegramClient.prototype as any)._initSession; + vi.spyOn(TelegramClient.prototype as any, '_initSession').mockImplementation(async function (this: any) { + await new Promise<void>((resolve) => { resume = resolve; }); + await originalInit.call(this); + // Substitute just the sender transport. TelegramClient.connect() and + // destroy() stay real, including SDK work that occurs after initialization. + this._sender = { + authKey: this.session.getAuthKey(), + connect: async () => { connected = true; return true; }, + send: async () => ({}), + disconnect: async () => { connected = false; disconnects++; }, + }; + }); + const callback = vi.fn(); + const pending = withClient({ apiId: 1, apiHash: 'synthetic', sessionString: '' }, callback, { timeout: 10 }); + const rejected = expect(pending).rejects.toMatchObject({ code: 'TIMEOUT' }); + await vi.advanceTimersByTimeAsync(10); + await rejected; + expect(connected).toBe(false); + resume(); + await vi.advanceTimersByTimeAsync(0); + expect(callback).not.toHaveBeenCalled(); + expect(connected).toBe(false); + // Teleproto refuses to connect after destroy, even if initialization finishes late. + expect(disconnects).toBe(0); + expect(vi.getTimerCount()).toBe(0); + }); + + it('preserves preset precedence through a real session import and config reload', async () => { + const path = join(dir, 'config.json'); + const config = createConfig(path); + config.set('apiId', 10); + config.set('apiHash', 'global-synthetic'); + config.set('presets', { + desktop: { apiId: 20, apiHash: 'desktop-synthetic', fetchedAt: new Date().toISOString() }, + android: { apiId: 30, apiHash: 'android-synthetic', fetchedAt: new Date().toISOString() }, + }); + config.set('profiles', { + work: { client: 'desktop', created: '2026-09-06T00:00:00Z' }, + personal: { client: 'android', created: '2026-09-06T00:00:00Z' }, + }); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + await importAction.call({ optsWithGlobals: () => ({ profile: 'work', config: path, skipVerify: true, quiet: true }) } as any, 'synthetic-imported-session'); + expect(JSON.parse(String(stdout.mock.calls[0][0]))).toMatchObject({ ok: true, data: { imported: true, profile: 'work' } }); + expect(stderr).not.toHaveBeenCalled(); + const fresh = createConfig(path); + expect(fresh.get('profiles.work.client')).toBe('desktop'); + expect(fresh.get('profiles.personal.client')).toBe('android'); + expect(await new SessionStore(dir).load('work')).toBe('synthetic-imported-session'); + await expect(getCredentialsOrThrow(fresh, undefined, 'work')).resolves.toMatchObject({ apiId: 20 }); + await expect(getCredentialsOrThrow(fresh, 'android', 'work')).resolves.toMatchObject({ apiId: 30 }); + await expect(getCredentialsOrThrow(fresh, undefined, 'legacy')).resolves.toMatchObject({ apiId: 10 }); + vi.stubEnv('TG_API_ID', '40'); + vi.stubEnv('TG_API_HASH', 'environment-synthetic'); + await expect(getCredentialsOrThrow(fresh, 'android', 'work')).resolves.toMatchObject({ apiId: 40 }); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('rejects a malformed environment API ID when only the hash comes from config', async () => { + const config = createConfig(join(dir, 'config.json')); + config.set('apiHash', 'synthetic'); + vi.stubEnv('TG_API_ID', '12junk'); + await expect(getCredentialsOrThrow(config)).rejects.toMatchObject({ code: 'CREDENTIAL_ERROR' }); + }); + + it('verifies import with the selected preset even if unused global credentials are invalid', async () => { + const path = join(dir, 'config.json'); + const config = createConfig(path); + config.set('apiId', 'obsolete-invalid-global-id' as any); + config.set('apiHash', 'unused-global-synthetic'); + config.set('presets', { + desktop: { apiId: 20, apiHash: 'desktop-synthetic', fetchedAt: new Date().toISOString() }, + }); + config.set('profiles', { work: { client: 'desktop', created: '2026-09-06T00:00:00Z' } }); + const session = new sessions.StringSession(''); + session.setDC(2, '127.0.0.1', 443); + const key = new AuthKey(); + await key.setKey(Buffer.alloc(256, 7)); + session.setAuthKey(key); + const serialized = session.save(); + vi.spyOn(TelegramClient.prototype, 'connect').mockResolvedValue(true); + vi.spyOn(TelegramClient.prototype, 'checkAuthorization').mockResolvedValue(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + await importAction.call({ optsWithGlobals: () => ({ profile: 'work', config: path, quiet: true }) } as any, serialized); + expect(JSON.parse(String(stdout.mock.calls[0][0]))).toMatchObject({ ok: true, data: { imported: true, verified: true } }); + expect(await new SessionStore(dir).load('work')).toBe(serialized); + expect(createConfig(path).get('profiles.work.client')).toBe('desktop'); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/daemon-api-cross-review.test.ts b/cli/tests/unit/daemon-api-cross-review.test.ts new file mode 100644 index 0000000..13056ba --- /dev/null +++ b/cli/tests/unit/daemon-api-cross-review.test.ts @@ -0,0 +1,271 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { Api, TelegramClient, sessions, errors } from 'teleproto'; +import bigInt from 'big-integer'; +import { Logger, LogLevel } from 'teleproto/extensions/Logger.js'; +import { createRequestClient } from '../../src/lib/daemon/request-client.js'; +import { DaemonServer } from '../../src/lib/daemon/server.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { executeDaemonCommand } from '../../src/lib/daemon/execute.js'; + +function deferred<T>() { + let resolve!: (value: T) => void; + const promise = new Promise<T>(done => { resolve = done; }); + return { promise, resolve }; +} + +function sharedClient() { + const logger = new Logger(LogLevel.NONE); + const client = new TelegramClient(new sessions.StringSession(''), 1, 'synthetic', { baseLogger: logger }); + client.session.setDC(4, '127.0.0.1', 80); + (client as any)._connectedDeferred.resolve(); + return client; +} + +afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('independent real SDK daemon client review', () => { + it('serializes a real SDK dialog message initialized with the default Markdown parse mode', async () => { + const shared = sharedClient(); + const peer = new Api.PeerUser({ userId: bigInt(7) }); + const response = new Api.messages.Dialogs({ + users: [new Api.User({ id: bigInt(7), accessHash: bigInt(8), firstName: 'Fixture' })], + chats: [], + messages: [new Api.Message({ + id: 9, peerId: peer, date: 1700000000, message: 'Bold fixture', + entities: [new Api.MessageEntityBold({ offset: 0, length: 4 })], + })], + dialogs: [new Api.Dialog({ + peer, topMessage: 9, readInboxMaxId: 0, readOutboxMaxId: 0, + unreadCount: 0, unreadMentionsCount: 0, unreadReactionsCount: 0, + notifySettings: new Api.PeerNotifySettings({}), + })], + }); + const enqueue = vi.fn((state: any) => state.resolve(response)); + (shared as any)._sender = { isConnected: () => true, addStateToQueue: enqueue }; + const signal = new AbortController().signal; + const view = createRequestClient(shared, signal); + const result = await executeDaemonCommand(view.client, 'fixture', { argv: ['chat', 'list', '--limit', '1'] }, signal); + // The SDK returns TotalList subclasses; compare the API's serialized wire shape. + expect(JSON.parse(JSON.stringify(result))).toMatchObject({ output: { ok: true, data: { chats: [{ id: '7' }], total: 1 } }, exitCode: 0 }); + expect(response.messages[0].text).toBe('**Bold** fixture'); + expect(enqueue).toHaveBeenCalledOnce(); + await view.settled(); + }); + + it('uses real SDK default Markdown parsing and initializes the sent message response', async () => { + const shared = sharedClient(); + const enqueue = vi.fn((state: any) => { + expect(state.request).toBeInstanceOf(Api.messages.SendMessage); + state.resolve(new Api.UpdateShortSentMessage({ + id: 77, pts: 1, ptsCount: 1, date: 1700000000, out: true, + entities: state.request.entities, + })); + }); + (shared as any)._sender = { isConnected: () => true, addStateToQueue: enqueue }; + const view = createRequestClient(shared, new AbortController().signal); + const peer = new Api.InputPeerUser({ userId: bigInt(7), accessHash: bigInt(8) }); + const sent = await view.client.sendMessage(peer, { message: '**Bold** and __italic__' }); + expect(sent.id).toBe(77); + expect(sent.message).toBe('Bold and italic'); + expect(sent.text).toBe('**Bold** and __italic__'); + const request = enqueue.mock.calls[0][0].request; + expect(request.message).toBe('Bold and italic'); + expect(request.entities[0]).toBeInstanceOf(Api.MessageEntityBold); + expect(request.entities[1]).toBeInstanceOf(Api.MessageEntityItalic); + expect(enqueue).toHaveBeenCalledOnce(); + await view.settled(); + }); + + it('preserves connection and socket constructors required by real SDK media sender setup', async () => { + vi.useFakeTimers(); + const shared = sharedClient(); + const controller = new AbortController(); + // Replace transport connection only; _connectSender itself is the installed SDK. + const sender = { + authKey: { getKey: () => Buffer.alloc(256) }, + connect: vi.fn(async () => true), disconnect: vi.fn(async () => {}), + _authenticated: true, + }; + vi.spyOn(shared, 'getDC').mockResolvedValue({ id: 4, ipAddress: '127.0.0.1', port: 80 } as any); + const errorsSeen: unknown[] = []; + (shared as any)._errorHandler = async (error: unknown) => { + errorsSeen.push(error); + controller.abort(error); + }; + const view = createRequestClient(shared, controller.signal); + const result = (view.client as any)._connectSender(sender, 4).then( + (value: unknown) => ({ value }), (error: unknown) => ({ error }), + ); + await vi.advanceTimersByTimeAsync(1000); + expect(await result).toMatchObject({ value: { _authenticated: true } }); + expect(sender.connect.mock.calls[0][0].dcId).toBe(4); + expect(errorsSeen).toEqual([]); + expect(sender.connect).toHaveBeenCalledOnce(); + await view.settled(); + }); + + it('does not store cancelled request callbacks in a reusable exported MTProtoSender', async () => { + vi.useFakeTimers(); + const shared = sharedClient(); + const controller = new AbortController(); + // Real sender creation, callback binding and exported-sender cache; no network. + vi.spyOn(shared as any, '_connectSender').mockImplementation(async (sender: any) => { + sender._userConnected = true; + return sender; + }); + const view = createRequestClient(shared, controller.signal); + await view.client.getSender(2); + const sender = await (shared as any)._network.getSession(2).ensureConnected(); + const setAuthKey = vi.spyOn(shared.session, 'setAuthKey'); + controller.abort(new Error('The originating request ended')); + await view.settled(); + + // A later key rotation or connection-break callback belongs to the shared + // transport, even if the command which first borrowed it has timed out. + const callback = Promise.resolve().then(() => sender.opts.authKeyCallback(sender.authKey, 2)); + await expect(callback).resolves.toBeUndefined(); + expect(setAuthKey).toHaveBeenCalledWith(sender.authKey, 2); + const next = createRequestClient(shared, new AbortController().signal); + await expect(next.client.getSender(2)).resolves.toBeDefined(); + await next.settled(); + }); + + it('completes an already-started SDK DC switch when the initiating request aborts during disconnect', async () => { + const shared = sharedClient(); + const controller = new AbortController(); + const disconnectStarted = deferred<void>(); + const disconnectFinish = deferred<void>(); + const oldSender = { + authKey: { setKey: vi.fn(async () => {}) }, + isConnected: () => true, + }; + (shared as any)._sender = oldSender; + vi.spyOn(shared, 'getDC').mockResolvedValue({ id: 2, ipAddress: '127.0.0.1', port: 80 } as any); + (shared as any)._sender.disconnect = vi.fn(async () => { + disconnectStarted.resolve(); + await disconnectFinish.promise; + }); + const connect = vi.spyOn(shared, 'connect').mockImplementation(async function () { + (this as any)._sender = { isConnected: () => true }; + return true; + }); + const view = createRequestClient(shared, controller.signal); + const switching = (view.client as any)._switchDC(2).catch(() => undefined); + await disconnectStarted.promise; + controller.abort(new Error('Request timed out')); + disconnectFinish.resolve(); + await switching; + await view.settled(); + expect(connect).toHaveBeenCalledOnce(); + expect(shared.connected).toBe(true); + const subsequent = createRequestClient(shared, new AbortController().signal); + expect(subsequent.client.connected).toBe(true); + }); + + it('runs real message iterators and getters on a fresh request after cancelling another one', async () => { + const shared = sharedClient(); + const response = new Api.messages.Messages({ + messages: [new Api.Message({ id: 7, peerId: new Api.PeerUser({ userId: bigInt(1) }), date: 1700000000, message: 'fixture' })], + chats: [], users: [], + }); + const enqueue = vi.fn((state: any) => state.resolve(response)); + (shared as any)._sender = { isConnected: () => true, addStateToQueue: enqueue }; + const controller = new AbortController(); + const first = createRequestClient(shared, controller.signal); + const peer = new Api.InputPeerUser({ userId: bigInt(1), accessHash: bigInt(2) }); + const iterator = first.client.iterMessages(peer, { ids: [7] })[Symbol.asyncIterator](); + expect((await iterator.next()).value?.id).toBe(7); + controller.abort(new Error('cancelled')); + expect(() => iterator.next()).toThrow('cancelled'); + await first.settled(); + const second = createRequestClient(shared, new AbortController().signal); + expect(second.client.connected).toBe(true); + const messages = await second.client.getMessages(peer, { ids: [7] }); + expect(Array.from(messages, message => message.id)).toEqual([7]); + expect(enqueue).toHaveBeenCalledTimes(2); + await second.settled(); + }); + + it('does not replay CONNECTION_NOT_INITED and leaves the shared sender usable', async () => { + const shared = sharedClient(); + const failure = new Error('CONNECTION_NOT_INITED'); + const enqueue = vi.fn((state: any) => state.reject(failure)); + (shared as any)._sender = { isConnected: () => true, addStateToQueue: enqueue }; + const disconnect = vi.spyOn(shared, 'disconnect'); + const view = createRequestClient(shared, new AbortController().signal); + await expect(view.client.invoke(new Api.help.GetConfig())).rejects.toBe(failure); + await view.settled(); + expect(disconnect).not.toHaveBeenCalled(); + expect(shared.connected).toBe(true); + expect(enqueue).toHaveBeenCalledOnce(); + }); + + it('destroys a transport which late maintenance reopens before releasing the daemon session lease', async () => { + const shared = sharedClient(); + const controller = new AbortController(); + const disconnectStarted = deferred<void>(); + const disconnectFinish = deferred<void>(); + let connected = true; + (shared as any)._sender = { + authKey: { setKey: vi.fn(async () => {}) }, isConnected: () => connected, + }; + vi.spyOn(shared, 'getDC').mockResolvedValue({ id: 2, ipAddress: '127.0.0.1', port: 80 } as any); + (shared as any)._sender.disconnect = vi.fn(async () => { + disconnectStarted.resolve(); + await disconnectFinish.promise; + }); + vi.spyOn(shared, 'connect').mockImplementation(async function () { + connected = true; + (this as any)._sender = { isConnected: () => connected }; + return true; + }); + const destroy = vi.spyOn(shared, 'destroy').mockImplementation(async () => { connected = false; }); + const view = createRequestClient(shared, controller.signal); + const operation = (view.client as any)._switchDC(2).catch(() => undefined); + const done = operation.then(() => view.settled()); + const server = new DaemonServer(new DaemonPaths('/synthetic-unused', 'fixture'), { apiId: 1, apiHash: 'synthetic' }); + (server as any).client = shared; + (server as any).activeRequests.add({ controller, done }); + let connectedAtRelease: boolean | undefined; + const release = vi.fn(async () => { connectedAtRelease = connected; }); + (server as any).releaseSession = release; + await disconnectStarted.promise; + const stopping = server.stop(); + await vi.waitFor(() => expect(destroy).toHaveBeenCalled()); + expect(release).not.toHaveBeenCalled(); + disconnectFinish.resolve(); + await stopping; + expect(connectedAtRelease).toBe(false); + expect(connected).toBe(false); + expect(release).toHaveBeenCalledOnce(); + }); + + it('never replays a server-error write, even before cancellation', async () => { + const shared = sharedClient(); + const initialRetries = (shared as any)._requestRetries; + const failure = new Error('RPC_CALL_FAIL'); + const enqueue = vi.fn((state: any) => state.reject(failure)); + (shared as any)._sender = { addStateToQueue: enqueue }; + const view = createRequestClient(shared, new AbortController().signal); + await expect(view.client.invoke(new Api.help.GetConfig())).rejects.toBe(failure); + await view.settled(); + expect(enqueue).toHaveBeenCalledOnce(); + expect((shared as any)._requestRetries).toBe(initialRetries); + }); + + it('surfaces the SDK FloodWait error immediately instead of sleeping or replaying a write', async () => { + const shared = sharedClient(); + const request = new Api.help.GetConfig(); + const flood = new errors.FloodWaitError({ capture: 30, request }); + const enqueue = vi.fn((state: any) => state.reject(flood)); + (shared as any)._sender = { addStateToQueue: enqueue }; + const view = createRequestClient(shared, new AbortController().signal); + await expect(view.client.invoke(request)).rejects.toBe(flood); + await view.settled(); + expect(enqueue).toHaveBeenCalledOnce(); + expect(shared.floodSleepThreshold).toBe(60); + }); +}); diff --git a/cli/tests/unit/daemon-api-process.test.ts b/cli/tests/unit/daemon-api-process.test.ts new file mode 100644 index 0000000..2a3612b --- /dev/null +++ b/cli/tests/unit/daemon-api-process.test.ts @@ -0,0 +1,222 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { build, type Plugin } from 'esbuild'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; + +const require = createRequire(import.meta.url); +interface ProcessResult { stdout: string; stderr: string; code: number | null; signal: NodeJS.Signals | null } +interface JournalEvent { event: string; pid: number; text?: string } + +/** Real CLI children, persistent daemon process and Unix sockets, with no Telegram network. */ +describe('daemon command API across real processes', () => { + let dir: string; + let cliEntry: string; + let config: string; + let journalPath: string; + let paths: DaemonPaths; + let daemonPid: number; + let sessionPath: string; + const children = new Set<ChildProcess>(); + + function journal(): JournalEvent[] { + if (!existsSync(journalPath)) return []; + return readFileSync(journalPath, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)); + } + + function launch(args: string[], stdin = ''): { child: ChildProcess; result: Promise<ProcessResult>; stdout: () => string } { + const child = spawn(process.execPath, [cliEntry, '--config', config, '--profile', 'p', '--quiet', ...args], { + stdio: ['pipe', 'pipe', 'pipe'], + // Explicit config and synthetic credentials only. Never inherit a real account/session. + env: { PATH: process.env.PATH, HOME: dir, TG_API_ID: '1', TG_API_HASH: 'synthetic-api-hash', TG_DAEMON_API_TEST_JOURNAL: journalPath }, + }); + children.add(child); + let stdout = ''; + let stderr = ''; + child.stdout!.on('data', (chunk) => { stdout += chunk.toString(); }); + child.stderr!.on('data', (chunk) => { stderr += chunk.toString(); }); + const result = new Promise<ProcessResult>((resolveResult, reject) => { + const timeout = setTimeout(() => { + child.kill('SIGKILL'); + reject(new Error(`Offline CLI did not exit: ${JSON.stringify(args)}; stdout=${stdout}; stderr=${stderr}`)); + }, 10_000); + child.once('error', (error) => { clearTimeout(timeout); reject(error); }); + child.once('close', (code, signal) => { + clearTimeout(timeout); + children.delete(child); + resolveResult({ stdout, stderr, code, signal }); + }); + }); + child.stdin!.end(stdin); + return { child, result, stdout: () => stdout }; + } + + async function cli(args: string[], stdin?: string): Promise<ProcessResult> { + return launch(args, stdin).result; + } + + function envelope(result: ProcessResult, code = 0): any { + expect(result.signal).toBeNull(); + expect(result.code).toBe(code); + expect(result.stderr).toBe(''); + const lines = result.stdout.trim().split('\n'); + expect(lines).toHaveLength(1); + return JSON.parse(lines[0]); + } + + async function rpc(method: string, params: Record<string, unknown> = {}): Promise<any> { + const client = new DaemonClient(paths.socketPath); + try { return await client.call(method, params, { timeoutMs: 3000 }); } + finally { client.close(); } + } + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'tga-')); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ type: 'module', version: '0.0.0-offline' })); + const configDir = join(dir, 'c'); + mkdirSync(configDir); + config = join(configDir, 'config.json'); + writeFileSync(config, '{"profiles":{}}'); + await new SessionStore(configDir).save('p', 'synthetic-session'); + sessionPath = join(configDir, 'sessions', 'p.session'); + journalPath = join(dir, 'events.jsonl'); + paths = new DaemonPaths(configDir, 'p'); + cliEntry = join(dir, 'bin', 'tg.mjs'); + const plugin: Plugin = { name: 'offline-daemon-api', setup(builder) { + builder.onResolve({ filter: /^teleproto$/ }, () => ({ path: resolve('tests/fixtures/daemon-api-telegram.ts') })); + builder.onResolve({ filter: /^[^./]/ }, (args) => ({ + path: args.path.startsWith('node:') ? args.path : require.resolve(args.path), external: true, + })); + } }; + const options = { bundle: true, platform: 'node' as const, format: 'esm' as const, target: 'node20', logLevel: 'silent' as const, plugins: [plugin] }; + await Promise.all([ + build({ ...options, entryPoints: [resolve('src/bin/tg.ts')], outfile: cliEntry }), + build({ ...options, entryPoints: [resolve('src/lib/daemon/entry.ts')], outfile: join(dir, 'lib', 'daemon', 'entry.js') }), + ]); + const started = envelope(await cli(['daemon', 'start', '--idle-timeout', '0'])); + expect(started).toMatchObject({ ok: true, data: { profile: 'p', socket: paths.socketPath } }); + daemonPid = started.data.pid; + expect(paths.readPid()).toBe(daemonPid); + expect(await rpc('ping')).toBe('pong'); + }, 20_000); + + afterAll(async () => { + for (const child of children) child.kill('SIGKILL'); + if (paths?.socketExists()) { + try { await rpc('shutdown'); } + catch { if (daemonPid) { try { process.kill(daemonPid, 'SIGTERM'); } catch {} } } + await vi.waitFor(() => { + expect(paths.socketExists()).toBe(false); + expect(paths.readPid()).toBeNull(); + }, { timeout: 3000 }); + } + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it('routes sequential list, history and send through the same daemon session', async () => { + expect(envelope(await cli(['--daemon', 'chat', 'list', '--limit', '2']))).toMatchObject({ + ok: true, data: { chats: [{ id: '7' }, { id: '-1001234567890' }], total: 2 }, + }); + expect(envelope(await cli(['--daemon', 'message', 'history', 'me', '--limit', '2']))).toMatchObject({ + ok: true, data: { messages: [{ id: 30, text: 'seed newest' }, { id: 20 }], total: 3 }, + }); + const sent = envelope(await cli(['--daemon', 'message', 'send', 'me', 'sequential send'])); + expect(sent).toMatchObject({ ok: true, data: { text: 'sequential send', senderId: '7' } }); + expect(envelope(await cli(['--daemon', 'message', 'history', 'me', '--limit', '1']))).toMatchObject({ + ok: true, data: { messages: [{ id: sent.data.id, text: sent.data.text }] }, + }); + }); + + it('transports piped stdin and literal option-shaped message text without reparsing it', async () => { + const piped = envelope(await cli(['--daemon', 'message', 'send', 'me', '-'], 'first line\nsecond line\n')); + expect(piped).toMatchObject({ ok: true, data: { text: 'first line\nsecond line' } }); + const literal = '--daemon --profile other $(echo must-stay-literal)'; + expect(envelope(await cli(['--daemon', 'message', 'send', '--', 'me', literal]))).toMatchObject({ + ok: true, data: { text: literal }, + }); + expect(envelope(await cli(['--daemon', 'message', 'send', 'me', '-'], ''), 1)).toMatchObject({ ok: false, code: 'EMPTY_MESSAGE' }); + }); + + it('keeps raw API envelopes and stdin independent from CLI formatting', async () => { + expect(await rpc('execute', { argv: ['message', 'send', '--', 'me', 'raw API'] })).toMatchObject({ + output: { ok: true, data: { text: 'raw API' } }, exitCode: 0, + }); + expect(await rpc('execute', { argv: ['message', 'send', '--', 'me', '-'], stdin: 'API stdin\n' })).toMatchObject({ + output: { ok: true, data: { text: 'API stdin' } }, exitCode: 0, + }); + expect(await rpc('execute', { argv: ['message', 'send', '--', 'me', '-'] })).toMatchObject({ + output: { ok: false, code: 'STDIN_REQUIRED' }, exitCode: 1, + }); + }); + + it('isolates concurrent success, failure, field projection and JSONL output', async () => { + const [slow, failure, lines, full] = await Promise.all([ + cli(['--daemon', '--fields', 'id,text', 'message', 'send', 'me', 'fixture:slow concurrent']), + cli(['--daemon', 'message', 'send', 'me', 'fixture:fail']), + cli(['--daemon', '--jsonl', '--fields', 'id,text', 'message', 'history', 'me', '--limit', '2']), + cli(['--daemon', 'message', 'history', 'me', '--limit', '1']), + ]); + const sent = envelope(slow); + expect(sent).toEqual({ ok: true, data: { id: expect.any(Number), text: 'fixture:slow concurrent' } }); + expect(envelope(failure, 1)).toMatchObject({ ok: false, code: 'CHAT_WRITE_FORBIDDEN' }); + expect(lines).toMatchObject({ code: 0, signal: null, stderr: '' }); + const rows = lines.stdout.trim().split('\n').map((line) => JSON.parse(line)); + expect(rows).toHaveLength(2); + for (const row of rows) expect(row).toEqual({ id: expect.any(Number), text: expect.any(String) }); + expect(envelope(full)).toMatchObject({ ok: true, data: { messages: [{ date: expect.any(String), senderId: '7' }], total: expect.any(Number) } }); + expect(envelope(await cli(['--daemon', 'chat', 'list', '--limit', '1']))).toMatchObject({ ok: true, data: { chats: [{ title: 'Saved Messages' }] } }); + }); + + it('returns structured invalid arguments without changing the daemon exit status', async () => { + for (const args of [ + ['--daemon', 'chat', 'list', '--limit', 'NaN'], + ['--daemon', 'message', 'history', 'me', '--limit', '-1'], + ['--daemon', 'message', 'send', 'me'], + ['--daemon', 'unknown-command'], + ]) expect(envelope(await cli(args), 1)).toMatchObject({ ok: false, code: expect.any(String) }); + expect(await rpc('execute', { argv: ['message', 'history', '--nonsense', 'me'] })).toMatchObject({ output: { ok: false, code: 'INVALID_OPTIONS' }, exitCode: 1 }); + expect(await rpc('ping')).toBe('pong'); + }); + + it('blocks direct connection and auth/session commands while the daemon owns the profile', async () => { + const before = journal().filter((event) => event.event === 'constructor').length; + expect(envelope(await cli(['chat', 'list']), 1)).toMatchObject({ ok: false, code: 'DAEMON_ALREADY_RUNNING' }); + for (const args of [['auth', 'status'], ['--daemon', 'auth', 'status'], ['--daemon', 'session', 'export']]) { + expect(envelope(await cli(args), 1)).toMatchObject({ ok: false, code: expect.any(String) }); + } + for (const argv of [['auth', 'status'], ['session', 'export'], ['daemon', 'stop'], ['message', 'watch', 'me']]) { + expect(await rpc('execute', { argv })).toMatchObject({ output: { ok: false, code: 'DAEMON_PROXY_UNAVAILABLE' }, exitCode: 1 }); + } + expect(journal().filter((event) => event.event === 'constructor')).toHaveLength(before); + expect(readFileSync(sessionPath, 'utf8')).toBe('synthetic-session'); + }); + + it('delivers watch events during execute without capturing them in the command response', async () => { + const subscriptions = journal().filter((event) => event.event === 'subscribe').length; + const watcher = launch(['message', 'watch', 'me']); + try { + await vi.waitFor(() => expect(journal().filter((event) => event.event === 'subscribe')).toHaveLength(subscriptions + 1), { timeout: 3000 }); + const sent = envelope(await cli(['--daemon', 'message', 'send', 'me', 'watched execute'])); + expect(sent).toMatchObject({ ok: true, data: { text: 'watched execute' } }); + await vi.waitFor(() => expect(watcher.stdout()).toContain('watched execute'), { timeout: 3000 }); + watcher.child.kill('SIGINT'); + const notification = envelope(await watcher.result); + expect(notification).toMatchObject({ ok: true, data: { id: sent.data.id, text: 'watched execute' } }); + await vi.waitFor(() => expect(journal().some((event) => event.event === 'unsubscribe')).toBe(true), { timeout: 1000 }); + } finally { + if (watcher.child.exitCode === null) watcher.child.kill('SIGKILL'); + } + }); + + it('constructs and connects exactly once for every CLI and API request', () => { + expect(journal().filter((event) => event.event === 'constructor')).toEqual([{ event: 'constructor', pid: daemonPid }]); + expect(journal().filter((event) => event.event === 'connect')).toEqual([{ event: 'connect', pid: daemonPid }]); + expect(journal().filter((event) => event.event === 'destroy')).toHaveLength(0); + expect(new Set(journal().map((event) => event.pid))).toEqual(new Set([daemonPid])); + }); +}); diff --git a/cli/tests/unit/daemon-client-connect.test.ts b/cli/tests/unit/daemon-client-connect.test.ts new file mode 100644 index 0000000..b9f5a81 --- /dev/null +++ b/cli/tests/unit/daemon-client-connect.test.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { EventEmitter } from 'node:events'; + +const { mockCreateConnection } = vi.hoisted(() => ({ mockCreateConnection: vi.fn() })); +vi.mock('node:net', () => ({ createConnection: mockCreateConnection })); +import { DaemonClient } from '../../src/lib/daemon/client.js'; + +class PendingSocket extends EventEmitter { + write = vi.fn(); + destroy = vi.fn(() => this); +} + +describe('DaemonClient connection deadline', () => { + afterEach(() => vi.useRealTimers()); + + it.each(['call', 'watch'] as const)('bounds a stalled %s connection and destroys it', async (mode) => { + vi.useFakeTimers(); + const socket = new PendingSocket(); + mockCreateConnection.mockReturnValue(socket); + const client = new DaemonClient('/unused'); + const pending = mode === 'call' + ? client.call('ping', {}, { timeoutMs: 100 }) + : client.watch({}, () => {}, { timeoutMs: 100 }); + const assertion = expect(pending).rejects.toThrow('timed out'); + await vi.advanceTimersByTimeAsync(100); + await assertion; + expect(socket.destroy).toHaveBeenCalledOnce(); + expect(socket.write).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('contains post-connect errors and clears pending deadlines', async () => { + vi.useFakeTimers(); + const socket = new PendingSocket(); + mockCreateConnection.mockReturnValue(socket); + const pending = new DaemonClient('/unused').call('ping', {}); + const assertion = expect(pending).rejects.toThrow('Socket failed'); + socket.emit('connect'); + socket.emit('error', new Error('Socket failed')); + await assertion; + socket.emit('error', new Error('Late error')); + expect(socket.destroy).toHaveBeenCalledOnce(); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/cli/tests/unit/daemon-client-transport.test.ts b/cli/tests/unit/daemon-client-transport.test.ts new file mode 100644 index 0000000..c75b5ac --- /dev/null +++ b/cli/tests/unit/daemon-client-transport.test.ts @@ -0,0 +1,140 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createServer, type Server, type Socket } from 'node:net'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DaemonClient, DaemonRpcError } from '../../src/lib/daemon/client.js'; +import { encodeError, encodeNotification, encodeResponse } from '../../src/lib/daemon/protocol.js'; + +/** Real local sockets; the daemon transport is the only substituted boundary. */ +describe('DaemonClient transport failures', () => { + let dir: string; + let path: string; + let server: Server; + let client: DaemonClient; + const sockets = new Set<Socket>(); + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'tg-rpc-')); + path = join(dir, 'rpc.sock'); + client = new DaemonClient(path); + }); + + afterEach(async () => { + client.close(); + for (const socket of sockets) socket.destroy(); + sockets.clear(); + if (server) await new Promise<void>((resolve) => server.close(() => resolve())); + rmSync(dir, { recursive: true, force: true }); + }); + + async function listen(onConnection: (socket: Socket) => void) { + server = createServer((socket) => { + sockets.add(socket); + socket.on('error', () => {}); + socket.on('close', () => sockets.delete(socket)); + onConnection(socket); + socket.resume(); + }); + await new Promise<void>((resolve) => server.listen(path, resolve)); + } + + it('rejects immediate EOF without waiting for its request deadline', async () => { + await listen((socket) => socket.end()); + const start = Date.now(); + await expect(client.call('ping', {}, { timeoutMs: 3000 })).rejects.toThrow('closed before response'); + expect(Date.now() - start).toBeLessThan(1000); + }); + + it('accepts a final complete response before EOF', async () => { + await listen((socket) => socket.on('data', () => socket.end(encodeResponse('pong', 1) + '\n'))); + await expect(client.call('ping', {})).resolves.toBe('pong'); + }); + + it('ignores mismatched response and error IDs, then accepts the matching result', async () => { + await listen((socket) => socket.on('data', () => socket.write([ + encodeResponse('wrong', 999), encodeError(-32000, 'unrelated', null, 998), encodeResponse('pong', 1), '', + ].join('\n')))); + await expect(client.call('ping', {})).resolves.toBe('pong'); + }); + + it('does not treat an unmatched ID as success on EOF', async () => { + await listen((socket) => socket.on('data', () => socket.end(encodeResponse('wrong', 999) + '\n'))); + await expect(client.call('ping', {})).rejects.toThrow('closed before response'); + }); + + it('preserves matching RPC error codes and structured details', async () => { + const data = { tgCode: 'FLOOD_WAIT', seconds: 42 }; + await listen((socket) => socket.on('data', () => socket.write(encodeError(-32001, 'Try later', data, 1) + '\n'))); + const error = await client.call('ping', {}).catch((err: unknown) => err); + expect(error).toBeInstanceOf(DaemonRpcError); + expect(error).toMatchObject({ code: -32001, message: 'Try later', data }); + }); + + it('rejects malformed and unterminated responses', async () => { + await listen((socket) => socket.on('data', () => socket.end('not json\n'))); + await expect(client.call('ping', {})).rejects.toThrow('Invalid JSON'); + }); + + it('times out a connected request that gets only unrelated responses', async () => { + await listen((socket) => socket.on('data', () => socket.write(encodeResponse('wrong', 999) + '\n'))); + await expect(client.call('ping', {}, { timeoutMs: 30 })).rejects.toThrow('timed out'); + await vi.waitFor(() => expect(sockets.size).toBe(0)); + }); + + it('times out a missing subscribe ack and releases the connection', async () => { + await listen(() => {}); + await expect(client.watch({}, () => {}, { timeoutMs: 30 })).rejects.toThrow('subscribe timed out'); + await vi.waitFor(() => expect(sockets.size).toBe(0)); + }); + + it('rejects unexpected disconnection after subscribe ack', async () => { + await listen((socket) => socket.on('data', () => socket.end(encodeResponse({ subscribed: true }, 1) + '\n'))); + await expect(client.watch({}, () => {})).rejects.toThrow('disconnected while watching'); + }); + + it('delivers only notifications after matching ack and resolves intentional cancellation', async () => { + const seen: unknown[] = []; + await listen((socket) => socket.on('data', () => socket.write([ + encodeNotification('message', { before: true }), + encodeResponse({ subscribed: true }, 999), + encodeNotification('message', { stillBefore: true }), + encodeResponse({ subscribed: true }, 1), + encodeNotification('message', { after: true }), '', + ].join('\n')))); + await client.watch({}, (message) => { seen.push(message); client.close(); }); + expect(seen).toEqual([{ after: true }]); + }); + + it('keeps watching past the ack deadline and closes cleanly on demand', async () => { + let peer: Socket | undefined; + await listen((socket) => { + peer = socket; + socket.on('data', () => socket.write(encodeResponse({ subscribed: true }, 1) + '\n')); + }); + const seen = vi.fn(); + const watching = client.watch({}, seen, { timeoutMs: 40 }); + await new Promise((resolve) => setTimeout(resolve, 80)); + peer!.write(encodeNotification('message', { id: 1 }) + '\n'); + await vi.waitFor(() => expect(seen).toHaveBeenCalledWith({ id: 1 })); + client.close(); + await expect(watching).resolves.toBeUndefined(); + }); + + it('cancels concurrent calls and watches, including before connection', async () => { + await listen(() => {}); + const calls = [client.call('ping', {}), client.call('status', {})]; + const assertions = calls.map((call) => expect(call).rejects.toThrow('cancelled')); + const watch = client.watch({}, () => {}); + client.close(); + await Promise.all([...assertions, expect(watch).resolves.toBeUndefined()]); + await vi.waitFor(() => expect(sockets.size).toBe(0)); + }); + + it('contains callback exceptions and closes the failed watcher', async () => { + await listen((socket) => socket.on('data', () => socket.write([ + encodeResponse({}, 1), encodeNotification('message', { id: 1 }), '', + ].join('\n')))); + await expect(client.watch({}, () => { throw new Error('Consumer failed'); })).rejects.toThrow('Consumer failed'); + }); +}); diff --git a/cli/tests/unit/daemon-client.test.ts b/cli/tests/unit/daemon-client.test.ts new file mode 100644 index 0000000..6670c15 --- /dev/null +++ b/cli/tests/unit/daemon-client.test.ts @@ -0,0 +1,96 @@ +// tests/unit/daemon-client.test.ts +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; + +const { clientHandlers, mockGetEntity } = vi.hoisted(() => { + const clientHandlers: Array<(event: any) => void> = []; + return { + clientHandlers, + mockGetEntity: vi.fn(async () => ({ id: 42, className: 'User' })), + }; +}); +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => ({ + connect: vi.fn().mockResolvedValue(undefined), + destroy: vi.fn().mockResolvedValue(undefined), + getEntity: mockGetEntity, + addEventHandler: vi.fn((h: (event: any) => void) => { + clientHandlers.push(h); + }), + removeEventHandler: vi.fn(), + })), + sessions: { StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })) }, +})); + +import { DaemonServer } from '../../src/lib/daemon/server.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; + +describe('DaemonClient', () => { + let tempDir: string; + let paths: DaemonPaths; + let server: DaemonServer; + + beforeEach(async () => { + clientHandlers.length = 0; + mockGetEntity.mockImplementation(async () => ({ id: 42, className: 'User' })); + tempDir = mkdtempSync(join(tmpdir(), 'tg-daemon-cli-')); + paths = new DaemonPaths(tempDir, 'test'); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + }); + + afterEach(async () => { + await server.stop(); + rmSync(tempDir, { recursive: true, force: true }); + }); + + it('sends a ping and receives pong', async () => { + const client = new DaemonClient(paths.socketPath); + const result = await client.call('ping', {}); + expect(result).toBe('pong'); + client.close(); + }); + + it('receives status response', async () => { + const client = new DaemonClient(paths.socketPath); + const result = await client.call('status', {}) as any; + expect(result.running).toBe(true); + expect(typeof result.pid).toBe('number'); + client.close(); + }); + + it('throws on unknown method', async () => { + const client = new DaemonClient(paths.socketPath); + await expect(client.call('bogus', {})).rejects.toThrow(/Unknown method/); + client.close(); + }); + + it('watch yields serialized messages after subscribe ack', async () => { + const client = new DaemonClient(paths.socketPath); + const seen: unknown[] = []; + + const watching = client.watch({ chat: 'alice' }, (payload) => { + seen.push(payload); + client.close(); + }); + + await vi.waitFor(() => expect(clientHandlers.length).toBe(1)); + clientHandlers[0]({ + message: { id: 11, date: 1_700_000_000, message: 'ping', chatId: 42 }, + }); + + await watching; + expect(seen).toHaveLength(1); + expect((seen[0] as any).id).toBe(11); + expect((seen[0] as any).text).toBe('ping'); + }); + + it('throws when socket does not exist', async () => { + const client = new DaemonClient('/tmp/nonexistent-tg-daemon.sock'); + await expect(client.call('ping', {})).rejects.toThrow(); + client.close(); + }); +}); diff --git a/cli/tests/unit/daemon-command-io.test.ts b/cli/tests/unit/daemon-command-io.test.ts new file mode 100644 index 0000000..292e475 --- /dev/null +++ b/cli/tests/unit/daemon-command-io.test.ts @@ -0,0 +1,200 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { Api, type TelegramClient } from 'teleproto'; +import bigInt from 'big-integer'; +import type { Command } from 'commander'; +import { runWithDaemonContext, type DaemonExecutionContext } from '../../src/lib/daemon/execution-context.js'; + +const forbidden = vi.hoisted(() => ({ + config: vi.fn(() => { throw new Error('Unexpected config access'); }), + credentials: vi.fn(() => { throw new Error('Unexpected credential access'); }), + session: vi.fn(() => { throw new Error('Unexpected session access'); }), + client: vi.fn(() => { throw new Error('Unexpected client creation'); }), +})); +vi.mock('../../src/lib/config.js', () => ({ createConfig: forbidden.config, getCredentialsOrThrow: forbidden.credentials })); +vi.mock('../../src/lib/session-store.js', () => ({ SessionStore: forbidden.session })); +vi.mock('../../src/lib/client.js', () => ({ withClient: forbidden.client })); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: vi.fn(async () => ({ id: bigInt(42), className: 'User' })), + assertForum: vi.fn(async () => {}), +})); + +import { messageSendAction } from '../../src/commands/message/send.js'; +import { messageEditAction } from '../../src/commands/message/edit.js'; +import { mediaSendAction } from '../../src/commands/media/send.js'; +import { mediaDownloadAction } from '../../src/commands/media/download.js'; + +function command(args: string[] = [], extra: Record<string, unknown> = {}): Command { + return { + args, + optsWithGlobals: () => ({ profile: 'default', quiet: false, verbose: true, json: true, human: false, ...extra }), + } as unknown as Command; +} + +function message(id = 42, text = 'result'): Api.Message { + return new Api.Message({ id, peerId: new Api.PeerUser({ userId: bigInt(42) }), date: 1700000000, message: text }); +} + +function mediaMessage(id = 42): Api.Message { + const msg = message(id); + msg.media = new Api.MessageMediaDocument({ + document: new Api.Document({ + id: bigInt(123), accessHash: bigInt(456), fileReference: Buffer.alloc(0), + date: 1700000000, mimeType: 'text/plain', size: bigInt(7), dcId: 2, + attributes: [new Api.DocumentAttributeFilename({ fileName: 'payload.txt' })], + }), + }); + return msg; +} + +function context(extra: Partial<DaemonExecutionContext> = {}): DaemonExecutionContext { + return { + profile: 'default', signal: new AbortController().signal, exitCode: 0, + client: { + connect: vi.fn(), destroy: vi.fn(), + sendMessage: vi.fn(async (_entity, opts) => message(42, opts.message)), + editMessage: vi.fn(async (_entity, opts) => message(opts.message, opts.text)), + sendFile: vi.fn(async () => message()), + getMessages: vi.fn(async (_entity, opts) => [mediaMessage(opts.ids[0])]), + downloadMedia: vi.fn(async () => Buffer.from('payload')), + } as unknown as TelegramClient, + ...extra, + }; +} + +let directory: string; +let originalExitCode: typeof process.exitCode; +beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'tg-daemon-command-io-')); + originalExitCode = process.exitCode; + process.exitCode = 0; + vi.clearAllMocks(); +}); +afterEach(async () => { + process.exitCode = originalExitCode; + vi.restoreAllMocks(); + await rm(directory, { recursive: true, force: true }); + for (const fn of Object.values(forbidden)) expect(fn).not.toHaveBeenCalled(); +}); + +const textActions = [ + { name: 'send', action: () => messageSendAction.call(command(), '@user', '-') }, + { name: 'edit', action: () => messageEditAction.call(command(), '@user', '42', '-') }, +]; + +describe('daemon message stdin', () => { + it.each(textActions)('$name uses only request stdin and preserves the local trimEnd behavior', async ({ name, action }) => { + const stdin = vi.spyOn(process.stdin, Symbol.asyncIterator).mockImplementation(() => { throw new Error('Daemon stdin must never be read'); }); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const current = context({ stdin: ' request message\n\n' }); + await runWithDaemonContext(current, action); + const method = name === 'send' ? current.client.sendMessage : current.client.editMessage; + expect(method).toHaveBeenCalledWith(expect.anything(), expect.objectContaining(name === 'send' + ? { message: ' request message' } : { text: ' request message', message: 42 })); + expect(current.output).toMatchObject({ ok: true, data: { id: 42, text: ' request message' } }); + expect(stdin).not.toHaveBeenCalled(); + expect(stdout).not.toHaveBeenCalled(); + }); + + it.each(textActions)('$name reports missing request stdin without reading daemon stdin or making RPCs', async ({ action }) => { + const stdin = vi.spyOn(process.stdin, Symbol.asyncIterator).mockImplementation(() => { throw new Error('Daemon stdin must never be read'); }); + const current = context(); + await runWithDaemonContext(current, action); + expect(current.output).toMatchObject({ ok: false, code: 'STDIN_REQUIRED' }); + expect(current.exitCode).toBe(1); + expect(process.exitCode).toBe(0); + expect(current.client.sendMessage).not.toHaveBeenCalled(); + expect(current.client.editMessage).not.toHaveBeenCalled(); + expect(stdin).not.toHaveBeenCalled(); + }); + + it.each(textActions)('$name distinguishes provided empty stdin from missing stdin', async ({ action }) => { + const current = context({ stdin: '' }); + await runWithDaemonContext(current, action); + expect(current.output).toMatchObject({ ok: false, code: 'EMPTY_MESSAGE' }); + }); + + it('keeps simultaneous stdin values and outputs isolated', async () => { + const first = context({ stdin: 'first\n' }); + const second = context({ stdin: 'second\n' }); + await Promise.all([ + runWithDaemonContext(first, () => messageSendAction.call(command(), '@first', '-')), + runWithDaemonContext(second, () => messageEditAction.call(command(), '@second', '43', '-')), + ]); + expect(first.output).toMatchObject({ ok: true, data: { id: 42, text: 'first' } }); + expect(second.output).toMatchObject({ ok: true, data: { id: 43, text: 'second' } }); + }); +}); + +describe('daemon media paths', () => { + it('checks and uploads files relative to the calling client cwd, including albums and absolute paths', async () => { + const cwd = join(directory, 'caller'); + await mkdir(cwd); + await writeFile(join(cwd, 'one.jpg'), 'synthetic image'); + const absolute = join(directory, 'two.jpg'); + await writeFile(absolute, 'synthetic image'); + const current = context({ cwd }); + vi.mocked(current.client.sendFile).mockResolvedValue([message(1), message(2)] as any); + const processCwd = process.cwd(); + const chdir = vi.spyOn(process, 'chdir'); + await runWithDaemonContext(current, () => mediaSendAction.call(command(['@user', 'one.jpg', absolute]))); + expect(current.client.sendFile).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ file: [join(cwd, 'one.jpg'), absolute] })); + expect(current.output).toMatchObject({ ok: true, data: { sent: 2, partial: false, errors: [] } }); + expect(chdir).not.toHaveBeenCalled(); + expect(process.cwd()).toBe(processCwd); + }); + + it('reports unavailable files from the request cwd before upload', async () => { + const current = context({ cwd: directory }); + await runWithDaemonContext(current, () => mediaSendAction.call(command(['@user', 'absent.jpg']))); + expect(current.output).toMatchObject({ ok: false, code: 'FILE_NOT_FOUND' }); + expect(current.client.sendFile).not.toHaveBeenCalled(); + }); + + it.each([ + { output: undefined, ids: '42', expected: 'payload.txt' }, + { output: 'renamed.txt', ids: '42', expected: 'renamed.txt' }, + { output: 'batch', ids: '42,43', expected: 'batch/payload.txt' }, + ])('resolves download paths from request cwd: $output / $ids', async ({ output, ids, expected }) => { + const current = context({ cwd: directory }); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const chdir = vi.spyOn(process, 'chdir'); + vi.mocked(current.client.downloadMedia).mockImplementation(async (_msg, opts) => { + opts!.progressCallback?.(bigInt(7), bigInt(7)); + return Buffer.from('payload'); + }); + await runWithDaemonContext(current, () => mediaDownloadAction.call(command(['@user', ids], { output }))); + expect(current.client.downloadMedia).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ outputFile: resolve(directory, expected) })); + expect(current.output).toMatchObject({ ok: true }); + expect(current.exitCode).toBe(0); + expect(stderr).not.toHaveBeenCalled(); + expect(chdir).not.toHaveBeenCalled(); + }); + + it('preserves absolute download targets', async () => { + const target = join(directory, 'absolute.txt'); + const current = context({ cwd: join(directory, 'other') }); + await runWithDaemonContext(current, () => mediaDownloadAction.call(command(['@user', '42'], { output: target }))); + expect(current.client.downloadMedia).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ outputFile: target })); + }); + + it.each([undefined, 'relative'])('rejects absent or relative API cwd=%j before file access or RPC', async cwd => { + for (const action of [mediaSendAction, mediaDownloadAction]) { + const current = context({ cwd }); + await runWithDaemonContext(current, () => action.call(command(['@user', action === mediaSendAction ? 'a.jpg' : '42']))); + expect(current.output).toMatchObject({ ok: false, code: 'INVALID_OPTIONS' }); + expect(current.client.sendFile).not.toHaveBeenCalled(); + expect(current.client.getMessages).not.toHaveBeenCalled(); + } + }); + + it('uses independent directories for concurrent downloads', async () => { + const first = context({ cwd: join(directory, 'first') }); + const second = context({ cwd: join(directory, 'second') }); + await Promise.all([first, second].map(current => runWithDaemonContext(current, () => mediaDownloadAction.call(command(['@user', '42']))))); + expect(first.client.downloadMedia).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ outputFile: join(directory, 'first/payload.txt') })); + expect(second.client.downloadMedia).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ outputFile: join(directory, 'second/payload.txt') })); + }); +}); diff --git a/cli/tests/unit/daemon-commands.test.ts b/cli/tests/unit/daemon-commands.test.ts new file mode 100644 index 0000000..3f2848d --- /dev/null +++ b/cli/tests/unit/daemon-commands.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; + +describe('DaemonPaths integration for commands', () => { + let tempDir: string; + + beforeEach(() => { + vi.clearAllMocks(); + tempDir = mkdtempSync(join(tmpdir(), 'tg-daemon-cmd-')); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it('status reports not running when no PID file', () => { + const paths = new DaemonPaths(tempDir, 'default'); + expect(paths.readPid()).toBeNull(); + expect(paths.socketExists()).toBe(false); + }); + + it('status reports PID when PID file exists', () => { + const paths = new DaemonPaths(tempDir, 'default'); + paths.writePid(99999); + expect(paths.readPid()).toBe(99999); + }); +}); diff --git a/cli/tests/unit/daemon-cross-review.test.ts b/cli/tests/unit/daemon-cross-review.test.ts new file mode 100644 index 0000000..8730bde --- /dev/null +++ b/cli/tests/unit/daemon-cross-review.test.ts @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { DaemonServer } from '../../src/lib/daemon/server.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; +import { SessionStore } from '../../src/lib/session-store.js'; + +const mocks = vi.hoisted(() => ({ connect: vi.fn(), destroy: vi.fn(), add: vi.fn(), remove: vi.fn() })); +vi.mock('teleproto', async importOriginal => { + const actual = await importOriginal<typeof import('teleproto')>(); + return { + ...actual, + sessions: { StringSession: class {} }, + TelegramClient: class { + connect = mocks.connect; + destroy = mocks.destroy; + addEventHandler = mocks.add; + removeEventHandler = mocks.remove; + getEntity = vi.fn().mockResolvedValue(new actual.Api.User({ id: 7n as any, firstName: 'Fixture' })); + }, + }; +}); + +describe('independent daemon lifecycle review', () => { + let dir: string; + let daemon: DaemonServer; + let rpc: DaemonClient; + let releaseConnect: (() => void) | undefined; + + beforeEach(async () => { + vi.clearAllMocks(); + mocks.connect.mockResolvedValue(undefined); + mocks.destroy.mockResolvedValue(undefined); + dir = await mkdtemp(join(tmpdir(), 'tg-daemon-cross-')); + await new SessionStore(dir).save('fixture', 'synthetic-session'); + const paths = new DaemonPaths(dir, 'fixture'); + daemon = new DaemonServer(paths, { apiId: 1, apiHash: 'synthetic' }, { idleTimeout: 0 }); + rpc = new DaemonClient(paths.socketPath); + }); + + afterEach(async () => { + releaseConnect?.(); + releaseConnect = undefined; + rpc.close(); + await daemon.stop(); + await rm(dir, { recursive: true, force: true }); + }); + + it('shutdown interrupts an in-flight connect before waiting for startup completion', async () => { + let failConnect!: (err: Error) => void; + const connecting = new Promise<void>((resolve, reject) => { + releaseConnect = resolve; + failConnect = reject; + }); + mocks.connect.mockReturnValue(connecting); + mocks.destroy.mockImplementation(async () => { failConnect(new Error('Connection interrupted')); }); + const starting = daemon.start().catch(err => err); + await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalledOnce()); + const stopping = daemon.stop(); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalled(), { timeout: 150 }); + await stopping; + expect(await starting).toBeInstanceOf(Error); + await expect(new SessionStore(dir).withLock('fixture', async () => true)).resolves.toBe(true); + }); + + it('RPC subscription rejects an explicitly empty topic instead of broadening it to all messages', async () => { + await daemon.start(); + await expect(rpc.call('subscribe', { chat: 'fixture', topic: '' }, { timeoutMs: 500 })).rejects.toThrow(/topic/i); + expect(mocks.add).not.toHaveBeenCalled(); + }); + + it('stopping a rejected duplicate instance preserves the running owner socket and PID', async () => { + await daemon.start(); + const paths = new DaemonPaths(dir, 'fixture'); + const duplicate = new DaemonServer(paths, { apiId: 1, apiHash: 'synthetic' }, { idleTimeout: 0 }); + await expect(duplicate.start()).rejects.toThrow(/already running/); + await duplicate.stop(); + expect(paths.readPid()).toBe(process.pid); + await expect(rpc.call('ping', {}, { timeoutMs: 500 })).resolves.toBe('pong'); + }); +}); diff --git a/cli/tests/unit/daemon-detach-process.test.ts b/cli/tests/unit/daemon-detach-process.test.ts new file mode 100644 index 0000000..6a83294 --- /dev/null +++ b/cli/tests/unit/daemon-detach-process.test.ts @@ -0,0 +1,80 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { build } from 'esbuild'; +import { spawnSync } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { mkdtempSync, writeFileSync, rmSync, mkdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; + +const require = createRequire(import.meta.url); + +/** Real fork/IPC, parent process and daemon socket; only MTProto is replaced. */ +describe('background daemon detaches from its launcher process', () => { + let dir: string; + let parentEntry: string; + let paths: DaemonPaths; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'tgd-')); + writeFileSync(join(dir, 'package.json'), '{"type":"module"}'); + const configDir = join(dir, 'config'); + mkdirSync(configDir); + const config = join(configDir, 'config.json'); + writeFileSync(config, '{"profiles":{}}'); + await new SessionStore(configDir).save('p', 'synthetic-session'); + paths = new DaemonPaths(configDir, 'p'); + parentEntry = join(dir, 'bin', 'tg.mjs'); + const plugins = [{ name: 'offline-mtproto', setup(builder: any) { + builder.onResolve({ filter: /^teleproto$/ }, () => ({ path: 'teleproto', namespace: 'offline' })); + builder.onResolve({ filter: /^\//, namespace: 'offline' }, (args: any) => ({ path: args.path, external: true })); + builder.onLoad({ filter: /.*/, namespace: 'offline' }, () => ({ loader: 'js', contents: ` + export { Api } from ${JSON.stringify(require.resolve('teleproto/tl/api.js'))}; + export const sessions = { StringSession: class { constructor(value) { this.value = value; } save() { return this.value; } } }; + export class TelegramClient { async connect() {} async destroy() {} } + ` })); + builder.onResolve({ filter: /^[^./]/ }, (args: any) => ({ + path: args.path.startsWith('node:') ? args.path : require.resolve(args.path), external: true, + })); + } }]; + const options = { bundle: true, platform: 'node' as const, format: 'esm' as const, target: 'node20', logLevel: 'silent' as const, plugins }; + await build({ ...options, entryPoints: [resolve('src/lib/daemon/entry.ts')], outfile: join(dir, 'lib', 'daemon', 'entry.js') }); + await build({ ...options, outfile: parentEntry, stdin: { resolveDir: process.cwd(), contents: ` + import { daemonStartAction } from ${JSON.stringify(resolve('src/commands/daemon/start.ts'))}; + await daemonStartAction.call({optsWithGlobals: () => ({profile:'p', quiet:true, config:${JSON.stringify(config)}, idleTimeout:'0'})}); + ` } }); + }); + + afterEach(async () => { + if (!paths.socketExists()) return; + const rpc = new DaemonClient(paths.socketPath); + try { await rpc.call('shutdown', {}, { timeoutMs: 1000 }); } + finally { rpc.close(); } + await vi.waitFor(() => { + expect(paths.readPid()).toBeNull(); + expect(paths.socketExists()).toBe(false); + }, { timeout: 2000 }); + }); + + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + it('exits normally after reporting success while the detached daemon keeps answering requests', async () => { + const parent = spawnSync(process.execPath, [parentEntry], { + encoding: 'utf8', timeout: 2000, + // No inherited Telegram credentials or user configuration enter the fixture. + env: { PATH: process.env.PATH, TG_API_ID: '1', TG_API_HASH: 'synthetic-api-hash' }, + }); + const envelope = JSON.parse(parent.stdout.trim()); + expect(envelope).toMatchObject({ ok: true, data: { profile: 'p', socket: paths.socketPath } }); + expect(parent.stderr).toBe(''); + expect(parent.error).toBeUndefined(); + expect(parent.signal).toBeNull(); + expect(parent.status).toBe(0); + expect(paths.readPid()).toBe(envelope.data.pid); + const rpc = new DaemonClient(paths.socketPath); + try { await expect(rpc.call('ping', {}, { timeoutMs: 1000 })).resolves.toBe('pong'); } + finally { rpc.close(); } + }); +}); diff --git a/cli/tests/unit/daemon-entry-path.test.ts b/cli/tests/unit/daemon-entry-path.test.ts new file mode 100644 index 0000000..2d3a22f --- /dev/null +++ b/cli/tests/unit/daemon-entry-path.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { resolveDaemonEntry } from '../../src/lib/daemon/entry-path.js'; + +describe('resolveDaemonEntry', () => { + let root: string; + const origArgv1 = process.argv[1]; + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'tg-daemon-entry-')); + }); + + afterEach(() => { + process.argv[1] = origArgv1; + rmSync(root, { recursive: true, force: true }); + }); + + it('resolves dist/lib/daemon/entry.js from dist/bin/tg.js', () => { + const binDir = join(root, 'dist', 'bin'); + const entry = join(root, 'dist', 'lib', 'daemon', 'entry.js'); + mkdirSync(binDir, { recursive: true }); + mkdirSync(join(root, 'dist', 'lib', 'daemon'), { recursive: true }); + writeFileSync(join(binDir, 'tg.js'), ''); + writeFileSync(entry, ''); + + process.argv[1] = join(binDir, 'tg.js'); + const url = pathToFileURL(join(binDir, 'tg.js')).href; + expect(resolveDaemonEntry(url)).toBe(entry); + }); + + it('resolves dist/lib/daemon/entry.js from a dist/ chunk', () => { + const distDir = join(root, 'dist'); + const entry = join(distDir, 'lib', 'daemon', 'entry.js'); + mkdirSync(join(distDir, 'lib', 'daemon'), { recursive: true }); + writeFileSync(join(distDir, 'chunk-ABC.js'), ''); + writeFileSync(entry, ''); + + process.argv[1] = join(distDir, 'chunk-ABC.js'); + const url = pathToFileURL(join(distDir, 'chunk-ABC.js')).href; + expect(resolveDaemonEntry(url)).toBe(entry); + }); + + it('does not resolve to <pkg>/lib/daemon/entry.js when only dist/ has the file', () => { + const binDir = join(root, 'dist', 'bin'); + const distEntry = join(root, 'dist', 'lib', 'daemon', 'entry.js'); + const wrongEntry = join(root, 'lib', 'daemon', 'entry.js'); + mkdirSync(binDir, { recursive: true }); + mkdirSync(join(root, 'dist', 'lib', 'daemon'), { recursive: true }); + mkdirSync(join(root, 'lib', 'daemon'), { recursive: true }); + writeFileSync(join(binDir, 'tg.js'), ''); + writeFileSync(distEntry, ''); + writeFileSync(wrongEntry, ''); + + process.argv[1] = join(binDir, 'tg.js'); + const url = pathToFileURL(join(binDir, 'tg.js')).href; + // First existing candidate from dist/bin is ../lib/daemon/entry.js → dist/lib/... + expect(resolveDaemonEntry(url)).toBe(distEntry); + expect(resolveDaemonEntry(url)).not.toBe(wrongEntry); + }); +}); diff --git a/cli/tests/unit/daemon-execute-server.test.ts b/cli/tests/unit/daemon-execute-server.test.ts new file mode 100644 index 0000000..ce67090 --- /dev/null +++ b/cli/tests/unit/daemon-execute-server.test.ts @@ -0,0 +1,356 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createConnection } from 'node:net'; +import { Api } from 'teleproto'; +import { DaemonServer } from '../../src/lib/daemon/server.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; +import { SessionStore } from '../../src/lib/session-store.js'; + +const mocks = vi.hoisted(() => ({ constructor: vi.fn(), connect: vi.fn(), destroy: vi.fn(), entity: vi.fn(), invoke: vi.fn(), messages: vi.fn() })); +vi.mock('teleproto', async importOriginal => { + const actual = await importOriginal<typeof import('teleproto')>(); + return { + ...actual, + sessions: { StringSession: class {} }, + TelegramClient: class { + connected = false; + constructor(...args: unknown[]) { mocks.constructor(...args); } + async connect() { await mocks.connect(); this.connected = true; } + async destroy() { await mocks.destroy(); this.connected = false; } + getEntity = mocks.entity; + invoke = mocks.invoke; + getMessages = mocks.messages; + addEventHandler = vi.fn(); + removeEventHandler = vi.fn(); + }, + }; +}); + +function deferred<T>() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} + +/** Real sockets + real command handlers/ALS; only MTProto transport is replaced. */ +describe('persistent daemon execute API', () => { + let dir: string; + let paths: DaemonPaths; + let server: DaemonServer; + let skipStop = false; + const clients: DaemonClient[] = []; + beforeEach(() => { + vi.clearAllMocks(); + skipStop = false; + process.exitCode = 0; + mocks.connect.mockResolvedValue(undefined); + mocks.destroy.mockResolvedValue(undefined); + mocks.entity.mockResolvedValue(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + mocks.invoke.mockResolvedValue(true); + mocks.messages.mockResolvedValue([]); + dir = mkdtempSync(join(tmpdir(), 'tg-execute-')); + paths = new DaemonPaths(dir, 'fixture'); + }); + afterEach(async () => { + for (const client of clients) client.close(); + clients.length = 0; + if (server && !skipStop) await server.stop(); + vi.restoreAllMocks(); + process.exitCode = 0; + rmSync(dir, { recursive: true, force: true }); + }); + function client() { + const current = new DaemonClient(paths.socketPath); + clients.push(current); + return current; + } + async function start(opts?: { idleTimeout?: number; onIdle?: () => void }) { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'synthetic', sessionString: 'synthetic-session' }, opts); + await server.start(); + } + async function status() { return client().call('status', {}) as Promise<Record<string, unknown>>; } + + it('reuses one connected client for multiple commands and advertises the API', async () => { + await start(); + writeFileSync(join(dir, 'config.json'), 'invalid JSON: execute must never load this'); + const rpc = client(); + for (const name of ['alice', 'bob']) { + await expect(rpc.execute(['chat', 'resolve', name])).resolves.toMatchObject({ output: { ok: true, data: { id: '7', title: 'Fixture' } }, exitCode: 0 }); + } + expect(mocks.constructor).toHaveBeenCalledOnce(); + expect(mocks.connect).toHaveBeenCalledOnce(); + expect(mocks.destroy).not.toHaveBeenCalled(); + expect(await status()).toMatchObject({ running: true, connected: true, apiVersion: 1, capabilities: ['execute', 'subscribe'], activeRequests: 0 }); + }); + + it('isolates concurrent success/failure outputs and keeps stdout and daemon exit status untouched', async () => { + await start(); + const good = deferred<Api.User>(); + const bad = deferred<Api.User>(); + mocks.entity.mockImplementation((name: string) => name === 'good' ? good.promise : bad.promise); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const success = client().execute(['chat', 'resolve', 'good']); + const failure = client().execute(['chat', 'resolve', 'bad']); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledTimes(2)); + bad.reject(Object.assign(new Error('Access denied'), { errorMessage: 'CHAT_ADMIN_REQUIRED', code: 400 })); + expect(await failure).toMatchObject({ output: { ok: false, code: 'CHAT_ADMIN_REQUIRED' }, exitCode: 1 }); + good.resolve(new Api.User({ id: 8n as any, firstName: 'Good' })); + expect(await success).toMatchObject({ output: { ok: true, data: { id: '8', title: 'Good' } }, exitCode: 0 }); + expect(stdout).not.toHaveBeenCalled(); + expect(stderr).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(0); + expect(await client().call('ping', {})).toBe('pong'); + expect(mocks.destroy).not.toHaveBeenCalled(); + }); + + it('returns structured command validation errors without harming the connection', async () => { + await start(); + const rpc = client(); + for (const argv of [['auth', 'logout'], ['message', 'send'], ['chat', 'resolve', 'alice', '--config', '/unused']]) { + await expect(rpc.call('execute', { argv })).resolves.toMatchObject({ output: { ok: false }, exitCode: 1 }); + } + expect(mocks.entity).not.toHaveBeenCalled(); + await expect(rpc.execute(['chat', 'resolve', 'alice'])).resolves.toMatchObject({ output: { ok: true } }); + }); + + it('times out promptly but keeps late work active and prevents a subsequent write', async () => { + const onIdle = vi.fn(); + await start({ idleTimeout: 40, onIdle }); + mocks.entity.mockResolvedValue(new Api.Chat({ id: 7n as any, title: 'Chat' })); + const pending = deferred<boolean>(); + mocks.invoke.mockReturnValue(pending.promise); + const result = client().execute(['chat', 'edit', 'chat', '--title', 'First', '--description', 'Second'], { timeoutMs: 30 }); + await expect(result).rejects.toMatchObject({ data: { tgCode: 'TIMEOUT' }, message: expect.stringContaining('unknown') }); + expect(mocks.invoke).toHaveBeenCalledOnce(); + await new Promise(resolve => setTimeout(resolve, 90)); + expect(onIdle).not.toHaveBeenCalled(); + expect(await status()).toMatchObject({ activeRequests: 1, connected: true }); + pending.resolve(true); + await vi.waitFor(() => expect(onIdle).toHaveBeenCalledOnce()); + expect(mocks.invoke).toHaveBeenCalledOnce(); + expect(mocks.destroy).toHaveBeenCalledOnce(); + }); + + it('aborts disconnected callers while retaining their unfinished work', async () => { + await start(); + mocks.entity.mockResolvedValue(new Api.Chat({ id: 7n as any, title: 'Chat' })); + const pending = deferred<boolean>(); + mocks.invoke.mockReturnValue(pending.promise); + const rpc = client(); + const result = rpc.execute(['chat', 'edit', 'chat', '--title', 'First', '--description', 'Second']); + const rejected = expect(result).rejects.toThrow('cancelled'); + await vi.waitFor(() => expect(mocks.invoke).toHaveBeenCalledOnce()); + rpc.close(); + await rejected; + await vi.waitFor(() => expect((server as any).sockets.size).toBe(0)); + expect(await status()).toMatchObject({ activeRequests: 1 }); + pending.resolve(true); + await vi.waitFor(() => expect((server as any).activeRequests.size).toBe(0)); + expect(mocks.invoke).toHaveBeenCalledOnce(); + expect(mocks.destroy).not.toHaveBeenCalled(); + }); + + it('keeps detached SDK work active even after returning a successful command result', async () => { + const onIdle = vi.fn(); + await start({ idleTimeout: 30, onIdle }); + const pending = deferred<boolean>(); + mocks.invoke.mockReturnValue(pending.promise); + mocks.entity.mockImplementation(async function (this: any) { + void this.invoke({ synthetic: true }); + return new Api.User({ id: 7n as any, firstName: 'Fixture' }); + }); + await expect(client().execute(['chat', 'resolve', 'alice'])).resolves.toMatchObject({ output: { ok: true } }); + await vi.waitFor(() => expect((server as any).sockets.size).toBe(0)); + expect((server as any).activeRequests.size).toBe(1); + await new Promise(resolve => setTimeout(resolve, 70)); + expect(onIdle).not.toHaveBeenCalled(); + expect(mocks.destroy).not.toHaveBeenCalled(); + pending.reject(new Error('Late detached RPC failure')); + await vi.waitFor(() => expect(onIdle).toHaveBeenCalledOnce()); + expect((server as any).activeRequests.size).toBe(0); + }); + + it('retains unfinished subscription preparation after caller cancellation and prevents late handler registration', async () => { + const onIdle = vi.fn(); + await start({ idleTimeout: 30, onIdle }); + const shared = server.getClient()!; + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + const rpc = client(); + const subscribed = rpc.call('subscribe', { chat: 'wait' }).catch(error => error); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledOnce()); + rpc.close(); + await subscribed; + await vi.waitFor(() => expect((server as any).sockets.size).toBe(0)); + expect((server as any).activeRequests.size).toBe(1); + await new Promise(resolve => setTimeout(resolve, 70)); + expect(onIdle).not.toHaveBeenCalled(); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await vi.waitFor(() => expect(onIdle).toHaveBeenCalledOnce()); + expect(shared.addEventHandler).not.toHaveBeenCalled(); + }); + + it('holds the session lease through late subscription setup during daemon shutdown', async () => { + await start(); + const shared = server.getClient()!; + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + const result = client().call('subscribe', { chat: 'wait' }).catch(error => error); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledOnce()); + const stopping = server.stop(); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce()); + await expect(new SessionStore(dir).acquireLock('fixture')).rejects.toMatchObject({ code: 'ELOCKED' }); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await Promise.all([stopping, result]); + expect(shared.addEventHandler).not.toHaveBeenCalled(); + await expect(new SessionStore(dir).withLock('fixture', async () => 'free')).resolves.toBe('free'); + }); + + it('enforces the concurrent command limit and never retries rejected work', async () => { + await start(); + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + const rpcClients = Array.from({ length: 16 }, () => client()); + const running = rpcClients.map(rpc => rpc.execute(['chat', 'resolve', 'wait']).catch(err => err)); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledTimes(16)); + await expect(client().execute(['chat', 'resolve', 'overflow'])).rejects.toMatchObject({ data: { tgCode: 'DAEMON_BUSY' } }); + expect(mocks.entity).toHaveBeenCalledTimes(16); + for (const rpc of rpcClients) rpc.close(); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await Promise.all(running); + await vi.waitFor(() => expect((server as any).activeRequests.size).toBe(0)); + }); + + it('returns a small structured error when a completed response exceeds the frame bound', async () => { + await start(); + mocks.entity.mockResolvedValue(new Api.User({ id: 7n as any, firstName: 'x'.repeat(1_048_576) })); + await expect(client().execute(['chat', 'resolve', 'large'])).rejects.toMatchObject({ data: { tgCode: 'DAEMON_RESPONSE_TOO_LARGE' } }); + await expect(client().call('ping', {})).resolves.toBe('pong'); + expect(mocks.destroy).not.toHaveBeenCalled(); + }); + + it('keeps the session lease during shutdown until already-started operations settle', async () => { + await start(); + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + const result = client().execute(['chat', 'resolve', 'wait']).catch(error => error); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledOnce()); + let stopped = false; + const stopping = server.stop().then(() => { stopped = true; }); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce()); + await expect(new SessionStore(dir).acquireLock('fixture')).rejects.toMatchObject({ code: 'ELOCKED' }); + expect(stopped).toBe(false); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await Promise.all([stopping, result]); + await expect(new SessionStore(dir).withLock('fixture', async () => 'free')).resolves.toBe('free'); + }); + + it('destroys a transport recreated by late DC migration before releasing the session lease', async () => { + await start(); + const migrating = deferred<void>(); + const shared = server.getClient() as any; + shared._switchDC = async function () { + await migrating.promise; + this.connected = true; + }; + mocks.entity.mockImplementation(async function (this: any) { + await this._switchDC(2); + return new Api.User({ id: 7n as any, firstName: 'Fixture' }); + }); + const result = client().execute(['chat', 'resolve', 'wait']).catch(error => error); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledOnce()); + const stopping = server.stop(); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce()); + expect(shared.connected).toBe(false); + migrating.resolve(); + await Promise.all([stopping, result]); + expect(mocks.destroy).toHaveBeenCalledTimes(2); + expect(shared.connected).toBe(false); + await expect(new SessionStore(dir).withLock('fixture', async () => 'free')).resolves.toBe('free'); + }); + + it('retains ownership if destroying a late transport fails after the initial teardown succeeded', async () => { + const originalAcquire = SessionStore.prototype.acquireLock; + let releaseLease!: () => Promise<void>; + const acquire = vi.spyOn(SessionStore.prototype, 'acquireLock').mockImplementation(async function (profile) { + releaseLease = await originalAcquire.call(this, profile); + return releaseLease; + }); + await start(); + acquire.mockRestore(); + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + mocks.destroy.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('Late transport teardown failed')); + const result = client().execute(['chat', 'resolve', 'wait']).catch(error => error); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledOnce()); + skipStop = true; + try { + const stopping = server.stop(); + const failure = expect(stopping).rejects.toThrow('Late transport teardown failed'); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledOnce()); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await Promise.all([failure, result]); + expect(mocks.destroy).toHaveBeenCalledTimes(2); + await expect(new SessionStore(dir).acquireLock('fixture')).rejects.toMatchObject({ code: 'ELOCKED' }); + } finally { + await releaseLease(); + } + }); + + it('cancels all pipelined requests on one socket without accumulating per-request close listeners', async () => { + await start(); + const pending = deferred<Api.User>(); + mocks.entity.mockReturnValue(pending.promise); + const socket = createConnection(paths.socketPath); + await new Promise<void>((resolve, reject) => { socket.once('connect', resolve); socket.once('error', reject); }); + try { + socket.write(Array.from({ length: 16 }, (_, id) => JSON.stringify({ + jsonrpc: '2.0', id, method: 'execute', params: { argv: ['chat', 'resolve', 'wait'] }, + }) + '\n').join('')); + await vi.waitFor(() => expect(mocks.entity).toHaveBeenCalledTimes(16)); + const acceptedSocket = [...(server as any).sockets][0]; + expect(acceptedSocket.listenerCount('close')).toBeLessThan(10); + socket.destroy(); + await vi.waitFor(() => expect((server as any).sockets.size).toBe(0)); + for (const request of (server as any).activeRequests) { + expect(request.controller.signal.aborted).toBe(true); + } + expect((server as any).activeRequests.size).toBe(16); + } finally { + socket.destroy(); + pending.resolve(new Api.User({ id: 7n as any, firstName: 'Fixture' })); + await vi.waitFor(() => expect((server as any).activeRequests.size).toBe(0)); + } + }); + + it('does not release session ownership after shared-client destruction fails', async () => { + const originalAcquire = SessionStore.prototype.acquireLock; + let releaseLease!: () => Promise<void>; + const acquire = vi.spyOn(SessionStore.prototype, 'acquireLock').mockImplementation(async function (profile) { + releaseLease = await originalAcquire.call(this, profile); + return releaseLease; + }); + await start(); + acquire.mockRestore(); + mocks.destroy.mockRejectedValueOnce(new Error('Synthetic teardown failure')); + skipStop = true; + try { + await expect(server.stop()).rejects.toThrow('Synthetic teardown failure'); + await expect(new SessionStore(dir).acquireLock('fixture')).rejects.toMatchObject({ code: 'ELOCKED' }); + } finally { + // The client is a fake; explicitly dispose the intentionally retained lease. + await releaseLease(); + } + }); + + it.each([0, -1, 0.5, 120001, '30', null])('rejects invalid execute timeout %j before SDK work', async (timeoutMs) => { + await start(); + await expect(client().call('execute', { argv: ['chat', 'resolve', 'alice'], timeoutMs })).rejects.toMatchObject({ data: { tgCode: 'INVALID_INPUT' } }); + expect(mocks.entity).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/daemon-execute.test.ts b/cli/tests/unit/daemon-execute.test.ts new file mode 100644 index 0000000..26e642c --- /dev/null +++ b/cli/tests/unit/daemon-execute.test.ts @@ -0,0 +1,90 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { executeDaemonCommand } from '../../src/lib/daemon/execute.js'; +import { validateDaemonCommand } from '../../src/lib/daemon/command-protocol.js'; +import { TgError } from '../../src/lib/errors.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +describe('daemon execute request boundary', () => { + let client: any; + let controller: AbortController; + let previousExitCode: typeof process.exitCode; + beforeEach(() => { + previousExitCode = process.exitCode; + controller = new AbortController(); + client = { + getEntity: vi.fn().mockResolvedValue(new Api.User({ id: bigInt(7), accessHash: bigInt(11), firstName: 'Synthetic' })), + sendMessage: vi.fn().mockResolvedValue(new Api.Message({ + id: 31, peerId: new Api.PeerUser({ userId: bigInt(7) }), date: 1700000000, message: 'Synthetic reply', + })), + connect: vi.fn(), destroy: vi.fn(), + }; + }); + afterEach(() => { expect(process.exitCode).toBe(previousExitCode); process.exitCode = previousExitCode; }); + const invoke = (argv: string[], extras = {}) => executeDaemonCommand(client, 'default', { argv, ...extras }, controller.signal); + + it('retains a literal option-looking message and request stdin as data', async () => { + const literal = await invoke(['message', 'send', '--', 'me', '--profile=another']); + expect(literal.exitCode).toBe(0); + expect(client.sendMessage.mock.calls[0][1].message).toBe('--profile=another'); + const piped = await invoke(['message', 'send', 'me', '-'], { stdin: 'piped\ntext\n' }); + expect(piped.output.ok).toBe(true); + expect(client.sendMessage.mock.calls[1][1].message).toBe('piped\ntext'); + expect(client.connect).not.toHaveBeenCalled(); + expect(client.destroy).not.toHaveBeenCalled(); + }); + + it.each([ + ['message', 'send', '--profile=another', 'me', 'text'], + ['message', 'send', '--config=/tmp/unrelated', 'me', 'text'], + ['message', 'send', '--daemon', 'me', 'text'], + ['message', 'send', '--fields=id', 'me', 'text'], + ['message', 'send', '--help'], + ['message', 'send', 'me', 'text', 'extra'], + ])('rejects global flags/help/excess arguments before a Telegram call: %j', async (...argv) => { + const result = await invoke(argv); + expect(result).toMatchObject({ output: { ok: false, code: ErrorCode.INVALID_OPTIONS }, exitCode: 1 }); + expect(client.getEntity).not.toHaveBeenCalled(); + expect(client.sendMessage).not.toHaveBeenCalled(); + }); + + it.each([['auth', 'logout'], ['session', 'export'], ['daemon', 'stop'], ['completion', 'bash'], ['message', 'watch', 'me']])( + 'refuses lifecycle/streaming paths: %j', async (...argv) => { + const result = await invoke(argv); + expect(result).toMatchObject({ output: { ok: false, code: ErrorCode.DAEMON_PROXY_UNAVAILABLE }, exitCode: 1 }); + expect(client.getEntity).not.toHaveBeenCalled(); + }, + ); + + it('validates required and repeated options through Commander before RPC', async () => { + const result = await invoke(['message', 'poll', '--option=First', '--option=Second', 'me']); + expect(result).toMatchObject({ output: { ok: false, code: ErrorCode.INVALID_OPTIONS }, exitCode: 1 }); + expect(client.getEntity).not.toHaveBeenCalled(); + }); + + it('returns cancellation even if an operation has a late successful result', async () => { + client.sendMessage.mockImplementation(async () => { + controller.abort(new TgError('Outcome may be unknown', ErrorCode.TIMEOUT)); + return new Api.Message({ id: 31, peerId: new Api.PeerUser({ userId: bigInt(7) }), date: 1700000000, message: 'late' }); + }); + const result = await invoke(['message', 'send', 'me', 'text']); + expect(result).toMatchObject({ output: { ok: false, code: ErrorCode.TIMEOUT }, exitCode: 1 }); + expect(client.sendMessage).toHaveBeenCalledTimes(1); + expect(client.destroy).not.toHaveBeenCalled(); + }); + + it.each([ + null, [], { argv: 'message history me' }, { argv: ['message', 'send', 'me', '\0'] }, + { argv: ['chat', 'list'], config: '/tmp/other' }, + { argv: ['chat', 'list'], timeoutMs: 0 }, { argv: ['chat', 'list'], timeoutMs: 120001 }, + { argv: ['chat', 'list'], stdin: 123 }, { argv: ['media', 'send', 'me', 'file'], cwd: 'relative' }, + { argv: ['media', 'download', 'me', '1'] }, + ])('rejects malformed request shapes: %j', params => { + expect(() => validateDaemonCommand(params as any)).toThrow(TgError); + }); + + it('counts UTF-8 bytes rather than characters for request frame limits', () => { + expect(() => validateDaemonCommand({ argv: ['message', 'send', 'me', '-'], stdin: '😀'.repeat(270000) })).toThrow(/frame limit/); + }); +}); diff --git a/cli/tests/unit/daemon-execution-context.test.ts b/cli/tests/unit/daemon-execution-context.test.ts new file mode 100644 index 0000000..7b9f1a9 --- /dev/null +++ b/cli/tests/unit/daemon-execution-context.test.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { TelegramClient } from 'teleproto'; +import { + captureDaemonOutput, getDaemonContext, markExitFailure, runWithDaemonContext, runOutsideDaemonContext, + type DaemonExecutionContext, +} from '../../src/lib/daemon/execution-context.js'; +import { + outputSuccess, outputError, logStatus, logVerbose, + setOutputMode, setJsonlMode, setToonMode, setFieldSelection, +} from '../../src/lib/output.js'; +import { setQuietMode, setVerboseMode, isQuietMode, isVerboseMode } from '../../src/lib/cli-mode.js'; +import { outputBatchResult } from '../../src/lib/batch-results.js'; +import { TgError } from '../../src/lib/errors.js'; + +const forbidden = vi.hoisted(() => ({ + config: vi.fn(() => { throw new Error('Unexpected config access'); }), + credentials: vi.fn(() => { throw new Error('Unexpected credential access'); }), + session: vi.fn(() => { throw new Error('Unexpected session access'); }), + client: vi.fn(() => { throw new Error('Unexpected client creation'); }), +})); +vi.mock('../../src/lib/config.js', () => ({ createConfig: forbidden.config, getCredentialsOrThrow: forbidden.credentials })); +vi.mock('../../src/lib/session-store.js', () => ({ SessionStore: forbidden.session })); +vi.mock('../../src/lib/client.js', () => ({ withClient: forbidden.client })); + +import { withAuth } from '../../src/lib/with-auth.js'; + +function context(profile = 'default'): DaemonExecutionContext { + return { + profile, + signal: new AbortController().signal, + client: { connect: vi.fn(), destroy: vi.fn() } as unknown as TelegramClient, + exitCode: 0, + }; +} + +function deferred() { + let resolve!: () => void; + const promise = new Promise<void>(done => { resolve = done; }); + return { promise, resolve }; +} + +let originalExitCode: typeof process.exitCode; +beforeEach(() => { + originalExitCode = process.exitCode; + process.exitCode = 0; + vi.clearAllMocks(); +}); +afterEach(() => { + process.exitCode = originalExitCode; + setOutputMode(false); + setJsonlMode(false); + setToonMode(false); + setFieldSelection(null); + setQuietMode(false); + setVerboseMode(false); + vi.restoreAllMocks(); + for (const fn of Object.values(forbidden)) expect(fn).not.toHaveBeenCalled(); +}); + +describe('daemon execution context', () => { + it('isolates overlapping async outputs and partial failures without touching process streams or exit code', async () => { + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const first = context('first'); + const second = context('second'); + const firstReady = deferred(); + const secondDone = deferred(); + + await Promise.all([ + runWithDaemonContext(first, async () => { + firstReady.resolve(); + await secondDone.promise; + expect(getDaemonContext()).toBe(first); + outputBatchResult({ messages: [{ id: 7 }] }, [{ input: '8', code: 'PEER_ID_INVALID', error: 'Peer not found' }]); + }), + runWithDaemonContext(second, async () => { + await firstReady.promise; + expect(getDaemonContext()).toBe(second); + outputSuccess({ id: 'second', nested: { untouched: true } }); + secondDone.resolve(); + }), + ]); + + expect(first.output).toEqual({ ok: true, data: { messages: [{ id: 7 }], partial: true, errors: [{ input: '8', code: 'PEER_ID_INVALID', error: 'Peer not found' }] } }); + expect(first.exitCode).toBe(1); + expect(second.output).toEqual({ ok: true, data: { id: 'second', nested: { untouched: true } } }); + expect(second.exitCode).toBe(0); + expect(process.exitCode).toBe(0); + expect(stdout).not.toHaveBeenCalled(); + expect(stderr).not.toHaveBeenCalled(); + expect(getDaemonContext()).toBeUndefined(); + }); + + it.each(['json', 'jsonl', 'toon', 'human'])('captures raw DTOs before %s formatting and field selection', async mode => { + setJsonlMode(mode === 'jsonl'); + setToonMode(mode === 'toon'); + setOutputMode(mode === 'human'); + setFieldSelection(['id']); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const current = context(); + const dto = { users: [{ id: '123', name: 'Kept' }], total: 1 }; + await runWithDaemonContext(current, () => outputSuccess(dto)); + expect(current.output).toEqual({ ok: true, data: dto }); + expect((current.output as any).data).toBe(dto); + expect(stdout).not.toHaveBeenCalled(); + }); + + it('captures one structured error, retains it across late output, and keeps the daemon alive', async () => { + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const current = context(); + await runWithDaemonContext(current, async () => { + outputError('Request expired', 'TIMEOUT'); + await Promise.resolve(); + outputSuccess({ late: true }); + }); + expect(current.output).toEqual({ ok: false, error: 'Request expired', code: 'TIMEOUT' }); + expect(current.exitCode).toBe(1); + expect(process.exitCode).toBe(0); + expect(stdout).not.toHaveBeenCalled(); + }); + + it('suppresses status and verbose logging even with explicit quiet=false, then restores local logging flags', async () => { + setVerboseMode(true); + setQuietMode(false); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + await runWithDaemonContext(context(), async () => { + expect(isQuietMode()).toBe(true); + expect(isVerboseMode()).toBe(false); + logStatus('request progress', false); + logVerbose('request detail'); + }); + expect(stderr).not.toHaveBeenCalled(); + expect(isQuietMode()).toBe(false); + expect(isVerboseMode()).toBe(true); + logStatus('direct progress'); + expect(stderr).toHaveBeenCalledWith('direct progress\n'); + }); + + it('restores outer contexts after nesting and rejection', async () => { + const outer = context('outer'); + const inner = context('inner'); + await runWithDaemonContext(outer, async () => { + await expect(runWithDaemonContext(inner, async () => { + await Promise.resolve(); + expect(getDaemonContext()).toBe(inner); + throw new Error('nested failure'); + })).rejects.toThrow('nested failure'); + expect(getDaemonContext()).toBe(outer); + }); + expect(getDaemonContext()).toBeUndefined(); + expect(captureDaemonOutput({ ok: true, data: null })).toBe(false); + markExitFailure(); + expect(process.exitCode).toBe(1); + }); + + it('starts shared async maintenance without retaining the originating request and restores its caller', async () => { + const current = context(); + const resume = deferred(); + let maintenance!: Promise<DaemonExecutionContext | undefined>; + await runWithDaemonContext(current, () => { + maintenance = runOutsideDaemonContext(async () => { + expect(getDaemonContext()).toBeUndefined(); + await resume.promise; + return getDaemonContext(); + }); + expect(getDaemonContext()).toBe(current); + expect(() => runOutsideDaemonContext(() => { throw new Error('maintenance setup failed'); })).toThrow('maintenance setup failed'); + expect(getDaemonContext()).toBe(current); + outputSuccess({ id: 'original response' }); + }); + resume.resolve(); + await expect(maintenance).resolves.toBeUndefined(); + expect(current.output).toEqual({ ok: true, data: { id: 'original response' } }); + expect(getDaemonContext()).toBeUndefined(); + }); +}); + +describe('withAuth on the persistent daemon client', () => { + it('reuses the existing client across commands without config, session, connect, destroy, or daemon discovery', async () => { + const current = context(); + const callback = vi.fn(async client => { expect(client).toBe(current.client); }); + await runWithDaemonContext(current, async () => { + await withAuth({ profile: 'default', daemon: true, config: '/must/not/read' }, callback); + await withAuth({ profile: 'default' }, callback); + }); + expect(callback).toHaveBeenCalledTimes(2); + expect(current.client.connect).not.toHaveBeenCalled(); + expect(current.client.destroy).not.toHaveBeenCalled(); + expect(current.exitCode).toBe(0); + }); + + it.each([['other', 'INVALID_OPTIONS'], ['', 'INVALID_INPUT'], ['../profile', 'INVALID_INPUT']])('rejects a mismatched or invalid profile %j before callback', async (profile, code) => { + const current = context(); + const callback = vi.fn(); + await runWithDaemonContext(current, () => withAuth({ profile }, callback)); + expect(callback).not.toHaveBeenCalled(); + expect(current.output).toMatchObject({ ok: false, code }); + expect(current.exitCode).toBe(1); + expect(process.exitCode).toBe(0); + }); + + it('does not invoke callbacks on already cancelled requests', async () => { + const current = context(); + current.signal = AbortSignal.abort(new TgError('Request timed out', 'TIMEOUT')); + const callback = vi.fn(); + await runWithDaemonContext(current, () => withAuth({ profile: 'default' }, callback)); + expect(callback).not.toHaveBeenCalled(); + expect(current.output).toEqual({ ok: false, error: 'Request timed out', code: 'TIMEOUT' }); + }); + + it('captures cancellation during the callback and translates RPC errors with the usual codes', async () => { + const controller = new AbortController(); + const cancelled = context(); + cancelled.signal = controller.signal; + await runWithDaemonContext(cancelled, () => withAuth({ profile: 'default' }, async () => { + controller.abort(new TgError('Request timed out', 'TIMEOUT')); + })); + expect(cancelled.output).toMatchObject({ ok: false, code: 'TIMEOUT' }); + + const denied = context(); + await runWithDaemonContext(denied, () => withAuth({ profile: 'default' }, async () => { + await Promise.resolve(); + throw { errorMessage: 'CHAT_ADMIN_REQUIRED' }; + })); + expect(denied.output).toEqual({ ok: false, error: 'Admin privileges required', code: 'CHAT_ADMIN_REQUIRED' }); + expect(process.exitCode).toBe(0); + }); +}); diff --git a/cli/tests/unit/daemon-frames.test.ts b/cli/tests/unit/daemon-frames.test.ts new file mode 100644 index 0000000..0042935 --- /dev/null +++ b/cli/tests/unit/daemon-frames.test.ts @@ -0,0 +1,43 @@ +import { describe, it, expect } from 'vitest'; +import { JsonLineDecoder, MAX_FRAME_BYTES } from '../../src/lib/daemon/frames.js'; + +describe('NDJSON byte framing', () => { + it('retains UTF-8 bytes across arbitrary chunk boundaries', () => { + const decoder = new JsonLineDecoder(); + const bytes = Buffer.from('{"text":"Привет 🌍"}\n'); + const lines: string[] = []; + for (const byte of bytes) decoder.push(Buffer.from([byte]), (line) => lines.push(line)); + expect(lines).toEqual(['{"text":"Привет 🌍"}']); + }); + + it('accepts several legal frames even when a data event exceeds the limit', () => { + const decoder = new JsonLineDecoder(); + const line = 'x'.repeat(MAX_FRAME_BYTES); + const lines: string[] = []; + decoder.push(Buffer.from(line + '\n' + line + '\n'), (value) => lines.push(value)); + expect(lines).toEqual([line, line]); + }); + + it('rejects an oversized fragmented frame after a complete preceding frame', () => { + const decoder = new JsonLineDecoder(); + const seen: string[] = []; + decoder.push(Buffer.from('ping\n' + 'x'.repeat(MAX_FRAME_BYTES - 3)), (line) => seen.push(line)); + expect(() => decoder.push(Buffer.from('1234\n'), () => {})).toThrow('Message too large'); + expect(seen).toEqual(['ping']); + }); + + it('counts encoded bytes rather than characters', () => { + const decoder = new JsonLineDecoder(); + expect(() => decoder.push(Buffer.from('я'.repeat(MAX_FRAME_BYTES / 2 + 1) + '\n'), () => {})) + .toThrow('Message too large'); + }); + + it('does not deliver an unterminated frame', () => { + const decoder = new JsonLineDecoder(); + const lines: string[] = []; + decoder.push(Buffer.from('one\ntwo'), (line) => lines.push(line)); + expect(lines).toEqual(['one']); + decoder.push(Buffer.from('\n'), (line) => lines.push(line)); + expect(lines).toEqual(['one', 'two']); + }); +}); diff --git a/cli/tests/unit/daemon-lifecycle.test.ts b/cli/tests/unit/daemon-lifecycle.test.ts new file mode 100644 index 0000000..07f9418 --- /dev/null +++ b/cli/tests/unit/daemon-lifecycle.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { + isProcessAlive, + daemonChildEnv, + installDaemonSignals, + waitWhile, +} from '../../src/lib/daemon/lifecycle.js'; + +describe('isProcessAlive', () => { + it('returns true for the current process', () => { + expect(isProcessAlive(process.pid)).toBe(true); + }); + + it('returns false for an unused pid', () => { + expect(isProcessAlive(2_147_483_647)).toBe(false); + }); + + it('treats EPERM as alive', () => { + const spy = vi.spyOn(process, 'kill').mockImplementation(() => { + const err = new Error('EPERM') as NodeJS.ErrnoException; + err.code = 'EPERM'; + throw err; + }); + try { + expect(isProcessAlive(1)).toBe(true); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('daemonChildEnv', () => { + it('passes the resolved transport and removes an inherited stale choice', () => { + vi.stubEnv('TG_DAEMON_TRANSPORT', 'wss'); + try { + const opts = { configDir: '/tmp/cfg', profile: 'work', idleTimeout: 0 }; + expect(daemonChildEnv({ ...opts, transport: 'tcp' }).TG_DAEMON_TRANSPORT).toBe('tcp'); + expect(daemonChildEnv({ ...opts, transport: 'wss' }).TG_DAEMON_TRANSPORT).toBe('wss'); + expect(daemonChildEnv(opts).TG_DAEMON_TRANSPORT).toBeUndefined(); + } finally { vi.unstubAllEnvs(); } + }); + + it('does not pass session string or api hash', () => { + const prevSession = process.env.TG_DAEMON_SESSION; + process.env.TG_DAEMON_SESSION = 'should-not-leak'; + process.env.TG_DAEMON_API_HASH = 'hash-leak'; + const env = daemonChildEnv({ + configDir: '/tmp/cfg', + profile: 'default', + idleTimeout: 300_000, + }); + expect(env.TG_DAEMON_SESSION).toBeUndefined(); + expect(env.TG_DAEMON_API_HASH).toBeUndefined(); + expect(env.TG_DAEMON_API_ID).toBeUndefined(); + expect(env.TG_DAEMON_CONFIG_DIR).toBe('/tmp/cfg'); + expect(env.TG_DAEMON_PROFILE).toBe('default'); + expect(env.TG_DAEMON_IDLE_TIMEOUT).toBe('300000'); + expect(env.TG_DAEMON_PID_PRECLAIMED).toBe('1'); + if (prevSession === undefined) delete process.env.TG_DAEMON_SESSION; + else process.env.TG_DAEMON_SESSION = prevSession; + delete process.env.TG_DAEMON_API_HASH; + }); +}); + +describe('installDaemonSignals', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('calls stop then process.exit(0) on SIGTERM', async () => { + const stop = vi.fn().mockResolvedValue(undefined); + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + const uninstall = installDaemonSignals(stop); + process.emit('SIGTERM'); + await vi.waitFor(() => expect(stop).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(0)); + uninstall(); + }); + + it('calls stop then process.exit(0) on SIGINT', async () => { + const stop = vi.fn().mockResolvedValue(undefined); + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + const uninstall = installDaemonSignals(stop); + process.emit('SIGINT'); + await vi.waitFor(() => expect(stop).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(0)); + uninstall(); + }); +}); + +describe('waitWhile', () => { + it('returns true when predicate becomes false', async () => { + let n = 2; + const ok = await waitWhile(() => n-- > 0, 1000, 1); + expect(ok).toBe(true); + }); + + it('returns false when the predicate stays true until timeout', async () => { + const ok = await waitWhile(() => true, 20, 5); + expect(ok).toBe(false); + }); +}); diff --git a/cli/tests/unit/daemon-parse-mode-sdk.test.ts b/cli/tests/unit/daemon-parse-mode-sdk.test.ts new file mode 100644 index 0000000..eb2e9e8 --- /dev/null +++ b/cli/tests/unit/daemon-parse-mode-sdk.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it, vi } from 'vitest'; +import { Api, TelegramClient, sessions } from 'teleproto'; +import bigInt from 'big-integer'; +import { Logger, LogLevel } from 'teleproto/extensions/Logger.js'; +import { createRequestClient } from '../../src/lib/daemon/request-client.js'; +import { executeDaemonCommand } from '../../src/lib/daemon/execute.js'; +import { serializeMessage } from '../../src/lib/serialize.js'; + +function fixture() { + const client = new TelegramClient(new sessions.StringSession(''), 1, 'synthetic', { + baseLogger: new Logger(LogLevel.NONE), + }); + (client as any)._connectedDeferred.resolve(); + const user = new Api.User({ id: bigInt(7), accessHash: bigInt(8), firstName: 'Fixture' }); + const message = () => new Api.Message({ + id: 9, peerId: new Api.PeerUser({ userId: user.id }), date: 1700000000, + message: 'hello', entities: [new Api.MessageEntityBold({ offset: 0, length: 5 })], + }); + const enqueue = vi.fn((state: any) => { + if (state.request instanceof Api.messages.GetDialogs) { + state.resolve(new Api.messages.Dialogs({ + dialogs: [new Api.Dialog({ + peer: new Api.PeerUser({ userId: user.id }), topMessage: 9, + readInboxMaxId: 9, readOutboxMaxId: 9, unreadCount: 0, unreadMentionsCount: 0, + unreadReactionsCount: 0, notifySettings: new Api.PeerNotifySettings({}), + draft: new Api.DraftMessage({ + message: 'draft', date: 1700000000, + entities: [new Api.MessageEntityItalic({ offset: 0, length: 5 })], + }), + })], + messages: [message()], users: [user], chats: [], + })); + } else if (state.request instanceof Api.messages.GetMessages) { + state.resolve(new Api.messages.Messages({ messages: [message()], users: [user], chats: [] })); + } else { + state.reject(new Error(`Unexpected offline request: ${state.request.className}`)); + } + }); + (client as any)._sender = { isConnected: () => true, addStateToQueue: enqueue }; + return { client, user, enqueue }; +} + +describe('real SDK parse mode through the daemon request view', () => { + it('executes chat list with the default MarkdownParser and real SDK dialog/draft construction', async () => { + const shared = fixture(); + const controller = new AbortController(); + const view = createRequestClient(shared.client, controller.signal); + const result = await executeDaemonCommand(view.client, 'fixture', { argv: ['chat', 'list', '--limit', '3'] }, controller.signal); + await view.settled(); + // GramJS TotalList is an Array subclass; compare the actual wire DTO. + expect(JSON.parse(JSON.stringify(result))).toMatchObject({ + output: { ok: true, data: { chats: [{ id: '7', title: 'Fixture', type: 'user' }], total: 1 } }, exitCode: 0, + }); + expect(shared.enqueue).toHaveBeenCalledOnce(); + expect(shared.client.parseMode!.unparse('draft', [new Api.MessageEntityItalic({ offset: 0, length: 5 })])).toBe('__draft__'); + }); + + it('preserves real message text parsing and serialization before and after another request is cancelled', async () => { + const shared = fixture(); + const peer = new Api.InputPeerUser({ userId: shared.user.id, accessHash: bigInt(8) }); + for (const cancelled of [true, false]) { + const controller = new AbortController(); + const view = createRequestClient(shared.client, controller.signal); + const messages = await view.client.getMessages(peer, { ids: [9] }); + await view.settled(); + if (cancelled) controller.abort(new Error('request ended')); + // These are pure SDK getters on an already-returned message. + expect(messages[0].text).toBe('**hello**'); + expect(serializeMessage(messages[0])).toMatchObject({ id: 9, text: '**hello**' }); + const [text, entities] = view.client.parseMode!.parse('__changed__'); + expect(text).toBe('changed'); + expect(entities).toHaveLength(1); + expect(entities[0]).toBeInstanceOf(Api.MessageEntityItalic); + expect(entities[0].offset).toBe(0); + expect(entities[0].length).toBe(7); + } + expect(shared.enqueue).toHaveBeenCalledTimes(2); + }); + + it('preserves callable metadata, static properties and construction without bypassing cancellation of calls', () => { + class Resource { + static version = 'fixture'; + constructor(readonly label: string) {} + } + function method(this: { label: string }, suffix: string) { return this.label + suffix; } + Object.defineProperty(method, 'metadata', { value: { enabled: true }, writable: false }); + const underlying = { Resource, method, label: 'value' }; + const controller = new AbortController(); + const view = createRequestClient(underlying as any, controller.signal).client as any; + const resource = new view.Resource('instance'); + expect(resource).toBeInstanceOf(Resource); + expect(resource.label).toBe('instance'); + expect(view.Resource.version).toBe('fixture'); + expect(view.method.name).toBe('method'); + expect(view.method.length).toBe(1); + expect(view.method.metadata).toEqual({ enabled: true }); + expect(view.method('!')).toBe('value!'); + controller.abort(new Error('cancelled')); + expect(() => view.method('!')).toThrow('cancelled'); + expect(() => new view.Resource('late')).toThrow('cancelled'); + }); +}); diff --git a/cli/tests/unit/daemon-pid.test.ts b/cli/tests/unit/daemon-pid.test.ts new file mode 100644 index 0000000..004fa86 --- /dev/null +++ b/cli/tests/unit/daemon-pid.test.ts @@ -0,0 +1,91 @@ +// tests/unit/daemon-pid.test.ts +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; + +describe('DaemonPaths', () => { + let tempDir: string; + let paths: DaemonPaths; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), 'tg-daemon-test-')); + paths = new DaemonPaths(tempDir, 'default'); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it('computes socket path under config dir', () => { + expect(paths.socketPath).toBe(join(tempDir, 'daemon', 'default.sock')); + }); + + it('computes pid path under config dir', () => { + expect(paths.pidPath).toBe(join(tempDir, 'daemon', 'default.pid')); + }); + + it('strips path traversal from the profile name', () => { + const sneaky = new DaemonPaths(tempDir, '../tmp/evil'); + expect(sneaky.socketPath).toBe(join(tempDir, 'daemon', 'evil.sock')); + expect(sneaky.socketPath).not.toContain('..'); + }); + + it('validates socket path length for AF_UNIX limit', () => { + expect(() => paths.validateSocketPath()).not.toThrow(); + }); + + it('rejects socket path exceeding 104 chars', () => { + const longDir = join(tempDir, 'a'.repeat(100)); + const longPaths = new DaemonPaths(longDir, 'default'); + expect(() => longPaths.validateSocketPath()).toThrow(/too long/); + }); + + it('writes and reads PID file', () => { + paths.writePid(12345); + expect(paths.readPid()).toBe(12345); + }); + + it('writePidExclusive fails if the pid file already exists', () => { + expect(paths.writePidExclusive(1)).toBe(true); + expect(paths.writePidExclusive(2)).toBe(false); + expect(paths.readPid()).toBe(1); + }); + + it('returns null when PID file does not exist', () => { + expect(paths.readPid()).toBeNull(); + }); + + it.each(['123junk', '1.5', '-1', '0', '4194305', '1e3', ''])('rejects malformed or unsafe pid %j', (value) => { + paths.ensureDir(); + writeFileSync(paths.pidPath, value); + expect(paths.readPid()).toBeNull(); + }); + + it('removes PID and socket files on cleanup', () => { + paths.writePid(12345); + paths.cleanup(); + expect(paths.readPid()).toBeNull(); + }); + + it('checks if socket file exists', () => { + expect(paths.socketExists()).toBe(false); + }); + + it('cleanupOwned unlinks socket then pid only when the file still has our pid', () => { + paths.writePidExclusive(111); + writeFileSync(paths.socketPath, ''); + paths.cleanupOwned(111); + expect(paths.readPid()).toBeNull(); + expect(paths.socketExists()).toBe(false); + }); + + it('cleanupOwned does not unlink a successor pid or socket', () => { + paths.writePidExclusive(222); + writeFileSync(paths.socketPath, ''); + paths.cleanupOwned(111); + expect(paths.readPid()).toBe(222); + expect(paths.socketExists()).toBe(true); + }); +}); diff --git a/cli/tests/unit/daemon-protocol.test.ts b/cli/tests/unit/daemon-protocol.test.ts new file mode 100644 index 0000000..a077c79 --- /dev/null +++ b/cli/tests/unit/daemon-protocol.test.ts @@ -0,0 +1,79 @@ +// tests/unit/daemon-protocol.test.ts +import { describe, it, expect } from 'vitest'; +import { + encodeRequest, + encodeResponse, + encodeError, + encodeNotification, + parseMessage, +} from '../../src/lib/daemon/protocol.js'; + +describe('daemon protocol', () => { + it('encodes a JSON-RPC request', () => { + const msg = encodeRequest('ping', {}, 1); + const parsed = JSON.parse(msg); + expect(parsed.jsonrpc).toBe('2.0'); + expect(parsed.method).toBe('ping'); + expect(parsed.id).toBe(1); + }); + + it('encodes a JSON-RPC success response', () => { + const msg = encodeResponse({ ok: true, data: { chats: [] } }, 1); + const parsed = JSON.parse(msg); + expect(parsed.jsonrpc).toBe('2.0'); + expect(parsed.result.ok).toBe(true); + expect(parsed.id).toBe(1); + }); + + it('encodes a JSON-RPC error response', () => { + const msg = encodeError(-32000, 'Peer not found', { tgCode: 'PEER_NOT_FOUND' }, 1); + const parsed = JSON.parse(msg); + expect(parsed.error.code).toBe(-32000); + expect(parsed.error.message).toBe('Peer not found'); + expect(parsed.error.data.tgCode).toBe('PEER_NOT_FOUND'); + }); + + it('parses a valid JSON-RPC request', () => { + const raw = JSON.stringify({ jsonrpc: '2.0', method: 'ping', params: {}, id: 1 }); + const msg = parseMessage(raw); + expect(msg.type).toBe('request'); + expect((msg as any).method).toBe('ping'); + }); + + it('parses a valid JSON-RPC response', () => { + const raw = JSON.stringify({ jsonrpc: '2.0', result: { ok: true }, id: 1 }); + const msg = parseMessage(raw); + expect(msg.type).toBe('response'); + }); + + it('parses a valid JSON-RPC error', () => { + const raw = JSON.stringify({ jsonrpc: '2.0', error: { code: -1, message: 'err' }, id: 1 }); + const msg = parseMessage(raw); + expect(msg.type).toBe('error'); + }); + + it('throws on invalid JSON', () => { + expect(() => parseMessage('not json{')).toThrow(); + }); + + it('throws on missing jsonrpc field', () => { + expect(() => parseMessage(JSON.stringify({ method: 'ping' }))).toThrow(); + }); + + it('encodes a JSON-RPC notification with no id', () => { + const msg = encodeNotification('message', { id: 1, text: 'hi' }); + const parsed = JSON.parse(msg); + expect(parsed.jsonrpc).toBe('2.0'); + expect(parsed.method).toBe('message'); + expect(parsed.params.text).toBe('hi'); + expect(parsed).not.toHaveProperty('id'); + }); + + it('parses a notification (method, no id) separately from a request', () => { + const raw = JSON.stringify({ jsonrpc: '2.0', method: 'message', params: { id: 7 } }); + const msg = parseMessage(raw); + expect(msg.type).toBe('notification'); + expect((msg as any).method).toBe('message'); + expect((msg as any).params.id).toBe(7); + }); +}); diff --git a/cli/tests/unit/daemon-request-client.test.ts b/cli/tests/unit/daemon-request-client.test.ts new file mode 100644 index 0000000..56dea72 --- /dev/null +++ b/cli/tests/unit/daemon-request-client.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createRequestClient } from '../../src/lib/daemon/request-client.js'; +import { getDaemonContext, runWithDaemonContext } from '../../src/lib/daemon/execution-context.js'; + +function deferred<T>() { + let resolve!: (value: T) => void; + const promise = new Promise<T>(yes => { resolve = yes; }); + return { promise, resolve }; +} + +describe('daemon request cancellation proxy', () => { + it('guards captured methods and nested SDK calls after an await', async () => { + const controller = new AbortController(); + const gate = deferred<void>(); + const underlying = { + invoke: vi.fn(async () => 'written'), + async sendMessage() { await gate.promise; return this.invoke(); }, + }; + const view = createRequestClient(underlying as any, controller.signal); + const captured = view.client.invoke; + const sent = view.client.sendMessage('unused', { message: 'text' }); + const rejected = expect(sent).rejects.toThrow('cancelled'); + controller.abort(new Error('cancelled')); + expect(() => captured({} as any)).toThrow('cancelled'); + gate.resolve(); + await rejected; + await view.settled(); + expect(underlying.invoke).not.toHaveBeenCalled(); + }); + + it('tracks an in-flight lazy iterator step but prevents the following next call', async () => { + const controller = new AbortController(); + const gate = deferred<IteratorResult<number>>(); + const next = vi.fn(() => gate.promise); + const underlying = { iterMessages: () => ({ [Symbol.asyncIterator]: () => ({ next }) }) }; + const view = createRequestClient(underlying as any, controller.signal); + const iterator = view.client.iterMessages(undefined, {})[Symbol.asyncIterator](); + const first = iterator.next(); + controller.abort(new Error('cancelled')); + let settled = false; + const completion = view.settled().then(() => { settled = true; }); + await Promise.resolve(); + expect(settled).toBe(false); + gate.resolve({ done: false, value: 1 }); + await first; + expect(() => iterator.next()).toThrow('cancelled'); + await completion; + expect(next).toHaveBeenCalledOnce(); + }); + + it('retains detached SDK promises without an unhandled rejection', async () => { + const controller = new AbortController(); + const gate = deferred<void>(); + const underlying = { invoke: vi.fn(async () => { await gate.promise; throw new Error('Late RPC error'); }) }; + const view = createRequestClient(underlying as any, controller.signal); + void view.client.invoke({} as any); + let settled = false; + const completion = view.settled().then(() => { settled = true; }); + await Promise.resolve(); + expect(settled).toBe(false); + gate.resolve(); + await completion; + expect(settled).toBe(true); + }); + + it('protects sender queues and exported senders captured before cancellation', async () => { + const controller = new AbortController(); + const sender = { addStateToQueue: vi.fn(), send: vi.fn(async () => 'sent') }; + const underlying = { _sender: sender, getSender: async () => sender }; + const view = createRequestClient(underlying as any, controller.signal); + const main = (view.client as any)._sender; + const exported = await (view.client as any).getSender(); + controller.abort(new Error('cancelled')); + expect(() => main.addStateToQueue({})).toThrow('cancelled'); + expect(() => exported.send({})).toThrow('cancelled'); + await view.settled(); + expect(sender.addStateToQueue).not.toHaveBeenCalled(); + expect(sender.send).not.toHaveBeenCalled(); + }); + + it('sets request-local retry policy while preserving shared options and SDK migration calls', async () => { + const controller = new AbortController(); + const underlying = { + _requestRetries: 9, + floodSleepThreshold: 60, + connect: vi.fn(async () => true), + async _switchDC() { return this.connect(); }, + }; + const view = createRequestClient(underlying as any, controller.signal); + expect((view.client as any)._requestRetries).toBe(1); + expect(view.client.floodSleepThreshold).toBe(0); + await expect((view.client as any)._switchDC()).resolves.toBe(true); + await view.settled(); + expect(underlying.connect).toHaveBeenCalledOnce(); + expect(underlying._requestRetries).toBe(9); + expect(underlying.floodSleepThreshold).toBe(60); + }); + + it('starts shared transport maintenance outside the request context while keeping command calls isolated', async () => { + const controller = new AbortController(); + const gate = deferred<void>(); + const observed: unknown[] = []; + const underlying = { + async getSender() { + observed.push(getDaemonContext()); + await gate.promise; + observed.push(getDaemonContext()); + return { send: vi.fn() }; + }, + invoke: vi.fn(async () => getDaemonContext()), + }; + const view = createRequestClient(underlying as any, controller.signal); + const context = { client: view.client, signal: controller.signal, profile: 'fixture', exitCode: 0 }; + const running = runWithDaemonContext(context, async () => { + const sender = view.client.getSender(2); + expect(getDaemonContext()).toBe(context); + expect(await view.client.invoke({} as any)).toBe(context); + return sender; + }); + gate.resolve(); + await running; + await view.settled(); + expect(observed).toEqual([undefined, undefined]); + expect(getDaemonContext()).toBeUndefined(); + }); +}); diff --git a/cli/tests/unit/daemon-server.test.ts b/cli/tests/unit/daemon-server.test.ts new file mode 100644 index 0000000..e3b0774 --- /dev/null +++ b/cli/tests/unit/daemon-server.test.ts @@ -0,0 +1,369 @@ +// tests/unit/daemon-server.test.ts +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, unlinkSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createConnection } from 'node:net'; +import { once } from 'node:events'; + +// Mock telegram +const mockConnect = vi.fn().mockResolvedValue(undefined); +const mockDestroy = vi.fn().mockResolvedValue(undefined); +const mockGetEntity = vi.fn().mockResolvedValue({ id: 42, className: 'User' }); +const updateHandlers: Array<(event: any) => void> = []; +const mockAddEventHandler = vi.fn((handler: (event: any) => void) => { + updateHandlers.push(handler); +}); +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getEntity: mockGetEntity, + addEventHandler: mockAddEventHandler, + removeEventHandler: vi.fn(), +}; + +vi.mock('teleproto', async () => ({ + ...await vi.importActual('teleproto'), + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })) }, +})); + +vi.mock('teleproto/events/NewMessage.js', () => ({ + NewMessage: class NewMessage { + constructor(_opts: any = {}) {} + }, +})); + +import { NewMessage } from 'teleproto/events/NewMessage.js'; +import { DaemonServer } from '../../src/lib/daemon/server.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { encodeRequest, parseMessage } from '../../src/lib/daemon/protocol.js'; + +describe('DaemonServer', () => { + let tempDir: string; + let paths: DaemonPaths; + let server: DaemonServer; + + beforeEach(() => { + vi.clearAllMocks(); + mockGetEntity.mockImplementation(async () => ({ id: 42, className: 'User' })); + mockAddEventHandler.mockImplementation((handler: (event: any) => void) => { + updateHandlers.push(handler); + }); + updateHandlers.length = 0; + tempDir = mkdtempSync(join(tmpdir(), 'tg-daemon-srv-')); + paths = new DaemonPaths(tempDir, 'test'); + }); + + afterEach(async () => { + if (server) await server.stop(); + rmSync(tempDir, { recursive: true, force: true }); + }); + + it('does not announce readiness and releases ownership after failed connection retries', async () => { + mockConnect.mockResolvedValueOnce(false); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await expect(server.start()).rejects.toMatchObject({ code: 'CONNECTION_FAILED' }); + expect(paths.socketExists()).toBe(false); + expect(paths.readPid()).toBeNull(); + expect(mockDestroy).toHaveBeenCalledOnce(); + const release = await new SessionStore(tempDir).acquireLock('test'); + await release(); + }); + + it.each(['tcp', 'wss'] as const)('starts with %s and accepts connections on Unix socket', async transport => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's', transport }); + await server.start(); + expect(paths.socketExists()).toBe(true); + const { TelegramClient } = await import('teleproto'); + expect(TelegramClient).toHaveBeenLastCalledWith(expect.anything(), 1, 'h', expect.objectContaining({ useWSS: transport === 'wss' })); + + // Connect and send ping + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + sock.write(encodeRequest('ping', {}, 1) + '\n'); + + const [data] = await once(sock, 'data'); + const msg = parseMessage(data.toString().trim()); + expect(msg.type).toBe('response'); + expect((msg as any).result).toBe('pong'); + + sock.destroy(); + }); + + it.each([-1, 0.5, NaN, Infinity, 2_147_483_648])('rejects unsafe idle timeout %s before connecting', (idleTimeout) => { + expect(() => new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }, { idleTimeout })) + .toThrow('Daemon idle timeout'); + expect(mockConnect).not.toHaveBeenCalled(); + }); + + it('responds with error for unknown methods', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + sock.write(encodeRequest('nonexistent', {}, 2) + '\n'); + + const [data] = await once(sock, 'data'); + const msg = parseMessage(data.toString().trim()); + expect(msg.type).toBe('error'); + expect((msg as any).error.code).toBe(-32601); + }); + + it('subscribe acks then pushes message notifications on the same socket', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + + const lines: string[] = []; + sock.on('data', (buf) => { + for (const line of buf.toString().split('\n').filter(Boolean)) lines.push(line); + }); + + sock.write(encodeRequest('subscribe', { chat: 'alice' }, 3) + '\n'); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(1)); + + const ack = parseMessage(lines[0]); + expect(ack.type).toBe('response'); + expect((ack as any).result).toEqual({ subscribed: true, chat: 'alice', topic: null }); + expect(updateHandlers.length).toBe(1); + + updateHandlers[0]({ + message: { id: 9, date: 1_700_000_000, message: 'hello', chatId: 42 }, + }); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(2)); + + const note = parseMessage(lines[1]); + expect(note.type).toBe('notification'); + expect((note as any).method).toBe('message'); + expect((note as any).params.id).toBe(9); + expect((note as any).params.text).toBe('hello'); + expect(mockAddEventHandler).toHaveBeenCalledWith(expect.any(Function), expect.any(NewMessage)); + + sock.destroy(); + }); + + it('stops cleanly and removes socket', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + await server.stop(); + expect(paths.socketExists()).toBe(false); + }); + + it('calls onIdle after idle timeout stop', async () => { + const onIdle = vi.fn(); + server = new DaemonServer( + paths, + { apiId: 1, apiHash: 'h', sessionString: 's' }, + { idleTimeout: 40, onIdle }, + ); + await server.start(); + await vi.waitFor(() => expect(onIdle).toHaveBeenCalledOnce(), { timeout: 2000 }); + expect(paths.socketExists()).toBe(false); + }); + + it('does not idle-stop while a client is connected', async () => { + const onIdle = vi.fn(); + server = new DaemonServer( + paths, + { apiId: 1, apiHash: 'h', sessionString: 's' }, + { idleTimeout: 40, onIdle }, + ); + await server.start(); + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + await new Promise((r) => setTimeout(r, 80)); + expect(onIdle).not.toHaveBeenCalled(); + expect(paths.socketExists()).toBe(true); + sock.destroy(); + }); + + it('stop() is safe to call concurrently', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + await Promise.all([server.stop(), server.stop()]); + expect(paths.socketExists()).toBe(false); + }); + + it('drops updates with no peer id and matches basic groups as -{id}', async () => { + mockGetEntity.mockResolvedValueOnce({ id: 99, className: 'Chat' }); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + const lines: string[] = []; + sock.on('data', (buf) => { + for (const line of buf.toString().split('\n').filter(Boolean)) lines.push(line); + }); + + sock.write(encodeRequest('subscribe', { chat: 'groupchat' }, 4) + '\n'); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(1)); + + updateHandlers[0]({ message: { id: 1, date: 1, message: 'no-peer' } }); + updateHandlers[0]({ + message: { id: 2, date: 1, message: 'group-hi', peerId: { chatId: 99 } }, + }); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(2)); + + const note = parseMessage(lines[1]); + expect(note.type).toBe('notification'); + expect((note as any).params.id).toBe(2); + expect(lines.length).toBe(2); + + sock.destroy(); + }); + + it('does not replace a live daemon socket', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + const other = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await expect(other.start()).rejects.toThrow(/already running/); + expect(paths.socketExists()).toBe(true); + }); + + it('does not unlink a live socket when the pid file is missing', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + unlinkSync(paths.pidPath); + const other = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await expect(other.start()).rejects.toThrow(/already running/); + expect(paths.socketExists()).toBe(true); + }); + + it('starts when the parent already wrote this process pid', async () => { + expect(paths.writePidExclusive(process.pid)).toBe(true); + server = new DaemonServer( + paths, + { apiId: 1, apiHash: 'h', sessionString: 's' }, + { pidPreclaimed: true }, + ); + await server.start(); + expect(paths.socketExists()).toBe(true); + expect(paths.readPid()).toBe(process.pid); + }); + + it('passes topic-root and General unthreaded messages through --topic', async () => { + mockGetEntity.mockResolvedValue({ id: 42, className: 'User' }); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + + const sock = createConnection(paths.socketPath); + await once(sock, 'connect'); + const lines: string[] = []; + sock.on('data', (buf) => { + for (const line of buf.toString().split('\n').filter(Boolean)) lines.push(line); + }); + + sock.write(encodeRequest('subscribe', { chat: 'alice', topic: 1 }, 5) + '\n'); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(1)); + + const handler = updateHandlers[updateHandlers.length - 1]; + handler({ + message: { id: 1, date: 1, message: 'root', chatId: 42 }, + }); + handler({ + message: { id: 8, date: 1, message: 'general', chatId: 42 }, + }); + handler({ + message: { + id: 12, + date: 1, + message: 'general-reply', + chatId: 42, + replyTo: { replyToMsgId: 8 }, + }, + }); + handler({ + message: { + id: 20, + date: 1, + message: 'other-topic', + chatId: 42, + replyTo: { forumTopic: true, replyToTopId: 9, replyToMsgId: 15 }, + }, + }); + await vi.waitFor(() => expect(lines.length).toBeGreaterThanOrEqual(4)); + + const texts = lines.slice(1).map((line) => { + const note = parseMessage(line); + return (note as any).params.text; + }); + expect(texts).toEqual(['root', 'general', 'general-reply']); + expect(lines.length).toBe(4); + + sock.destroy(); + }); + + it('isolates oversized fragmented frames and keeps subscribers and ping alive', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + const subscriber = createConnection(paths.socketPath); + const seen: string[] = []; + subscriber.on('data', (buf) => seen.push(buf.toString())); + await once(subscriber, 'connect'); + subscriber.write(encodeRequest('subscribe', { chat: 'alice' }, 8) + '\n'); + await vi.waitFor(() => expect(updateHandlers.length).toBe(1)); + + const offender = createConnection(paths.socketPath); + offender.on('error', () => {}); + await once(offender, 'connect'); + const closed = new Promise<void>((resolve) => offender.once('close', () => resolve())); + offender.write(Buffer.alloc(700_000, 120)); + offender.write(Buffer.alloc(400_000, 120)); + await closed; + + updateHandlers[0]({ message: { id: 13, date: 1, message: 'still alive', chatId: 42 } }); + await vi.waitFor(() => expect(seen.join('')).toContain('still alive')); + const healthy = createConnection(paths.socketPath); + await once(healthy, 'connect'); + const reply = once(healthy, 'data'); + healthy.write(encodeRequest('ping', {}, 9) + '\n'); + expect(parseMessage((await reply)[0].toString().trim())).toMatchObject({ type: 'response', result: 'pong', id: 9 }); + healthy.destroy(); + subscriber.destroy(); + }); + + it('contains socket errors raised after connection and preserves the server', async () => { + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + const peer = createConnection(paths.socketPath); + peer.on('error', () => {}); + await once(peer, 'connect'); + await vi.waitFor(() => expect((server as any).sockets.size).toBe(1)); + const socket = [...(server as any).sockets][0] as import('node:net').Socket; + socket.destroy(new Error('Synthetic connection failure')); + await new Promise<void>((resolve) => peer.once('close', () => resolve())); + expect(paths.socketExists()).toBe(true); + }); + + it('does not attach a leaked update handler when subscriber closes during entity resolution', async () => { + let resolveEntity!: (entity: unknown) => void; + mockGetEntity.mockImplementationOnce(() => new Promise((resolve) => { resolveEntity = resolve; })); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await server.start(); + const peer = createConnection(paths.socketPath); + await once(peer, 'connect'); + peer.write(encodeRequest('subscribe', { chat: 'alice' }, 10) + '\n'); + await vi.waitFor(() => expect(mockGetEntity).toHaveBeenCalled()); + peer.destroy(); + await vi.waitFor(() => expect((server as any).sockets.size).toBe(0)); + resolveEntity({ id: 42, className: 'User' }); + await new Promise((resolve) => setImmediate(resolve)); + expect(mockAddEventHandler).not.toHaveBeenCalled(); + }); + + it('releases session ownership after a failed MTProto connection', async () => { + mockConnect.mockRejectedValueOnce(new Error('Cannot connect')); + server = new DaemonServer(paths, { apiId: 1, apiHash: 'h', sessionString: 's' }); + await expect(server.start()).rejects.toThrow('Cannot connect'); + const { SessionStore } = await import('../../src/lib/session-store.js'); + await expect(new SessionStore(tempDir).withLock('test', async () => 'free')).resolves.toBe('free'); + expect(mockDestroy).toHaveBeenCalledOnce(); + }); + +}); diff --git a/cli/tests/unit/daemon-start.test.ts b/cli/tests/unit/daemon-start.test.ts new file mode 100644 index 0000000..d95c94b --- /dev/null +++ b/cli/tests/unit/daemon-start.test.ts @@ -0,0 +1,184 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockOutputError = vi.fn(); +const mockOutputSuccess = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ path: '/tmp/mock-config.json', get: vi.fn() })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 1, apiHash: 'h' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + load: vi.fn().mockResolvedValue('session'), + })), +})); + +const mockCall = vi.fn(); +vi.mock('../../src/lib/daemon/client.js', () => ({ + DaemonClient: vi.fn().mockImplementation(() => ({ + call: mockCall, + close: vi.fn(), + })), +})); + +const mockReadPid = vi.fn(); +const mockSocketExists = vi.fn(); +const mockCleanup = vi.fn(); +const mockWritePidExclusive = vi.fn(() => true); +const mockCleanupOwned = vi.fn(); +vi.mock('../../src/lib/daemon/pid.js', () => ({ + DaemonPaths: vi.fn().mockImplementation(() => ({ + readPid: mockReadPid, + socketExists: mockSocketExists, + cleanup: mockCleanup, + writePidExclusive: mockWritePidExclusive, + cleanupOwned: mockCleanupOwned, + socketPath: '/tmp/mock.sock', + })), +})); + +const mockIsProcessAlive = vi.fn(); +const mockWaitWhile = vi.fn().mockResolvedValue(true); +vi.mock('../../src/lib/daemon/lifecycle.js', () => ({ + isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args), + waitWhile: (...args: any[]) => mockWaitWhile(...args), + daemonChildEnv: vi.fn(), + installDaemonSignals: vi.fn(), +})); + +vi.mock('../../src/lib/daemon/entry-path.js', () => ({ + resolveDaemonEntry: vi.fn(() => '/tmp/entry.js'), +})); + +const mockFork = vi.fn(); +vi.mock('node:child_process', () => ({ + fork: (...args: any[]) => mockFork(...args), +})); + +import { daemonStartAction } from '../../src/commands/daemon/start.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +function ctx(extra: Record<string, unknown> = {}) { + return { + optsWithGlobals: () => ({ profile: 'default', quiet: true, config: undefined, ...extra }), + }; +} + +describe('daemonStartAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockSocketExists.mockReturnValue(false); + mockReadPid.mockReturnValue(null); + mockIsProcessAlive.mockReturnValue(false); + }); + + it('aborts when ping fails but the pid is still alive', async () => { + mockSocketExists.mockReturnValue(true); + mockCall.mockRejectedValue(new Error('timeout')); + mockReadPid.mockReturnValue(4242); + mockIsProcessAlive.mockReturnValue(true); + + await daemonStartAction.call(ctx() as any); + + expect(mockCleanup).not.toHaveBeenCalled(); + expect(mockFork).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('not responding'), + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + }); + + it.each(['tcp', 'wss'])('passes %s to the child and reports success only after ping', async transport => { + mockSocketExists + .mockReturnValueOnce(false) + .mockReturnValue(true); + mockCall.mockResolvedValue('pong'); + mockReadPid.mockReturnValue(77); + const child = { pid: 99, connected: true, disconnect: vi.fn(), unref: vi.fn() }; + mockFork.mockReturnValue(child); + + await daemonStartAction.call(ctx({ transport }) as any); + + const { daemonChildEnv } = await import('../../src/lib/daemon/lifecycle.js'); + expect(daemonChildEnv).toHaveBeenCalledWith(expect.objectContaining({ transport })); + + expect(mockWritePidExclusive).toHaveBeenCalledWith(99); + expect(child.disconnect).toHaveBeenCalledOnce(); + expect(child.disconnect.mock.invocationCallOrder[0]).toBeLessThan(child.unref.mock.invocationCallOrder[0]); + expect(mockCall).toHaveBeenCalledWith('ping', {}, { timeoutMs: 1000 }); + expect(mockOutputSuccess).toHaveBeenCalledWith({ + pid: 77, + socket: '/tmp/mock.sock', + profile: 'default', + }); + }); + + it('claims the pid file before waiting for pong', async () => { + const order: string[] = []; + mockWritePidExclusive.mockImplementation(() => { + order.push('pid'); + return true; + }); + let socketChecks = 0; + mockSocketExists.mockImplementation(() => { + socketChecks++; + if (socketChecks === 1) return false; + order.push('socket'); + return true; + }); + mockCall.mockImplementation(async () => { + order.push('ping'); + return 'pong'; + }); + mockReadPid.mockReturnValue(42); + mockFork.mockReturnValue({ pid: 42, unref: vi.fn() }); + + await daemonStartAction.call(ctx() as any); + + expect(order[0]).toBe('pid'); + expect(order).toContain('ping'); + }); + + it('kills the child and cleans owned files when ping never arrives', async () => { + vi.useFakeTimers(); + mockSocketExists.mockReturnValue(false); + mockFork.mockReturnValue({ pid: 88, unref: vi.fn() }); + mockWritePidExclusive.mockReturnValue(true); + mockIsProcessAlive.mockReturnValue(false); + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any); + + try { + const pending = daemonStartAction.call(ctx() as any); + await vi.advanceTimersByTimeAsync(10_500); + await pending; + expect(killSpy).toHaveBeenCalledWith(88, 'SIGTERM'); + expect(mockCleanupOwned).toHaveBeenCalledWith(88); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon failed to start within 10 seconds', + ErrorCode.DAEMON_START_FAILED, + ); + } finally { + killSpy.mockRestore(); + vi.useRealTimers(); + } + }); + + it('errors DAEMON_ALREADY_RUNNING when the socket already pongs', async () => { + mockSocketExists.mockReturnValue(true); + mockCall.mockResolvedValue('pong'); + + await daemonStartAction.call(ctx() as any); + + expect(mockFork).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon is already running', + ErrorCode.DAEMON_ALREADY_RUNNING, + ); + }); +}); diff --git a/cli/tests/unit/daemon-stop.test.ts b/cli/tests/unit/daemon-stop.test.ts new file mode 100644 index 0000000..0001120 --- /dev/null +++ b/cli/tests/unit/daemon-stop.test.ts @@ -0,0 +1,168 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ path: '/tmp/mock-config.json' })), +})); + +const mockCall = vi.fn(); +const mockClose = vi.fn(); +vi.mock('../../src/lib/daemon/client.js', () => ({ + DaemonClient: vi.fn().mockImplementation(() => ({ + call: mockCall, + close: mockClose, + })), +})); + +const mockReadPid = vi.fn(); +const mockSocketExists = vi.fn(); +const mockCleanup = vi.fn(); +vi.mock('../../src/lib/daemon/pid.js', () => ({ + DaemonPaths: vi.fn().mockImplementation(() => ({ + readPid: mockReadPid, + socketExists: mockSocketExists, + cleanup: mockCleanup, + socketPath: '/tmp/mock.sock', + })), +})); + +const mockIsProcessAlive = vi.fn(); +const mockWaitWhile = vi.fn().mockResolvedValue(true); +vi.mock('../../src/lib/daemon/lifecycle.js', () => ({ + isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args), + waitWhile: (...args: any[]) => mockWaitWhile(...args), +})); + +import { daemonStopAction } from '../../src/commands/daemon/stop.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +function ctx() { + return { + optsWithGlobals: () => ({ profile: 'default', quiet: true, config: undefined }), + }; +} + +describe('daemonStopAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockWaitWhile.mockResolvedValue(true); + }); + + it('errors when daemon is not running', async () => { + mockReadPid.mockReturnValue(null); + mockSocketExists.mockReturnValue(false); + + await daemonStopAction.call(ctx() as any); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon is not running', + ErrorCode.DAEMON_NOT_RUNNING, + ); + expect(mockCleanup).not.toHaveBeenCalled(); + }); + + it('waits for the socket after shutdown and does not SIGTERM if it is already gone', async () => { + mockReadPid.mockReturnValue(12345); + mockCall.mockResolvedValue({ shuttingDown: true }); + mockIsProcessAlive.mockReturnValue(false); + mockSocketExists + .mockReturnValueOnce(true) + .mockReturnValueOnce(false); + + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any); + try { + await daemonStopAction.call(ctx() as any); + expect(mockCall).toHaveBeenCalledWith('shutdown', {}); + expect(mockWaitWhile).toHaveBeenCalled(); + expect(killSpy).not.toHaveBeenCalled(); + expect(mockCleanup).toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledWith({ stopped: true, profile: 'default' }); + } finally { + killSpy.mockRestore(); + } + }); + + it('sends SIGTERM when the process is alive even if the socket is gone', async () => { + mockReadPid.mockReturnValue(12345); + mockSocketExists.mockReturnValue(false); + mockIsProcessAlive.mockReturnValue(true); + + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any); + try { + await daemonStopAction.call(ctx() as any); + expect(killSpy).toHaveBeenCalledWith(12345, 'SIGTERM'); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon did not stop (process still running)', + ErrorCode.DAEMON_STOP_FAILED, + ); + expect(mockCleanup).not.toHaveBeenCalled(); + } finally { + killSpy.mockRestore(); + } + }); + + it('does not unlink a socket that still answers ping when pid file is missing', async () => { + mockReadPid.mockReturnValue(null); + mockSocketExists.mockReturnValue(true); + mockIsProcessAlive.mockReturnValue(false); + mockCall + .mockRejectedValueOnce(new Error('shutdown failed')) + .mockResolvedValueOnce('pong'); + + await daemonStopAction.call(ctx() as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('still accepting'), + ErrorCode.DAEMON_STOP_FAILED, + ); + expect(mockCleanup).not.toHaveBeenCalled(); + }); + + it('does not cleanup when a successor already rewrote the pid file', async () => { + mockReadPid + .mockReturnValueOnce(12345) + .mockReturnValue(99999); + mockSocketExists.mockReturnValue(false); + mockIsProcessAlive + .mockReturnValueOnce(true) + .mockReturnValue(false); + + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any); + try { + await daemonStopAction.call(ctx() as any); + expect(killSpy).toHaveBeenCalledWith(12345, 'SIGTERM'); + expect(mockCleanup).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledWith({ stopped: true, profile: 'default' }); + } finally { + killSpy.mockRestore(); + } + }); + + it('does not unlink the socket while the process is still alive', async () => { + mockReadPid.mockReturnValue(12345); + mockSocketExists.mockReturnValue(true); + mockCall.mockRejectedValue(new Error('unresponsive')); + mockIsProcessAlive.mockReturnValue(true); + + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any); + try { + await daemonStopAction.call(ctx() as any); + expect(killSpy).toHaveBeenCalledWith(12345, 'SIGTERM'); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon did not stop (process still running)', + ErrorCode.DAEMON_STOP_FAILED, + ); + expect(mockCleanup).not.toHaveBeenCalled(); + } finally { + killSpy.mockRestore(); + } + }); +}); diff --git a/cli/tests/unit/dialog-scan-fixture.ts b/cli/tests/unit/dialog-scan-fixture.ts new file mode 100644 index 0000000..a619fbc --- /dev/null +++ b/cli/tests/unit/dialog-scan-fixture.ts @@ -0,0 +1,11 @@ +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +export function dialogPage(start: number, length: number, slice = false) { + const users = Array.from({ length }, (_, i) => new Api.User({ id: bigInt(start + i), accessHash: bigInt(987654321), firstName: 'Fixture', contact: true })); + const dialogs = users.map((u, i) => new Api.Dialog({ peer: new Api.PeerUser({ userId: u.id }), topMessage: start + i, + readInboxMaxId: 0, readOutboxMaxId: 0, unreadCount: 0, unreadMentionsCount: 0, unreadReactionsCount: 0, + notifySettings: new Api.PeerNotifySettings({}), pts: 0 })); + const messages = dialogs.map(d => new Api.Message({ id: d.topMessage, peerId: d.peer, date: 1700000000 - d.topMessage, message: 'PRIVATE BODY' })); + const args = { users, chats: [], dialogs, messages }; + return slice ? new Api.messages.DialogsSlice({ ...args, count: 1000 }) : new Api.messages.Dialogs(args); +} diff --git a/cli/tests/unit/dialog-scan.test.ts b/cli/tests/unit/dialog-scan.test.ts new file mode 100644 index 0000000..70d6221 --- /dev/null +++ b/cli/tests/unit/dialog-scan.test.ts @@ -0,0 +1,72 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { Api } from 'teleproto'; +import { scanDialogs } from '../../src/commands/bridge/dialog-scan.js'; +import { runOrganize } from '../../src/commands/bridge/organize.js'; +import { dialogPage } from './dialog-scan-fixture.js'; + +afterEach(() => vi.useRealTimers()); +describe('resumable dialog metadata', () => { + it('continues with server offsets, includes pins/archive, reuses collected pages', async () => { + const first = dialogPage(1, 100, true); first.dialogs[0].pinned = true; first.dialogs[0].folderId = 1; + const c = { invoke: vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce(dialogPage(101, 2)) }; + const a = await scanDialogs(c as any, 'main', 100); + const b = await scanDialogs(c as any, 'main', 200, a.cursor); + expect(b.rows).toHaveLength(102); expect(b.complete).toBe(true); + expect(b.rows[0]).toMatchObject({ pinned: true, archived: true }); + expect(c.invoke.mock.calls[1][0]).toMatchObject({ offsetId: 100, offsetDate: 1699999900, excludePinned: true }); + expect(c.invoke.mock.calls[1][0].offsetPeer).toBeInstanceOf(Api.InputPeerUser); + await scanDialogs(c as any, 'main', 200, a.cursor); + expect(c.invoke).toHaveBeenCalledTimes(2); + expect(JSON.stringify(b)).not.toMatch(/987654321|PRIVATE BODY|accessHash/); + }); + it('preserves progress at FloodWait and enforces cooldown even with refresh', async () => { + vi.useFakeTimers(); + const c = { invoke: vi.fn().mockResolvedValueOnce(dialogPage(1, 100, true)) + .mockRejectedValueOnce(Object.assign(new Error('FLOOD_WAIT_27'), { seconds: 27 })) + .mockResolvedValueOnce(dialogPage(101, 1)) }; + const a = await scanDialogs(c as any, 'main', 200); + expect(a.scanned).toBe(100); expect(a.retry_after_seconds).toBe(27); expect(a.complete).toBe(false); + const waiting = await scanDialogs(c as any, 'main', 200, a.cursor); + expect(waiting.scanned).toBe(100); + await scanDialogs(c as any, 'main', 200, undefined, true); + expect(c.invoke).toHaveBeenCalledTimes(2); + vi.advanceTimersByTime(27000); + const b = await scanDialogs(c as any, 'main', 200, a.cursor); + expect(b.complete).toBe(true); expect(b.scanned).toBe(101); + expect(c.invoke.mock.calls[2][0].offsetId).toBe(100); + }); + it('bounds each call and rejects cross-account/session and expired cursors', async () => { + vi.useFakeTimers(); let start = 1; + const c = { invoke: vi.fn(async () => { const r = dialogPage(start, 100, true); start += 100; return r; }) }; + const a = await scanDialogs(c as any, 'main', 10000); + expect(a.scanned).toBe(500); expect(a.complete).toBe(false); expect(c.invoke).toHaveBeenCalledTimes(5); + await expect(scanDialogs(c as any, 'reserve', 100, a.cursor)).rejects.toThrow('expired'); + await expect(scanDialogs({ invoke: c.invoke } as any, 'main', 100, a.cursor)).rejects.toThrow('expired'); + vi.advanceTimersByTime(31 * 60000); + await expect(scanDialogs(c as any, 'main', 100, a.cursor)).rejects.toThrow('expired'); + }); + it('shares state across request views of one session; deduplicates moving rows', async () => { + const session = {}, invoke = vi.fn().mockResolvedValueOnce(dialogPage(1, 100, true)).mockResolvedValueOnce(dialogPage(100, 2)); + const a = await scanDialogs({ session, invoke } as any, 'main', 100); + const b = await scanDialogs({ session, invoke } as any, 'main', 200, a.cursor); + expect(b.scanned).toBe(101); + }); + it('does not retry unknown failures and rejects stalled cursors', async () => { + const c = { invoke: vi.fn().mockRejectedValue(new Error('TIMEOUT')) }; + await expect(scanDialogs(c as any, 'main', 100)).rejects.toThrow('TIMEOUT'); + expect(c.invoke).toHaveBeenCalledOnce(); + c.invoke.mockResolvedValue(dialogPage(1, 100, true)); + await expect(scanDialogs(c as any, 'main', 200)).rejects.toThrow('did not advance'); + }); + it('legacy offset pages and audits share one snapshot; inherited mute is resolved', async () => { + const c = { invoke: vi.fn().mockResolvedValueOnce(dialogPage(1, 100, true)).mockResolvedValueOnce(dialogPage(101, 2)), + getDialogFilters: vi.fn(async () => ({ filters: [], tagsEnabled: false })), + getNotifySettings: vi.fn(async () => ({ muteUntil: 2147483647 })) }; + const first: any = await runOrganize(c as any, { action: 'dialogs', account: 'main', limit: 100 }); + const second: any = await runOrganize(c as any, { action: 'dialogs', account: 'main', limit: 100, offset: 100 }); + expect(second.chats).toHaveLength(2); expect(second.has_more).toBe(false); + const audit: any = await runOrganize(c as any, { action: 'audit', account: 'main', scan_limit: 200, cursor: first.cursor }); + expect(audit.complete).toBe(true); expect(audit.chats[0].muted).toBe(true); + expect(c.invoke).toHaveBeenCalledTimes(2); + }); +}); diff --git a/cli/tests/unit/entity-map.test.ts b/cli/tests/unit/entity-map.test.ts new file mode 100644 index 0000000..9374ed6 --- /dev/null +++ b/cli/tests/unit/entity-map.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect } from 'vitest'; +import { buildEntityMap } from '../../src/lib/entity-map.js'; + +describe('buildEntityMap', () => { + it('builds map from users and chats arrays', () => { + const result = { + users: [ + { id: { toString: () => '100' }, firstName: 'Alice' }, + { id: { toString: () => '200' }, firstName: 'Bob' }, + ], + chats: [ + { id: { toString: () => '300' }, title: 'Group', className: 'Chat' }, + ], + }; + + const map = buildEntityMap(result); + expect(map.size).toBe(3); + expect(map.get('100')?.firstName).toBe('Alice'); + expect(map.get('200')?.firstName).toBe('Bob'); + expect(map.get('-300')?.title).toBe('Group'); + }); + + it('handles undefined users', () => { + const result = { chats: [{ id: { toString: () => '1' }, title: 'C', className: 'Channel' }] }; + const map = buildEntityMap(result); + expect(map.size).toBe(1); + expect(map.get('-1001')?.title).toBe('C'); + }); + + it('handles undefined chats', () => { + const result = { users: [{ id: { toString: () => '1' }, firstName: 'A' }] }; + const map = buildEntityMap(result); + expect(map.size).toBe(1); + expect(map.get('1')?.firstName).toBe('A'); + }); + + it('handles both undefined', () => { + const map = buildEntityMap({}); + expect(map.size).toBe(0); + }); + + it('handles empty arrays', () => { + const map = buildEntityMap({ users: [], chats: [] }); + expect(map.size).toBe(0); + }); + + it('uses BigInteger-style id.toString()', () => { + const bigIntLike = { toString: () => '9007199254740993' }; + const result = { + users: [{ id: bigIntLike, firstName: 'Big' }], + }; + const map = buildEntityMap(result); + expect(map.has('9007199254740993')).toBe(true); + }); + + it('keeps users, chats and channels with the same raw ID distinct', () => { + const result = { + users: [{ id: { toString: () => '1' }, firstName: 'User' }], + chats: [{ id: { toString: () => '1' }, title: 'Chat', className: 'Chat' }, { id: { toString: () => '1' }, title: 'Channel', className: 'Channel' }], + }; + const map = buildEntityMap(result); + expect(map.size).toBe(3); + expect(map.get('1')?.firstName).toBe('User'); + expect(map.get('-1')?.title).toBe('Chat'); + expect(map.get('-1001')?.title).toBe('Channel'); + }); +}); diff --git a/cli/tests/unit/entity-markdown.test.ts b/cli/tests/unit/entity-markdown.test.ts new file mode 100644 index 0000000..a9eecc3 --- /dev/null +++ b/cli/tests/unit/entity-markdown.test.ts @@ -0,0 +1,149 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Mock telegram Api classes for entity type checking (instanceof) +const { + MockBold, MockItalic, MockCode, MockPre, MockTextUrl, MockStrike, + MockBlockquote, MockMentionName, MockSpoiler, MockUnderline, MockCustomEmoji, +} = vi.hoisted(() => { + class MockBold { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockItalic { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockCode { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockPre { offset: number; length: number; language: string; constructor(args: any) { this.offset = args.offset; this.length = args.length; this.language = args.language ?? ''; } } + class MockTextUrl { offset: number; length: number; url: string; constructor(args: any) { this.offset = args.offset; this.length = args.length; this.url = args.url; } } + class MockStrike { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockBlockquote { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockMentionName { offset: number; length: number; userId: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; this.userId = args.userId; } } + class MockSpoiler { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockUnderline { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockCustomEmoji { offset: number; length: number; documentId: string; constructor(args: any) { this.offset = args.offset; this.length = args.length; this.documentId = args.documentId; } } + return { + MockBold, MockItalic, MockCode, MockPre, MockTextUrl, MockStrike, + MockBlockquote, MockMentionName, MockSpoiler, MockUnderline, MockCustomEmoji, + }; +}); + +vi.mock('teleproto', () => ({ + Api: { + MessageEntityBold: MockBold, + MessageEntityItalic: MockItalic, + MessageEntityCode: MockCode, + MessageEntityPre: MockPre, + MessageEntityTextUrl: MockTextUrl, + MessageEntityStrike: MockStrike, + MessageEntityBlockquote: MockBlockquote, + MessageEntityMentionName: MockMentionName, + MessageEntitySpoiler: MockSpoiler, + MessageEntityUnderline: MockUnderline, + MessageEntityCustomEmoji: MockCustomEmoji, + }, +})); + +import { entitiesToMarkdown } from '../../src/lib/entity-to-markdown.js'; + +describe('entitiesToMarkdown', () => { + it('returns text unchanged when entities is undefined', () => { + const result = entitiesToMarkdown('Hello world', undefined); + expect(result).toBe('Hello world'); + }); + + it('returns text unchanged when entities array is empty', () => { + const result = entitiesToMarkdown('Hello world', []); + expect(result).toBe('Hello world'); + }); + + it('converts bold entity to **text**', () => { + const entities = [new MockBold({ offset: 0, length: 5 })]; + const result = entitiesToMarkdown('Hello world', entities as any); + expect(result).toBe('**Hello** world'); + }); + + it('converts italic entity to _text_', () => { + const entities = [new MockItalic({ offset: 6, length: 5 })]; + const result = entitiesToMarkdown('Hello world', entities as any); + expect(result).toBe('Hello _world_'); + }); + + it('converts code entity to `text`', () => { + const entities = [new MockCode({ offset: 4, length: 3 })]; + const result = entitiesToMarkdown('Use foo here', entities as any); + expect(result).toBe('Use `foo` here'); + }); + + it('converts pre entity to ```lang\\ntext\\n```', () => { + const entities = [new MockPre({ offset: 0, length: 13, language: 'js' })]; + const result = entitiesToMarkdown('console.log()', entities as any); + expect(result).toBe('```js\nconsole.log()\n```'); + }); + + it('converts pre entity with no language', () => { + const entities = [new MockPre({ offset: 0, length: 5, language: '' })]; + const result = entitiesToMarkdown('hello', entities as any); + expect(result).toBe('```\nhello\n```'); + }); + + it('converts text url entity to [text](url)', () => { + const entities = [new MockTextUrl({ offset: 6, length: 4, url: 'https://example.com' })]; + const result = entitiesToMarkdown('Click here now', entities as any); + expect(result).toBe('Click [here](https://example.com) now'); + }); + + it('converts strikethrough entity to ~~text~~', () => { + const entities = [new MockStrike({ offset: 0, length: 4 })]; + const result = entitiesToMarkdown('done task', entities as any); + expect(result).toBe('~~done~~ task'); + }); + + it('converts blockquote entity to > text', () => { + const entities = [new MockBlockquote({ offset: 0, length: 12 })]; + const result = entitiesToMarkdown('quoted text.', entities as any); + expect(result).toBe('> quoted text.'); + }); + + it('converts multiline blockquote with > prefix on each line', () => { + const entities = [new MockBlockquote({ offset: 0, length: 11 })]; + const result = entitiesToMarkdown('line1\nline2', entities as any); + expect(result).toBe('> line1\n> line2'); + }); + + it('converts mention name entity to [text](tg://user?id=ID)', () => { + const entities = [new MockMentionName({ offset: 0, length: 4, userId: 12345 })]; + const result = entitiesToMarkdown('John said hi', entities as any); + expect(result).toBe('[John](tg://user?id=12345) said hi'); + }); + + it('handles multiple entities in same text (process from end to avoid offset shifts)', () => { + const entities = [ + new MockBold({ offset: 0, length: 5 }), + new MockItalic({ offset: 6, length: 5 }), + ]; + const result = entitiesToMarkdown('Hello world', entities as any); + expect(result).toBe('**Hello** _world_'); + }); + + it('handles adjacent entities correctly', () => { + const entities = [ + new MockBold({ offset: 0, length: 3 }), + new MockItalic({ offset: 3, length: 3 }), + ]; + const result = entitiesToMarkdown('abcdef', entities as any); + expect(result).toBe('**abc**_def_'); + }); + + it('converts spoiler entity to ||text||', () => { + const entities = [new MockSpoiler({ offset: 0, length: 6 })]; + const result = entitiesToMarkdown('secret revealed', entities as any); + expect(result).toBe('||secret|| revealed'); + }); + + it('converts underline entity to <u>text</u>', () => { + const entities = [new MockUnderline({ offset: 0, length: 4 })]; + const result = entitiesToMarkdown('note this', entities as any); + expect(result).toBe('<u>note</u> this'); + }); + + it('converts custom emoji to a tg://emoji markdown image', () => { + const entities = [new MockCustomEmoji({ offset: 0, length: 2, documentId: '99' })]; + const result = entitiesToMarkdown('👋 hi', entities as any); + expect(result).toBe('![👋](tg://emoji?id=99) hi'); + }); +}); diff --git a/cli/tests/unit/error-codes.test.ts b/cli/tests/unit/error-codes.test.ts new file mode 100644 index 0000000..b7f17d2 --- /dev/null +++ b/cli/tests/unit/error-codes.test.ts @@ -0,0 +1,21 @@ +import { describe, it, expect } from 'vitest'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +describe('ErrorCode', () => { + it('exports NOT_AUTHENTICATED constant', () => { + expect(ErrorCode.NOT_AUTHENTICATED).toBe('NOT_AUTHENTICATED'); + }); + + it('exports all expected codes as frozen object', () => { + expect(Object.isFrozen(ErrorCode)).toBe(true); + expect(typeof ErrorCode.PEER_NOT_FOUND).toBe('string'); + expect(typeof ErrorCode.TIMEOUT).toBe('string'); + expect(typeof ErrorCode.NOT_A_FORUM).toBe('string'); + }); + + it('has values equal to keys (convention)', () => { + for (const [key, value] of Object.entries(ErrorCode)) { + expect(value).toBe(key); + } + }); +}); diff --git a/cli/tests/unit/errors.test.ts b/cli/tests/unit/errors.test.ts new file mode 100644 index 0000000..dfea258 --- /dev/null +++ b/cli/tests/unit/errors.test.ts @@ -0,0 +1,121 @@ +import { describe, it, expect } from 'vitest'; +import { translateTelegramError, formatError, TgError } from '../../src/lib/errors.js'; + +describe('translateTelegramError', () => { + it('reports profile lock contention with an actionable session error', () => { + const error = Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED' }); + expect(translateTelegramError(error)).toEqual({ + message: 'Session profile is busy. Wait for the running command or stop its daemon.', + code: 'SESSION_ERROR', + }); + expect(formatError(error).code).toBe('SESSION_ERROR'); + }); + // Known RPCError mappings + it('maps MESSAGE_EDIT_TIME_EXPIRED to human-readable message', () => { + const err = { errorMessage: 'MESSAGE_EDIT_TIME_EXPIRED' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Cannot edit: 48-hour edit window has expired', + code: 'MESSAGE_EDIT_TIME_EXPIRED', + }); + }); + + it('maps MESSAGE_AUTHOR_REQUIRED to human-readable message', () => { + const err = { errorMessage: 'MESSAGE_AUTHOR_REQUIRED' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Cannot edit: you can only edit your own messages', + code: 'MESSAGE_AUTHOR_REQUIRED', + }); + }); + + it('maps MESSAGE_DELETE_FORBIDDEN to human-readable message', () => { + const err = { errorMessage: 'MESSAGE_DELETE_FORBIDDEN' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Cannot delete this message', + code: 'MESSAGE_DELETE_FORBIDDEN', + }); + }); + + it('maps CHAT_ADMIN_REQUIRED to human-readable message', () => { + const err = { errorMessage: 'CHAT_ADMIN_REQUIRED' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Admin privileges required', + code: 'CHAT_ADMIN_REQUIRED', + }); + }); + + it('maps MESSAGE_ID_INVALID to human-readable message', () => { + const err = { errorMessage: 'MESSAGE_ID_INVALID' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Message not found', + code: 'MESSAGE_ID_INVALID', + }); + }); + + it('maps MESSAGE_NOT_MODIFIED to human-readable message', () => { + const err = { errorMessage: 'MESSAGE_NOT_MODIFIED' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Message content unchanged', + code: 'MESSAGE_NOT_MODIFIED', + }); + }); + + it('maps PREMIUM_ACCOUNT_REQUIRED for public search', () => { + const err = { errorMessage: 'PREMIUM_ACCOUNT_REQUIRED' }; + expect(translateTelegramError(err)).toEqual({ + message: 'Telegram Premium is required for this search', + code: 'PREMIUM_ACCOUNT_REQUIRED', + }); + }); + + it('maps PEER_ID_INVALID to human-readable message', () => { + const err = { errorMessage: 'PEER_ID_INVALID' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Peer not found', + code: 'PEER_ID_INVALID', + }); + }); + + // Unknown RPCError passthrough + it('passes through unknown RPCError errorMessage as both message and code', () => { + const err = { errorMessage: 'SOME_UNKNOWN_ERROR' }; + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'SOME_UNKNOWN_ERROR', + code: 'SOME_UNKNOWN_ERROR', + }); + }); + + // Non-RPCError fallback to formatError + it('falls back to formatError for non-RPCError Error instances', () => { + const err = new Error('Connection failed'); + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Connection failed', + code: 'UNKNOWN_ERROR', + }); + }); + + it('falls back to formatError for TgError instances', () => { + const err = new TgError('Session expired', 'SESSION_ERROR'); + const result = translateTelegramError(err); + expect(result).toEqual({ + message: 'Session expired', + code: 'SESSION_ERROR', + }); + }); + + it('falls back to formatError for plain string errors', () => { + const result = translateTelegramError('something broke'); + expect(result).toEqual({ + message: 'something broke', + code: 'UNKNOWN_ERROR', + }); + }); +}); diff --git a/cli/tests/unit/fields.test.ts b/cli/tests/unit/fields.test.ts new file mode 100644 index 0000000..835d3cf --- /dev/null +++ b/cli/tests/unit/fields.test.ts @@ -0,0 +1,196 @@ +import { describe, it, expect } from 'vitest'; +import { pickFields, applyFieldSelection, extractListItems } from '../../src/lib/fields.js'; + +describe('pickFields', () => { + it('does not traverse or write prototype-related fields', () => { + const source = JSON.parse('{"__proto__":{"tgReviewMarker":true},"constructor":{"prototype":{"tgReviewMarker":true}},"nested":{"prototype":{"tgReviewMarker":true}}}'); + try { + expect(pickFields(source, ['__proto__.tgReviewMarker', 'constructor.prototype.tgReviewMarker', 'nested.prototype.tgReviewMarker'])).toEqual({}); + expect(({} as Record<string, unknown>).tgReviewMarker).toBeUndefined(); + } finally { + delete (Object.prototype as Record<string, unknown>).tgReviewMarker; + } + }); + + it('selects only own source properties', () => { + const source = Object.assign(Object.create({ inherited: { id: 7 } }), { id: 42 }); + expect(pickFields(source, ['id', 'inherited.id', 'toString'])).toEqual({ id: 42 }); + }); + it('picks flat fields from an object', () => { + const result = pickFields({ id: 1, text: 'hi', date: '2026-01-01' }, ['id', 'text']); + expect(result).toEqual({ id: 1, text: 'hi' }); + }); + + it('picks dot-notation nested fields', () => { + const obj = { id: 1, media: { filename: 'a.jpg', fileSize: 100 } }; + const result = pickFields(obj, ['id', 'media.filename']); + expect(result).toEqual({ id: 1, media: { filename: 'a.jpg' } }); + }); + + it('silently omits nonexistent fields', () => { + const result = pickFields({ id: 1, text: 'hi' }, ['nonexistent']); + expect(result).toEqual({}); + }); + + it('handles missing intermediate paths without crashing', () => { + const result = pickFields({ id: 1 }, ['nested.deep.field']); + expect(result).toEqual({}); + }); + + it('picks multiple flat fields', () => { + const result = pickFields({ a: 1, b: 2, c: 3 }, ['a', 'c']); + expect(result).toEqual({ a: 1, c: 3 }); + }); + + it('returns empty object when fields array is empty', () => { + const result = pickFields({ id: 1, text: 'hi' }, []); + expect(result).toEqual({}); + }); + + it('picks deeply nested dot-notation fields', () => { + const obj = { a: { b: { c: { d: 42 } } } }; + const result = pickFields(obj, ['a.b.c.d']); + expect(result).toEqual({ a: { b: { c: { d: 42 } } } }); + }); + + it('handles null values at intermediate paths', () => { + const obj = { a: null } as Record<string, unknown>; + const result = pickFields(obj, ['a.b']); + expect(result).toEqual({}); + }); +}); + +describe('applyFieldSelection', () => { + it('does not copy prototype-related list metadata', () => { + const source = JSON.parse('{"messages":[{"id":42}],"__proto__":{"tgReviewMarker":true}}'); + const result = applyFieldSelection(source, ['id']); + expect(result).toEqual({ messages: [{ id: 42 }] }); + expect(Object.getPrototypeOf(result)).toBe(Object.prototype); + }); + it('filters array items and preserves metadata', () => { + const data = { + messages: [{ id: 1, text: 'hi', date: '2026-01-01' }], + total: 5, + }; + const result = applyFieldSelection(data, ['id']); + expect(result).toEqual({ messages: [{ id: 1 }], total: 5 }); + }); + + it('preserves non-array data with field filtering on scalar entries', () => { + const data = { status: 'ok' }; + const result = applyFieldSelection(data, ['status']); + expect(result).toEqual({ status: 'ok' }); + }); + + it('returns null unchanged', () => { + const result = applyFieldSelection(null, ['id']); + expect(result).toBeNull(); + }); + + it('returns non-object unchanged', () => { + const result = applyFieldSelection('hello', ['id']); + expect(result).toBe('hello'); + }); + + it('preserves multiple metadata fields', () => { + const data = { + messages: [{ id: 1, text: 'hi' }], + total: 10, + count: 1, + }; + const result = applyFieldSelection(data, ['id']); + expect(result).toEqual({ messages: [{ id: 1 }], total: 10, count: 1 }); + }); + + it('handles multiple list items', () => { + const data = { + chats: [ + { id: '1', title: 'Chat 1', type: 'group' }, + { id: '2', title: 'Chat 2', type: 'channel' }, + ], + total: 2, + }; + const result = applyFieldSelection(data, ['id', 'title']); + expect(result).toEqual({ + chats: [ + { id: '1', title: 'Chat 1' }, + { id: '2', title: 'Chat 2' }, + ], + total: 2, + }); + }); + + it('filters single-object output (e.g., MessageItem from message send)', () => { + const data = { id: 42, text: 'hello', date: '2026-01-01', senderId: '123', mediaType: null }; + const result = applyFieldSelection(data, ['id', 'text']); + expect(result).toEqual({ id: 42, text: 'hello' }); + }); + + it('filters single-object with dot-notation fields', () => { + const data = { id: 1, media: { filename: 'a.jpg', fileSize: 100 }, text: 'caption' }; + const result = applyFieldSelection(data, ['id', 'media.filename']); + expect(result).toEqual({ id: 1, media: { filename: 'a.jpg' } }); + }); + + it('filters DownloadResult single object', () => { + const data = { path: '/tmp/photo.jpg', filename: 'photo.jpg', size: 1024, mediaType: 'photo', messageId: 42 }; + const result = applyFieldSelection(data, ['path', 'filename']); + expect(result).toEqual({ path: '/tmp/photo.jpg', filename: 'photo.jpg' }); + }); +}); + +describe('extractListItems', () => { + it('extracts messages array', () => { + const msg1 = { id: 1, text: 'a' }; + const msg2 = { id: 2, text: 'b' }; + expect(extractListItems({ messages: [msg1, msg2] })).toEqual([msg1, msg2]); + }); + + it('extracts chats array', () => { + const c1 = { id: '1', title: 'Chat' }; + expect(extractListItems({ chats: [c1] })).toEqual([c1]); + }); + + it('extracts members array', () => { + const m1 = { id: '1', username: 'alice' }; + expect(extractListItems({ members: [m1] })).toEqual([m1]); + }); + + it('extracts topics array', () => { + const t1 = { id: 1, title: 'Topic' }; + expect(extractListItems({ topics: [t1] })).toEqual([t1]); + }); + + it('extracts files array', () => { + const f1 = { path: '/tmp/file.txt' }; + expect(extractListItems({ files: [f1] })).toEqual([f1]); + }); + + it('returns null for non-list data', () => { + expect(extractListItems({ status: 'ok' })).toBeNull(); + }); + + it('returns null for null input', () => { + expect(extractListItems(null)).toBeNull(); + }); + + it('returns null for undefined input', () => { + expect(extractListItems(undefined)).toBeNull(); + }); + + it('returns null for non-object input', () => { + expect(extractListItems('hello')).toBeNull(); + }); + + it('extracts posts array (message replies)', () => { + const p = { id: 1, text: 'reply' }; + expect(extractListItems({ posts: [p] })).toEqual([p]); + }); +}); + +describe('applyFieldSelection empty lists', () => { + it('keeps empty messages and total instead of picking the wrapper', () => { + const result = applyFieldSelection({ messages: [], total: 5 }, ['id']); + expect(result).toEqual({ messages: [], total: 5 }); + }); +}); diff --git a/cli/tests/unit/format.test.ts b/cli/tests/unit/format.test.ts new file mode 100644 index 0000000..86283ba --- /dev/null +++ b/cli/tests/unit/format.test.ts @@ -0,0 +1,1069 @@ +import { describe, it, expect } from 'vitest'; +import { vi } from 'vitest'; + +// Mock telegram for media-utils (FILTER_MAP references Api) +vi.mock('teleproto', () => ({ + Api: { + InputMessagesFilterPhotos: class {}, + InputMessagesFilterVideo: class {}, + InputMessagesFilterDocument: class {}, + InputMessagesFilterUrl: class {}, + InputMessagesFilterVoice: class {}, + InputMessagesFilterMusic: class {}, + InputMessagesFilterGif: class {}, + InputMessagesFilterRoundVideo: class {}, + }, +})); + +import { + formatMessages, + formatChatList, + formatChatInfo, + formatMembers, + formatSearchResults, + formatGeneric, + formatData, + formatDownloadResult, + formatUploadResult, + formatGetResult, + formatDeleteResult, + formatPinResult, + formatUserProfile, + formatBlockedList, + formatPoll, +} from '../../src/lib/format.js'; +import type { + MessageItem, + PollData, + ChatListItem, + ChatInfo, + MemberItem, + SearchResultItem, + DownloadResult, + AlbumResult, + DeleteResult, + PinResult, + UserProfile, + BlockedListItem, +} from '../../src/lib/types.js'; + +describe('formatMessages', () => { + it('renders timestamp + sender + text', () => { + const messages: MessageItem[] = [ + { + id: 1, + text: 'Hello world', + date: '2026-03-11T12:30:00.000Z', + senderId: '123', + senderName: 'Alice', + replyToMsgId: null, + forwardFrom: null, + mediaType: null, + type: 'message', + }, + ]; + const result = formatMessages(messages); + // Should contain the sender name and message text + expect(result).toContain('Alice'); + expect(result).toContain('Hello world'); + // Should contain a timestamp pattern (YYYY-MM-DD HH:MM) + expect(result).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/); + }); + + it('shows reply annotation when replyToMsgId is set', () => { + const messages: MessageItem[] = [ + { + id: 2, + text: 'Thanks!', + date: '2026-03-11T12:31:00.000Z', + senderId: '456', + senderName: 'Bob', + replyToMsgId: 42, + forwardFrom: null, + mediaType: null, + type: 'message', + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('reply to 42'); + expect(result).toContain('Bob'); + expect(result).toContain('Thanks!'); + }); + + it('shows media tag when mediaType is set', () => { + const messages: MessageItem[] = [ + { + id: 3, + text: 'Check this out', + date: '2026-03-11T12:32:00.000Z', + senderId: '123', + senderName: 'Alice', + replyToMsgId: null, + forwardFrom: null, + mediaType: 'photo', + type: 'message', + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('[photo]'); + expect(result).toContain('Alice'); + }); + + it('handles empty array', () => { + const result = formatMessages([]); + expect(result).toBe(''); + }); + + it('uses "Unknown" for null sender name', () => { + const messages: MessageItem[] = [ + { + id: 4, + text: 'Mystery message', + date: '2026-03-11T12:33:00.000Z', + senderId: null, + senderName: null, + replyToMsgId: null, + forwardFrom: null, + mediaType: null, + type: 'message', + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('Unknown'); + expect(result).toContain('Mystery message'); + }); +}); + +describe('formatChatList', () => { + it('renders type + title + username + unread', () => { + const chats: ChatListItem[] = [ + { id: '1', title: 'Dev Group', type: 'supergroup', username: 'devs', unreadCount: 5 }, + ]; + const result = formatChatList(chats); + expect(result).toContain('supergroup'); + expect(result).toContain('Dev Group'); + expect(result).toContain('@devs'); + expect(result).toContain('5 unread'); + }); + + it('handles missing username and zero unread', () => { + const chats: ChatListItem[] = [ + { id: '2', title: 'Private Chat', type: 'user', username: null, unreadCount: 0 }, + ]; + const result = formatChatList(chats); + expect(result).toContain('user'); + expect(result).toContain('Private Chat'); + expect(result).not.toContain('unread'); + expect(result).not.toContain('@'); + }); + + it('handles empty array', () => { + const result = formatChatList([]); + expect(result).toBe(''); + }); +}); + +describe('formatChatInfo', () => { + it('renders key-value pairs with labels', () => { + const info: ChatInfo = { + id: '1', + title: 'My Channel', + type: 'channel', + username: 'mychan', + description: 'A test channel', + memberCount: 1234, + creationDate: '2025-01-01', + photo: null, + linkedChatId: null, + slowmodeSeconds: null, + permissions: null, + inviteLink: null, + migratedFrom: null, + }; + const result = formatChatInfo(info); + expect(result).toContain('Title'); + expect(result).toContain('My Channel'); + expect(result).toContain('Type'); + expect(result).toContain('channel'); + expect(result).toContain('Username'); + expect(result).toContain('@mychan'); + expect(result).toContain('Description'); + expect(result).toContain('A test channel'); + expect(result).toContain('Members'); + expect(result).toContain('1,234'); + }); + + it('skips null fields', () => { + const info: ChatInfo = { + id: '1', + title: 'Minimal', + type: 'group', + username: null, + description: null, + memberCount: null, + creationDate: null, + photo: null, + linkedChatId: null, + slowmodeSeconds: null, + permissions: null, + inviteLink: null, + migratedFrom: null, + }; + const result = formatChatInfo(info); + expect(result).toContain('Title'); + expect(result).toContain('Type'); + expect(result).not.toContain('Username'); + expect(result).not.toContain('Description'); + expect(result).not.toContain('Members'); + }); +}); + +describe('formatMembers', () => { + it('renders name + username + bot tag', () => { + const members: MemberItem[] = [ + { id: '1', username: 'alice', firstName: 'Alice', lastName: null, isBot: false, status: null }, + { id: '2', username: 'mybot', firstName: 'My Bot', lastName: null, isBot: true, status: null }, + ]; + const result = formatMembers(members); + expect(result).toContain('Alice'); + expect(result).toContain('@alice'); + expect(result).toContain('My Bot'); + expect(result).toContain('@mybot'); + expect(result).toContain('[bot]'); + }); + + it('handles missing username', () => { + const members: MemberItem[] = [ + { id: '3', username: null, firstName: 'NoUsername', lastName: 'User', isBot: false, status: null }, + ]; + const result = formatMembers(members); + expect(result).toContain('NoUsername'); + expect(result).not.toContain('@'); + }); + + it('handles empty array', () => { + const result = formatMembers([]); + expect(result).toBe(''); + }); +}); + +describe('formatSearchResults', () => { + it('groups messages by chat title', () => { + const results: SearchResultItem[] = [ + { + id: 1, text: 'found this', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + chatId: '100', chatTitle: 'Dev Group', + }, + { + id: 2, text: 'also here', date: '2026-03-11T12:35:00.000Z', + senderId: '456', senderName: 'Bob', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + chatId: '200', chatTitle: 'General Chat', + }, + ]; + const result = formatSearchResults(results); + expect(result).toContain('Dev Group'); + expect(result).toContain('found this'); + expect(result).toContain('General Chat'); + expect(result).toContain('also here'); + }); + + it('handles empty array', () => { + const result = formatSearchResults([]); + expect(result).toBe(''); + }); +}); + +describe('formatGeneric', () => { + it('pretty-prints objects as indented JSON', () => { + const result = formatGeneric({ key: 'value', num: 42 }); + expect(result).toContain('"key"'); + expect(result).toContain('"value"'); + expect(result).toContain('42'); + // Should be indented (multi-line) + expect(result).toContain('\n'); + }); +}); + +describe('formatData', () => { + it('auto-detects message shape and dispatches to formatMessages', () => { + const data = { + messages: [ + { + id: 1, text: 'Hello', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }, + ], + total: 1, + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('Hello'); + }); + + it('auto-detects chat list shape', () => { + const data = { + chats: [ + { id: '1', title: 'Test', type: 'group', username: null, unreadCount: 0 }, + ], + total: 1, + }; + const result = formatData(data); + expect(result).toContain('group'); + expect(result).toContain('Test'); + }); + + it('auto-detects ChatInfo shape', () => { + const data: ChatInfo = { + id: '1', title: 'InfoTest', type: 'channel', username: 'test', + description: null, memberCount: 100, creationDate: null, + photo: null, linkedChatId: null, slowmodeSeconds: null, + permissions: null, inviteLink: null, migratedFrom: null, + }; + const result = formatData(data); + expect(result).toContain('InfoTest'); + expect(result).toContain('channel'); + }); + + it('auto-detects members shape', () => { + const data = { + members: [ + { id: '1', username: 'alice', firstName: 'Alice', lastName: null, isBot: false, status: null }, + ], + total: 1, + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('@alice'); + }); + + it('auto-detects search results shape (messages with chatTitle)', () => { + const data = { + messages: [ + { + id: 1, text: 'found', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + chatId: '100', chatTitle: 'SearchChat', + }, + ], + total: 1, + }; + const result = formatData(data); + expect(result).toContain('SearchChat'); + expect(result).toContain('found'); + }); + + it('auto-detects single MessageItem at top level', () => { + const data: MessageItem = { + id: 99, text: 'Sent!', date: '2026-03-12T06:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('Sent!'); + expect(result).toMatch(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/); + // Should NOT be JSON + expect(result).not.toContain('"id"'); + }); + + it('returns empty-state string for empty messages array', () => { + const result = formatData({ messages: [], total: 0 }); + expect(result).toBe('No messages.'); + }); + + it('returns empty-state string for empty chats array', () => { + const result = formatData({ chats: [], total: 0 }); + expect(result).toBe('No chats.'); + }); + + it('returns empty-state string for empty members array', () => { + const result = formatData({ members: [], total: 0 }); + expect(result).toBe('No members.'); + }); + + it('falls back to formatGeneric for unknown shapes', () => { + const data = { loggedIn: true, phone: '+1234' }; + const result = formatData(data); + expect(result).toContain('"loggedIn"'); + expect(result).toContain('true'); + }); + + it('auto-detects DownloadResult shape', () => { + const data: DownloadResult = { + path: '/tmp/photo_123.jpg', + filename: 'photo_123.jpg', + size: 245760, + mediaType: 'photo', + messageId: 123, + }; + const result = formatData(data); + expect(result).toContain('photo_123.jpg'); + expect(result).toContain('/tmp/photo_123.jpg'); + // Should NOT be raw JSON + expect(result).not.toContain('"path"'); + }); + + it('auto-detects AlbumResult shape', () => { + const data: AlbumResult = { + messages: [ + { + id: 1, text: 'Album photo', date: '2026-03-12T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + }, + ], + sent: 1, + }; + const result = formatData(data); + expect(result).toContain('Sent 1'); + expect(result).toContain('Alice'); + }); +}); + +describe('formatMessages - media annotations', () => { + it('shows rich media annotation with dimensions and size', () => { + const messages: MessageItem[] = [ + { + id: 1, text: 'Look!', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + media: { + filename: null, + fileSize: 245760, + mimeType: 'image/jpeg', + width: 1920, + height: 1080, + duration: null, + }, + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('photo'); + expect(result).toContain('1920x1080'); + expect(result).toContain('240KB'); + }); + + it('shows duration for video messages', () => { + const messages: MessageItem[] = [ + { + id: 2, text: '', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'video', type: 'message', + media: { + filename: null, + fileSize: 1258291, + mimeType: 'video/mp4', + width: 1280, + height: 720, + duration: 32, + }, + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('video'); + expect(result).toContain('1280x720'); + expect(result).toContain('0:32'); + expect(result).toContain('1.2MB'); + }); + + it('shows filename for document messages', () => { + const messages: MessageItem[] = [ + { + id: 3, text: '', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'document', type: 'message', + media: { + filename: 'report.pdf', + fileSize: 3565158, + mimeType: 'application/pdf', + width: null, + height: null, + duration: null, + }, + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('document'); + expect(result).toContain('report.pdf'); + expect(result).toContain('3.4MB'); + }); + + it('shows [mediaType] only when no media metadata present', () => { + const messages: MessageItem[] = [ + { + id: 4, text: 'check this', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + // no media field + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('[photo]'); + }); + + it('shows "(edited)" indicator when editDate is present', () => { + const messages: MessageItem[] = [ + { + id: 5, text: 'Updated text', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + editDate: '2026-03-11T12:35:00.000Z', + }, + ]; + const result = formatMessages(messages); + expect(result).toContain('(edited)'); + expect(result).toContain('Alice'); + expect(result).toContain('Updated text'); + }); + + it('does not show "(edited)" when editDate is absent', () => { + const messages: MessageItem[] = [ + { + id: 6, text: 'Original text', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }, + ]; + const result = formatMessages(messages); + expect(result).not.toContain('(edited)'); + }); +}); + +describe('formatGetResult', () => { + const msg: MessageItem = { + id: 100, text: 'Hello', date: '2026-03-12T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }; + + it('renders messages with notFound footer', () => { + const result = formatGetResult({ messages: [msg], notFound: [101, 103] }); + expect(result).toContain('Alice'); + expect(result).toContain('Hello'); + expect(result).toContain('Not found: 101, 103'); + }); + + it('renders messages without notFound when empty', () => { + const result = formatGetResult({ messages: [msg], notFound: [] }); + expect(result).toContain('Alice'); + expect(result).not.toContain('Not found'); + }); + + it('renders "No messages found." when messages empty', () => { + const result = formatGetResult({ messages: [], notFound: [100, 101] }); + expect(result).toContain('No messages found.'); + expect(result).toContain('Not found: 100, 101'); + }); + + it('renders "No messages found." with no notFound', () => { + const result = formatGetResult({ messages: [], notFound: [] }); + expect(result).toBe('No messages found.'); + }); +}); + +describe('formatData - getResult dispatch', () => { + it('dispatches { messages, notFound } to formatGetResult', () => { + const data = { + messages: [{ + id: 1, text: 'Hi', date: '2026-03-12T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }], + notFound: [99], + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('Not found: 99'); + }); + + it('dispatches { messages: [], notFound } correctly', () => { + const result = formatData({ messages: [], notFound: [1, 2, 3] }); + expect(result).toContain('No messages found.'); + expect(result).toContain('Not found: 1, 2, 3'); + }); +}); + +describe('formatDownloadResult', () => { + it('formats download result with all fields', () => { + const result = formatDownloadResult({ + path: '/tmp/photo_123.jpg', + filename: 'photo_123.jpg', + size: 245760, + mediaType: 'photo', + messageId: 123, + }); + expect(result).toContain('photo_123.jpg'); + expect(result).toContain('/tmp/photo_123.jpg'); + expect(result).toContain('240KB'); + expect(result).toContain('photo'); + }); +}); + +describe('formatUploadResult', () => { + it('formats album result with message count', () => { + const data: AlbumResult = { + messages: [ + { + id: 1, text: '', date: '2026-03-12T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + }, + { + id: 2, text: '', date: '2026-03-12T12:00:01.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + }, + ], + sent: 2, + }; + const result = formatUploadResult(data); + expect(result).toContain('Sent 2'); + }); + + it('formats single message result', () => { + const msg: MessageItem = { + id: 1, text: 'sent photo', date: '2026-03-12T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'photo', type: 'message', + }; + const result = formatUploadResult(msg); + expect(result).toContain('Alice'); + expect(result).toContain('sent photo'); + }); +}); + +describe('formatDeleteResult', () => { + it('formats deleted IDs with mode', () => { + const data: DeleteResult = { deleted: [1, 2, 3], failed: [], mode: 'revoke' }; + const result = formatDeleteResult(data); + expect(result).toBe('Deleted 3 messages (revoke).'); + }); + + it('formats single deleted message without plural', () => { + const data: DeleteResult = { deleted: [42], failed: [], mode: 'for-me' }; + const result = formatDeleteResult(data); + expect(result).toBe('Deleted 1 message (for-me).'); + }); + + it('formats failed entries in red', () => { + const data: DeleteResult = { + deleted: [1], + failed: [{ id: 2, reason: 'permission denied' }], + mode: 'revoke', + }; + const result = formatDeleteResult(data); + expect(result).toContain('Deleted 1 message (revoke).'); + expect(result).toContain('Failed: 2 (permission denied)'); + }); + + it('shows "No messages deleted." when both empty', () => { + const data: DeleteResult = { deleted: [], failed: [], mode: 'revoke' }; + const result = formatDeleteResult(data); + expect(result).toBe('No messages deleted.'); + }); +}); + +describe('formatPinResult', () => { + it('formats pinned + silent', () => { + const data: PinResult = { messageId: 456, chatId: '@group', action: 'pinned', silent: true }; + const result = formatPinResult(data); + expect(result).toBe('Pinned message 456 in @group (silent)'); + }); + + it('formats pinned + notified', () => { + const data: PinResult = { messageId: 456, chatId: '@group', action: 'pinned', silent: false }; + const result = formatPinResult(data); + expect(result).toBe('Pinned message 456 in @group (notified)'); + }); + + it('formats unpinned (no silent field)', () => { + const data: PinResult = { messageId: 456, chatId: '@group', action: 'unpinned' }; + const result = formatPinResult(data); + expect(result).toBe('Unpinned message 456 in @group'); + }); +}); + +describe('formatData - DeleteResult and PinResult dispatch', () => { + it('dispatches DeleteResult shape to formatDeleteResult', () => { + const data: DeleteResult = { deleted: [10, 20], failed: [], mode: 'revoke' }; + const result = formatData(data); + expect(result).toBe('Deleted 2 messages (revoke).'); + }); + + it('dispatches PinResult shape to formatPinResult', () => { + const data: PinResult = { messageId: 42, chatId: '123', action: 'pinned', silent: true }; + const result = formatData(data); + expect(result).toBe('Pinned message 42 in 123 (silent)'); + }); + + it('dispatches unpinned PinResult shape to formatPinResult', () => { + const data: PinResult = { messageId: 42, chatId: '123', action: 'unpinned' }; + const result = formatData(data); + expect(result).toBe('Unpinned message 42 in 123'); + }); + + it('does not confuse react result (has emoji + action) with PinResult', () => { + const data = { messageId: 42, chatId: '123', emoji: '👍', action: 'added' }; + const result = formatData(data); + // Should fall through to generic JSON, NOT formatPinResult + expect(result).toContain('"emoji"'); + expect(result).toContain('"action"'); + }); +}); + +describe('formatUserProfile', () => { + const baseProfile: UserProfile = { + id: '12345', + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + phone: '+1234567890', + bio: 'Hello world', + photoCount: 5, + lastSeen: 'online', + isBot: false, + blocked: false, + commonChatsCount: 3, + premium: false, + verified: false, + mutualContact: false, + langCode: 'en', + }; + + it('renders single profile with all fields', () => { + const result = formatUserProfile([baseProfile], []); + expect(result).toContain('Alice Smith'); + expect(result).toContain('12345'); + expect(result).toContain('@alice'); + expect(result).toContain('+1234567890'); + expect(result).toContain('Hello world'); + expect(result).toContain('5'); + expect(result).toContain('3'); + expect(result).toContain('en'); + }); + + it('renders online status in green', () => { + const result = formatUserProfile([{ ...baseProfile, lastSeen: 'online' }], []); + // The text "online" should be present (may be wrapped in color codes) + expect(result).toContain('online'); + }); + + it('renders approximate status in dim with spaces', () => { + const result = formatUserProfile([{ ...baseProfile, lastSeen: 'within_week' }], []); + expect(result).toContain('within week'); + }); + + it('renders ISO timestamp as plain text', () => { + const result = formatUserProfile([{ ...baseProfile, lastSeen: '2026-03-13T09:00:00.000Z' }], []); + expect(result).toContain('2026-03-13T09:00:00.000Z'); + }); + + it('renders [restricted] phone as dim', () => { + const result = formatUserProfile([{ ...baseProfile, phone: '[restricted]' }], []); + expect(result).toContain('[restricted]'); + }); + + it('appends not found entries', () => { + const result = formatUserProfile([baseProfile], ['unknownuser', 'badid']); + expect(result).toContain('Not found: unknownuser, badid'); + }); + + it('renders bot-specific fields', () => { + const botProfile: UserProfile = { + ...baseProfile, + isBot: true, + lastSeen: null, + phone: null, + supportsInline: true, + botInlinePlaceholder: 'Search...', + }; + const result = formatUserProfile([botProfile], []); + expect(result).toContain('Bot'); + expect(result).toContain('Inline'); + expect(result).toContain('Search...'); + }); + + it('renders blocked flag in red', () => { + const result = formatUserProfile([{ ...baseProfile, blocked: true }], []); + expect(result).toContain('Blocked'); + expect(result).toContain('yes'); + }); + + it('renders premium flag in yellow', () => { + const result = formatUserProfile([{ ...baseProfile, premium: true }], []); + expect(result).toContain('Premium'); + }); + + it('renders verified flag in cyan', () => { + const result = formatUserProfile([{ ...baseProfile, verified: true }], []); + expect(result).toContain('Verified'); + }); + + it('does not show blocked/premium/verified when false', () => { + const result = formatUserProfile([baseProfile], []); + expect(result).not.toContain('Blocked'); + expect(result).not.toContain('Premium'); + expect(result).not.toContain('Verified'); + }); +}); + +describe('formatBlockedList', () => { + it('returns "No blocked users." for empty list', () => { + expect(formatBlockedList([])).toBe('No blocked users.'); + }); + + it('formats non-empty list via formatMembers pattern', () => { + const users: BlockedListItem[] = [ + { id: '1', firstName: 'Alice', lastName: null, username: 'alice', isBot: false }, + { id: '2', firstName: 'Bot', lastName: null, username: 'mybot', isBot: true }, + ]; + const result = formatBlockedList(users); + expect(result).toContain('Alice'); + expect(result).toContain('@alice'); + expect(result).toContain('Bot'); + expect(result).toContain('[bot]'); + }); +}); + +describe('formatData - UserProfileResult, BlockedListResult, BlockResult dispatch', () => { + it('dispatches UserProfileResult shape to formatUserProfile', () => { + const data = { + profiles: [{ + id: '100', firstName: 'Alice', lastName: null, username: 'alice', + phone: null, bio: null, photoCount: 0, lastSeen: null, isBot: false, + blocked: false, commonChatsCount: 0, premium: false, verified: false, + mutualContact: false, langCode: null, + }], + notFound: [], + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('100'); + expect(result).not.toContain('"profiles"'); + }); + + it('dispatches BlockedListResult shape with users to formatMembers', () => { + const data = { + users: [ + { id: '1', firstName: 'Dave', lastName: null, username: 'dave', isBot: false }, + ], + total: 5, + }; + const result = formatData(data); + expect(result).toContain('Dave'); + expect(result).toContain('@dave'); + }); + + it('dispatches empty BlockedListResult to "No blocked users."', () => { + const data = { users: [], total: 0 }; + const result = formatData(data); + expect(result).toBe('No blocked users.'); + }); + + it('dispatches BlockResult shape to "Blocked name" text', () => { + const data = { userId: '100', username: 'alice', firstName: 'Alice', action: 'blocked' }; + const result = formatData(data); + expect(result).toBe('Blocked Alice'); + }); + + it('dispatches unblock BlockResult shape to "Unblocked name" text', () => { + const data = { userId: '200', username: null, firstName: 'Bob', action: 'unblocked' }; + const result = formatData(data); + expect(result).toBe('Unblocked Bob'); + }); + + it('uses username when firstName is null for BlockResult', () => { + const data = { userId: '300', username: 'carol', firstName: null, action: 'blocked' }; + const result = formatData(data); + expect(result).toBe('Blocked carol'); + }); + + it('uses userId when both firstName and username are null for BlockResult', () => { + const data = { userId: '400', username: null, firstName: null, action: 'unblocked' }; + const result = formatData(data); + expect(result).toBe('Unblocked 400'); + }); +}); + +describe('formatPoll', () => { + const basePoll: PollData = { + question: 'Favorite color?', + options: [ + { text: 'Red', voters: 0, chosen: false, correct: false }, + { text: 'Blue', voters: 0, chosen: false, correct: false }, + ], + isQuiz: false, + isPublic: false, + isMultiple: false, + isClosed: false, + closePeriod: null, + closeDate: null, + totalVoters: 0, + correctOption: null, + solution: null, + }; + + it('renders basic poll with question and numbered options', () => { + const result = formatPoll(basePoll); + expect(result).toContain('Poll: Favorite color?'); + expect(result).toContain('1. Red'); + expect(result).toContain('2. Blue'); + }); + + it('shows vote counts when > 0', () => { + const poll: PollData = { + ...basePoll, + options: [ + { text: 'Red', voters: 5, chosen: false, correct: false }, + { text: 'Blue', voters: 1, chosen: false, correct: false }, + ], + }; + const result = formatPoll(poll); + expect(result).toContain('1. Red (5 votes)'); + expect(result).toContain('2. Blue (1 vote)'); + }); + + it('marks quiz correct answer with checkmark', () => { + const poll: PollData = { + ...basePoll, + isQuiz: true, + options: [ + { text: 'Berlin', voters: 0, chosen: false, correct: false }, + { text: 'Paris', voters: 0, chosen: false, correct: true }, + ], + correctOption: 2, + }; + const result = formatPoll(poll); + expect(result).toContain('2. Paris'); + expect(result).toMatch(/Paris\s*✓/); + expect(result).not.toMatch(/Berlin\s*✓/); + }); + + it('shows Quiz config tag', () => { + const poll: PollData = { ...basePoll, isQuiz: true }; + const result = formatPoll(poll); + expect(result).toContain('Quiz'); + }); + + it('shows Public config tag', () => { + const poll: PollData = { ...basePoll, isPublic: true }; + const result = formatPoll(poll); + expect(result).toContain('Public'); + }); + + it('shows Multiple config tag', () => { + const poll: PollData = { ...basePoll, isMultiple: true }; + const result = formatPoll(poll); + expect(result).toContain('Multiple'); + }); + + it('shows Closes in Ns tag', () => { + const poll: PollData = { ...basePoll, closePeriod: 30 }; + const result = formatPoll(poll); + expect(result).toContain('Closes in 30s'); + }); + + it('shows Closed tag and voter count for closed polls', () => { + const poll: PollData = { ...basePoll, isClosed: true, totalVoters: 12 }; + const result = formatPoll(poll); + expect(result).toContain('Closed'); + expect(result).toContain('12 voters'); + }); + + it('shows singular voter count', () => { + const poll: PollData = { ...basePoll, isClosed: true, totalVoters: 1 }; + const result = formatPoll(poll); + expect(result).toContain('1 voter'); + expect(result).not.toContain('1 voters'); + }); + + it('omits tag line when all flags false', () => { + const result = formatPoll(basePoll); + const lines = result.split('\n'); + // Should only have header + 2 option lines, no tag line + expect(lines.length).toBe(3); + }); + + it('joins multiple tags with dot separator', () => { + const poll: PollData = { ...basePoll, isQuiz: true, isPublic: true }; + const result = formatPoll(poll); + expect(result).toMatch(/Quiz\s*·\s*Public/); + }); +}); + +describe('formatMessages - poll rendering', () => { + it('renders poll inline when MessageItem has poll field', () => { + const msg: MessageItem = { + id: 1, text: '', date: '2026-03-13T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'poll', type: 'message', + poll: { + question: 'Pick one', + options: [ + { text: 'A', voters: 0, chosen: false, correct: false }, + { text: 'B', voters: 0, chosen: false, correct: false }, + ], + isQuiz: false, + isPublic: false, + isMultiple: false, + isClosed: false, + closePeriod: null, + closeDate: null, + totalVoters: 0, + correctOption: null, + solution: null, + }, + }; + const result = formatMessages([msg]); + expect(result).toContain('Alice'); + expect(result).toContain('Poll: Pick one'); + expect(result).toContain('1. A'); + expect(result).toContain('2. B'); + }); + + it('does not render poll when poll field is absent', () => { + const msg: MessageItem = { + id: 2, text: 'Normal message', date: '2026-03-13T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }; + const result = formatMessages([msg]); + expect(result).not.toContain('Poll:'); + }); +}); + +describe('formatData - poll message dispatch', () => { + it('dispatches single MessageItem with poll field correctly', () => { + const data: MessageItem = { + id: 1, text: '', date: '2026-03-13T12:00:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: 'poll', type: 'message', + poll: { + question: 'Test poll', + options: [ + { text: 'Yes', voters: 3, chosen: false, correct: false }, + { text: 'No', voters: 1, chosen: false, correct: false }, + ], + isQuiz: false, + isPublic: false, + isMultiple: false, + isClosed: false, + closePeriod: null, + closeDate: null, + totalVoters: 4, + correctOption: null, + solution: null, + }, + }; + const result = formatData(data); + expect(result).toContain('Alice'); + expect(result).toContain('Poll: Test poll'); + expect(result).toContain('1. Yes (3 votes)'); + expect(result).toContain('2. No (1 vote)'); + }); +}); diff --git a/cli/tests/unit/gramjs-logger.test.ts b/cli/tests/unit/gramjs-logger.test.ts new file mode 100644 index 0000000..7f29374 --- /dev/null +++ b/cli/tests/unit/gramjs-logger.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { LogLevel } from 'teleproto/extensions/Logger.js'; +import { TelegramClient } from 'teleproto'; +import { createClientForAuth, withClient } from '../../src/lib/client.js'; +import { createGramjsLogger } from '../../src/lib/gramjs-logger.js'; +import { setQuietMode, setVerboseMode } from '../../src/lib/cli-mode.js'; + +afterEach(() => { + setQuietMode(false); + setVerboseMode(false); + vi.restoreAllMocks(); +}); + +describe('gramjs diagnostics with the real SDK', () => { + it.each([false, true])('keeps the constructor and teardown off stdout (quiet=%s)', async (quiet) => { + setQuietMode(quiet); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const client = await createClientForAuth(1, 'synthetic-hash'); + try { + expect(stdout).not.toHaveBeenCalled(); + expect(stderr).not.toHaveBeenCalled(); + } finally { + await client.destroy(); + } + expect(stdout).not.toHaveBeenCalled(); + if (quiet) expect(stderr).not.toHaveBeenCalled(); + }); + + it('withClient installs the logger before the real constructor runs', async () => { + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + vi.spyOn(TelegramClient.prototype, 'connect').mockResolvedValue(true); + await expect(withClient({ apiId: 1, apiHash: 'synthetic-hash', sessionString: '' }, async () => 'ok')).resolves.toBe('ok'); + expect(stdout).not.toHaveBeenCalled(); + }); + + it('shows verbose constructor diagnostics on stderr', async () => { + setVerboseMode(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const client = await createClientForAuth(1, 'synthetic-hash'); + await client.destroy(); + expect(stdout).not.toHaveBeenCalled(); + expect(stderr.mock.calls.flat().join('')).toContain('Running teleproto version'); + }); + + it('honors quiet over verbose and routes warning/error diagnostics only to stderr', () => { + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const logger = createGramjsLogger(); + logger.debug('debug hidden'); + logger.info('info hidden'); + logger.warn('warning'); + logger.error('error'); + expect(stderr).toHaveBeenCalledTimes(2); + setVerboseMode(true); + logger.debug('debug visible'); + expect(stderr).toHaveBeenCalledTimes(3); + setQuietMode(true); + logger.error('hidden'); + expect(logger.canSend(LogLevel.ERROR)).toBe(false); + expect(stderr).toHaveBeenCalledTimes(3); + expect(stdout).not.toHaveBeenCalled(); + }); + + it('redacts configured secrets and raw protocol payload diagnostics', () => { + setVerboseMode(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const logger = createGramjsLogger(['synthetic-session', 'synthetic-hash']); + logger.error('synthetic-session synthetic-hash synthetic-session'); + logger.info('Received response without parent request: sensitive payload'); + logger.info('Type 123 not found, remaining data sensitive bytes'); + const logged = stderr.mock.calls.flat().join(''); + expect(logged).not.toContain('synthetic-'); + expect(logged).not.toContain('sensitive'); + expect(logged).toContain('[redacted]'); + }); +}); diff --git a/cli/tests/unit/library-exports.test.ts b/cli/tests/unit/library-exports.test.ts new file mode 100644 index 0000000..293446c --- /dev/null +++ b/cli/tests/unit/library-exports.test.ts @@ -0,0 +1,27 @@ +import { describe, it, expect } from 'vitest'; +import { + ErrorCode, + withAuth, + resolveEntity, + withClient, + SessionStore, + outputSuccess, + outputError, + TgError, +} from '../../src/index.js'; + +describe('public library exports', () => { + it('re-exports ErrorCode, withAuth, and resolveEntity', () => { + expect(ErrorCode.NOT_AUTHENTICATED).toBe('NOT_AUTHENTICATED'); + expect(typeof withAuth).toBe('function'); + expect(typeof resolveEntity).toBe('function'); + }); + + it('re-exports client, session, output, and error helpers', () => { + expect(typeof withClient).toBe('function'); + expect(typeof SessionStore).toBe('function'); + expect(typeof outputSuccess).toBe('function'); + expect(typeof outputError).toBe('function'); + expect(new TgError('x', 'Y')).toBeInstanceOf(Error); + }); +}); diff --git a/cli/tests/unit/media-download.test.ts b/cli/tests/unit/media-download.test.ts new file mode 100644 index 0000000..2f9ca38 --- /dev/null +++ b/cli/tests/unit/media-download.test.ts @@ -0,0 +1,385 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetMessages, + mockDownloadMedia, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetMessages: vi.fn().mockResolvedValue([]), + mockDownloadMedia: vi.fn().mockResolvedValue(undefined), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getMessages: mockGetMessages, + downloadMedia: mockDownloadMedia, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + MessageMediaPhoto: class MessageMediaPhoto {}, + MessageMediaDocument: class MessageMediaDocument {}, + DocumentAttributeFilename: class DocumentAttributeFilename {}, + DocumentAttributeVideo: class DocumentAttributeVideo {}, + DocumentAttributeAudio: class DocumentAttributeAudio {}, + DocumentAttributeSticker: class DocumentAttributeSticker {}, + DocumentAttributeImageSize: class DocumentAttributeImageSize {}, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +const mockExtractMediaInfo = vi.fn(); +const mockDetectMedia = vi.fn(); +vi.mock('../../src/lib/serialize.js', () => ({ + extractMediaInfo: (...args: any[]) => mockExtractMediaInfo(...args), + detectMedia: (...args: any[]) => mockDetectMedia(...args), + serializeMessage: vi.fn(), +})); + +// Mock media-utils +const mockGenerateFilename = vi.fn(); +const mockFormatBytes = vi.fn(); +vi.mock('../../src/lib/media-utils.js', () => ({ + generateFilename: (...args: any[]) => mockGenerateFilename(...args), + formatBytes: (...args: any[]) => mockFormatBytes(...args), + detectFileType: vi.fn(), + FILTER_MAP: {}, + VALID_FILTERS: [], +})); + +// Import after mocks +import { mediaDownloadAction } from '../../src/commands/media/download.js'; + +// Create a mock Command context +function createMockCommandContext(args: string[], opts: Record<string, any> = {}) { + return { + args, + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + output: undefined, + ...opts, + })), + }; +} + +// Helper to create a mock message with media +function createMockMessageWithMedia(msgId: number, media: any = {}) { + return { + id: msgId, + media, + message: '', + date: 1710150900, + }; +} + +describe('mediaDownloadAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockDetectMedia.mockReturnValue({ mediaType: 'photo' }); + mockExtractMediaInfo.mockReturnValue({ + filename: null, + fileSize: 1024, + mimeType: 'image/jpeg', + width: 800, + height: 600, + duration: null, + }); + mockGenerateFilename.mockReturnValue('photo_123.jpg'); + mockFormatBytes.mockReturnValue('1KB'); + }); + + it('downloads single message media and returns DownloadResult', async () => { + const mockMsg = createMockMessageWithMedia(123, { _type: 'photo' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '123']); + await mediaDownloadAction.call(ctx as any); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testchat'); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ ids: [123] }), + ); + expect(mockDownloadMedia).toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result).toHaveProperty('path'); + expect(result).toHaveProperty('filename'); + expect(result).toHaveProperty('size'); + expect(result).toHaveProperty('mediaType', 'photo'); + expect(result).toHaveProperty('messageId', 123); + // Path should be absolute + expect(result.path).toBe(resolve(result.path)); + }); + + it('downloads batch media (comma-separated IDs) and returns batch result', async () => { + const mockMsg1 = createMockMessageWithMedia(100, { _type: 'photo' }); + const mockMsg2 = createMockMessageWithMedia(200, { _type: 'photo' }); + mockGetMessages + .mockResolvedValueOnce([mockMsg1]) + .mockResolvedValueOnce([mockMsg2]); + + const ctx = createMockCommandContext(['testchat', '100,200']); + await mediaDownloadAction.call(ctx as any); + + expect(mockGetMessages).toHaveBeenCalledTimes(2); + expect(mockDownloadMedia).toHaveBeenCalledTimes(2); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result).toHaveProperty('files'); + expect(result).toHaveProperty('downloaded', 2); + expect(result.files).toHaveLength(2); + }); + + it('returns NO_MEDIA error for message without media', async () => { + const mockMsg = createMockMessageWithMedia(456, null); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + mockDetectMedia.mockReturnValue({ mediaType: null }); + + const ctx = createMockCommandContext(['testchat', '456']); + await mediaDownloadAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('no downloadable media'), + 'NO_MEDIA', + ); + }); + + it('uses filename from media metadata when available', async () => { + mockExtractMediaInfo.mockReturnValue({ + filename: 'report.pdf', + fileSize: 2048, + mimeType: 'application/pdf', + width: null, + height: null, + duration: null, + }); + mockDetectMedia.mockReturnValue({ mediaType: 'document' }); + + const mockMsg = createMockMessageWithMedia(789, { _type: 'document' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '789']); + await mediaDownloadAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.filename).toBe('report.pdf'); + // generateFilename should NOT have been called since metadata had filename + expect(mockGenerateFilename).not.toHaveBeenCalled(); + }); + + it('falls back to generateFilename for photos without filename', async () => { + // Default mock already has filename: null + const mockMsg = createMockMessageWithMedia(555, { _type: 'photo' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '555']); + await mediaDownloadAction.call(ctx as any); + + expect(mockGenerateFilename).toHaveBeenCalledWith('photo', 555, 'image/jpeg'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.filename).toBe('photo_123.jpg'); + }); + + it('returns INVALID_ID error for non-numeric message IDs', async () => { + const ctx = createMockCommandContext(['testchat', 'abc']); + await mediaDownloadAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('sanitizes path traversal in Telegram-supplied filenames', async () => { + mockExtractMediaInfo.mockReturnValue({ + filename: '../../etc/passwd', + fileSize: 2048, + mimeType: 'application/octet-stream', + width: null, + height: null, + duration: null, + }); + mockDetectMedia.mockReturnValue({ mediaType: 'document' }); + + const mockMsg = createMockMessageWithMedia(999, { _type: 'document' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '999']); + await mediaDownloadAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + // basename() should strip path traversal, leaving just 'passwd' + expect(result.filename).toBe('passwd'); + expect(result.path).not.toContain('..'); + }); + + it('-o flag overrides output path and filename for single download', async () => { + const mockMsg = createMockMessageWithMedia(333, { _type: 'photo' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const dest = join(tmpdir(), `tg-custom-${process.pid}.jpg`); + const ctx = createMockCommandContext(['testchat', '333'], { output: dest }); + await mediaDownloadAction.call(ctx as any); + + expect(mockDownloadMedia).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ outputFile: resolve(dest) }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.path).toBe(resolve(dest)); + expect(result.filename).toBe(`tg-custom-${process.pid}.jpg`); + }); + + it('batch download collects failed ids instead of aborting', async () => { + const photoA = createMockMessageWithMedia(100, { _type: 'photo' }); + const text = createMockMessageWithMedia(200, null); + const photoB = createMockMessageWithMedia(300, { _type: 'photo' }); + mockGetMessages + .mockResolvedValueOnce([photoA]) + .mockResolvedValueOnce([text]) + .mockResolvedValueOnce([photoB]); + mockDetectMedia.mockImplementation((media: any) => { + if (!media) return { mediaType: null }; + return { mediaType: media._type ?? 'photo' }; + }); + + const ctx = createMockCommandContext(['testchat', '100,200,300']); + await mediaDownloadAction.call(ctx as any); + + expect(mockDownloadMedia).toHaveBeenCalledTimes(2); + expect(mockOutputError).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.downloaded).toBe(2); + expect(result.files).toHaveLength(2); + expect(result.failed).toEqual([ + expect.objectContaining({ messageId: 200, code: 'NO_MEDIA' }), + ]); + }); + + it('rejects poll and sticker as not downloadable', async () => { + const poll = createMockMessageWithMedia(10, { _type: 'poll' }); + mockGetMessages.mockResolvedValueOnce([poll]); + mockDetectMedia.mockReturnValueOnce({ mediaType: 'poll' }); + + const ctx = createMockCommandContext(['testchat', '10']); + await mediaDownloadAction.call(ctx as any); + + expect(mockDownloadMedia).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('no downloadable media'), + 'NO_MEDIA', + ); + }); + + describe('overwrite guard', () => { + let dir: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'tg-dl-')); + }); + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + }); + + it('refuses an existing file without --force', async () => { + const dest = join(dir, 'exists.jpg'); + writeFileSync(dest, 'already here'); + const mockMsg = createMockMessageWithMedia(333, { _type: 'photo' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '333'], { output: dest }); + await mediaDownloadAction.call(ctx as any); + + expect(mockDownloadMedia).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('File exists'), + 'FILE_EXISTS', + ); + }); + + it('overwrites an existing file with --force', async () => { + const dest = join(dir, 'exists.jpg'); + writeFileSync(dest, 'already here'); + const mockMsg = createMockMessageWithMedia(333, { _type: 'photo' }); + mockGetMessages.mockResolvedValueOnce([mockMsg]); + + const ctx = createMockCommandContext(['testchat', '333'], { output: dest, force: true }); + await mediaDownloadAction.call(ctx as any); + + expect(mockDownloadMedia).toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + }); +}); diff --git a/cli/tests/unit/media-send.test.ts b/cli/tests/unit/media-send.test.ts new file mode 100644 index 0000000..3074274 --- /dev/null +++ b/cli/tests/unit/media-send.test.ts @@ -0,0 +1,363 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { resolve } from 'node:path'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockSendFile, + mockGetMessages, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockSendFile: vi.fn(), + mockGetMessages: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + sendFile: mockSendFile, + getMessages: mockGetMessages, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + MessageMediaPhoto: class MessageMediaPhoto {}, + MessageMediaDocument: class MessageMediaDocument {}, + DocumentAttributeFilename: class DocumentAttributeFilename {}, + DocumentAttributeVideo: class DocumentAttributeVideo {}, + DocumentAttributeAudio: class DocumentAttributeAudio {}, + DocumentAttributeSticker: class DocumentAttributeSticker {}, + DocumentAttributeImageSize: class DocumentAttributeImageSize {}, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +const mockAssertForum = vi.fn().mockResolvedValue(undefined); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + assertForum: (...args: any[]) => mockAssertForum(...args), +})); + +// Mock serialize +const mockSerializeMessage = vi.fn().mockImplementation((msg: any) => ({ + id: msg.id, + text: msg.message ?? '', + date: '2025-03-11T12:00:00.000Z', + senderId: null, + senderName: null, + replyToMsgId: null, + forwardFrom: null, + mediaType: 'photo', + type: 'message' as const, +})); +vi.mock('../../src/lib/serialize.js', () => ({ + serializeMessage: (...args: any[]) => mockSerializeMessage(...args), + extractMediaInfo: vi.fn(), + detectMedia: vi.fn(), +})); + +// Mock media-utils +const mockDetectFileType = vi.fn().mockReturnValue('photo'); +vi.mock('../../src/lib/media-utils.js', () => ({ + detectFileType: (...args: any[]) => mockDetectFileType(...args), + generateFilename: vi.fn(), + formatBytes: vi.fn(), + FILTER_MAP: {}, + VALID_FILTERS: [], +})); + +// Mock fs.access +const mockAccess = vi.fn().mockResolvedValue(undefined); +vi.mock('node:fs/promises', () => ({ + access: (...args: any[]) => mockAccess(...args), +})); + +// Import after mocks +import { mediaSendAction } from '../../src/commands/media/send.js'; + +// Create a mock Command context +function createMockCommandContext(args: string[], opts: Record<string, any> = {}) { + return { + args, + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + caption: undefined, + replyTo: undefined, + ...opts, + })), + }; +} + +describe('mediaSendAction', () => { + const originalExitCode = process.exitCode; + afterEach(() => { process.exitCode = originalExitCode; }); + beforeEach(() => { + vi.clearAllMocks(); + mockAccess.mockResolvedValue(undefined); + mockDetectFileType.mockReturnValue('photo'); + mockSendFile.mockResolvedValue({ + id: 100, + message: '', + date: 1710150900, + media: { _type: 'photo' }, + }); + }); + + it('sends single file and returns serialized MessageItem', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg']); + await mediaSendAction.call(ctx as any); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testchat'); + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + file: resolve('photo.jpg'), + }), + ); + expect(mockSerializeMessage).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result).toHaveProperty('id'); + expect(result).toHaveProperty('mediaType'); + }); + + it('sends album (multiple files) and returns album result', async () => { + const albumMsgs = [ + { id: 101, message: '', date: 1710150900, media: {} }, + { id: 104, message: '', date: 1710150900, media: {} }, + { id: 109, message: '', date: 1710150900, media: {} }, + ]; + mockSendFile.mockResolvedValueOnce(albumMsgs); + + const ctx = createMockCommandContext(['testchat', 'a.jpg', 'b.jpg', 'c.jpg']); + await mediaSendAction.call(ctx as any); + + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + file: expect.arrayContaining([ + resolve('a.jpg'), + resolve('b.jpg'), + resolve('c.jpg'), + ]), + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result).toHaveProperty('messages'); + expect(result).toHaveProperty('sent', 3); + expect(result.messages).toHaveLength(3); + }); + + it('passes --caption to sendFile', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { caption: 'My caption' }); + await mediaSendAction.call(ctx as any); + + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + caption: 'My caption', + }), + ); + }); + + it('passes --reply-to parsed as integer to sendFile', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { replyTo: '42' }); + await mediaSendAction.call(ctx as any); + + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + replyTo: 42, + }), + ); + }); + + it('detects voice note for .ogg files and sets voiceNote: true', async () => { + mockDetectFileType.mockReturnValue('voice'); + + const ctx = createMockCommandContext(['testchat', 'audio.ogg']); + await mediaSendAction.call(ctx as any); + + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + voiceNote: true, + }), + ); + }); + + it('returns FILE_NOT_FOUND error when file does not exist', async () => { + mockAccess.mockRejectedValueOnce(new Error('ENOENT')); + + const ctx = createMockCommandContext(['testchat', 'nonexistent.jpg']); + await mediaSendAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('File not found'), + 'FILE_NOT_FOUND', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('returns ALBUM_TOO_LARGE error for more than 10 files', async () => { + const files = Array.from({ length: 11 }, (_, i) => `file${i}.jpg`); + const ctx = createMockCommandContext(['testchat', ...files]); + await mediaSendAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('maximum of 10'), + 'ALBUM_TOO_LARGE', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('reports only messages returned by Telegram when album response is partial', async () => { + mockSendFile.mockResolvedValueOnce([ + { id: 101, message: '', date: 1710150900, media: {} }, + { id: 109, message: '', date: 1710150900, media: {} }, + ]); + const ctx = createMockCommandContext(['testchat', 'a.jpg', 'b.jpg', 'c.jpg']); + await mediaSendAction.call(ctx as any); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.sent).toBe(2); + expect(result.messages.map((m: any) => m.id)).toEqual([101, 109]); + expect(result.warning).toMatch(/2 messages for 3 files/); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('returns INVALID_REPLY_TO error for non-numeric --reply-to', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { replyTo: 'abc' }); + await mediaSendAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid reply-to message ID'), + 'INVALID_REPLY_TO', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('sets forceDocument for .pdf files', async () => { + mockDetectFileType.mockReturnValue('document'); + + const ctx = createMockCommandContext(['testchat', 'report.pdf']); + await mediaSendAction.call(ctx as any); + + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + forceDocument: true, + }), + ); + }); + + // ---- Topic tests (Finding 4: external verification coverage gap) ---- + + it('sends to topic by passing topicId as replyTo', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { topic: '42' }); + await mediaSendAction.call(ctx as any); + + expect(mockAssertForum).toHaveBeenCalledWith( + expect.objectContaining({ className: 'Channel' }), + 42, + ); + expect(mockSendFile).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + replyTo: 42, + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('rejects combining --topic and --reply-to', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { topic: '42', replyTo: '99' }); + await mediaSendAction.call(ctx as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--topic and --reply-to'), + 'INVALID_OPTIONS', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('returns error when --topic used on non-forum chat', async () => { + // assertForum throws TgError which goes through formatError in catch block + const { TgError } = await import('../../src/lib/errors.js'); + mockAssertForum.mockRejectedValueOnce( + new TgError('Chat is not a forum-enabled supergroup', 'NOT_A_FORUM'), + ); + + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { topic: '42' }); + await mediaSendAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('forum'), + 'NOT_A_FORUM', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('returns INVALID_TOPIC_ID for non-numeric --topic', async () => { + const ctx = createMockCommandContext(['testchat', 'photo.jpg'], { topic: 'abc' }); + await mediaSendAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid topic ID'), + 'INVALID_TOPIC_ID', + ); + expect(mockSendFile).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/media-utils.test.ts b/cli/tests/unit/media-utils.test.ts new file mode 100644 index 0000000..f09d0fd --- /dev/null +++ b/cli/tests/unit/media-utils.test.ts @@ -0,0 +1,255 @@ +import { describe, it, expect, vi } from 'vitest'; + +// Mock telegram Api for FILTER_MAP factory functions +const { + MockFilterPhotos, + MockFilterVideo, + MockFilterPhotoVideo, + MockFilterDocument, + MockFilterUrl, + MockFilterGif, + MockFilterVoice, + MockFilterMusic, + MockFilterRoundVideo, + MockFilterRoundVoice, + MockFilterChatPhotos, + MockFilterPhoneCalls, + MockFilterMyMentions, + MockFilterGeo, + MockFilterContacts, + MockFilterPinned, +} = vi.hoisted(() => { + class MockFilterPhotos {} + class MockFilterVideo {} + class MockFilterPhotoVideo {} + class MockFilterDocument {} + class MockFilterUrl {} + class MockFilterGif {} + class MockFilterVoice {} + class MockFilterMusic {} + class MockFilterRoundVideo {} + class MockFilterRoundVoice {} + class MockFilterChatPhotos {} + class MockFilterPhoneCalls {} + class MockFilterMyMentions {} + class MockFilterGeo {} + class MockFilterContacts {} + class MockFilterPinned {} + return { + MockFilterPhotos, + MockFilterVideo, + MockFilterPhotoVideo, + MockFilterDocument, + MockFilterUrl, + MockFilterGif, + MockFilterVoice, + MockFilterMusic, + MockFilterRoundVideo, + MockFilterRoundVoice, + MockFilterChatPhotos, + MockFilterPhoneCalls, + MockFilterMyMentions, + MockFilterGeo, + MockFilterContacts, + MockFilterPinned, + }; +}); + +vi.mock('teleproto', () => ({ + Api: { + InputMessagesFilterPhotos: MockFilterPhotos, + InputMessagesFilterVideo: MockFilterVideo, + InputMessagesFilterPhotoVideo: MockFilterPhotoVideo, + InputMessagesFilterDocument: MockFilterDocument, + InputMessagesFilterUrl: MockFilterUrl, + InputMessagesFilterGif: MockFilterGif, + InputMessagesFilterVoice: MockFilterVoice, + InputMessagesFilterMusic: MockFilterMusic, + InputMessagesFilterRoundVideo: MockFilterRoundVideo, + InputMessagesFilterRoundVoice: MockFilterRoundVoice, + InputMessagesFilterChatPhotos: MockFilterChatPhotos, + InputMessagesFilterPhoneCalls: MockFilterPhoneCalls, + InputMessagesFilterMyMentions: MockFilterMyMentions, + InputMessagesFilterGeo: MockFilterGeo, + InputMessagesFilterContacts: MockFilterContacts, + InputMessagesFilterPinned: MockFilterPinned, + }, +})); + +import { + FILTER_MAP, + VALID_FILTERS, + generateFilename, + detectFileType, + formatBytes, +} from '../../src/lib/media-utils.js'; + +describe('FILTER_MAP', () => { + it('has all 16 MTProto search filters', () => { + expect(Object.keys(FILTER_MAP)).toHaveLength(16); + }); + + it('contains all expected filter names', () => { + const expected = [ + 'photos', 'videos', 'photo_video', 'documents', 'urls', 'gifs', + 'voice', 'music', 'round', 'round_voice', 'chat_photos', + 'phone_calls', 'mentions', 'geo', 'contacts', 'pinned', + ]; + for (const name of expected) { + expect(FILTER_MAP).toHaveProperty(name); + } + }); + + it('each value is a factory function returning a filter instance', () => { + expect(FILTER_MAP.photos()).toBeInstanceOf(MockFilterPhotos); + expect(FILTER_MAP.videos()).toBeInstanceOf(MockFilterVideo); + expect(FILTER_MAP.photo_video()).toBeInstanceOf(MockFilterPhotoVideo); + expect(FILTER_MAP.documents()).toBeInstanceOf(MockFilterDocument); + expect(FILTER_MAP.urls()).toBeInstanceOf(MockFilterUrl); + expect(FILTER_MAP.gifs()).toBeInstanceOf(MockFilterGif); + expect(FILTER_MAP.voice()).toBeInstanceOf(MockFilterVoice); + expect(FILTER_MAP.music()).toBeInstanceOf(MockFilterMusic); + expect(FILTER_MAP.round()).toBeInstanceOf(MockFilterRoundVideo); + expect(FILTER_MAP.round_voice()).toBeInstanceOf(MockFilterRoundVoice); + expect(FILTER_MAP.chat_photos()).toBeInstanceOf(MockFilterChatPhotos); + expect(FILTER_MAP.phone_calls()).toBeInstanceOf(MockFilterPhoneCalls); + expect(FILTER_MAP.mentions()).toBeInstanceOf(MockFilterMyMentions); + expect(FILTER_MAP.geo()).toBeInstanceOf(MockFilterGeo); + expect(FILTER_MAP.contacts()).toBeInstanceOf(MockFilterContacts); + expect(FILTER_MAP.pinned()).toBeInstanceOf(MockFilterPinned); + }); + + it('factory functions create fresh instances each call', () => { + const a = FILTER_MAP.photos(); + const b = FILTER_MAP.photos(); + expect(a).not.toBe(b); + }); +}); + +describe('VALID_FILTERS', () => { + it('matches Object.keys(FILTER_MAP)', () => { + expect(VALID_FILTERS).toEqual(Object.keys(FILTER_MAP)); + }); +}); + +describe('generateFilename', () => { + it('generates filename with jpeg extension for image/jpeg', () => { + expect(generateFilename('photo', 12345, 'image/jpeg')).toBe('photo_12345.jpg'); + }); + + it('generates filename with mp4 extension for video/mp4', () => { + expect(generateFilename('video', 99, 'video/mp4')).toBe('video_99.mp4'); + }); + + it('generates filename with png extension for image/png', () => { + expect(generateFilename('photo', 1, 'image/png')).toBe('photo_1.png'); + }); + + it('generates filename with ogg extension for audio/ogg', () => { + expect(generateFilename('voice', 5, 'audio/ogg')).toBe('voice_5.ogg'); + }); + + it('generates filename with mp3 extension for audio/mpeg', () => { + expect(generateFilename('audio', 7, 'audio/mpeg')).toBe('audio_7.mp3'); + }); + + it('falls back to .bin for null mimeType', () => { + expect(generateFilename('document', 1, null)).toBe('document_1.bin'); + }); + + it('falls back to .bin for unknown mimeType', () => { + expect(generateFilename('document', 2, 'application/octet-stream')).toBe('document_2.bin'); + }); +}); + +describe('detectFileType', () => { + it('returns photo for .jpg', () => { + expect(detectFileType('.jpg')).toBe('photo'); + }); + + it('returns photo for .jpeg', () => { + expect(detectFileType('.jpeg')).toBe('photo'); + }); + + it('returns photo for .png', () => { + expect(detectFileType('.png')).toBe('photo'); + }); + + it('returns photo for .gif', () => { + expect(detectFileType('.gif')).toBe('photo'); + }); + + it('returns photo for .bmp', () => { + expect(detectFileType('.bmp')).toBe('photo'); + }); + + it('returns photo for .webp', () => { + expect(detectFileType('.webp')).toBe('photo'); + }); + + it('returns video for .mp4', () => { + expect(detectFileType('.mp4')).toBe('video'); + }); + + it('returns video for .mov', () => { + expect(detectFileType('.mov')).toBe('video'); + }); + + it('returns video for .avi', () => { + expect(detectFileType('.avi')).toBe('video'); + }); + + it('returns video for .mkv', () => { + expect(detectFileType('.mkv')).toBe('video'); + }); + + it('returns video for .webm', () => { + expect(detectFileType('.webm')).toBe('video'); + }); + + it('returns voice for .ogg', () => { + expect(detectFileType('.ogg')).toBe('voice'); + }); + + it('returns voice for .opus', () => { + expect(detectFileType('.opus')).toBe('voice'); + }); + + it('returns document for .pdf', () => { + expect(detectFileType('.pdf')).toBe('document'); + }); + + it('returns document for .txt', () => { + expect(detectFileType('.txt')).toBe('document'); + }); + + it('returns document for unknown extension', () => { + expect(detectFileType('.xyz')).toBe('document'); + }); +}); + +describe('formatBytes', () => { + it('formats 0 bytes', () => { + expect(formatBytes(0)).toBe('0B'); + }); + + it('formats bytes under 1024', () => { + expect(formatBytes(500)).toBe('500B'); + }); + + it('formats exactly 1024 as 1KB', () => { + expect(formatBytes(1024)).toBe('1KB'); + }); + + it('formats KB with rounding', () => { + expect(formatBytes(1536)).toBe('2KB'); + }); + + it('formats MB with one decimal', () => { + expect(formatBytes(1258291)).toBe('1.2MB'); + }); + + it('formats GB with one decimal', () => { + expect(formatBytes(1073741824)).toBe('1.0GB'); + }); +}); diff --git a/cli/tests/unit/message-delete.test.ts b/cli/tests/unit/message-delete.test.ts new file mode 100644 index 0000000..ded046b --- /dev/null +++ b/cli/tests/unit/message-delete.test.ts @@ -0,0 +1,225 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockDeleteMessages, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockDeleteMessages: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + deleteMessages: mockDeleteMessages, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize (for bigIntToString) +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: bigint) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { messageDeleteAction } from '../../src/commands/message/delete.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageDeleteAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockDeleteMessages.mockResolvedValue([]); + }); + + it('outputs DELETE_MODE_REQUIRED when neither --revoke nor --for-me is set', async () => { + const ctx = createMockCommandContext(); + await messageDeleteAction.call(ctx as any, 'testchat', '1,2,3'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Specify --revoke (delete for everyone) or --for-me (delete for self)', + 'DELETE_MODE_REQUIRED', + ); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_OPTIONS when both --revoke and --for-me are set', async () => { + const ctx = createMockCommandContext({ revoke: true, forMe: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '1,2,3'); + + expect(mockOutputError).toHaveBeenCalledWith( + '--revoke and --for-me are mutually exclusive', + 'INVALID_OPTIONS', + ); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + }); + + it('calls client.deleteMessages with revoke: true when --revoke is set', async () => { + const ctx = createMockCommandContext({ revoke: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '10,20'); + + expect(mockDeleteMessages).toHaveBeenCalledWith( + expect.anything(), + [10, 20], + { revoke: true }, + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('calls client.deleteMessages with revoke: false when --for-me is set', async () => { + mockResolveEntity.mockResolvedValueOnce({ id: BigInt(123), className: 'User' }); + const ctx = createMockCommandContext({ forMe: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '10,20'); + + expect(mockDeleteMessages).toHaveBeenCalledWith( + expect.anything(), + [10, 20], + { revoke: false }, + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('outputs DeleteResult shape on success with revoke mode', async () => { + const ctx = createMockCommandContext({ revoke: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '5,10,15'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + deleted: [5, 10, 15], + failed: [], + mode: 'revoke', + }); + }); + + it('outputs DeleteResult shape on success with for-me mode', async () => { + mockResolveEntity.mockResolvedValueOnce({ id: BigInt(123), className: 'Chat' }); + const ctx = createMockCommandContext({ forMe: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '5'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + deleted: [5], + failed: [], + mode: 'for-me', + }); + }); + + it('outputs INVALID_MSG_ID for non-numeric IDs', async () => { + const ctx = createMockCommandContext({ revoke: true }); + await messageDeleteAction.call(ctx as any, 'testchat', 'abc,10'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('abc'), + 'INVALID_MESSAGE_ID', + ); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + }); + + it('rejects mixed strings like "12abc" as invalid IDs', async () => { + const ctx = createMockCommandContext({ revoke: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '12abc'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('12abc'), + 'INVALID_MESSAGE_ID', + ); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + }); + + it('outputs TOO_MANY_IDS when >100 IDs provided', async () => { + const ctx = createMockCommandContext({ revoke: true }); + const ids = Array.from({ length: 101 }, (_, i) => String(i + 1)).join(','); + await messageDeleteAction.call(ctx as any, 'testchat', ids); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('100'), + 'TOO_MANY_IDS', + ); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + }); + + it('translates RPCError via translateTelegramError', async () => { + mockDeleteMessages.mockRejectedValueOnce({ errorMessage: 'MESSAGE_DELETE_FORBIDDEN' }); + + const ctx = createMockCommandContext({ revoke: true }); + await messageDeleteAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Cannot delete this message', + 'MESSAGE_DELETE_FORBIDDEN', + ); + }); +}); diff --git a/cli/tests/unit/message-edit.test.ts b/cli/tests/unit/message-edit.test.ts new file mode 100644 index 0000000..3a1c309 --- /dev/null +++ b/cli/tests/unit/message-edit.test.ts @@ -0,0 +1,261 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockEditMessage, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockEditMessage: vi.fn().mockResolvedValue({}), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + editMessage: mockEditMessage, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +const mockSerializeMessage = vi.fn().mockReturnValue({ + id: 42, + text: 'edited text', + date: '2026-03-13T12:00:00.000Z', + senderId: '123', + senderName: 'Alice', + replyToMsgId: null, + forwardFrom: null, + mediaType: null, + type: 'message', + editDate: '2026-03-13T12:05:00.000Z', +}); +vi.mock('../../src/lib/serialize.js', () => ({ + serializeMessage: (...args: any[]) => mockSerializeMessage(...args), +})); + +// Mock errors +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { messageEditAction } from '../../src/commands/message/edit.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageEditAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + // Reset editMessage to return a valid message by default + mockEditMessage.mockResolvedValue({ + id: 42, + message: 'edited text', + date: 1710150900, + editDate: 1710151200, + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + }); + }); + + it('edits a message and returns serialized MessageItem via outputSuccess', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '42', 'edited text'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testchat'); + expect(mockEditMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 42, text: 'edited text' }), + ); + expect(mockSerializeMessage).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data).toHaveProperty('id'); + expect(data).toHaveProperty('text'); + expect(data).toHaveProperty('editDate'); + }); + + it('outputs STDIN_REQUIRED when text is "-" and stdin is TTY', async () => { + const origIsTTY = process.stdin.isTTY; + try { + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true }); + + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '42', '-'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('requires piped input'), + 'STDIN_REQUIRED', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + + it('outputs INVALID_MESSAGE_ID for non-numeric message ID', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', 'notanumber', 'new text'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for mixed string like "12abc"', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '12abc', 'new text'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for zero', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '0', 'new text'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for negative number', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '-5', 'new text'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + }); + + it('outputs EMPTY_MESSAGE for empty text', async () => { + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '42', ''); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Message text is required'), + 'EMPTY_MESSAGE', + ); + expect(mockEditMessage).not.toHaveBeenCalled(); + }); + + it('translates RPCError MESSAGE_EDIT_TIME_EXPIRED to human-readable message', async () => { + mockEditMessage.mockRejectedValueOnce({ errorMessage: 'MESSAGE_EDIT_TIME_EXPIRED' }); + + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '42', 'too late'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Cannot edit: 48-hour edit window has expired', + 'MESSAGE_EDIT_TIME_EXPIRED', + ); + }); + + it('reads from stdin when text is "-" and stdin is piped', async () => { + const origIsTTY = process.stdin.isTTY; + const origStdin = process.stdin[Symbol.asyncIterator]; + try { + Object.defineProperty(process.stdin, 'isTTY', { value: undefined, configurable: true }); + + const stdinContent = Buffer.from('piped edit content\n'); + (process.stdin as any)[Symbol.asyncIterator] = async function* () { + yield stdinContent; + }; + + const ctx = createMockCommandContext(); + await messageEditAction.call(ctx as any, 'testchat', '42', '-'); + + expect(mockEditMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 42, text: 'piped edit content' }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + (process.stdin as any)[Symbol.asyncIterator] = origStdin; + } + }); +}); diff --git a/cli/tests/unit/message-forward.test.ts b/cli/tests/unit/message-forward.test.ts new file mode 100644 index 0000000..fb49e15 --- /dev/null +++ b/cli/tests/unit/message-forward.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockForwardMessages, + MockMediaPhoto, + MockMediaDocument, + MockMediaPoll, + MockAttrSticker, + MockAttrVideo, + MockAttrAudio, + MockAttrFilename, + MockAttrImageSize, + MockActionChatCreate, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockForwardMessages: vi.fn().mockResolvedValue([]), + MockMediaPhoto: class {}, + MockMediaDocument: class {}, + MockMediaPoll: class {}, + MockAttrSticker: class { alt = ''; }, + MockAttrVideo: class {}, + MockAttrAudio: class { voice = false; }, + MockAttrFilename: class { fileName = ''; }, + MockAttrImageSize: class { w = 0; h = 0; }, + MockActionChatCreate: class {}, +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + forwardMessages: mockForwardMessages, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + MessageMediaPhoto: MockMediaPhoto, + MessageMediaDocument: MockMediaDocument, + MessageMediaPoll: MockMediaPoll, + DocumentAttributeSticker: MockAttrSticker, + DocumentAttributeVideo: MockAttrVideo, + DocumentAttributeAudio: MockAttrAudio, + DocumentAttributeFilename: MockAttrFilename, + DocumentAttributeImageSize: MockAttrImageSize, + MessageActionChatCreate: MockActionChatCreate, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution -- return different entities for different inputs +const mockResolveEntity = vi.fn().mockImplementation(async (_client: any, input: string) => { + if (input === 'source') return { id: BigInt(100), className: 'Channel' }; + if (input === 'dest') return { id: BigInt(200), className: 'Channel' }; + return { id: BigInt(999), className: 'Channel' }; +}); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Helper to create mock message objects +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Forwarded message', + date: 1710150900, + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + }; + return { ...defaults, ...overrides }; +} + +// Import after mocks +import { messageForwardAction } from '../../src/commands/message/forward.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageForwardAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('forwards a single message and returns forwarded count with messages', async () => { + const forwardedMsgs = [createMockMessage({ id: 50, message: 'Forwarded' })]; + mockForwardMessages.mockResolvedValueOnce(forwardedMsgs); + + const ctx = createMockCommandContext(); + await messageForwardAction.call(ctx as any, 'source', '123', 'dest'); + + // Should resolve both source and destination entities + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'source'); + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'dest'); + + // Should call forwardMessages with fromPeer + expect(mockForwardMessages).toHaveBeenCalledWith( + expect.anything(), // toEntity + expect.objectContaining({ + messages: [123], + fromPeer: expect.anything(), // fromEntity + }), + ); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.forwarded).toBe(1); + expect(data.messages).toHaveLength(1); + }); + + it('forwards multiple comma-separated message IDs', async () => { + const forwardedMsgs = [ + createMockMessage({ id: 50 }), + createMockMessage({ id: 51 }), + createMockMessage({ id: 52 }), + ]; + mockForwardMessages.mockResolvedValueOnce(forwardedMsgs); + + const ctx = createMockCommandContext(); + await messageForwardAction.call(ctx as any, 'source', '10,20,30', 'dest'); + + expect(mockForwardMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + messages: [10, 20, 30], + }), + ); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.forwarded).toBe(3); + expect(data.messages).toHaveLength(3); + }); + + it('rejects invalid message IDs with INVALID_MESSAGE_IDS error', async () => { + const ctx = createMockCommandContext(); + await messageForwardAction.call(ctx as any, 'source', '10,abc,30', 'dest'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message IDs'), + 'INVALID_MESSAGE_ID', + ); + expect(mockForwardMessages).not.toHaveBeenCalled(); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await messageForwardAction.call(ctx as any, 'source', '10', 'dest'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + it('handles whitespace in comma-separated IDs', async () => { + const forwardedMsgs = [createMockMessage({ id: 50 }), createMockMessage({ id: 51 })]; + mockForwardMessages.mockResolvedValueOnce(forwardedMsgs); + + const ctx = createMockCommandContext(); + await messageForwardAction.call(ctx as any, 'source', ' 10 , 20 ', 'dest'); + + expect(mockForwardMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + messages: [10, 20], + }), + ); + }); +}); diff --git a/cli/tests/unit/message-get.test.ts b/cli/tests/unit/message-get.test.ts new file mode 100644 index 0000000..32b6b9c --- /dev/null +++ b/cli/tests/unit/message-get.test.ts @@ -0,0 +1,277 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetMessages, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetMessages: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getMessages: mockGetMessages, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +const mockSerializeMessage = vi.fn().mockImplementation((msg: any, _sender?: any) => ({ + id: msg.id, + text: msg.message ?? '', + date: '2026-03-12T12:00:00.000Z', + senderId: msg.senderId?.toString() ?? null, + senderName: 'Test User', + replyToMsgId: null, + forwardFrom: null, + mediaType: null, + type: 'message', +})); +vi.mock('../../src/lib/serialize.js', async (importOriginal) => ({ + ...(await importOriginal<typeof import('../../src/lib/serialize.js')>()), + serializeMessage: (...args: any[]) => mockSerializeMessage(...args), +})); + +// Mock entity-map +const mockBuildEntityMap = vi.fn().mockReturnValue(new Map()); +vi.mock('../../src/lib/entity-map.js', () => ({ + buildEntityMap: (...args: any[]) => mockBuildEntityMap(...args), +})); + +// Import after mocks +import { messageGetAction } from '../../src/commands/message/get.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +// Helper to create mock message objects (gramjs style) +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Hello world', + date: 1710150900, + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + fromId: { userId: BigInt(456) }, + _sender: { id: BigInt(456), firstName: 'Test', lastName: 'User' }, + }; + return { ...defaults, ...overrides }; +} + +describe('messageGetAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns messages for valid IDs', async () => { + const messages = [ + createMockMessage({ id: 100 }), + createMockMessage({ id: 101 }), + createMockMessage({ id: 102 }), + ]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100,101,102'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'mychat'); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ ids: [100, 101, 102] }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(3); + expect(data.notFound).toEqual([]); + }); + + it('populates notFound for missing IDs', async () => { + const messages = [ + createMockMessage({ id: 100 }), + undefined, + createMockMessage({ id: 102 }), + ]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100,101,102'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + expect(data.notFound).toEqual([101]); + }); + + it('rejects invalid IDs', async () => { + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', 'abc,0,-1'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message IDs'), + 'INVALID_MESSAGE_ID', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('rejects over 100 IDs', async () => { + const ids = Array.from({ length: 101 }, (_, i) => i + 1).join(','); + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', ids); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Maximum 100 IDs per request'), + 'TOO_MANY_IDS', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('preserves order', async () => { + const messages = [ + createMockMessage({ id: 3 }), + createMockMessage({ id: 1 }), + createMockMessage({ id: 2 }), + ]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '3,1,2'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(3); + // Messages should preserve input order (positional matching) + expect(data.messages[0].id).toBe(3); + expect(data.messages[1].id).toBe(1); + expect(data.messages[2].id).toBe(2); + }); + + it('all not found returns empty messages with full notFound', async () => { + const messages = [undefined, undefined, undefined]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100,101,102'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toEqual([]); + expect(data.notFound).toEqual([100, 101, 102]); + }); + + it('falls back to buildEntityMap when _sender is missing', async () => { + const entityUser = { id: BigInt(789), firstName: 'Entity', lastName: 'User' }; + mockBuildEntityMap.mockReturnValueOnce(new Map([['789', entityUser]])); + + const messages = [ + createMockMessage({ id: 100, _sender: null, fromId: { userId: BigInt(789) } }), + ]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100'); + + expect(mockBuildEntityMap).toHaveBeenCalledWith(messages); + // serializeMessage should receive the entity from the map, not null + expect(mockSerializeMessage).toHaveBeenCalledWith( + messages[0], + entityUser, + ); + }); + + it('passes undefined sender when neither _sender nor entity map has data', async () => { + mockBuildEntityMap.mockReturnValueOnce(new Map()); + + const messages = [ + createMockMessage({ id: 100, _sender: null, fromId: { userId: BigInt(999) } }), + ]; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100'); + + expect(mockSerializeMessage).toHaveBeenCalledWith(messages[0], undefined); + }); + + it('unauthenticated returns NOT_AUTHENTICATED', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null); + }); + + const ctx = createMockCommandContext(); + await messageGetAction.call(ctx as any, 'mychat', '100'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/message-history-envelope.test.ts b/cli/tests/unit/message-history-envelope.test.ts new file mode 100644 index 0000000..a3e6c8e --- /dev/null +++ b/cli/tests/unit/message-history-envelope.test.ts @@ -0,0 +1,61 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +const mockGetMessages = vi.fn(); +vi.mock('../../src/lib/with-auth.js', () => ({ + withAuth: vi.fn(async (_opts: any, fn: any) => + fn({ getMessages: mockGetMessages }), + ), +})); + +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: vi.fn().mockResolvedValue({ id: 1, className: 'User' }), + assertForum: vi.fn().mockResolvedValue(undefined), +})); + +import { messageHistoryAction } from '../../src/commands/message/history.js'; + +describe('message history envelope (no output/serialize mock)', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + vi.clearAllMocks(); + process.exitCode = 0; + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + process.exitCode = 0; + }); + + it('includes senderName from msg._sender in the JSON envelope', async () => { + mockGetMessages.mockResolvedValue([ + { + id: 7, + date: 1_700_000_000, + message: 'hello', + senderId: 99, + _sender: { firstName: 'Alice', lastName: 'Smith' }, + }, + ]); + + await messageHistoryAction.call( + { + optsWithGlobals: () => ({ + profile: 'default', + quiet: true, + json: true, + limit: '50', + offset: '0', + }), + } as any, + '@alice', + ); + + const parsed = JSON.parse(stdoutSpy.mock.calls[0][0] as string); + expect(parsed.ok).toBe(true); + expect(parsed.data.messages[0].id).toBe(7); + expect(parsed.data.messages[0].text).toBe('hello'); + expect(parsed.data.messages[0].senderName).toBe('Alice Smith'); + }); +}); diff --git a/cli/tests/unit/message-history.test.ts b/cli/tests/unit/message-history.test.ts new file mode 100644 index 0000000..d192e72 --- /dev/null +++ b/cli/tests/unit/message-history.test.ts @@ -0,0 +1,361 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetMessages, + MockMediaPhoto, + MockMediaDocument, + MockMediaPoll, + MockAttrSticker, + MockAttrVideo, + MockAttrAudio, + MockAttrFilename, + MockAttrImageSize, + MockActionChatCreate, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetMessages: vi.fn().mockResolvedValue([]), + MockMediaPhoto: class {}, + MockMediaDocument: class {}, + MockMediaPoll: class {}, + MockAttrSticker: class { alt = ''; }, + MockAttrVideo: class {}, + MockAttrAudio: class { voice = false; }, + MockAttrFilename: class { fileName = ''; }, + MockAttrImageSize: class { w = 0; h = 0; }, + MockActionChatCreate: class {}, +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getMessages: mockGetMessages, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + MessageMediaPhoto: MockMediaPhoto, + MessageMediaDocument: MockMediaDocument, + MessageMediaPoll: MockMediaPoll, + DocumentAttributeSticker: MockAttrSticker, + DocumentAttributeVideo: MockAttrVideo, + DocumentAttributeAudio: MockAttrAudio, + DocumentAttributeFilename: MockAttrFilename, + DocumentAttributeImageSize: MockAttrImageSize, + MessageActionChatCreate: MockActionChatCreate, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +const mockAssertForum = vi.fn().mockResolvedValue(undefined); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + assertForum: (...args: any[]) => mockAssertForum(...args), +})); + +// Helper to create mock message objects +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Hello world', + date: 1710150900, // 2024-03-11T09:55:00Z + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + }; + return { ...defaults, ...overrides }; +} + +// Import after mocks +import { messageHistoryAction } from '../../src/commands/message/history.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('messageHistoryAction', () => { + it('rejects an explicitly empty topic before connecting', async () => { + await messageHistoryAction.call(createMockCommandContext({ topic: '' }) as any, 'testchat'); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), 'INVALID_TOPIC_ID'); + expect(mockResolveEntity).not.toHaveBeenCalled(); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns messages array and total count for a chat', async () => { + const messages = [ + createMockMessage({ id: 10, message: 'Message 10' }), + createMockMessage({ id: 9, message: 'Message 9' }), + ]; + (messages as any).total = 50; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testchat'); + expect(mockGetMessages).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + expect(data.total).toBe(50); + expect(data.messages[0].id).toBe(10); + expect(data.messages[1].id).toBe(9); + }); + + it('passes --limit and --offset as pagination params', async () => { + const messages: any[] = []; + (messages as any).total = 100; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + limit: 10, + addOffset: 5, + }), + ); + }); + + it('filters messages by --since date (post-filter)', async () => { + const messages = [ + createMockMessage({ id: 3, date: 1710300000 }), // 2024-03-13 + createMockMessage({ id: 2, date: 1710200000 }), // 2024-03-12 + createMockMessage({ id: 1, date: 1710100000 }), // 2024-03-11 + ]; + (messages as any).total = 3; + mockGetMessages.mockResolvedValueOnce(messages); + + // Filter: only messages after March 12 midnight + const ctx = createMockCommandContext({ since: '2024-03-12T00:00:00Z' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + // Should include only messages on or after March 12 + expect(data.messages.every((m: any) => new Date(m.date).getTime() >= new Date('2024-03-12T00:00:00Z').getTime())).toBe(true); + }); + + it('rejects invalid --since without calling Telegram', async () => { + const ctx = createMockCommandContext({ since: 'not-a-date' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--since'), + 'INVALID_INPUT', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('rejects invalid --until without calling Telegram', async () => { + const ctx = createMockCommandContext({ until: 'garbage' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--until'), + 'INVALID_INPUT', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('sets offsetDate when --until is provided', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ until: '2024-03-10T00:00:00Z' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + const expectedTimestamp = Math.floor(new Date('2024-03-10T00:00:00Z').getTime() / 1000); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + offsetDate: expectedTimestamp, + }), + ); + }); + + it('applies both --since and --until together', async () => { + const messages = [ + createMockMessage({ id: 3, date: 1710300000 }), // 2024-03-13 + createMockMessage({ id: 2, date: 1710200000 }), // 2024-03-12 + ]; + (messages as any).total = 2; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ + since: '2024-03-12T00:00:00Z', + until: '2024-03-14T00:00:00Z', + }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + // --until should set offsetDate + const untilTimestamp = Math.floor(new Date('2024-03-14T00:00:00Z').getTime() / 1000); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + offsetDate: untilTimestamp, + }), + ); + + // --since should post-filter + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages.length).toBeGreaterThanOrEqual(1); + }); + + it('handles empty chat (no messages)', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageHistoryAction.call(ctx as any, 'emptychat'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(0); + expect(data.total).toBe(0); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + // ---- Topic tests (Phase 5, Plan 03) ---- + + it('passes replyTo to getMessages when --topic is provided', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ topic: '42' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockAssertForum).toHaveBeenCalledWith( + expect.objectContaining({ className: 'Channel' }), + 42, + ); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ replyTo: 42 }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('does not pass replyTo when --topic is not provided', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.not.objectContaining({ replyTo: expect.anything() }), + ); + }); + + it('outputs error for non-forum entity when --topic is used', async () => { + const { TgError } = await import('../../src/lib/errors.js'); + mockAssertForum.mockRejectedValueOnce( + new TgError('Chat is not a forum-enabled supergroup', 'NOT_A_FORUM'), + ); + + const ctx = createMockCommandContext({ topic: '42' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Chat is not a forum-enabled supergroup', + 'NOT_A_FORUM', + ); + }); + + it('outputs error for invalid topic ID', async () => { + const ctx = createMockCommandContext({ topic: 'abc' }); + await messageHistoryAction.call(ctx as any, 'testchat'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Invalid topic ID: must be a number', + 'INVALID_TOPIC_ID', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/message-pin.test.ts b/cli/tests/unit/message-pin.test.ts new file mode 100644 index 0000000..f8821a5 --- /dev/null +++ b/cli/tests/unit/message-pin.test.ts @@ -0,0 +1,201 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockPinMessage, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockPinMessage: vi.fn().mockResolvedValue(undefined), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + pinMessage: mockPinMessage, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(456), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize (for bigIntToString) +vi.mock('../../src/lib/serialize.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/serialize.js')>(); + return { ...actual, bigIntToString: (v: bigint) => String(v) }; +}); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { messagePinAction } from '../../src/commands/message/pin.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messagePinAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockPinMessage.mockResolvedValue(undefined); + }); + + it('pins silently by default (notify: false)', async () => { + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', '42'); + + expect(mockPinMessage).toHaveBeenCalledWith( + expect.anything(), + 42, + { notify: false }, + ); + }); + + it('pins with notification when --notify is set', async () => { + const ctx = createMockCommandContext({ notify: true }); + await messagePinAction.call(ctx as any, 'testchat', '42'); + + expect(mockPinMessage).toHaveBeenCalledWith( + expect.anything(), + 42, + { notify: true }, + ); + }); + + it('outputs PinResult with silent: true by default', async () => { + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + messageId: 42, + chatId: '-100456', + action: 'pinned', + silent: true, + }); + }); + + it('outputs PinResult with silent: false when --notify', async () => { + const ctx = createMockCommandContext({ notify: true }); + await messagePinAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + messageId: 42, + chatId: '-100456', + action: 'pinned', + silent: false, + }); + }); + + it('outputs INVALID_MESSAGE_ID for non-numeric message ID', async () => { + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', 'notanumber'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockPinMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for mixed string like "12abc"', async () => { + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', '12abc'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockPinMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for zero', async () => { + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', '0'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockPinMessage).not.toHaveBeenCalled(); + }); + + it('translates RPCError via translateTelegramError', async () => { + mockPinMessage.mockRejectedValueOnce({ errorMessage: 'CHAT_ADMIN_REQUIRED' }); + + const ctx = createMockCommandContext(); + await messagePinAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Admin privileges required', + 'CHAT_ADMIN_REQUIRED', + ); + }); +}); diff --git a/cli/tests/unit/message-pinned.test.ts b/cli/tests/unit/message-pinned.test.ts new file mode 100644 index 0000000..91cca0a --- /dev/null +++ b/cli/tests/unit/message-pinned.test.ts @@ -0,0 +1,218 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetMessages, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetMessages: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getMessages: mockGetMessages, +}; + +// Hoisted mock for InputMessagesFilterPinned +const { MockInputMessagesFilterPinned } = vi.hoisted(() => { + class MockInputMessagesFilterPinned {} + return { MockInputMessagesFilterPinned }; +}); + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + InputMessagesFilterPinned: MockInputMessagesFilterPinned, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +const mockSerializeMessage = vi.fn().mockImplementation((msg: any, _sender?: any) => ({ + id: msg.id, + text: msg.message ?? '', + date: '2026-03-12T12:00:00.000Z', + senderId: msg.senderId?.toString() ?? null, + senderName: 'Test User', + replyToMsgId: null, + forwardFrom: null, + mediaType: null, + type: 'message', +})); +vi.mock('../../src/lib/serialize.js', () => ({ + serializeMessage: (...args: any[]) => mockSerializeMessage(...args), +})); + +// Import after mocks +import { messagePinnedAction } from '../../src/commands/message/pinned.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +// Helper to create mock message objects +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Hello world', + date: 1710150900, + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + _sender: { id: BigInt(456), firstName: 'Test', lastName: 'User' }, + }; + return { ...defaults, ...overrides }; +} + +describe('messagePinnedAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns pinned messages', async () => { + const messages = [ + createMockMessage({ id: 10 }), + createMockMessage({ id: 20 }), + ]; + (messages as any).total = 5; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messagePinnedAction.call(ctx as any, 'mychat'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'mychat'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + expect(data.total).toBe(5); + }); + + it('empty chat returns empty result', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messagePinnedAction.call(ctx as any, 'mychat'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toEqual([]); + expect(data.total).toBe(0); + }); + + it('pagination passes limit and addOffset', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await messagePinnedAction.call(ctx as any, 'mychat'); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + limit: 10, + addOffset: 5, + }), + ); + }); + + it('passes search empty string for pinned filter', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext(); + await messagePinnedAction.call(ctx as any, 'mychat'); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: '', + filter: expect.any(MockInputMessagesFilterPinned), + }), + ); + }); + + it('unauthenticated returns NOT_AUTHENTICATED', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null); + }); + + const ctx = createMockCommandContext(); + await messagePinnedAction.call(ctx as any, 'mychat'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/message-poll.test.ts b/cli/tests/unit/message-poll.test.ts new file mode 100644 index 0000000..7423396 --- /dev/null +++ b/cli/tests/unit/message-poll.test.ts @@ -0,0 +1,360 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockSendFile, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockSendFile: vi.fn().mockResolvedValue({ id: 99, message: '', date: 1710000000 }), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + sendFile: mockSendFile, +}; + +// Mock telegram with Api classes needed for polls +vi.mock('teleproto', () => { + class Poll { + constructor(public params: any) {} + } + class InputPollAnswer { + constructor(public params: any) {} + } + class TextWithEntities { + constructor(public params: any) {} + } + class InputMediaPoll { + constructor(public params: any) {} + } + return { + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Poll, + InputPollAnswer, + TextWithEntities, + InputMediaPoll, + }, + }; +}); + +vi.mock('teleproto/Helpers.js', () => ({ + generateRandomLong: vi.fn(() => BigInt(123456)), +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(456), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +const mockSerializeMessage = vi.fn().mockReturnValue({ + id: 99, + text: '', + date: '2026-03-13T00:00:00.000Z', + senderId: '123', + senderName: 'Tester', + replyToMsgId: null, + forwardFrom: null, + mediaType: 'poll', + type: 'message', +}); +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: bigint) => String(v), + serializeMessage: (...args: any[]) => mockSerializeMessage(...args), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { validatePollOpts, messagePollAction } from '../../src/commands/message/poll.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('validatePollOpts', () => { + it.each(['12junk', '-1', '1.5', '1e2', '2147483648', '9007199254740993', ''])('rejects invalid close-in without parseInt truncation: %s', closeIn => { + expect(validatePollOpts({ question: 'Pick', option: ['A', 'B'], closeIn })?.code).toBe('INVALID_CLOSE_IN'); + }); + + it.each(['1junk', '1.5', '1e0', '2147483648'])('rejects invalid correct index: %s', correct => { + expect(validatePollOpts({ question: 'Pick', option: ['A', 'B'], quiz: true, correct })?.code).toBe('INVALID_CORRECT_INDEX'); + }); + const validOpts = { + question: 'Favorite color?', + option: ['Red', 'Blue'], + }; + + it('returns null for valid basic poll', () => { + expect(validatePollOpts(validOpts)).toBeNull(); + }); + + it('rejects empty question', () => { + const result = validatePollOpts({ ...validOpts, question: '' }); + expect(result).toEqual({ error: 'Poll question cannot be empty', code: 'EMPTY_QUESTION' }); + }); + + it('rejects whitespace-only question', () => { + const result = validatePollOpts({ ...validOpts, question: ' ' }); + expect(result).toEqual({ error: 'Poll question cannot be empty', code: 'EMPTY_QUESTION' }); + }); + + it('rejects question > 300 chars', () => { + const result = validatePollOpts({ ...validOpts, question: 'x'.repeat(301) }); + expect(result).toEqual({ error: 'Question too long (max 300 chars)', code: 'QUESTION_TOO_LONG' }); + }); + + it('rejects < 2 options', () => { + const result = validatePollOpts({ ...validOpts, option: ['Only one'] }); + expect(result).toEqual({ error: 'Poll requires 2-10 options', code: 'TOO_FEW_OPTIONS' }); + }); + + it('rejects > 10 options', () => { + const opts = { ...validOpts, option: Array.from({ length: 11 }, (_, i) => `Opt ${i}`) }; + const result = validatePollOpts(opts); + expect(result).toEqual({ error: 'Poll requires 2-10 options', code: 'TOO_MANY_OPTIONS' }); + }); + + it('rejects empty option', () => { + const result = validatePollOpts({ ...validOpts, option: ['Red', ''] }); + expect(result).toEqual({ error: 'Poll option cannot be empty', code: 'EMPTY_OPTION' }); + }); + + it('rejects whitespace-only option', () => { + const result = validatePollOpts({ ...validOpts, option: ['Red', ' '] }); + expect(result).toEqual({ error: 'Poll option cannot be empty', code: 'EMPTY_OPTION' }); + }); + + it('rejects option > 100 chars', () => { + const result = validatePollOpts({ ...validOpts, option: ['Red', 'x'.repeat(101)] }); + expect(result).toEqual({ error: 'Option too long (max 100 chars)', code: 'OPTION_TOO_LONG' }); + }); + + it('rejects duplicate option text', () => { + const result = validatePollOpts({ ...validOpts, option: ['Red', 'Blue', 'Red'] }); + expect(result).toEqual({ error: "Duplicate option text: 'Red'", code: 'DUPLICATE_OPTION' }); + }); + + it('rejects --quiz without --correct', () => { + const result = validatePollOpts({ ...validOpts, quiz: true }); + expect(result).toEqual({ error: 'Quiz mode requires --correct <index>', code: 'QUIZ_MISSING_CORRECT' }); + }); + + it('rejects --solution without --quiz', () => { + const result = validatePollOpts({ ...validOpts, solution: 'Because reasons' }); + expect(result).toEqual({ error: '--solution requires --quiz mode', code: 'SOLUTION_WITHOUT_QUIZ' }); + }); + + it('rejects --multiple with --quiz', () => { + const result = validatePollOpts({ ...validOpts, quiz: true, correct: '1', multiple: true }); + expect(result).toEqual({ error: 'Quiz mode cannot use --multiple', code: 'QUIZ_MULTIPLE_CONFLICT' }); + }); + + it('rejects --correct out of range (too high)', () => { + const result = validatePollOpts({ ...validOpts, quiz: true, correct: '5' }); + expect(result).toEqual({ error: 'Correct index must be 1-2', code: 'INVALID_CORRECT_INDEX' }); + }); + + it('rejects --correct out of range (zero)', () => { + const result = validatePollOpts({ ...validOpts, quiz: true, correct: '0' }); + expect(result).toEqual({ error: 'Correct index must be 1-2', code: 'INVALID_CORRECT_INDEX' }); + }); + + it('rejects --correct NaN', () => { + const result = validatePollOpts({ ...validOpts, quiz: true, correct: 'abc' }); + expect(result).toEqual({ error: 'Correct index must be 1-2', code: 'INVALID_CORRECT_INDEX' }); + }); + + it('rejects --close-in <= 0', () => { + const result = validatePollOpts({ ...validOpts, closeIn: '0' }); + expect(result).toEqual({ error: 'Close-in seconds must be > 0', code: 'INVALID_CLOSE_IN' }); + }); + + it('rejects --close-in NaN', () => { + const result = validatePollOpts({ ...validOpts, closeIn: 'soon' }); + expect(result).toEqual({ error: 'Close-in seconds must be > 0', code: 'INVALID_CLOSE_IN' }); + }); + + it('accepts valid quiz poll', () => { + const result = validatePollOpts({ ...validOpts, quiz: true, correct: '1', solution: 'Reason' }); + expect(result).toBeNull(); + }); + + it('accepts valid poll with --multiple, --public, --close-in', () => { + const result = validatePollOpts({ ...validOpts, multiple: true, public: true, closeIn: '30' }); + expect(result).toBeNull(); + }); +}); + +describe('messagePollAction', () => { + it('reports an unknown sent poll result without repeating the write', async () => { + mockSendFile.mockResolvedValueOnce(undefined); + await messagePollAction.call(createMockCommandContext({ question: 'Choose', option: ['A', 'B'] }) as any, 'testchat'); + expect(mockSendFile).toHaveBeenCalledOnce(); + expect(mockOutputError).toHaveBeenCalledWith(expect.stringContaining('duplicate'), 'MESSAGE_RESULT_UNAVAILABLE'); + expect(mockOutputSuccess).not.toHaveBeenCalled(); + }); + beforeEach(() => { + vi.clearAllMocks(); + mockSendFile.mockResolvedValue({ id: 99, message: '', date: 1710000000 }); + }); + + it('sends basic poll via sendFile with InputMediaPoll', async () => { + const ctx = createMockCommandContext({ + question: 'Favorite color?', + option: ['Red', 'Blue'], + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockSendFile).toHaveBeenCalledTimes(1); + const call = mockSendFile.mock.calls[0]; + // First arg is entity, second is options with file: InputMediaPoll + expect(call[1]).toHaveProperty('file'); + expect(mockOutputSuccess).toHaveBeenCalled(); + expect(mockOutputError).not.toHaveBeenCalled(); + }); + + it('sends quiz poll with correctAnswers', async () => { + const ctx = createMockCommandContext({ + question: 'Capital of France?', + option: ['Berlin', 'Paris', 'London'], + quiz: true, + correct: '2', + solution: 'Paris is the capital of France', + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockSendFile).toHaveBeenCalledTimes(1); + const call = mockSendFile.mock.calls[0]; + const inputMedia = call[1].file; + // correctAnswers should reference index 1 (0-based for option 2) + expect(inputMedia.params.correctAnswers).toBeDefined(); + expect(inputMedia.params.solution).toBe('Paris is the capital of France'); + expect(mockOutputSuccess).toHaveBeenCalled(); + }); + + it('sends poll with --multiple, --public, --close-in', async () => { + const ctx = createMockCommandContext({ + question: 'Pick colors', + option: ['Red', 'Blue', 'Green'], + multiple: true, + public: true, + closeIn: '60', + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockSendFile).toHaveBeenCalledTimes(1); + const call = mockSendFile.mock.calls[0]; + const inputMedia = call[1].file; + const poll = inputMedia.params.poll; + expect(poll.params.multipleChoice).toBe(true); + expect(poll.params.publicVoters).toBe(true); + expect(poll.params.closePeriod).toBe(60); + expect(mockOutputSuccess).toHaveBeenCalled(); + }); + + it('calls outputError for validation failure without calling sendFile', async () => { + const ctx = createMockCommandContext({ + question: '', + option: ['Red', 'Blue'], + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockOutputError).toHaveBeenCalledWith('Poll question cannot be empty', 'EMPTY_QUESTION'); + expect(mockSendFile).not.toHaveBeenCalled(); + }); + + it('returns serialized MessageItem via outputSuccess', async () => { + const ctx = createMockCommandContext({ + question: 'Test?', + option: ['A', 'B'], + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockSerializeMessage).toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledWith(expect.objectContaining({ + id: 99, + mediaType: 'poll', + })); + }); + + it('translates RPCError via translateTelegramError', async () => { + mockSendFile.mockRejectedValueOnce({ errorMessage: 'CHAT_SEND_POLL_FORBIDDEN' }); + + const ctx = createMockCommandContext({ + question: 'Test?', + option: ['A', 'B'], + }); + await messagePollAction.call(ctx as any, 'testchat'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'You cannot send polls in this chat', + 'CHAT_SEND_POLL_FORBIDDEN', + ); + }); +}); diff --git a/cli/tests/unit/message-react.test.ts b/cli/tests/unit/message-react.test.ts new file mode 100644 index 0000000..f296319 --- /dev/null +++ b/cli/tests/unit/message-react.test.ts @@ -0,0 +1,197 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client and Api types +const { + mockConnect, + mockDestroy, + mockInvoke, + mockSendReactionConstructor, + mockReactionEmojiConstructor, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue({}), + mockSendReactionConstructor: vi.fn().mockImplementation((args: any) => ({ + _type: 'SendReaction', + ...args, + })), + mockReactionEmojiConstructor: vi.fn().mockImplementation((args: any) => ({ + _type: 'ReactionEmoji', + ...args, + })), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + messages: { + SendReaction: mockSendReactionConstructor, + }, + ReactionEmoji: mockReactionEmojiConstructor, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Import after mocks +import { messageReactAction } from '../../src/commands/message/react.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageReactAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('adds a reaction using Api.ReactionEmoji wrapper', async () => { + const ctx = createMockCommandContext(); + await messageReactAction.call(ctx as any, 'testchat', '42', '👍'); + + // Verify ReactionEmoji was constructed with the emoji + expect(mockReactionEmojiConstructor).toHaveBeenCalledWith({ emoticon: '👍' }); + + // Verify SendReaction was constructed with correct params + expect(mockSendReactionConstructor).toHaveBeenCalledWith( + expect.objectContaining({ + peer: expect.anything(), + msgId: 42, + reaction: expect.arrayContaining([ + expect.objectContaining({ _type: 'ReactionEmoji', emoticon: '👍' }), + ]), + }), + ); + + // Verify invoke was called + expect(mockInvoke).toHaveBeenCalledOnce(); + + // Verify output + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messageId).toBe(42); + expect(data.emoji).toBe('👍'); + expect(data.action).toBe('added'); + expect(data.chatId).toBeDefined(); + }); + + it('removes a reaction with --remove flag (empty reaction array)', async () => { + const ctx = createMockCommandContext({ remove: true }); + await messageReactAction.call(ctx as any, 'testchat', '42', '👍'); + + // Verify SendReaction was constructed with empty reaction array + expect(mockSendReactionConstructor).toHaveBeenCalledWith( + expect.objectContaining({ + peer: expect.anything(), + msgId: 42, + reaction: [], + }), + ); + + // ReactionEmoji should NOT be constructed for remove + expect(mockReactionEmojiConstructor).not.toHaveBeenCalled(); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.action).toBe('removed'); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await messageReactAction.call(ctx as any, 'testchat', '42', '👍'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + it('parses message ID as integer', async () => { + const ctx = createMockCommandContext(); + await messageReactAction.call(ctx as any, 'testchat', '999', '❤️'); + + expect(mockSendReactionConstructor).toHaveBeenCalledWith( + expect.objectContaining({ + msgId: 999, + }), + ); + }); + + it('rejects invalid message ID with INVALID_MESSAGE_ID error', async () => { + const ctx = createMockCommandContext(); + await messageReactAction.call(ctx as any, 'testchat', 'abc', '👍'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/message-replies.test.ts b/cli/tests/unit/message-replies.test.ts new file mode 100644 index 0000000..47c1b2f --- /dev/null +++ b/cli/tests/unit/message-replies.test.ts @@ -0,0 +1,250 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const { mockConnect, mockDestroy, mockInvoke } = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn(), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + messages: { + GetReplies: vi.fn().mockImplementation((opts: any) => opts), + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +vi.mock('../../src/lib/serialize.js', async (importOriginal) => ({ + ...(await importOriginal<typeof import('../../src/lib/serialize.js')>()), + serializeMessage: vi.fn((msg: any, sender?: any) => ({ + id: String(msg.id), + text: msg.message ?? '', + date: new Date(msg.date * 1000).toISOString(), + senderId: sender ? String(sender.id) : null, + })), +})); + +vi.mock('../../src/lib/entity-map.js', () => ({ + buildEntityMap: vi.fn((result: any) => { + const map = new Map<string, any>(); + for (const u of result.users ?? []) { + map.set(u.id.toString(), u); + } + for (const c of result.chats ?? []) { + map.set(c.id.toString(), c); + } + return map; + }), +})); + +import { messageRepliesAction } from '../../src/commands/message/replies.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +function createMockReplyResult(messages: any[], count = 0) { + return { + messages, + users: [], + chats: [], + count, + }; +} + +function createMockMessage(id: number, text = 'reply') { + return { + id, + message: text, + date: 1710150900, + fromId: { userId: { toString: () => '456' } }, + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + }; +} + +describe('messageRepliesAction', () => { + const originalExitCode = process.exitCode; + afterEach(() => { process.exitCode = originalExitCode; }); + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('single post mode → outputs messages, total, postId', async () => { + const result = createMockReplyResult([ + createMockMessage(1, 'first reply'), + createMockMessage(2, 'second reply'), + ], 10); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '42'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.postId).toBe(42); + expect(data.total).toBe(10); + expect(data.messages).toHaveLength(2); + }); + + it('batch mode → outputs array of results', async () => { + const result1 = createMockReplyResult([createMockMessage(1)], 5); + const result2 = createMockReplyResult([createMockMessage(2)], 3); + mockInvoke.mockResolvedValueOnce(result1).mockResolvedValueOnce(result2); + + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '10,20'); + + expect(mockInvoke).toHaveBeenCalledTimes(2); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.posts).toHaveLength(2); + expect(data.posts[0].postId).toBe(10); + expect(data.posts[0].total).toBe(5); + expect(data.posts[1].postId).toBe(20); + expect(data.posts[1].total).toBe(3); + }); + + it('batch with error on one post preserves successes and reports the failure', async () => { + const result1 = createMockReplyResult([createMockMessage(1)], 5); + mockInvoke + .mockResolvedValueOnce(result1) + .mockRejectedValueOnce(new Error('MSG_ID_INVALID')); + + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '10,99'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.posts).toHaveLength(1); + expect(data.posts[0].messages).toHaveLength(1); + expect(data.partial).toBe(true); + expect(data.errors).toEqual([{ input: '99', error: 'MSG_ID_INVALID', code: 'UNKNOWN_ERROR' }]); + expect(process.exitCode).toBe(1); + }); + + it('invalid message ID (non-number) → error', async () => { + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', 'abc'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message IDs'), + 'INVALID_MESSAGE_ID', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('invalid message ID (zero) → error', async () => { + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '0'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message IDs'), + 'INVALID_MESSAGE_ID', + ); + }); + + it('invalid message ID (negative) → error', async () => { + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '-5'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message IDs'), + 'INVALID_MESSAGE_ID', + ); + }); + + it('respects --limit and --offset options', async () => { + const result = createMockReplyResult([], 100); + mockInvoke.mockResolvedValueOnce(result); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await messageRepliesAction.call(ctx as any, '@channel', '42'); + + const invokeArg = mockInvoke.mock.calls[0][0]; + expect(invokeArg.limit).toBe(10); + expect(invokeArg.addOffset).toBe(5); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', '42'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + it('empty message IDs string → error', async () => { + const ctx = createMockCommandContext(); + await messageRepliesAction.call(ctx as any, '@channel', ''); + + expect(mockOutputError).toHaveBeenCalled(); + expect(mockInvoke).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/message-search-public.test.ts b/cli/tests/unit/message-search-public.test.ts new file mode 100644 index 0000000..9e7bc1b --- /dev/null +++ b/cli/tests/unit/message-search-public.test.ts @@ -0,0 +1,269 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const { mockInvoke, mockGetMessages, mockGetInputEntity } = vi.hoisted(() => ({ + mockInvoke: vi.fn(), + mockGetMessages: vi.fn(), + mockGetInputEntity: vi.fn(async (entity: unknown) => entity), +})); + +const mockClientInstance = { + connect: vi.fn(), + destroy: vi.fn(), + invoke: mockInvoke, + getMessages: mockGetMessages, + getInputEntity: mockGetInputEntity, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { StringSession: vi.fn() }, + Api: { + InputPeerEmpty: class InputPeerEmpty { + className = 'InputPeerEmpty'; + }, + channels: { + SearchPosts: class SearchPosts { + className = 'channels.SearchPosts'; + hashtag: string; + offsetRate: number; + offsetPeer: unknown; + offsetId: number; + limit: number; + constructor(args: any) { + this.hashtag = args.hashtag; + this.offsetRate = args.offsetRate; + this.offsetPeer = args.offsetPeer; + this.offsetId = args.offsetId; + this.limit = args.limit; + } + }, + }, + InputMessagesFilterPhotos: class {}, + InputMessagesFilterVideo: class {}, + InputMessagesFilterPhotoVideo: class {}, + InputMessagesFilterDocument: class {}, + InputMessagesFilterUrl: class {}, + InputMessagesFilterGif: class {}, + InputMessagesFilterVoice: class {}, + InputMessagesFilterMusic: class {}, + InputMessagesFilterRoundVideo: class {}, + InputMessagesFilterRoundVoice: class {}, + InputMessagesFilterChatPhotos: class {}, + InputMessagesFilterPhoneCalls: class {}, + InputMessagesFilterMyMentions: class {}, + InputMessagesFilterGeo: class {}, + InputMessagesFilterContacts: class {}, + InputMessagesFilterPinned: class {}, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn(async (_p: string, fn: (s: string) => Promise<any>) => fn('test-session')), + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + assertForum: vi.fn(), +})); + +import { messageSearchAction } from '../../src/commands/message/search.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +function ctx(opts: Record<string, unknown> = {}) { + return { + optsWithGlobals: () => ({ + profile: 'default', + quiet: true, + json: true, + human: false, + verbose: false, + query: undefined, + chat: undefined, + limit: '50', + offset: '0', + ...opts, + }), + }; +} + +function post(overrides: Record<string, unknown> = {}) { + return { + id: 10, + message: 'hello #bitcoin', + date: 1_700_000_000, + senderId: BigInt(1), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + peerId: { channelId: BigInt(999) }, + ...overrides, + }; +} + +describe('message search --public', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue({ messages: [], chats: [], count: 0 }); + }); + + it('requires --query', async () => { + await messageSearchAction.call(ctx({ public: true }) as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--query'), + ErrorCode.MISSING_QUERY, + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('rejects --public with --chat', async () => { + await messageSearchAction.call(ctx({ public: true, query: 'btc', chat: '@x' }) as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--chat'), + ErrorCode.INVALID_OPTIONS, + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('rejects --public with --filter', async () => { + await messageSearchAction.call(ctx({ public: true, query: 'btc', filter: 'photos' }) as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--filter'), + ErrorCode.INVALID_OPTIONS, + ); + }); + + it('rejects a multi-word query', async () => { + await messageSearchAction.call(ctx({ public: true, query: 'meeting notes' }) as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('hashtag'), + ErrorCode.INVALID_OPTIONS, + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('invokes channels.SearchPosts with a stripped hashtag', async () => { + const channel = { id: BigInt(999), className: 'Channel', title: 'Coin News', username: 'coinnews' }; + mockInvoke.mockResolvedValueOnce({ + messages: [post()], + chats: [channel], + count: 1, + nextRate: 42, + }); + + await messageSearchAction.call(ctx({ public: true, query: '#bitcoin', limit: '20' }) as any); + + expect(mockGetMessages).not.toHaveBeenCalled(); + expect(mockInvoke).toHaveBeenCalledOnce(); + const req = mockInvoke.mock.calls[0][0]; + expect(req.className).toBe('channels.SearchPosts'); + expect(req.hashtag).toBe('bitcoin'); + expect(req.offsetRate).toBe(0); + expect(req.offsetId).toBe(0); + expect(req.limit).toBe(20); + expect(req.offsetPeer.className).toBe('InputPeerEmpty'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(1); + expect(data.messages[0].chatId).toBe('-100999'); + expect(data.messages[0].chatTitle).toBe('Coin News'); + expect(data.total).toBe(1); + expect(data.hasMore).toBe(true); + expect(data.nextRate).toBe(42); + expect(data.nextOffsetId).toBe(10); + expect(data.nextOffsetPeer).toBe('-100999'); + }); + + it('passes pagination cursor --offset/--peer/--after', async () => { + mockResolveEntity.mockResolvedValueOnce({ id: BigInt(999), className: 'Channel' }); + mockGetInputEntity.mockResolvedValueOnce({ className: 'InputPeerChannel', channelId: BigInt(999) }); + mockInvoke.mockResolvedValueOnce({ messages: [], chats: [], count: 0 }); + + await messageSearchAction.call(ctx({ + public: true, + query: 'bitcoin', + offset: '77', + peer: '-100999', + after: '10', + }) as any); + + const req = mockInvoke.mock.calls[0][0]; + expect(req.offsetRate).toBe(77); + expect(req.offsetId).toBe(10); + expect(req.offsetPeer).toEqual({ className: 'InputPeerChannel', channelId: BigInt(999) }); + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '-100999'); + }); + + it('hasMore is false on a short last page', async () => { + mockInvoke.mockResolvedValueOnce({ + messages: [post({ id: 3 })], + chats: [{ id: BigInt(999), className: 'Channel', title: 'X' }], + count: 1, + }); + + await messageSearchAction.call(ctx({ public: true, query: 'btc', limit: '50' }) as any); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.hasMore).toBe(false); + expect(data.nextRate).toBeNull(); + expect(data.nextOffsetId).toBeNull(); + expect(data.nextOffsetPeer).toBeNull(); + }); + + it('includes search_flood when the API returns it', async () => { + mockInvoke.mockResolvedValueOnce({ + messages: [], + chats: [], + count: 0, + searchFlood: { + remains: 2, + totalDaily: 10, + waitTill: 1_700_000_100, + starsAmount: BigInt(30), + queryIsFree: true, + }, + }); + + await messageSearchAction.call(ctx({ public: true, query: 'btc' }) as any); + expect(mockOutputSuccess.mock.calls[0][0].flood).toEqual({ + remains: 2, + totalDaily: 10, + waitTill: 1_700_000_100, + starsAmount: '30', + queryIsFree: true, + }); + }); + + it('rejects --peer without --public', async () => { + await messageSearchAction.call(ctx({ query: 'hi', peer: '@x' }) as any); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--public'), + ErrorCode.INVALID_OPTIONS, + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/message-search.test.ts b/cli/tests/unit/message-search.test.ts new file mode 100644 index 0000000..0bd4001 --- /dev/null +++ b/cli/tests/unit/message-search.test.ts @@ -0,0 +1,625 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockGetMessages, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockGetMessages: vi.fn().mockResolvedValue([]), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + getMessages: mockGetMessages, + getInputEntity: vi.fn().mockResolvedValue({ className: 'InputPeerChannel' }), + invoke: vi.fn().mockResolvedValue({ messages: [], users: [], chats: [], count: 0 }), + iterMessages: vi.fn((...args: any[]) => { + const iterator = { + total: 0, + async *[Symbol.asyncIterator]() { + const messages = await mockGetMessages(...args); + iterator.total = (messages as any).total ?? messages.length; + yield* messages; + }, + }; + return iterator; + }), +}; + +// Hoisted mock classes for telegram Api +const { + MockInputMessagesFilterPhotos, + MockMediaPhoto, + MockMediaDocument, + MockMediaPoll, + MockAttrSticker, + MockAttrVideo, + MockAttrAudio, + MockAttrFilename, + MockAttrImageSize, + MockActionChatCreate, +} = vi.hoisted(() => ({ + MockInputMessagesFilterPhotos: class {}, + MockMediaPhoto: class {}, + MockMediaDocument: class {}, + MockMediaPoll: class {}, + MockAttrSticker: class { alt = ''; }, + MockAttrVideo: class {}, + MockAttrAudio: class { voice = false; }, + MockAttrFilename: class { fileName = ''; }, + MockAttrImageSize: class { w = 0; h = 0; }, + MockActionChatCreate: class {}, +})); + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + messages: { Search: class { constructor(args: any) { Object.assign(this, args); } } }, + InputMessagesFilterEmpty: class {}, + InputMessagesFilterPhotos: MockInputMessagesFilterPhotos, + InputMessagesFilterVideo: class {}, + InputMessagesFilterDocument: class {}, + InputMessagesFilterUrl: class {}, + InputMessagesFilterVoice: class {}, + InputMessagesFilterMusic: class {}, + InputMessagesFilterGif: class {}, + InputMessagesFilterRoundVideo: class {}, + MessageMediaPhoto: MockMediaPhoto, + MessageMediaDocument: MockMediaDocument, + MessageMediaPoll: MockMediaPoll, + DocumentAttributeSticker: MockAttrSticker, + DocumentAttributeVideo: MockAttrVideo, + DocumentAttributeAudio: MockAttrAudio, + DocumentAttributeFilename: MockAttrFilename, + DocumentAttributeImageSize: MockAttrImageSize, + MessageActionChatCreate: MockActionChatCreate, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +const mockAssertForum = vi.fn().mockResolvedValue(undefined); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + assertForum: (...args: any[]) => mockAssertForum(...args), +})); + +// Helper to create mock message objects +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Hello world', + date: 1710150900, + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + peerId: { channelId: BigInt(100), chatId: null, userId: null }, + chat: { title: 'Test Chat' }, + }; + return { ...defaults, ...overrides }; +} + +// Import after mocks +import { messageSearchAction } from '../../src/commands/message/search.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + query: undefined, + chat: undefined, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('messageSearchAction', () => { + const originalExitCode = process.exitCode; + afterEach(() => { process.exitCode = originalExitCode; }); + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('searches within a specific chat when --chat is provided', async () => { + const messages = [ + createMockMessage({ id: 5, message: 'Found keyword here' }), + ]; + (messages as any).total = 1; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ chat: 'mychat', query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'mychat'); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: 'keyword', + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(1); + expect(data.total).toBe(1); + }); + + it('searches globally when --chat is not provided', async () => { + const messages = [ + createMockMessage({ + id: 10, + message: 'Global result', + peerId: { channelId: BigInt(200), chatId: null, userId: null }, + chat: { title: 'Some Channel' }, + }), + ]; + (messages as any).total = 1; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + // Should NOT call resolveEntity for global search + expect(mockResolveEntity).not.toHaveBeenCalled(); + // Should call getMessages with undefined entity + expect(mockGetMessages).toHaveBeenCalledWith( + undefined, + expect.objectContaining({ + search: 'keyword', + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('global search results include chatId and chatTitle', async () => { + const messages = [ + createMockMessage({ + id: 10, + message: 'Result one', + peerId: { channelId: BigInt(200), chatId: null, userId: null }, + chat: { title: 'Channel Alpha' }, + }), + createMockMessage({ + id: 20, + message: 'Result two', + peerId: { channelId: null, chatId: BigInt(300), userId: null }, + chat: { title: 'Group Beta' }, + }), + ]; + (messages as any).total = 2; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + expect(data.messages[0]).toHaveProperty('chatId'); + expect(data.messages[0]).toHaveProperty('chatTitle'); + expect(data.messages[0].chatId).toBe('-100200'); + expect(data.messages[0].chatTitle).toBe('Channel Alpha'); + expect(data.messages[1].chatId).toBe('-300'); + expect(data.messages[1].chatTitle).toBe('Group Beta'); + }); + + it('outputs error when --query is missing', async () => { + const ctx = createMockCommandContext({ query: undefined }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--query'), + 'MISSING_QUERY', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('applies --limit and --offset pagination', async () => { + const messages: any[] = []; + (messages as any).total = 100; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ chat: 'mychat', query: 'test', limit: '10', offset: '5' }); + await messageSearchAction.call(ctx as any); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + limit: 10, + addOffset: 5, + search: 'test', + }), + ); + }); + + it('global search resolves DM chat names from firstName/lastName', async () => { + const messages = [ + createMockMessage({ + id: 30, + message: 'DM result', + peerId: { channelId: null, chatId: null, userId: BigInt(400) }, + chat: { firstName: 'John', lastName: 'Doe', title: undefined }, + }), + ]; + (messages as any).total = 1; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages[0].chatTitle).toBe('John Doe'); + expect(data.messages[0].chatId).toBe('400'); + }); + + it('global search resolves DM chat names with firstName only', async () => { + const messages = [ + createMockMessage({ + id: 31, + message: 'DM result 2', + peerId: { channelId: null, chatId: null, userId: BigInt(500) }, + chat: { firstName: 'Alice', lastName: undefined, title: undefined }, + }), + ]; + (messages as any).total = 1; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages[0].chatTitle).toBe('Alice'); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext({ query: 'keyword' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + // ---- Filter tests (Phase 4) ---- + + it('succeeds with --filter and no --query', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ filter: 'photos', chat: 'mychat' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).not.toHaveBeenCalled(); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: '', + filter: expect.any(MockInputMessagesFilterPhotos), + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('works with both --filter and --query together', async () => { + const messages: any[] = []; + (messages as any).total = 0; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ filter: 'photos', query: 'landscape', chat: 'mychat' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).not.toHaveBeenCalled(); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: 'landscape', + filter: expect.any(MockInputMessagesFilterPhotos), + }), + ); + }); + + it('errors when neither --query nor --filter provided', async () => { + const ctx = createMockCommandContext({ query: undefined, filter: undefined }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--query'), + 'MISSING_QUERY', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('errors with invalid filter name', async () => { + const ctx = createMockCommandContext({ filter: 'invalid_filter', chat: 'mychat' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Unknown filter'), + 'INVALID_FILTER', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('backward compatible: query-only search still works', async () => { + const messages = [ + createMockMessage({ id: 50, message: 'old style search' }), + ]; + (messages as any).total = 1; + mockGetMessages.mockResolvedValueOnce(messages); + + const ctx = createMockCommandContext({ query: 'old', chat: 'mychat' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).not.toHaveBeenCalled(); + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: 'old', + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + // ---- Multi-chat search tests (Phase 5, Plan 03, READ-06) ---- + + it('multi-chat search resolves each chat and merges results', async () => { + // Chat A results + const msgsA = [ + createMockMessage({ + id: 10, message: 'A result', date: 1710300000, + peerId: { channelId: BigInt(100), chatId: null, userId: null }, + chat: { title: 'Chat A' }, + }), + ]; + (msgsA as any).total = 1; + + // Chat B results + const msgsB = [ + createMockMessage({ + id: 20, message: 'B result', date: 1710400000, + peerId: { channelId: BigInt(200), chatId: null, userId: null }, + chat: { title: 'Chat B' }, + }), + ]; + (msgsB as any).total = 1; + + mockResolveEntity + .mockResolvedValueOnce({ id: BigInt(100), className: 'Channel' }) + .mockResolvedValueOnce({ id: BigInt(200), className: 'Channel' }); + mockGetMessages + .mockResolvedValueOnce(msgsA) + .mockResolvedValueOnce(msgsB); + + const ctx = createMockCommandContext({ chat: '@chatA,@chatB', query: 'test' }); + await messageSearchAction.call(ctx as any); + + expect(mockResolveEntity).toHaveBeenCalledTimes(2); + expect(mockGetMessages).toHaveBeenCalledTimes(2); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + // Sorted newest first (B has later date) + expect(data.messages[0].chatTitle).toBe('Chat B'); + expect(data.messages[1].chatTitle).toBe('Chat A'); + // Each has chatId and chatTitle + expect(data.messages[0]).toHaveProperty('chatId'); + expect(data.messages[0]).toHaveProperty('chatTitle'); + }); + + it('multi-chat search truncates to --limit total', async () => { + const msgsA = [ + createMockMessage({ id: 1, date: 1710100000, peerId: { channelId: BigInt(100), chatId: null, userId: null }, chat: { title: 'A' } }), + createMockMessage({ id: 2, date: 1710200000, peerId: { channelId: BigInt(100), chatId: null, userId: null }, chat: { title: 'A' } }), + ]; + (msgsA as any).total = 2; + + const msgsB = [ + createMockMessage({ id: 3, date: 1710300000, peerId: { channelId: BigInt(200), chatId: null, userId: null }, chat: { title: 'B' } }), + ]; + (msgsB as any).total = 1; + + mockResolveEntity + .mockResolvedValueOnce({ id: BigInt(100), className: 'Channel' }) + .mockResolvedValueOnce({ id: BigInt(200), className: 'Channel' }); + mockGetMessages + .mockResolvedValueOnce(msgsA) + .mockResolvedValueOnce(msgsB); + + const ctx = createMockCommandContext({ chat: '@chatA,@chatB', query: 'test', limit: '2' }); + await messageSearchAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(2); + expect(data.total).toBe(2); + }); + + it('multi-chat search logs warning on individual chat failure and continues', async () => { + const msgsB = [ + createMockMessage({ + id: 5, date: 1710100000, + peerId: { channelId: BigInt(200), chatId: null, userId: null }, + chat: { title: 'Chat B' }, + }), + ]; + (msgsB as any).total = 1; + + mockResolveEntity + .mockRejectedValueOnce(new Error('Chat A not found')) + .mockResolvedValueOnce({ id: BigInt(200), className: 'Channel' }); + mockGetMessages.mockResolvedValueOnce(msgsB); + + const ctx = createMockCommandContext({ chat: '@chatA,@chatB', query: 'test' }); + await messageSearchAction.call(ctx as any); + + // Warning logged to stderr + expect(mockLogStatus).toHaveBeenCalledWith( + expect.stringContaining('Warning'), + expect.anything(), + ); + // Results from chat B still returned + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.messages).toHaveLength(1); + expect(data.messages[0].chatTitle).toBe('Chat B'); + }); + + it('single-chat search with --topic uses Search with topMsgId', async () => { + const messages: any[] = []; + (messages as any).total = 0; + const ctx = createMockCommandContext({ chat: 'mychat', query: 'test', topic: '42' }); + await messageSearchAction.call(ctx as any); + + expect(mockAssertForum).toHaveBeenCalledWith( + expect.objectContaining({ className: 'Channel' }), + 42, + ); + expect(mockClientInstance.invoke).toHaveBeenCalledWith( + expect.objectContaining({ topMsgId: 42, q: 'test' }), + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); + + it('--topic without --chat returns INVALID_OPTIONS', async () => { + const ctx = createMockCommandContext({ query: 'test', topic: '42' }); + await messageSearchAction.call(ctx as any); + expect(mockOutputError).toHaveBeenCalledWith( + '--topic requires a single --chat', + 'INVALID_OPTIONS', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('--topic with multi-chat search returns INVALID_OPTIONS error', async () => { + const ctx = createMockCommandContext({ chat: '@a,@b', query: 'test', topic: '42' }); + await messageSearchAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + '--topic cannot be used with multi-chat search', + 'INVALID_OPTIONS', + ); + expect(mockGetMessages).not.toHaveBeenCalled(); + }); + + it('multi-chat search applies --offset after merge, not per-chat', async () => { + // 3 results per chat, request offset=2 limit=2 — should skip first 2 merged results + const msgsA = [ + createMockMessage({ id: 1, date: 1710100000, peerId: { channelId: BigInt(100), chatId: null, userId: null }, chat: { title: 'A' } }), + createMockMessage({ id: 2, date: 1710200000, peerId: { channelId: BigInt(100), chatId: null, userId: null }, chat: { title: 'A' } }), + createMockMessage({ id: 3, date: 1710500000, peerId: { channelId: BigInt(100), chatId: null, userId: null }, chat: { title: 'A' } }), + ]; + (msgsA as any).total = 3; + + const msgsB = [ + createMockMessage({ id: 4, date: 1710300000, peerId: { channelId: BigInt(200), chatId: null, userId: null }, chat: { title: 'B' } }), + createMockMessage({ id: 5, date: 1710400000, peerId: { channelId: BigInt(200), chatId: null, userId: null }, chat: { title: 'B' } }), + ]; + (msgsB as any).total = 2; + + mockResolveEntity + .mockResolvedValueOnce({ id: BigInt(100), className: 'Channel' }) + .mockResolvedValueOnce({ id: BigInt(200), className: 'Channel' }); + mockGetMessages + .mockResolvedValueOnce(msgsA) + .mockResolvedValueOnce(msgsB); + + const ctx = createMockCommandContext({ chat: '@chatA,@chatB', query: 'test', limit: '2', offset: '2' }); + await messageSearchAction.call(ctx as any); + + const data = mockOutputSuccess.mock.calls[0][0]; + // Merged sorted: id3(500k), id5(400k), id4(300k), id2(200k), id1(100k) + // After offset=2: id4(300k), id2(200k) — then limit=2 + expect(data.messages).toHaveLength(2); + expect(data.total).toBe(2); + }); + + it('all flags compose: multi-chat + filter + query + limit', async () => { + const msgs = [ + createMockMessage({ + id: 1, date: 1710100000, + peerId: { channelId: BigInt(100), chatId: null, userId: null }, + chat: { title: 'Chat A' }, + }), + ]; + (msgs as any).total = 1; + + mockResolveEntity.mockResolvedValueOnce({ id: BigInt(100), className: 'Channel' }); + mockGetMessages.mockResolvedValueOnce(msgs); + + const ctx = createMockCommandContext({ chat: '@chatA', query: 'sunset', filter: 'photos', limit: '20' }); + await messageSearchAction.call(ctx as any); + + expect(mockGetMessages).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + search: 'sunset', + limit: 20, + filter: expect.any(MockInputMessagesFilterPhotos), + }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + }); +}); diff --git a/cli/tests/unit/message-send.test.ts b/cli/tests/unit/message-send.test.ts new file mode 100644 index 0000000..ee844cf --- /dev/null +++ b/cli/tests/unit/message-send.test.ts @@ -0,0 +1,328 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogStatus = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: (...args: any[]) => mockLogStatus(...args), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockSendMessage, + MockMediaPhoto, + MockMediaDocument, + MockMediaPoll, + MockAttrSticker, + MockAttrVideo, + MockAttrAudio, + MockAttrFilename, + MockAttrImageSize, + MockActionChatCreate, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockSendMessage: vi.fn().mockResolvedValue({}), + MockMediaPhoto: class {}, + MockMediaDocument: class {}, + MockMediaPoll: class {}, + MockAttrSticker: class { alt = ''; }, + MockAttrVideo: class {}, + MockAttrAudio: class { voice = false; }, + MockAttrFilename: class { fileName = ''; }, + MockAttrImageSize: class { w = 0; h = 0; }, + MockActionChatCreate: class {}, +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + sendMessage: mockSendMessage, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + MessageMediaPhoto: MockMediaPhoto, + MessageMediaDocument: MockMediaDocument, + MessageMediaPoll: MockMediaPoll, + DocumentAttributeSticker: MockAttrSticker, + DocumentAttributeVideo: MockAttrVideo, + DocumentAttributeAudio: MockAttrAudio, + DocumentAttributeFilename: MockAttrFilename, + DocumentAttributeImageSize: MockAttrImageSize, + MessageActionChatCreate: MockActionChatCreate, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(123), className: 'Channel' }); +const mockAssertForum = vi.fn().mockResolvedValue(undefined); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), + assertForum: (...args: any[]) => mockAssertForum(...args), +})); + +// Helper to create mock message objects +function createMockMessage(overrides: Record<string, any> = {}) { + const defaults = { + id: 1, + message: 'Hello world', + date: 1710150900, // 2024-03-11T09:55:00Z + senderId: BigInt(456), + entities: [], + media: null, + action: null, + replyTo: null, + fwdFrom: null, + }; + return { ...defaults, ...overrides }; +} + +// Import after mocks +import { messageSendAction } from '../../src/commands/message/send.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageSendAction', () => { + it('reports an unknown send result without repeating the write', async () => { + mockSendMessage.mockResolvedValueOnce(undefined); + await messageSendAction.call(createMockCommandContext() as any, 'testchat', 'Test'); + expect(mockSendMessage).toHaveBeenCalledOnce(); + expect(mockOutputError).toHaveBeenCalledWith(expect.stringContaining('duplicate'), 'MESSAGE_RESULT_UNAVAILABLE'); + expect(mockOutputSuccess).not.toHaveBeenCalled(); + }); + beforeEach(() => { + vi.clearAllMocks(); + // Reset sendMessage to return a valid message by default + mockSendMessage.mockResolvedValue(createMockMessage({ id: 100, message: 'Test message' })); + }); + + it('sends a text message and returns serialized MessageItem', async () => { + const ctx = createMockCommandContext(); + await messageSendAction.call(ctx as any, 'testchat', 'Hello world'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'testchat'); + expect(mockSendMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 'Hello world' }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data).toHaveProperty('id'); + expect(data).toHaveProperty('text'); + expect(data).toHaveProperty('date'); + }); + + it('rejects an explicitly empty topic before connecting or sending', async () => { + await messageSendAction.call(createMockCommandContext({ topic: '' }) as any, 'testchat', 'Test'); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), 'INVALID_TOPIC_ID'); + expect(mockResolveEntity).not.toHaveBeenCalled(); + expect(mockSendMessage).not.toHaveBeenCalled(); + }); + + it.each(['12junk', '0', '-1', '1.5', '1e3', '2147483648', '9007199254740993', ''])('rejects invalid reply and comment IDs before connecting: %s', async (input) => { + for (const [option, code] of [['replyTo', 'INVALID_REPLY_TO'], ['commentTo', 'INVALID_COMMENT_TO']]) { + vi.clearAllMocks(); + await messageSendAction.call(createMockCommandContext({ [option]: input }) as any, 'testchat', 'Test'); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), code); + expect(mockSendMessage).not.toHaveBeenCalled(); + expect(mockResolveEntity).not.toHaveBeenCalled(); + } + }); + + it.each([{ commentTo: '42', replyTo: '43' }, { commentTo: '42', topic: '43' }])('rejects competing reply targets: %j', async opts => { + await messageSendAction.call(createMockCommandContext(opts) as any, 'testchat', 'Test'); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), 'INVALID_OPTIONS'); + expect(mockSendMessage).not.toHaveBeenCalled(); + }); + + it('sends a reply when --reply-to is provided', async () => { + const ctx = createMockCommandContext({ replyTo: '42' }); + await messageSendAction.call(ctx as any, 'testchat', 'Reply text'); + + expect(mockSendMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 'Reply text', replyTo: 42 }), + ); + }); + + it('parses replyTo as integer', async () => { + const ctx = createMockCommandContext({ replyTo: '999' }); + await messageSendAction.call(ctx as any, 'testchat', 'Reply'); + + const callArgs = mockSendMessage.mock.calls[0][1]; + expect(callArgs.replyTo).toBe(999); + expect(typeof callArgs.replyTo).toBe('number'); + }); + + it('outputs error for empty text', async () => { + const ctx = createMockCommandContext(); + await messageSendAction.call(ctx as any, 'testchat', ''); + + expect(mockOutputError).toHaveBeenCalledWith('Message text is required', 'EMPTY_MESSAGE'); + expect(mockSendMessage).not.toHaveBeenCalled(); + }); + + it('outputs error when not logged in', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn(''); + }); + + const ctx = createMockCommandContext(); + await messageSendAction.call(ctx as any, 'testchat', 'Hello'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Not logged in'), + 'NOT_AUTHENTICATED', + ); + }); + + it('outputs STDIN_REQUIRED error when text is "-" and stdin is TTY', async () => { + // Save original + const origIsTTY = process.stdin.isTTY; + try { + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true }); + + const ctx = createMockCommandContext(); + await messageSendAction.call(ctx as any, 'testchat', '-'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('requires piped input'), + 'STDIN_REQUIRED', + ); + expect(mockSendMessage).not.toHaveBeenCalled(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + } + }); + + it('reads from stdin when text is "-" and stdin is piped', async () => { + // Save original + const origIsTTY = process.stdin.isTTY; + const origStdin = process.stdin[Symbol.asyncIterator]; + try { + Object.defineProperty(process.stdin, 'isTTY', { value: undefined, configurable: true }); + + // Mock stdin as async iterable + const stdinContent = Buffer.from('piped message content\n'); + (process.stdin as any)[Symbol.asyncIterator] = async function* () { + yield stdinContent; + }; + + const ctx = createMockCommandContext(); + await messageSendAction.call(ctx as any, 'testchat', '-'); + + expect(mockSendMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 'piped message content' }), + ); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + } finally { + Object.defineProperty(process.stdin, 'isTTY', { value: origIsTTY, configurable: true }); + (process.stdin as any)[Symbol.asyncIterator] = origStdin; + } + }); + + // ---- Topic tests (Phase 5, Plan 03) ---- + + it('passes replyTo with topicId to sendMessage when --topic is provided', async () => { + const ctx = createMockCommandContext({ topic: '7' }); + await messageSendAction.call(ctx as any, 'testchat', 'Hello topic'); + + expect(mockAssertForum).toHaveBeenCalledWith( + expect.objectContaining({ className: 'Channel' }), + 7, + ); + expect(mockSendMessage).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ message: 'Hello topic', replyTo: 7 }), + ); + }); + + it('rejects combining --topic and --reply-to', async () => { + const ctx = createMockCommandContext({ topic: '7', replyTo: '99' }); + await messageSendAction.call(ctx as any, 'testchat', 'Topic wins'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--topic and --reply-to'), + 'INVALID_OPTIONS', + ); + expect(mockSendMessage).not.toHaveBeenCalled(); + }); + + it('outputs NOT_A_FORUM error when --topic is used on non-forum entity', async () => { + const { TgError } = await import('../../src/lib/errors.js'); + mockAssertForum.mockRejectedValueOnce( + new TgError('Chat is not a forum-enabled supergroup', 'NOT_A_FORUM'), + ); + + const ctx = createMockCommandContext({ topic: '7' }); + await messageSendAction.call(ctx as any, 'testchat', 'Hello'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Chat is not a forum-enabled supergroup', + 'NOT_A_FORUM', + ); + }); + + it('outputs error for invalid topic ID on send', async () => { + const ctx = createMockCommandContext({ topic: 'notanumber' }); + await messageSendAction.call(ctx as any, 'testchat', 'Hello'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Invalid topic ID: must be a number', + 'INVALID_TOPIC_ID', + ); + expect(mockSendMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/message-unpin.test.ts b/cli/tests/unit/message-unpin.test.ts new file mode 100644 index 0000000..478e83f --- /dev/null +++ b/cli/tests/unit/message-unpin.test.ts @@ -0,0 +1,176 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockUnpinMessage, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockUnpinMessage: vi.fn().mockResolvedValue(undefined), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + unpinMessage: mockUnpinMessage, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: {}, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn().mockResolvedValue({ id: BigInt(789), className: 'Channel' }); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize (for bigIntToString) +vi.mock('../../src/lib/serialize.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/serialize.js')>(); + return { ...actual, bigIntToString: (v: bigint) => String(v) }; +}); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { messageUnpinAction } from '../../src/commands/message/unpin.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('messageUnpinAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockUnpinMessage.mockResolvedValue(undefined); + }); + + it('calls client.unpinMessage with correct entity and message ID', async () => { + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', '42'); + + expect(mockUnpinMessage).toHaveBeenCalledWith( + expect.anything(), + 42, + ); + }); + + it('synthesizes PinResult confirmation with action unpinned (no silent field)', async () => { + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + messageId: 42, + chatId: '-100789', + action: 'unpinned', + }); + }); + + it('outputs INVALID_MESSAGE_ID for non-numeric message ID', async () => { + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', 'bad'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockUnpinMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for mixed string like "12abc"', async () => { + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', '12abc'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockUnpinMessage).not.toHaveBeenCalled(); + }); + + it('outputs INVALID_MESSAGE_ID for zero', async () => { + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', '0'); + + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('Invalid message ID'), + 'INVALID_MESSAGE_ID', + ); + expect(mockUnpinMessage).not.toHaveBeenCalled(); + }); + + it('translates RPCError via translateTelegramError', async () => { + mockUnpinMessage.mockRejectedValueOnce({ errorMessage: 'CHAT_ADMIN_REQUIRED' }); + + const ctx = createMockCommandContext(); + await messageUnpinAction.call(ctx as any, 'testchat', '42'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Admin privileges required', + 'CHAT_ADMIN_REQUIRED', + ); + }); +}); diff --git a/cli/tests/unit/message-watch.test.ts b/cli/tests/unit/message-watch.test.ts new file mode 100644 index 0000000..4e24a91 --- /dev/null +++ b/cli/tests/unit/message-watch.test.ts @@ -0,0 +1,125 @@ +// tests/unit/message-watch.test.ts +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockOutputError = vi.fn(); +const mockOutputSuccess = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), +})); + +const mockSocketExists = vi.fn(() => false); +vi.mock('../../src/lib/daemon/pid.js', () => ({ + DaemonPaths: vi.fn().mockImplementation(() => ({ + socketExists: mockSocketExists, + socketPath: '/tmp/test.sock', + })), +})); + +const mockWatch = vi.fn(); +const mockClose = vi.fn(); +vi.mock('../../src/lib/daemon/client.js', () => ({ + DaemonClient: vi.fn().mockImplementation(() => ({ + watch: mockWatch, + close: mockClose, + call: vi.fn(), + })), +})); + +import { messageWatchAction } from '../../src/commands/message/watch.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +describe('message watch', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('errors when daemon is not running', async () => { + mockSocketExists.mockReturnValue(false); + const cmd = { + optsWithGlobals: () => ({ profile: 'default', config: undefined }), + }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('daemon'), + ErrorCode.DAEMON_NOT_RUNNING, + ); + expect(mockWatch).not.toHaveBeenCalled(); + }); + + it('rejects a non-numeric --topic', async () => { + mockSocketExists.mockReturnValue(true); + const cmd = { + optsWithGlobals: () => ({ profile: 'default', topic: 'nope' }), + }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('topic'), + ErrorCode.INVALID_TOPIC_ID, + ); + expect(mockWatch).not.toHaveBeenCalled(); + }); + + it('rejects truncated topic ids like 12x', async () => { + mockSocketExists.mockReturnValue(true); + const cmd = { + optsWithGlobals: () => ({ profile: 'default', topic: '12x' }), + }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('topic'), + ErrorCode.INVALID_TOPIC_ID, + ); + expect(mockWatch).not.toHaveBeenCalled(); + }); + + it('rejects an explicitly empty topic without connecting', async () => { + const cmd = { optsWithGlobals: () => ({ profile: 'default', topic: '' }) }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockOutputError).toHaveBeenCalledWith(expect.any(String), ErrorCode.INVALID_TOPIC_ID); + expect(mockWatch).not.toHaveBeenCalled(); + }); + + it('reports unexpected daemon disconnect and removes signal listeners', async () => { + mockSocketExists.mockReturnValue(true); + const sigint = process.listenerCount('SIGINT'); + const sigterm = process.listenerCount('SIGTERM'); + mockWatch.mockRejectedValueOnce(new Error('Daemon disconnected while watching')); + const cmd = { optsWithGlobals: () => ({ profile: 'default' }) }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockOutputError).toHaveBeenCalledWith(expect.stringContaining('disconnected'), ErrorCode.DAEMON_CONNECTION_FAILED); + expect(mockClose).toHaveBeenCalledOnce(); + expect(process.listenerCount('SIGINT')).toBe(sigint); + expect(process.listenerCount('SIGTERM')).toBe(sigterm); + }); + + it('streams each daemon notification through outputSuccess', async () => { + mockSocketExists.mockReturnValue(true); + mockWatch.mockImplementation(async (_params: unknown, onMessage: (p: unknown) => void) => { + onMessage({ id: 5, text: 'hello', date: '2026-01-01T00:00:00.000Z' }); + }); + const cmd = { + optsWithGlobals: () => ({ profile: 'default', quiet: true }), + }; + await messageWatchAction.call(cmd as any, '@channel'); + expect(mockWatch).toHaveBeenCalledWith( + { chat: '@channel', topic: undefined }, + expect.any(Function), + ); + expect(mockOutputSuccess).toHaveBeenCalledWith({ + id: 5, + text: 'hello', + date: '2026-01-01T00:00:00.000Z', + }); + expect(mockOutputError).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/organize.test.ts b/cli/tests/unit/organize.test.ts new file mode 100644 index 0000000..0a96797 --- /dev/null +++ b/cli/tests/unit/organize.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { dialogPage } from './dialog-scan-fixture.js'; +import { runOrganize } from '../../src/commands/bridge/organize.js'; +import { executeDaemonCommand } from '../../src/lib/daemon/execute.js'; + +const user = new Api.InputPeerUser({ userId: bigInt('9007199254740993'), accessHash: bigInt('123456789') }); +const folder = () => new Api.DialogFilter({ id: 2, title: new Api.TextWithEntities({ text: 'Work', entities: [] }), + contacts: true, color: 3, pinnedPeers: [user], includePeers: [], excludePeers: [] }); +const client = () => ({ getDialogFilters: vi.fn(async () => ({ filters: [new Api.DialogFilterDefault(), folder()], tagsEnabled: true })), + getInputEntity: vi.fn(async () => user), updateDialogFilter: vi.fn(async () => true), updateDialogFiltersOrder: vi.fn(async () => true), + invoke: vi.fn(async () => dialogPage(1, 0)), editPeerFolders: vi.fn(), getNotifySettings: vi.fn(async () => ({ muteUntil: 0 })), + updateNotifySettings: vi.fn(async () => true), markAsRead: vi.fn(), saveDraft: vi.fn(async () => true), + getDialogs: vi.fn(async () => []) }); + +describe('organization operations', () => { + it('returns serializable folder metadata without access hashes, preserving large peer IDs', async () => { + const out: any = await runOrganize(client() as any, { action: 'folders', account: 'main' }); + expect(out.folders[1]).toMatchObject({ pinned: ['9007199254740993'], title: 'Work', color: 3 }); + expect(JSON.stringify(out)).not.toContain('123456789'); + expect(out.revision).toMatch(/^[a-f0-9]{64}$/); + }); + it('preview never mutates; patches preserve rules/pins/color and reject stale apply', async () => { + const c = client(); + const p = { action: 'folder-put', account: 'main', id: 2, patch: { title: 'New' } }; + const preview: any = await runOrganize(c as any, p); + expect(preview.after).toMatchObject({ title: 'New', color: 3, rules: { contacts: true }, pinned: ['9007199254740993'] }); + expect(c.updateDialogFilter).not.toHaveBeenCalled(); + await expect(runOrganize(c as any, { ...p, dry_run: false })).rejects.toThrow('requires'); + await expect(runOrganize(c as any, { ...p, dry_run: false, revision: '0'.repeat(64) })).rejects.toThrow('CONFLICT'); + expect(c.updateDialogFilter).not.toHaveBeenCalled(); + await runOrganize(c as any, { ...p, dry_run: false, revision: preview.revision }); + expect(c.updateDialogFilter).toHaveBeenCalledOnce(); + expect(c.updateDialogFilter.mock.calls[0][1]).toBeInstanceOf(Api.DialogFilter); + }); + it('validates unknown fields, unsafe operations and bounds before requests', async () => { + const c = client(); + for (const p of [{ action: 'invoke', account: 'main' }, { action: 'folders', account: 'other' }, + { action: 'dialogs', account: 'main', limit: 10000 }, + { action: 'folder-put', account: 'main', id: 2, patch: { accessHash: 'x' } }]) { + await expect(runOrganize(c as any, p)).rejects.toThrow(); + } + expect(c.getDialogs).not.toHaveBeenCalled(); expect(c.getDialogFilters).not.toHaveBeenCalled(); + }); + it('rejects missing/duplicate reorder entries and create collisions', async () => { + const c = client(); + for (const order of [[2], [0, 2, 2]]) await expect(runOrganize(c as any, { action: 'folder-order', account: 'main', order })).rejects.toThrow(); + await expect(runOrganize(c as any, { action: 'folder-put', account: 'main', id: 2, create: true, patch: { title: 'New' } })).rejects.toThrow('exists'); + expect(c.updateDialogFiltersOrder).not.toHaveBeenCalled(); + }); + it('refuses edits/deletion of shared folders', async () => { + const c = client(); + c.getDialogFilters.mockResolvedValue({ filters: [new Api.DialogFilterChatlist({ id: 2, title: new Api.TextWithEntities({ text: 'Shared', entities: [] }), pinnedPeers: [], includePeers: [] })], tagsEnabled: false } as any); + for (const p of [{ action: 'folder-delete' }, { action: 'folder-put', patch: { title: 'New' } }]) + await expect(runOrganize(c as any, { ...p, id: 2, account: 'main' })).rejects.toThrow(); + expect(c.updateDialogFilter).not.toHaveBeenCalled(); + }); + it('defaults every state change to preview and never retries failures', async () => { + const c = client(); + for (const p of [{ action: 'archive', archived: true }, { action: 'read', max_id: 3 }, + { action: 'dialog-pin', pinned: true }, { action: 'unread', unread: true }, { action: 'draft-save', text: 'hello' }]) + expect(await runOrganize(c as any, { ...p, account: 'main', chat: 'fixture' })).toMatchObject({ dry_run: true }); + expect(c.invoke).not.toHaveBeenCalled(); expect(c.markAsRead).not.toHaveBeenCalled(); expect(c.saveDraft).not.toHaveBeenCalled(); + c.editPeerFolders.mockRejectedValue(new Error('TIMEOUT')); + await expect(runOrganize(c as any, { action: 'archive', account: 'main', chat: 'fixture', archived: true, dry_run: false })).rejects.toThrow('TIMEOUT'); + expect(c.editPeerFolders).toHaveBeenCalledOnce(); + }); + it('audit respects explicit inclusion and flags partial scans without reading message bodies', async () => { + const c = client(); + c.invoke.mockResolvedValue(dialogPage(1, 2)); + const result: any = await runOrganize(c as any, { action: 'audit', account: 'main', scan_limit: 1 }); + expect(result.complete).toBe(false); + expect(result.chats[0]).toMatchObject({ folders: [2], muted: false }); + expect(c.markAsRead).not.toHaveBeenCalled(); + }); + it('works through the daemon command boundary', async () => { + const c = client(); + const r = await executeDaemonCommand(c as any, 'fixture_main', { argv: ['bridge', 'call', 'organize', JSON.stringify({ action: 'folders', account: 'main' })] }, new AbortController().signal); + expect(r.exitCode).toBe(0); expect(r.output.ok).toBe(true); + }); +}); diff --git a/cli/tests/unit/output-toon.test.ts b/cli/tests/unit/output-toon.test.ts new file mode 100644 index 0000000..dbcf500 --- /dev/null +++ b/cli/tests/unit/output-toon.test.ts @@ -0,0 +1,142 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { outputSuccess, outputError, setOutputMode, setJsonlMode, setFieldSelection, setToonMode } from '../../src/lib/output.js'; + +describe('outputSuccess in TOON mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(false); + setToonMode(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setToonMode(false); + }); + + it('writes TOON-formatted string to stdout, not JSON', () => { + outputSuccess({ messages: [{ id: 1, text: 'hi' }], total: 1 }); + + expect(stdoutSpy).toHaveBeenCalled(); + const written = stdoutSpy.mock.calls[0][0] as string; + // Should contain TOON markers like "ok: true" without JSON braces + expect(written).toContain('ok: true'); + // Should NOT be valid JSON with ok property + try { + const parsed = JSON.parse(written); + expect(parsed).not.toHaveProperty('ok'); + } catch { + // Expected: TOON is not valid JSON + } + }); + + it('output ends with newline', () => { + outputSuccess({ value: 42 }); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written.endsWith('\n')).toBe(true); + }); + + it('does not write to stderr', () => { + const stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + outputSuccess({ messages: [{ id: 1, text: 'test' }], total: 1 }); + expect(stderrSpy).not.toHaveBeenCalled(); + stderrSpy.mockRestore(); + }); +}); + +describe('outputSuccess in TOON mode with field selection', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(false); + setToonMode(true); + setFieldSelection(['id', 'text']); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setFieldSelection(null as unknown as string[]); + setToonMode(false); + }); + + it('filters fields before TOON encoding (selected fields present)', () => { + outputSuccess({ messages: [{ id: 1, text: 'hi', date: '2026-03-13' }], total: 1 }); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written).toContain('id'); + expect(written).toContain('text'); + }); + + it('filtered fields are absent from TOON output', () => { + outputSuccess({ messages: [{ id: 1, text: 'hi', date: '2026-03-13' }], total: 1 }); + + const written = stdoutSpy.mock.calls[0][0] as string; + // date was not in the field selection, so it should be absent + expect(written).not.toContain('2026-03-13'); + }); +}); + +describe('outputError in TOON mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(false); + setToonMode(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + stderrSpy.mockRestore(); + setToonMode(false); + }); + + it('writes TOON-encoded error to stdout, not stderr', () => { + outputError('fail', 'TEST_ERR'); + + expect(stdoutSpy).toHaveBeenCalled(); + expect(stderrSpy).not.toHaveBeenCalled(); + }); + + it('output contains ok: false, error message, and error code', () => { + outputError('fail', 'TEST_ERR'); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written).toContain('ok: false'); + expect(written).toContain('fail'); + expect(written).toContain('TEST_ERR'); + }); +}); + +describe('TOON mode does not interfere with other modes', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(false); + setToonMode(false); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setToonMode(false); + }); + + it('after setToonMode(false), outputSuccess produces normal JSON', () => { + setToonMode(false); + outputSuccess({ test: true }); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: true, data: { test: true } }); + }); +}); diff --git a/cli/tests/unit/output.test.ts b/cli/tests/unit/output.test.ts new file mode 100644 index 0000000..ecb5877 --- /dev/null +++ b/cli/tests/unit/output.test.ts @@ -0,0 +1,621 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { outputSuccess, outputError, logStatus, logVerbose, setOutputMode, getOutputMode, setJsonlMode, setFieldSelection, setToonMode, setQuietMode, setVerboseMode } from '../../src/lib/output.js'; + +afterEach(() => { + process.exitCode = 0; + setToonMode(false); + setQuietMode(false); + setVerboseMode(false); +}); + +describe('outputSuccess', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + }); + + it('writes JSON envelope with ok:true and data to stdout', () => { + outputSuccess({ user: 'test' }); + + expect(stdoutSpy).toHaveBeenCalledOnce(); + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: true, data: { user: 'test' } }); + }); + + it('appends a newline after the JSON', () => { + outputSuccess({ user: 'test' }); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written.endsWith('\n')).toBe(true); + }); + + it('does not write to stderr', () => { + const stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + outputSuccess({ user: 'test' }); + expect(stderrSpy).not.toHaveBeenCalled(); + stderrSpy.mockRestore(); + }); +}); + +describe('outputError exit code', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + process.exitCode = 0; + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + stderrSpy.mockRestore(); + setOutputMode(false); + setJsonlMode(false); + setToonMode(false); + process.exitCode = 0; + }); + + it('sets process.exitCode to 1 in JSON mode', () => { + outputError('fail', 'AUTH_ERR'); + expect(process.exitCode).toBe(1); + }); + + it('sets process.exitCode to 1 in human mode', () => { + setOutputMode(true); + outputError('fail', 'AUTH_ERR'); + expect(process.exitCode).toBe(1); + }); + + it('sets process.exitCode to 1 in JSONL mode', () => { + setJsonlMode(true); + outputError('fail', 'AUTH_ERR'); + expect(process.exitCode).toBe(1); + }); + + it('sets process.exitCode to 1 in TOON mode', () => { + setToonMode(true); + outputError('fail', 'AUTH_ERR'); + expect(process.exitCode).toBe(1); + }); + + it('does not call process.exit (destroy/finally must still run)', () => { + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never); + outputError('fail', 'AUTH_ERR'); + expect(exitSpy).not.toHaveBeenCalled(); + exitSpy.mockRestore(); + }); +}); + +describe('outputSuccess exit code', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + process.exitCode = 0; + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + process.exitCode = 0; + }); + + it('leaves process.exitCode at 0', () => { + outputSuccess({ ok: true }); + expect(process.exitCode).toBe(0); + }); +}); + +describe('outputError', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + }); + + it('writes JSON envelope with ok:false and error to stdout', () => { + outputError('fail', 'AUTH_ERR'); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: false, error: 'fail', code: 'AUTH_ERR' }); + }); + + it('omits code field when not provided', () => { + outputError('fail'); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: false, error: 'fail' }); + expect(parsed).not.toHaveProperty('code'); + }); + + it('appends a newline after the JSON', () => { + outputError('fail'); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written.endsWith('\n')).toBe(true); + }); +}); + +describe('logStatus', () => { + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + }); + + afterEach(() => { + stderrSpy.mockRestore(); + }); + + it('writes message to stderr with newline', () => { + logStatus('connecting...'); + + expect(stderrSpy).toHaveBeenCalledOnce(); + const written = stderrSpy.mock.calls[0][0] as string; + expect(written).toBe('connecting...\n'); + }); + + it('does not write to stdout', () => { + const stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + logStatus('connecting...'); + expect(stdoutSpy).not.toHaveBeenCalled(); + stdoutSpy.mockRestore(); + }); + + it('writes nothing when quiet is true', () => { + logStatus('msg', true); + + expect(stderrSpy).not.toHaveBeenCalled(); + }); + + it('honors global quiet mode when quiet arg is omitted', () => { + setQuietMode(true); + logStatus('msg'); + expect(stderrSpy).not.toHaveBeenCalled(); + }); +}); + +describe('logVerbose', () => { + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + setVerboseMode(false); + setQuietMode(false); + }); + + afterEach(() => { + stderrSpy.mockRestore(); + setVerboseMode(false); + setQuietMode(false); + }); + + it('writes nothing by default', () => { + logVerbose('rpc body'); + expect(stderrSpy).not.toHaveBeenCalled(); + }); + + it('writes to stderr when verbose mode is on', () => { + setVerboseMode(true); + logVerbose('rpc body'); + expect(stderrSpy).toHaveBeenCalledWith('rpc body\n'); + }); + + it('is suppressed by quiet mode', () => { + setVerboseMode(true); + setQuietMode(true); + logVerbose('rpc body'); + expect(stderrSpy).not.toHaveBeenCalled(); + }); +}); + +describe('setOutputMode / getOutputMode', () => { + afterEach(() => { + setOutputMode(false); // reset to default + }); + + it('defaults to false (JSON mode)', () => { + expect(getOutputMode()).toBe(false); + }); + + it('sets mode to human when called with true', () => { + setOutputMode(true); + expect(getOutputMode()).toBe(true); + }); + + it('resets to JSON mode when called with false', () => { + setOutputMode(true); + setOutputMode(false); + expect(getOutputMode()).toBe(false); + }); +}); + +describe('outputSuccess in human mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(true); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setOutputMode(false); + }); + + it('writes human-readable output instead of JSON envelope', () => { + outputSuccess({ loggedIn: true, phone: '+1234' }); + + const written = stdoutSpy.mock.calls[0][0] as string; + // Should NOT be a JSON envelope with ok:true + expect(() => { + const parsed = JSON.parse(written); + expect(parsed).not.toHaveProperty('ok'); + }).not.toThrow(); // formatGeneric produces valid JSON, but without envelope + }); + + it('formats messages in human mode', () => { + outputSuccess({ + messages: [ + { + id: 1, text: 'Hello', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }, + ], + total: 1, + }); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written).toContain('Alice'); + expect(written).toContain('Hello'); + }); +}); + +describe('outputError in human mode', () => { + let stderrSpy: ReturnType<typeof vi.spyOn>; + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(true); + }); + + afterEach(() => { + stderrSpy.mockRestore(); + stdoutSpy.mockRestore(); + setOutputMode(false); + }); + + it('writes error to stderr with "Error: " prefix', () => { + outputError('something failed', 'TEST_ERR'); + + expect(stderrSpy).toHaveBeenCalledOnce(); + const written = stderrSpy.mock.calls[0][0] as string; + expect(written).toContain('Error:'); + expect(written).toContain('something failed'); + }); + + it('does not write to stdout', () => { + outputError('fail'); + expect(stdoutSpy).not.toHaveBeenCalled(); + }); +}); + +describe('outputSuccess in default JSON mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + }); + + it('still writes JSON envelope when mode is not set', () => { + outputSuccess({ test: true }); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: true, data: { test: true } }); + }); +}); + +describe('outputSuccess in JSONL mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(true); + setFieldSelection(null as unknown as string[]); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setJsonlMode(false); + setFieldSelection(null as unknown as string[]); + }); + + it('writes one JSON object per line for list data, no envelope', () => { + const msg1 = { id: 1, text: 'hello' }; + const msg2 = { id: 2, text: 'world' }; + outputSuccess({ messages: [msg1, msg2], total: 2 }); + + expect(stdoutSpy).toHaveBeenCalledTimes(2); + const line1 = JSON.parse(stdoutSpy.mock.calls[0][0] as string); + const line2 = JSON.parse(stdoutSpy.mock.calls[1][0] as string); + expect(line1).toEqual(msg1); + expect(line2).toEqual(msg2); + }); + + it('each line ends with newline', () => { + outputSuccess({ messages: [{ id: 1 }], total: 1 }); + + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written.endsWith('\n')).toBe(true); + }); + + it('falls through to JSON envelope for non-list data', () => { + outputSuccess({ status: 'ok', loggedIn: true }); + + expect(stdoutSpy).toHaveBeenCalledOnce(); + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ ok: true, data: { status: 'ok', loggedIn: true } }); + }); + + it('composes with field selection', () => { + setFieldSelection(['id']); + outputSuccess({ + messages: [ + { id: 1, text: 'hello', date: '2026-01-01' }, + { id: 2, text: 'world', date: '2026-01-02' }, + ], + total: 2, + }); + + expect(stdoutSpy).toHaveBeenCalledTimes(2); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: 1 }); + expect(JSON.parse(stdoutSpy.mock.calls[1][0] as string)).toEqual({ id: 2 }); + }); + + it('works with chats array', () => { + outputSuccess({ chats: [{ id: '1', title: 'Test' }], total: 1 }); + + expect(stdoutSpy).toHaveBeenCalledOnce(); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: '1', title: 'Test' }); + }); + + it('works with profiles array (LIST_KEYS includes profiles)', () => { + outputSuccess({ profiles: [{ id: '100', firstName: 'Alice' }], notFound: [] }); + + expect(stdoutSpy).toHaveBeenCalledOnce(); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: '100', firstName: 'Alice' }); + }); + + it('reports notFound to stderr for profiles shape', () => { + const stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + outputSuccess({ profiles: [{ id: '100', firstName: 'Alice' }], notFound: ['bob', 'carol'] }); + + // profiles streamed to stdout + expect(stdoutSpy).toHaveBeenCalledOnce(); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: '100', firstName: 'Alice' }); + + // notFound reported to stderr + expect(stderrSpy).toHaveBeenCalledOnce(); + const stderrWritten = stderrSpy.mock.calls[0][0] as string; + expect(stderrWritten).toContain('bob'); + expect(stderrWritten).toContain('carol'); + stderrSpy.mockRestore(); + }); + + it('suppresses JSONL notFound on stderr when quiet', () => { + setQuietMode(true); + const stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + outputSuccess({ messages: [{ id: 1 }], notFound: [99] }); + expect(stdoutSpy).toHaveBeenCalledOnce(); + expect(stderrSpy).not.toHaveBeenCalled(); + stderrSpy.mockRestore(); + setQuietMode(false); + }); + + it('works with users array (LIST_KEYS includes users)', () => { + outputSuccess({ users: [{ id: '1', firstName: 'Dave', isBot: false }], total: 1 }); + + expect(stdoutSpy).toHaveBeenCalledOnce(); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: '1', firstName: 'Dave', isBot: false }); + }); + + it('streams batch download files and failed entries', () => { + outputSuccess({ + files: [{ path: '/tmp/a.jpg', filename: 'a.jpg', size: 1, mediaType: 'photo', messageId: 1 }], + downloaded: 1, + failed: [{ messageId: 2, error: 'no media', code: 'NO_MEDIA' }], + }); + + expect(stdoutSpy).toHaveBeenCalledTimes(2); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ + path: '/tmp/a.jpg', + filename: 'a.jpg', + size: 1, + mediaType: 'photo', + messageId: 1, + status: 'downloaded', + }); + expect(JSON.parse(stdoutSpy.mock.calls[1][0] as string)).toEqual({ + messageId: 2, + status: 'failed', + error: 'no media', + code: 'NO_MEDIA', + }); + }); + + it('streams DeleteResult as one JSONL line per deleted/failed ID', () => { + outputSuccess({ deleted: [10, 20, 30], failed: [], mode: 'revoke' }); + + expect(stdoutSpy).toHaveBeenCalledTimes(3); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: 10, status: 'deleted' }); + expect(JSON.parse(stdoutSpy.mock.calls[1][0] as string)).toEqual({ id: 20, status: 'deleted' }); + expect(JSON.parse(stdoutSpy.mock.calls[2][0] as string)).toEqual({ id: 30, status: 'deleted' }); + }); + + it('streams DeleteResult failed entries with reason', () => { + outputSuccess({ + deleted: [10], + failed: [{ id: 20, reason: 'permission denied' }], + mode: 'for-me', + }); + + expect(stdoutSpy).toHaveBeenCalledTimes(2); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: 10, status: 'deleted' }); + expect(JSON.parse(stdoutSpy.mock.calls[1][0] as string)).toEqual({ id: 20, status: 'failed', reason: 'permission denied' }); + }); + + it('streams DeleteResult with field selection', () => { + setFieldSelection(['id']); + outputSuccess({ deleted: [10, 20], failed: [], mode: 'revoke' }); + + expect(stdoutSpy).toHaveBeenCalledTimes(2); + expect(JSON.parse(stdoutSpy.mock.calls[0][0] as string)).toEqual({ id: 10 }); + expect(JSON.parse(stdoutSpy.mock.calls[1][0] as string)).toEqual({ id: 20 }); + }); +}); + +describe('outputSuccess with field selection in JSON mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(false); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setFieldSelection(null as unknown as string[]); + }); + + it('filters items but preserves envelope and metadata', () => { + setFieldSelection(['id']); + outputSuccess({ + messages: [{ id: 1, text: 'hello', date: '2026-01-01' }], + total: 5, + }); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed).toEqual({ + ok: true, + data: { messages: [{ id: 1 }], total: 5 }, + }); + }); + + it('preserves multiple metadata fields', () => { + setFieldSelection(['id', 'title']); + outputSuccess({ + chats: [{ id: '1', title: 'Chat', type: 'group' }], + total: 10, + count: 1, + }); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed.data.total).toBe(10); + expect(parsed.data.count).toBe(1); + expect(parsed.data.chats).toEqual([{ id: '1', title: 'Chat' }]); + }); + + it('does not filter when no field selection is set', () => { + outputSuccess({ messages: [{ id: 1, text: 'hi' }], total: 1 }); + + const written = stdoutSpy.mock.calls[0][0] as string; + const parsed = JSON.parse(written); + expect(parsed.data.messages[0]).toEqual({ id: 1, text: 'hi' }); + }); +}); + +describe('outputSuccess with field selection in human mode', () => { + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(true); + setFieldSelection(['id']); + }); + + afterEach(() => { + stdoutSpy.mockRestore(); + setOutputMode(false); + setFieldSelection(null as unknown as string[]); + }); + + it('silently ignores --fields in human mode', () => { + outputSuccess({ + messages: [ + { + id: 1, text: 'Hello', date: '2026-03-11T12:30:00.000Z', + senderId: '123', senderName: 'Alice', replyToMsgId: null, + forwardFrom: null, mediaType: null, type: 'message', + }, + ], + total: 1, + }); + + // Should still format as human-readable (not filtered to just id) + const written = stdoutSpy.mock.calls[0][0] as string; + expect(written).toContain('Alice'); + expect(written).toContain('Hello'); + }); +}); + +describe('outputError in JSONL mode', () => { + let stderrSpy: ReturnType<typeof vi.spyOn>; + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + stdoutSpy = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + setOutputMode(false); + setJsonlMode(true); + }); + + afterEach(() => { + stderrSpy.mockRestore(); + stdoutSpy.mockRestore(); + setJsonlMode(false); + }); + + it('writes error to stderr only, no envelope', () => { + outputError('something failed', 'TEST_ERR'); + + expect(stderrSpy).toHaveBeenCalledOnce(); + const written = stderrSpy.mock.calls[0][0] as string; + expect(written).toContain('Error:'); + expect(written).toContain('something failed'); + expect(written).toContain('[TEST_ERR]'); + expect(stdoutSpy).not.toHaveBeenCalled(); + }); + + it('writes error without code when not provided', () => { + outputError('oops'); + + const written = stderrSpy.mock.calls[0][0] as string; + expect(written).toBe('Error: oops\n'); + }); +}); diff --git a/cli/tests/unit/partial-output.test.ts b/cli/tests/unit/partial-output.test.ts new file mode 100644 index 0000000..4790698 --- /dev/null +++ b/cli/tests/unit/partial-output.test.ts @@ -0,0 +1,73 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { decode } from '@toon-format/toon'; +import { outputSuccess, setOutputMode, setJsonlMode, setToonMode, setFieldSelection, setQuietMode } from '../../src/lib/output.js'; + +const failure = { input: 'second', error: 'Admin privileges required', code: 'CHAT_ADMIN_REQUIRED' }; +const data = { messages: [{ id: 42, text: 'success' }], total: 1, partial: true, errors: [failure] }; +let stdout: ReturnType<typeof vi.spyOn>; +let stderr: ReturnType<typeof vi.spyOn>; +beforeEach(() => { + setOutputMode(false); + setJsonlMode(false); + setToonMode(false); + setFieldSelection(null); + setQuietMode(false); + stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); +}); +afterEach(() => { + vi.restoreAllMocks(); + setOutputMode(false); + setJsonlMode(false); + setToonMode(false); + setFieldSelection(null); + setQuietMode(false); + process.exitCode = 0; +}); +const written = () => stdout.mock.calls.map(call => String(call[0])).join(''); + +describe('partial batch output', () => { + it.each([{ errors: [] }, { errors: [failure] }])('filters single-object successes while preserving errors: %j', ({ errors }) => { + setFieldSelection(['id']); + outputSuccess({ id: 42, phone: '+10000000000', partial: errors.length > 0, errors }); + expect(JSON.parse(written())).toEqual({ ok: true, data: { id: 42, partial: errors.length > 0, errors } }); + }); + it.each(['json', 'toon'])('preserves failure details under --fields id in %s', mode => { + setFieldSelection(['id']); + setToonMode(mode === 'toon'); + outputSuccess(data); + const result = mode === 'toon' ? decode(written()) : JSON.parse(written()); + expect(result).toEqual({ ok: true, data: { ...data, messages: [{ id: 42 }] } }); + expect(stderr).not.toHaveBeenCalled(); + }); + + it('streams failure records without envelope even with --fields and --quiet', () => { + setJsonlMode(true); + setFieldSelection(['id']); + setQuietMode(true); + outputSuccess(data); + expect(written().trim().split('\n').map(line => JSON.parse(line))).toEqual([ + { id: 42 }, { status: 'failed', ...failure }, + ]); + expect(stderr).not.toHaveBeenCalled(); + }); + + it.each(['messages', 'posts', 'profiles', 'results'])('keeps all-failed %s batches observable in JSONL', key => { + setJsonlMode(true); + outputSuccess({ [key]: [], notFound: [], partial: true, errors: [failure] }); + expect(JSON.parse(written())).toEqual({ status: 'failed', ...failure }); + }); + + it('prints failure details in human mode even when the successful list is empty', () => { + setOutputMode(true); + setQuietMode(true); + outputSuccess({ ...data, messages: [] }); + expect(written()).toContain('Failed second: Admin privileges required [CHAT_ADMIN_REQUIRED]'); + }); + + it('does not introduce a failure record for a successful empty batch', () => { + setJsonlMode(true); + outputSuccess({ messages: [], partial: false, errors: [] }); + expect(written()).toBe(''); + }); +}); diff --git a/cli/tests/unit/peer-command.test.ts b/cli/tests/unit/peer-command.test.ts new file mode 100644 index 0000000..7ecf98a --- /dev/null +++ b/cli/tests/unit/peer-command.test.ts @@ -0,0 +1,152 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Hoisted mock state +const { + mockConnect, + mockDestroy, + MockChannel, + MockUser, +} = vi.hoisted(() => { + const _MockChannel = class Channel { + id: any; title: string; username: string | null; megagroup: boolean; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(100); this.title = args.title ?? 'Test Channel'; + this.username = args.username ?? null; this.megagroup = args.megagroup ?? false; + } + }; + const _MockUser = class User { + id: any; firstName: string; lastName: string | null; username: string | null; + constructor(args: any = {}) { + this.id = args.id ?? BigInt(300); this.firstName = args.firstName ?? 'Test'; + this.lastName = args.lastName ?? null; this.username = args.username ?? null; + } + }; + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + MockChannel: _MockChannel, + MockUser: _MockUser, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + Channel: MockChannel, + User: MockUser, + Chat: class Chat { + id: any; title: string; + constructor(args: any = {}) { this.id = args.id ?? BigInt(200); this.title = args.title ?? 'Group'; } + }, + }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => fn('test-session')), + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +import { chatResolveAction } from '../../src/commands/chat/resolve.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', quiet: false, config: undefined, + json: true, human: false, verbose: false, + ...opts, + })), + }; +} + +describe('chatResolveAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('resolves a username to entity info', async () => { + const entity = new MockChannel({ id: BigInt(100), title: 'My Channel', username: 'mychan', megagroup: false }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, 'mychan'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, 'mychan'); + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('-100100'); + expect(data.type).toBe('channel'); + expect(data.title).toBe('My Channel'); + expect(data.username).toBe('mychan'); + }); + + it('resolves a numeric ID', async () => { + const entity = new MockUser({ id: BigInt(300), firstName: 'Alice', username: 'alice' }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, '300'); + + expect(mockResolveEntity).toHaveBeenCalledWith(mockClientInstance, '300'); + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.id).toBe('300'); + expect(data.type).toBe('user'); + expect(data.title).toBe('Alice'); + }); + + it('outputs error for unknown peer', async () => { + mockResolveEntity.mockRejectedValueOnce(new Error('Peer not found: no such user')); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, 'nonexistent'); + + expect(mockOutputError).toHaveBeenCalledOnce(); + expect(mockOutputError.mock.calls[0][0]).toContain('Peer not found'); + }); + + it('resolves a supergroup', async () => { + const entity = new MockChannel({ id: BigInt(101), title: 'Supergroup', username: 'sg', megagroup: true }); + mockResolveEntity.mockResolvedValueOnce(entity); + + const ctx = createMockCommandContext(); + await chatResolveAction.call(ctx as any, 'sg'); + + const data = mockOutputSuccess.mock.calls[0][0]; + expect(data.type).toBe('supergroup'); + }); +}); diff --git a/cli/tests/unit/peer-resolve.test.ts b/cli/tests/unit/peer-resolve.test.ts new file mode 100644 index 0000000..2ed0a14 --- /dev/null +++ b/cli/tests/unit/peer-resolve.test.ts @@ -0,0 +1,264 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Mock errors module (import actual) +vi.mock('../../src/lib/errors.js', async () => { + const actual = await vi.importActual<typeof import('../../src/lib/errors.js')>('../../src/lib/errors.js'); + return actual; +}); + +// Mock telegram module +vi.mock('teleproto', () => ({ + Api: { + messages: { + CheckChatInvite: vi.fn().mockImplementation((args: any) => ({ hash: args.hash, className: 'messages.CheckChatInvite' })), + }, + }, +})); + +import { resolveEntity, extractInviteHash, assertForum } from '../../src/lib/peer.js'; +import { TgError } from '../../src/lib/errors.js'; + +describe('extractInviteHash', () => { + it('extracts hash from t.me/+HASH format', () => { + expect(extractInviteHash('https://t.me/+abc123')).toBe('abc123'); + }); + + it('extracts hash from t.me/joinchat/HASH format', () => { + expect(extractInviteHash('https://t.me/joinchat/abc123')).toBe('abc123'); + }); + + it('extracts hash from telegram.me/+HASH format', () => { + expect(extractInviteHash('https://telegram.me/+xyz789')).toBe('xyz789'); + }); + + it('handles links without https:// prefix', () => { + expect(extractInviteHash('t.me/+abc123')).toBe('abc123'); + }); + + it('handles hashes with dashes and underscores', () => { + expect(extractInviteHash('https://t.me/+abc_123-def')).toBe('abc_123-def'); + }); + + it('throws TgError for invalid invite link', () => { + expect(() => extractInviteHash('https://example.com/something')).toThrow(TgError); + expect(() => extractInviteHash('not a link at all')).toThrow(TgError); + }); + + it('throws with INVALID_INVITE code', () => { + try { + extractInviteHash('invalid'); + expect.unreachable('should have thrown'); + } catch (err) { + expect((err as TgError).code).toBe('INVALID_INVITE'); + } + }); +}); + +describe('resolveEntity', () => { + let mockClient: any; + + beforeEach(() => { + vi.clearAllMocks(); + mockClient = { + getEntity: vi.fn().mockResolvedValue({ id: 123, className: 'User' }), + invoke: vi.fn().mockResolvedValue({ chat: { id: 456, className: 'Channel' } }), + }; + }); + + it('resolves username without @ prefix', async () => { + await resolveEntity(mockClient, 'testuser'); + expect(mockClient.getEntity).toHaveBeenCalledWith('testuser'); + }); + + it.each(['username', '+15551234567', '-10012345'])('preserves RPC and transport failures resolving %s', async (input) => { + for (const error of [Object.assign(new Error('FLOOD_WAIT_30'), { errorMessage: 'FLOOD_WAIT_30', code: 420 }), new Error('connection reset')]) { + mockClient.getEntity.mockRejectedValueOnce(error); + await expect(resolveEntity(mockClient, input)).rejects.toBe(error); + } + }); + + it('preserves transport failures resolving invite links', async () => { + const error = new Error('connection reset'); + mockClient.invoke.mockRejectedValueOnce(error); + await expect(resolveEntity(mockClient, 'https://t.me/+hash')).rejects.toBe(error); + }); + + it('maps only confirmed missing usernames to PEER_NOT_FOUND', async () => { + mockClient.getEntity.mockRejectedValueOnce(Object.assign(new Error('USERNAME_NOT_OCCUPIED'), { errorMessage: 'USERNAME_NOT_OCCUPIED', code: 400 })); + await expect(resolveEntity(mockClient, 'missing')).rejects.toMatchObject({ code: 'PEER_NOT_FOUND' }); + }); + + it('rejects unsafe numeric peers before querying Telegram', async () => { + await expect(resolveEntity(mockClient, '9007199254740993')).rejects.toMatchObject({ code: 'INVALID_ID' }); + expect(mockClient.getEntity).not.toHaveBeenCalled(); + }); + + it('strips @ prefix from @username', async () => { + await resolveEntity(mockClient, '@testuser'); + expect(mockClient.getEntity).toHaveBeenCalledWith('testuser'); + }); + + it('parses positive numeric ID and calls getEntity with number', async () => { + await resolveEntity(mockClient, '12345'); + expect(mockClient.getEntity).toHaveBeenCalledWith(12345); + }); + + it('parses negative numeric ID for channel/group', async () => { + await resolveEntity(mockClient, '-1001234567'); + expect(mockClient.getEntity).toHaveBeenCalledWith(-1001234567); + }); + + it('handles phone number input starting with +digits', async () => { + await resolveEntity(mockClient, '+15551234567'); + expect(mockClient.getEntity).toHaveBeenCalledWith('+15551234567'); + }); + + it('throws NOT_A_MEMBER when invite preview has no chat', async () => { + mockClient.invoke.mockResolvedValueOnce({ className: 'ChatInvite' }); + await expect(resolveEntity(mockClient, 'https://t.me/+preview')).rejects.toMatchObject({ + code: 'NOT_A_MEMBER', + }); + }); + + it('uses CheckChatInvite for t.me/+HASH invite links', async () => { + await resolveEntity(mockClient, 'https://t.me/+abc123'); + expect(mockClient.invoke).toHaveBeenCalledOnce(); + // Should have invoked with a CheckChatInvite-like object + const invokeArg = mockClient.invoke.mock.calls[0][0]; + expect(invokeArg.hash).toBe('abc123'); + }); + + it('uses CheckChatInvite for t.me/joinchat/HASH invite links', async () => { + await resolveEntity(mockClient, 'https://t.me/joinchat/xyz789'); + expect(mockClient.invoke).toHaveBeenCalledOnce(); + const invokeArg = mockClient.invoke.mock.calls[0][0]; + expect(invokeArg.hash).toBe('xyz789'); + }); + + it('wraps getEntity errors in TgError with PEER_NOT_FOUND', async () => { + mockClient.getEntity.mockRejectedValue(new Error('entity not found')); + await expect(resolveEntity(mockClient, 'nonexistent')).rejects.toThrow(TgError); + try { + await resolveEntity(mockClient, 'nonexistent'); + } catch (err) { + expect((err as TgError).code).toBe('PEER_NOT_FOUND'); + } + }); + + it('wraps invoke errors in TgError with INVALID_INVITE', async () => { + mockClient.invoke.mockRejectedValue(new Error('invite hash invalid')); + await expect(resolveEntity(mockClient, 'https://t.me/+badHash')).rejects.toThrow(TgError); + try { + await resolveEntity(mockClient, 'https://t.me/+badHash'); + } catch (err) { + expect((err as TgError).code).toBe('INVALID_INVITE'); + } + }); + + it('returns the entity from getEntity call', async () => { + const mockEntity = { id: 999, className: 'Channel' }; + mockClient.getEntity.mockResolvedValue(mockEntity); + const result = await resolveEntity(mockClient, 'somechannel'); + expect(result).toBe(mockEntity); + }); + + it('wraps phone number getEntity errors in TgError with PEER_NOT_FOUND', async () => { + mockClient.getEntity.mockRejectedValue(new Error('phone not found')); + try { + await resolveEntity(mockClient, '+15551234567'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBeInstanceOf(TgError); + expect((err as TgError).code).toBe('PEER_NOT_FOUND'); + expect((err as TgError).message).toContain('phone not found'); + } + }); + + it('re-throws TgError as-is from phone number resolution', async () => { + const original = new TgError('custom error', 'CUSTOM'); + mockClient.getEntity.mockRejectedValue(original); + try { + await resolveEntity(mockClient, '+15551234567'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBe(original); + } + }); + + it('wraps numeric ID getEntity errors in TgError with PEER_NOT_FOUND', async () => { + mockClient.getEntity.mockRejectedValue(new Error('id not found')); + try { + await resolveEntity(mockClient, '12345'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBeInstanceOf(TgError); + expect((err as TgError).code).toBe('PEER_NOT_FOUND'); + expect((err as TgError).message).toContain('id not found'); + } + }); + + it('re-throws TgError as-is from numeric ID resolution', async () => { + const original = new TgError('custom error', 'CUSTOM'); + mockClient.getEntity.mockRejectedValue(original); + try { + await resolveEntity(mockClient, '-1001234567'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBe(original); + } + }); + + it('re-throws TgError as-is from username resolution', async () => { + const original = new TgError('custom error', 'CUSTOM'); + mockClient.getEntity.mockRejectedValue(original); + try { + await resolveEntity(mockClient, '@someone'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBe(original); + } + }); + + it('re-throws TgError as-is from invite link resolution', async () => { + const original = new TgError('custom error', 'CUSTOM'); + mockClient.invoke.mockRejectedValue(original); + try { + await resolveEntity(mockClient, 'https://t.me/+abc123'); + expect.unreachable('should have thrown'); + } catch (err) { + expect(err).toBe(original); + } + }); +}); + +describe('assertForum', () => { + it('does nothing when topicId is undefined', async () => { + await expect(assertForum({}, undefined)).resolves.toBeUndefined(); + }); + + it('throws NOT_A_FORUM when entity has no className', async () => { + await expect(assertForum({}, 7)).rejects.toThrow(TgError); + try { + await assertForum({}, 7); + expect.unreachable('should have thrown'); + } catch (err) { + expect((err as TgError).code).toBe('NOT_A_FORUM'); + } + }); + + it('throws NOT_A_FORUM when entity is not a Channel', async () => { + await expect(assertForum({ className: 'Chat' }, 7)).rejects.toThrow(TgError); + }); + + it('throws NOT_A_FORUM when Channel has forum === false', async () => { + await expect(assertForum({ className: 'Channel', forum: false }, 7)).rejects.toThrow(TgError); + }); + + it('passes when entity is a Channel with forum === true', async () => { + await expect(assertForum({ className: 'Channel', forum: true }, 7)).resolves.toBeUndefined(); + }); + + it('throws NOT_A_FORUM when Channel has forum undefined', async () => { + await expect(assertForum({ className: 'Channel' }, 7)).rejects.toThrow(TgError); + }); +}); diff --git a/cli/tests/unit/presets.test.ts b/cli/tests/unit/presets.test.ts new file mode 100644 index 0000000..1e4d19b --- /dev/null +++ b/cli/tests/unit/presets.test.ts @@ -0,0 +1,97 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Sample api.py content for testing +const SAMPLE_API_PY = ` +class APIData(object, metaclass=BaseAPIMetaClass): + api_id: int = None + api_hash: str = None + +class API: + class TelegramDesktop(APIData): + """Official Telegram for Desktop""" + api_id = 2040 + api_hash = "00000000000000000000000000000001" + device_model = "Desktop" + + class TelegramAndroid(APIData): + """Official Telegram for Android""" + api_id = 6 + api_hash = "00000000000000000000000000000002" + + class TelegramIOS(APIData): + """Official Telegram for iOS""" + api_id = 10840 + api_hash = "00000000000000000000000000000003" + + class TelegramMacOS(APIData): + """Official Telegram-Swift For MacOS""" + api_id = 2834 + api_hash = "00000000000000000000000000000004" + + class TelegramWeb_Z(APIData): + """Telegram Web Z""" + api_id = 2496 + api_hash = "00000000000000000000000000000005" +`; + +const SAMPLE_WITH_TEST_KEY = ` +class API: + class TelegramDesktop(APIData): + api_id = 2040 + api_hash = "00000000000000000000000000000001" + + class TestClient(APIData): + api_id = 17349 + api_hash = "00000000000000000000000000000006" +`; + +import { parseApiPy, PRESET_NAME_MAP, TEST_API_IDS } from '../../src/lib/presets.js'; + +describe('parseApiPy', () => { + it('parses all classes from sample api.py', () => { + const result = parseApiPy(SAMPLE_API_PY); + expect(result.size).toBe(5); + expect(result.get('desktop')).toEqual({ apiId: 2040, apiHash: '00000000000000000000000000000001' }); + expect(result.get('android')).toEqual({ apiId: 6, apiHash: '00000000000000000000000000000002' }); + expect(result.get('ios')).toEqual({ apiId: 10840, apiHash: '00000000000000000000000000000003' }); + expect(result.get('macos')).toEqual({ apiId: 2834, apiHash: '00000000000000000000000000000004' }); + expect(result.get('web-z')).toEqual({ apiId: 2496, apiHash: '00000000000000000000000000000005' }); + }); + + it('filters out known test api_ids', () => { + const result = parseApiPy(SAMPLE_WITH_TEST_KEY); + expect(result.size).toBe(1); + expect(result.has('desktop')).toBe(true); + // 17349 should be filtered out + for (const [, value] of result) { + expect(TEST_API_IDS).not.toContain(value.apiId); + } + }); + + it('maps class names to user-friendly preset names', () => { + expect(PRESET_NAME_MAP.TelegramDesktop).toBe('desktop'); + expect(PRESET_NAME_MAP.TelegramAndroid).toBe('android'); + expect(PRESET_NAME_MAP.TelegramAndroidX).toBe('android-x'); + expect(PRESET_NAME_MAP.TelegramIOS).toBe('ios'); + expect(PRESET_NAME_MAP.TelegramMacOS).toBe('macos'); + expect(PRESET_NAME_MAP.TelegramWeb_Z).toBe('web-z'); + expect(PRESET_NAME_MAP.TelegramWeb_K).toBe('web-k'); + expect(PRESET_NAME_MAP.Webogram).toBe('webogram'); + }); + + it('returns empty map for unparseable content', () => { + const result = parseApiPy('this is not python code'); + expect(result.size).toBe(0); + }); + + it('handles classes not in PRESET_NAME_MAP by lowercasing', () => { + const content = ` +class API: + class SomeNewClient(APIData): + api_id = 99999 + api_hash = "00000000000000000000000000000007" + `; + const result = parseApiPy(content); + expect(result.has('somenewclient')).toBe(true); + }); +}); diff --git a/cli/tests/unit/prompt.test.ts b/cli/tests/unit/prompt.test.ts new file mode 100644 index 0000000..a3ca3e2 --- /dev/null +++ b/cli/tests/unit/prompt.test.ts @@ -0,0 +1,68 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// Mock readline/promises before importing the module +const mockQuestion = vi.fn(); +const mockClose = vi.fn(); + +vi.mock('node:readline/promises', () => ({ + createInterface: vi.fn(() => ({ + question: mockQuestion, + close: mockClose, + })), +})); + +import { createPrompt } from '../../src/lib/prompt.js'; + +describe('createPrompt', () => { + let stderrSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(() => { + vi.clearAllMocks(); + stderrSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + }); + + afterEach(() => { + stderrSpy.mockRestore(); + }); + + it('ask() calls readline question and returns the answer', async () => { + mockQuestion.mockResolvedValueOnce('user input'); + + const prompt = createPrompt(); + const answer = await prompt.ask('Enter name: '); + + expect(mockQuestion).toHaveBeenCalledWith('Enter name: '); + expect(answer).toBe('user input'); + }); + + it('askSecret() writes prompt to stderr and suppresses echo', async () => { + mockQuestion.mockResolvedValueOnce('s3cret'); + + const prompt = createPrompt(); + const answer = await prompt.askSecret('Password: '); + + // Prompt written to stderr directly + expect(stderrSpy).toHaveBeenCalledWith('Password: '); + // Question called with empty string (muted output) + expect(mockQuestion).toHaveBeenCalledWith(''); + expect(answer).toBe('s3cret'); + // Newline written after secret input + expect(stderrSpy).toHaveBeenCalledWith('\n'); + }); + + it('askSecret() restores echo even on error', async () => { + mockQuestion.mockRejectedValueOnce(new Error('readline error')); + + const prompt = createPrompt(); + await expect(prompt.askSecret('Token: ')).rejects.toThrow('readline error'); + + // Newline still written (finally block) + expect(stderrSpy).toHaveBeenCalledWith('\n'); + }); + + it('close() calls readline close', () => { + const prompt = createPrompt(); + prompt.close(); + expect(mockClose).toHaveBeenCalledOnce(); + }); +}); diff --git a/cli/tests/unit/scheduled-messages-and-photos.test.ts b/cli/tests/unit/scheduled-messages-and-photos.test.ts new file mode 100644 index 0000000..3de51e4 --- /dev/null +++ b/cli/tests/unit/scheduled-messages-and-photos.test.ts @@ -0,0 +1,160 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { executeDaemonCommand } from '../../src/lib/daemon/execute.js'; +import { validateDaemonCommand } from '../../src/lib/daemon/command-protocol.js'; +import { parseSchedule } from '../../src/lib/schedule.js'; +import { formatData } from '../../src/lib/format.js'; + +const now = Date.parse('2030-01-01T00:00:00Z'); +describe('schedule timestamps', () => { + it('normalizes a zoned timestamp to Telegram seconds', () => { + expect(parseSchedule('2030-01-01T04:00:00+03:00', now)).toBe(Date.parse('2030-01-01T01:00:00Z') / 1000); + }); + it.each(['', 'tomorrow', '2030-01-01T01:00:00', '2030-02-30T01:00:00Z', + '2030-01-01T24:00:00Z', '2030-01-01T00:00:01Z', '2029-01-01T00:00:00Z', + '2030-01-01T01:00:00+25:00', '2040-01-01T00:00:00Z'])('rejects unsafe timestamp %s', value => { + expect(() => parseSchedule(value, now)).toThrow(); + }); +}); + +describe('scheduled sends and photo commands via daemon execute', () => { + let client: any; + let dir: string; + let previousExitCode: typeof process.exitCode; + const invoke = (argv: string[], extras = {}) => executeDaemonCommand(client, 'default', { argv, cwd: dir, ...extras }, new AbortController().signal); + beforeEach(() => { + previousExitCode = process.exitCode; + vi.spyOn(Date, 'now').mockReturnValue(now); + dir = mkdtempSync(join(tmpdir(), 'tg-photo-test-')); + client = { + getEntity: vi.fn().mockResolvedValue(new Api.User({ id: bigInt(7), accessHash: bigInt(11), firstName: 'Synthetic' })), + sendMessage: vi.fn().mockResolvedValue(new Api.Message({ id: 31, peerId: new Api.PeerUser({ userId: bigInt(7) }), date: now / 1000, message: 'Synthetic' })), + uploadFile: vi.fn().mockResolvedValue(new Api.InputFile({ id: bigInt(2), parts: 1, name: 'test.png', md5Checksum: '' })), + invoke: vi.fn().mockResolvedValue({ photo: { id: bigInt(987) } }), + downloadProfilePhoto: vi.fn().mockResolvedValue(Buffer.from('synthetic-photo')), + connect: vi.fn(), destroy: vi.fn(), + }; + }); + afterEach(() => { + expect(client.connect).not.toHaveBeenCalled(); + expect(client.destroy).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(previousExitCode); + vi.restoreAllMocks(); + rmSync(dir, { recursive: true, force: true }); + }); + + it('passes scheduling plus reply target and stdin through the daemon', async () => { + const result = await invoke(['message', 'send', 'me', '-', '--schedule', '2030-01-01T04:00:00+03:00', '--reply-to', '12'], { stdin: 'Scheduled synthetic text\n' }); + expect(result).toMatchObject({ output: { ok: true, data: { scheduledAt: '2030-01-01T01:00:00.000Z' } }, exitCode: 0 }); + expect(client.sendMessage).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ message: 'Scheduled synthetic text', replyTo: 12, schedule: now / 1000 + 3600 })); + expect(client.sendMessage).toHaveBeenCalledOnce(); + }); + + it('keeps immediate sends unchanged', async () => { + const result = await invoke(['message', 'send', 'me', 'Immediate']); + expect(result.output.ok).toBe(true); + expect(client.sendMessage.mock.calls[0][1]).not.toHaveProperty('schedule'); + expect((result.output as any).data).not.toHaveProperty('scheduledAt'); + }); + + it('rejects invalid schedule before resolving or sending', async () => { + const result = await invoke(['message', 'send', 'me', 'Text', '--schedule', '2030-01-01T01:00:00']); + expect(result).toMatchObject({ output: { ok: false, code: 'INVALID_SCHEDULE' }, exitCode: 1 }); + expect(client.getEntity).not.toHaveBeenCalled(); + expect(client.sendMessage).not.toHaveBeenCalled(); + }); + + it('does not accidentally send immediately if resolution outlives the schedule', async () => { + client.getEntity.mockImplementationOnce(async () => { + vi.mocked(Date.now).mockReturnValue(now + 3600_000); + return new Api.User({ id: bigInt(7), accessHash: bigInt(11) }); + }); + const result = await invoke(['message', 'send', 'me', 'Text', '--schedule', '2030-01-01T01:00:00Z']); + expect(result).toMatchObject({ output: { ok: false, code: 'INVALID_SCHEDULE' } }); + expect(client.sendMessage).not.toHaveBeenCalled(); + }); + + it('uses caller cwd and sets a personal photo without suggesting or sending', async () => { + writeFileSync(join(dir, 'photo.png'), Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); + const result = await invoke(['contact', 'set-photo', 'synthetic', 'photo.png']); + expect(result).toMatchObject({ output: { ok: true, data: { userId: '7', photoId: '987', personal: true, size: 8 } }, exitCode: 0 }); + const request = client.invoke.mock.calls[0][0]; + expect(request).toBeInstanceOf(Api.photos.UploadContactProfilePhoto); + expect(request.save).toBe(true); + expect(request.suggest).toBe(false); + expect(client.uploadFile.mock.calls[0][0].file.path).toBe(join(dir, 'photo.png')); + expect(client.sendMessage).not.toHaveBeenCalled(); + }); + + it('rejects missing or invalid photo input before authentication', async () => { + expect(await invoke(['contact', 'set-photo', 'synthetic', 'missing.png'])).toMatchObject({ output: { ok: false, code: 'FILE_NOT_FOUND' } }); + writeFileSync(join(dir, 'bad.png'), 'not an image'); + expect(await invoke(['contact', 'set-photo', 'synthetic', 'bad.png'])).toMatchObject({ output: { ok: false, code: 'INVALID_PHOTO' } }); + expect(client.getEntity).not.toHaveBeenCalled(); + expect(client.uploadFile).not.toHaveBeenCalled(); + }); + + it('reports an unknown photo result without repeating the upload', async () => { + writeFileSync(join(dir, 'photo.jpg'), Buffer.from([255, 216, 255, 0])); + client.invoke.mockResolvedValueOnce({ photo: {} }); + expect(await invoke(['contact', 'set-photo', 'synthetic', 'photo.jpg'])).toMatchObject({ output: { ok: false, code: 'PHOTO_RESULT_UNAVAILABLE' } }); + expect(client.uploadFile).toHaveBeenCalledOnce(); + expect(client.invoke).toHaveBeenCalledOnce(); + }); + + it('downloads a profile photo into the caller directory', async () => { + const result = await invoke(['user', 'download-photo', 'synthetic', '--output', 'avatar.jpg']); + expect(result).toMatchObject({ output: { ok: true, data: { userId: '7', profilePhoto: true, path: join(dir, 'avatar.jpg') } }, exitCode: 0 }); + expect(readFileSync(join(dir, 'avatar.jpg')).toString()).toBe('synthetic-photo'); + expect(client.downloadProfilePhoto).toHaveBeenCalledWith(expect.anything(), { isBig: true }); + }); + + it('preserves existing output unless force is explicit', async () => { + writeFileSync(join(dir, 'avatar.jpg'), 'original'); + expect(await invoke(['user', 'download-photo', 'synthetic', '-o', 'avatar.jpg'])).toMatchObject({ output: { ok: false, code: 'FILE_EXISTS' } }); + expect(client.downloadProfilePhoto).not.toHaveBeenCalled(); + expect(readFileSync(join(dir, 'avatar.jpg')).toString()).toBe('original'); + expect((await invoke(['user', 'download-photo', 'synthetic', '-o', 'avatar.jpg', '--force'])).exitCode).toBe(0); + expect(readFileSync(join(dir, 'avatar.jpg')).toString()).toBe('synthetic-photo'); + }); + + it('does not overwrite a file created during the download', async () => { + client.downloadProfilePhoto.mockImplementationOnce(async () => { + writeFileSync(join(dir, 'avatar.jpg'), 'concurrent'); + return Buffer.from('new'); + }); + expect(await invoke(['user', 'download-photo', 'synthetic', '-o', 'avatar.jpg'])).toMatchObject({ output: { ok: false, code: 'FILE_EXISTS' } }); + expect(readFileSync(join(dir, 'avatar.jpg')).toString()).toBe('concurrent'); + }); + + it('does not create an empty file when no photo is visible', async () => { + client.downloadProfilePhoto.mockResolvedValueOnce(Buffer.alloc(0)); + expect(await invoke(['user', 'download-photo', 'synthetic', '-o', 'avatar.jpg'])).toMatchObject({ output: { ok: false, code: 'NO_PROFILE_PHOTO' } }); + expect(existsSync(join(dir, 'avatar.jpg'))).toBe(false); + }); + + it('rejects non-user peers before upload/download', async () => { + client.getEntity.mockResolvedValue({ className: 'Channel', id: bigInt(8) }); + writeFileSync(join(dir, 'photo.jpg'), Buffer.from([255, 216, 255, 0])); + expect(await invoke(['contact', 'set-photo', 'channel', 'photo.jpg'])).toMatchObject({ output: { ok: false, code: 'NOT_A_USER' } }); + expect(await invoke(['user', 'download-photo', 'channel', '-o', 'avatar.jpg'])).toMatchObject({ output: { ok: false, code: 'NOT_A_USER' } }); + expect(client.uploadFile).not.toHaveBeenCalled(); + expect(client.downloadProfilePhoto).not.toHaveBeenCalled(); + }); + + it('requires cwd for file commands over the API', () => { + for (const argv of [['contact', 'set-photo', 'me', 'p.png'], ['user', 'download-photo', 'me', '-o', 'p.jpg']]) { + expect(() => validateDaemonCommand({ argv })).toThrow(); + } + }); + + it('renders photo results for humans', () => { + expect(formatData({ id: 31, text: 'Synthetic', date: '2030-01-01T00:00:00Z', scheduledAt: '2030-01-01T01:00:00Z' })).toContain('Scheduled for'); + expect(formatData({ userId: '7', photoId: '987', personal: true, size: 8 })).toContain('visible only to you'); + expect(formatData({ userId: '7', profilePhoto: true, path: '/tmp/avatar.jpg', size: 10 })).toContain('/tmp/avatar.jpg'); + }); +}); diff --git a/cli/tests/unit/serialize.test.ts b/cli/tests/unit/serialize.test.ts new file mode 100644 index 0000000..9aad631 --- /dev/null +++ b/cli/tests/unit/serialize.test.ts @@ -0,0 +1,758 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// Hoist mock classes for telegram Api +const { + MockBold, + MockMediaPhoto, + MockMediaDocument, + MockMediaPoll, + MockAttrSticker, + MockAttrVideo, + MockAttrAudio, + MockAttrFilename, + MockAttrImageSize, + MockActionChatCreate, +} = vi.hoisted(() => { + class MockBold { offset: number; length: number; constructor(args: any) { this.offset = args.offset; this.length = args.length; } } + class MockMediaPhoto {} + class MockMediaDocument {} + class MockMediaPoll {} + class MockAttrSticker { alt: string; constructor(a?: any) { this.alt = a?.alt ?? ''; } } + class MockAttrVideo { w?: number; h?: number; duration?: number; constructor(a?: any) { this.w = a?.w; this.h = a?.h; this.duration = a?.duration; } } + class MockAttrAudio { voice?: boolean; duration?: number; constructor(a?: any) { this.voice = a?.voice; this.duration = a?.duration; } } + class MockAttrFilename { fileName: string; constructor(a?: any) { this.fileName = a?.fileName ?? ''; } } + class MockAttrImageSize { w: number; h: number; constructor(a?: any) { this.w = a?.w ?? 0; this.h = a?.h ?? 0; } } + class MockActionChatCreate {} + return { MockBold, MockMediaPhoto, MockMediaDocument, MockMediaPoll, MockAttrSticker, MockAttrVideo, MockAttrAudio, MockAttrFilename, MockAttrImageSize, MockActionChatCreate }; +}); + +vi.mock('teleproto', () => ({ + Api: { + MessageEntityBold: MockBold, + MessageEntityItalic: class { offset: number; length: number; constructor(a: any) { this.offset = a.offset; this.length = a.length; } }, + MessageEntityCode: class { offset: number; length: number; constructor(a: any) { this.offset = a.offset; this.length = a.length; } }, + MessageEntityPre: class { offset: number; length: number; language: string; constructor(a: any) { this.offset = a.offset; this.length = a.length; this.language = a.language ?? ''; } }, + MessageEntityTextUrl: class { offset: number; length: number; url: string; constructor(a: any) { this.offset = a.offset; this.length = a.length; this.url = a.url; } }, + MessageEntityStrike: class { offset: number; length: number; constructor(a: any) { this.offset = a.offset; this.length = a.length; } }, + MessageEntityBlockquote: class { offset: number; length: number; constructor(a: any) { this.offset = a.offset; this.length = a.length; } }, + MessageEntityMentionName: class { offset: number; length: number; userId: number; constructor(a: any) { this.offset = a.offset; this.length = a.length; this.userId = a.userId; } }, + MessageMediaPhoto: MockMediaPhoto, + MessageMediaDocument: MockMediaDocument, + MessageMediaPoll: MockMediaPoll, + DocumentAttributeSticker: MockAttrSticker, + DocumentAttributeVideo: MockAttrVideo, + DocumentAttributeAudio: MockAttrAudio, + DocumentAttributeFilename: MockAttrFilename, + DocumentAttributeImageSize: MockAttrImageSize, + MessageActionChatCreate: MockActionChatCreate, + }, +})); + +import { + serializeDialog, + serializeMessage, + serializeSearchResult, + serializeMember, + bigIntToString, + markedPeerId, + messagePeerMarkedId, + serializeChatPhoto, + serializeBannedRights, + extractMediaInfo, + extractPollData, + detectMedia, +} from '../../src/lib/serialize.js'; + +// Helper to create a mock Dialog +function mockDialog(overrides: any = {}) { + const defaults: any = { + id: { toString: () => '12345' }, + title: 'Test Chat', + name: 'Test Chat', + unreadCount: 0, + isUser: false, + isGroup: false, + isChannel: false, + entity: {}, + }; + // Use Object.assign so explicit undefined values override defaults + return { ...defaults, ...overrides }; +} + +// Helper to create a mock Message +function mockMessage(overrides: any = {}) { + const defaults: any = { + id: 1, + message: 'Hello', + date: 1710150900, + entities: undefined, + media: null, + action: null, + senderId: { toString: () => '99999' }, + replyTo: null, + fwdFrom: null, + }; + return { ...defaults, ...overrides }; +} + +describe('serializeDialog', () => { + it('returns type "user" for user dialogs', () => { + const dialog = mockDialog({ isUser: true }); + const result = serializeDialog(dialog as any); + expect(result.type).toBe('user'); + expect(result.id).toBe('12345'); + expect(result.title).toBe('Test Chat'); + }); + + it('prefers gramjs dialog.id over an unmarked Forbidden entity', () => { + const dialog = mockDialog({ + id: { toString: () => '-1005' }, + entity: { id: 5, className: 'ChannelForbidden' }, + }); + expect(serializeDialog(dialog as any).id).toBe('-1005'); + }); + + it('returns type "group" for group dialogs', () => { + const dialog = mockDialog({ isGroup: true }); + const result = serializeDialog(dialog as any); + expect(result.type).toBe('group'); + }); + + it('returns type "channel" for broadcast channel dialogs', () => { + const dialog = mockDialog({ + isChannel: true, + entity: { broadcast: true, megagroup: false, username: 'testchannel' }, + }); + const result = serializeDialog(dialog as any); + expect(result.type).toBe('channel'); + }); + + it('returns type "supergroup" for megagroup channel dialogs', () => { + const dialog = mockDialog({ + isChannel: true, + entity: { megagroup: true, broadcast: false, username: 'supergroup' }, + }); + const result = serializeDialog(dialog as any); + expect(result.type).toBe('supergroup'); + }); + + it('serializes BigInteger ID as string', () => { + const bigId = { toString: () => '1001234567890' }; + const dialog = mockDialog({ id: bigId, isUser: true }); + const result = serializeDialog(dialog as any); + expect(result.id).toBe('1001234567890'); + expect(typeof result.id).toBe('string'); + }); + + it('returns null username when entity has no username', () => { + const dialog = mockDialog({ isUser: true, entity: {} }); + const result = serializeDialog(dialog as any); + expect(result.username).toBeNull(); + }); + + it('extracts username from entity', () => { + const dialog = mockDialog({ isUser: true, entity: { username: 'alice' } }); + const result = serializeDialog(dialog as any); + expect(result.username).toBe('alice'); + }); + + it('includes unreadCount', () => { + const dialog = mockDialog({ isUser: true, unreadCount: 5 }); + const result = serializeDialog(dialog as any); + expect(result.unreadCount).toBe(5); + }); + + it('uses title field, falling back to name', () => { + const dialog = mockDialog({ isUser: true, title: undefined, name: 'Fallback Name' }); + const result = serializeDialog(dialog as any); + expect(result.title).toBe('Fallback Name'); + }); + + it('handles null id gracefully', () => { + const dialog = mockDialog({ isUser: true, id: null }); + const result = serializeDialog(dialog as any); + expect(result.id).toBe(''); + }); +}); + +describe('serializeMessage', () => { + it('returns correct basic fields for a text message', () => { + const msg = mockMessage({ id: 42, message: 'Hello world' }); + const result = serializeMessage(msg as any); + expect(result.id).toBe(42); + expect(result.text).toBe('Hello world'); + expect(result.type).toBe('message'); + expect(result.senderId).toBe('99999'); + }); + + it('converts date to ISO 8601 UTC string', () => { + // 1710150900 = 2024-03-11T09:55:00.000Z + const msg = mockMessage({ date: 1710150900 }); + const result = serializeMessage(msg as any); + expect(result.date).toBe('2024-03-11T09:55:00.000Z'); + }); + + it('converts message entities to Markdown', () => { + const entities = [new MockBold({ offset: 0, length: 5 })]; + const msg = mockMessage({ message: 'Hello world', entities }); + const result = serializeMessage(msg as any); + expect(result.text).toBe('**Hello** world'); + }); + + it('includes senderName from senderEntity', () => { + const msg = mockMessage(); + const sender = { firstName: 'Alice', lastName: 'Bob' }; + const result = serializeMessage(msg as any, sender as any); + expect(result.senderName).toBe('Alice Bob'); + }); + + it('uses firstName only when lastName missing', () => { + const msg = mockMessage(); + const sender = { firstName: 'Alice' }; + const result = serializeMessage(msg as any, sender as any); + expect(result.senderName).toBe('Alice'); + }); + + it('fills senderName from msg._sender when no senderEntity is passed', () => { + const msg = mockMessage(); + (msg as any)._sender = { firstName: 'Carol', lastName: 'Diaz' }; + const result = serializeMessage(msg as any); + expect(result.senderName).toBe('Carol Diaz'); + }); + + it('prefers explicit senderEntity over msg._sender', () => { + const msg = mockMessage(); + (msg as any)._sender = { firstName: 'FromMsg' }; + const result = serializeMessage(msg as any, { firstName: 'Explicit' } as any); + expect(result.senderName).toBe('Explicit'); + }); + + it('includes replyToMsgId when message is a reply', () => { + const msg = mockMessage({ replyTo: { replyToMsgId: 10 } }); + const result = serializeMessage(msg as any); + expect(result.replyToMsgId).toBe(10); + }); + + it('returns null replyToMsgId when not a reply', () => { + const msg = mockMessage(); + const result = serializeMessage(msg as any); + expect(result.replyToMsgId).toBeNull(); + }); + + it('detects photo media type', () => { + const media = new MockMediaPhoto(); + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('photo'); + }); + + it('detects video media type', () => { + const media = new MockMediaDocument(); + (media as any).document = { attributes: [new MockAttrVideo()] }; + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('video'); + }); + + it('detects voice media type', () => { + const media = new MockMediaDocument(); + const audioAttr = new MockAttrAudio({ voice: true }); + (media as any).document = { attributes: [audioAttr] }; + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('voice'); + }); + + it('detects sticker media type with emoji', () => { + const media = new MockMediaDocument(); + const stickerAttr = new MockAttrSticker({ alt: '\u{1F600}' }); + (media as any).document = { attributes: [stickerAttr] }; + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('sticker'); + expect(result.emoji).toBe('\u{1F600}'); + }); + + it('returns type "service" with actionText for service messages', () => { + const action = new MockActionChatCreate(); + const msg = mockMessage({ action, message: '' }); + const result = serializeMessage(msg as any); + expect(result.type).toBe('service'); + expect(result.actionText).toBeDefined(); + }); + + it('returns null senderId when senderId is null', () => { + const msg = mockMessage({ senderId: null }); + const result = serializeMessage(msg as any); + expect(result.senderId).toBeNull(); + }); + + it('handles forwardFrom info', () => { + const msg = mockMessage({ + fwdFrom: { fromName: 'Forwarded User' }, + }); + const result = serializeMessage(msg as any); + expect(result.forwardFrom).toBe('Forwarded User'); + }); + + it('returns null forwardFrom when not forwarded', () => { + const msg = mockMessage(); + const result = serializeMessage(msg as any); + expect(result.forwardFrom).toBeNull(); + }); + + it('uses caption as text for media messages', () => { + const media = new MockMediaPhoto(); + const msg = mockMessage({ media, message: 'A nice photo caption' }); + const result = serializeMessage(msg as any); + expect(result.text).toBe('A nice photo caption'); + expect(result.mediaType).toBe('photo'); + }); +}); + +describe('serializeSearchResult', () => { + it('includes chatId and chatTitle in addition to message fields', () => { + const msg = mockMessage({ id: 10, message: 'search hit' }); + const result = serializeSearchResult(msg as any, '54321', 'Test Group'); + expect(result.id).toBe(10); + expect(result.text).toBe('search hit'); + expect(result.chatId).toBe('54321'); + expect(result.chatTitle).toBe('Test Group'); + }); +}); + +describe('serializeMember', () => { + it('serializes a user entity to MemberItem', () => { + const user = { + id: { toString: () => '67890' }, + username: 'bobuser', + firstName: 'Bob', + lastName: 'Smith', + bot: false, + status: { className: 'UserStatusOnline' }, + }; + const result = serializeMember(user as any); + expect(result.id).toBe('67890'); + expect(result.username).toBe('bobuser'); + expect(result.firstName).toBe('Bob'); + expect(result.lastName).toBe('Smith'); + expect(result.isBot).toBe(false); + }); + + it('handles null fields gracefully', () => { + const user = { + id: { toString: () => '11111' }, + username: null, + firstName: null, + lastName: null, + bot: true, + status: null, + }; + const result = serializeMember(user as any); + expect(result.id).toBe('11111'); + expect(result.username).toBeNull(); + expect(result.firstName).toBeNull(); + expect(result.lastName).toBeNull(); + expect(result.isBot).toBe(true); + expect(result.status).toBeNull(); + }); +}); + +describe('bigIntToString', () => { + it('converts BigInteger-like object to string', () => { + expect(bigIntToString({ toString: () => '9876543210' })).toBe('9876543210'); + }); + + it('returns empty string for null/undefined', () => { + expect(bigIntToString(null)).toBe(''); + expect(bigIntToString(undefined)).toBe(''); + }); + + it('converts numbers to string', () => { + expect(bigIntToString(12345)).toBe('12345'); + }); +}); + +describe('extractMediaInfo', () => { + it('returns null for null/undefined media', () => { + expect(extractMediaInfo(null)).toBeNull(); + expect(extractMediaInfo(undefined)).toBeNull(); + }); + + it('extracts info from MessageMediaPhoto', () => { + const photo = new MockMediaPhoto(); + // Simulate photo.photo with sizes array (largest size has w, h, size) + (photo as any).photo = { + sizes: [ + { w: 320, h: 240, size: 5000, className: 'PhotoSize' }, + { w: 1920, h: 1080, size: 245760, className: 'PhotoSize' }, + ], + }; + const info = extractMediaInfo(photo); + expect(info).not.toBeNull(); + expect(info!.mimeType).toBe('image/jpeg'); + expect(info!.filename).toBeNull(); + expect(info!.width).toBe(1920); + expect(info!.height).toBe(1080); + expect(info!.fileSize).toBe(245760); + expect(info!.duration).toBeNull(); + }); + + it('extracts info from MessageMediaDocument with video attributes', () => { + const media = new MockMediaDocument(); + (media as any).document = { + size: BigInt(1234567), + mimeType: 'video/mp4', + attributes: [ + new MockAttrVideo({ w: 1280, h: 720, duration: 32 }), + new MockAttrFilename({ fileName: 'clip.mp4' }), + ], + }; + const info = extractMediaInfo(media); + expect(info).not.toBeNull(); + expect(info!.mimeType).toBe('video/mp4'); + expect(info!.filename).toBe('clip.mp4'); + expect(info!.width).toBe(1280); + expect(info!.height).toBe(720); + expect(info!.duration).toBe(32); + expect(info!.fileSize).toBe(1234567); + }); + + it('extracts info from MessageMediaDocument with audio attributes', () => { + const media = new MockMediaDocument(); + (media as any).document = { + size: BigInt(98765), + mimeType: 'audio/ogg', + attributes: [ + new MockAttrAudio({ voice: true, duration: 15 }), + ], + }; + const info = extractMediaInfo(media); + expect(info).not.toBeNull(); + expect(info!.duration).toBe(15); + expect(info!.mimeType).toBe('audio/ogg'); + expect(info!.fileSize).toBe(98765); + }); + + it('handles gramjs BigInteger-like size values via toJSNumber()', () => { + const bigIntLike = { toJSNumber: () => 9876543210 }; + const media = new MockMediaDocument(); + (media as any).document = { + size: bigIntLike, + mimeType: 'application/pdf', + attributes: [ + new MockAttrFilename({ fileName: 'large.pdf' }), + ], + }; + const info = extractMediaInfo(media); + expect(info).not.toBeNull(); + expect(info!.fileSize).toBe(9876543210); + }); + + it('returns null for unsupported media types', () => { + const unknownMedia = { className: 'MessageMediaGeo' }; + expect(extractMediaInfo(unknownMedia)).toBeNull(); + }); +}); + +describe('serializeMessage - media field', () => { + it('includes media field for photo messages', () => { + const media = new MockMediaPhoto(); + (media as any).photo = { + sizes: [ + { w: 800, h: 600, size: 50000, className: 'PhotoSize' }, + ], + }; + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('photo'); + expect(result.media).toBeDefined(); + expect(result.media!.mimeType).toBe('image/jpeg'); + expect(result.media!.width).toBe(800); + expect(result.media!.height).toBe(600); + }); + + it('excludes media field for text-only messages (backward compatible)', () => { + const msg = mockMessage({ media: null }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBeNull(); + expect(result.media).toBeUndefined(); + }); + + it('includes media field for document messages', () => { + const media = new MockMediaDocument(); + (media as any).document = { + size: BigInt(5000), + mimeType: 'application/pdf', + attributes: [ + new MockAttrFilename({ fileName: 'report.pdf' }), + ], + }; + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('document'); + expect(result.media).toBeDefined(); + expect(result.media!.filename).toBe('report.pdf'); + expect(result.media!.mimeType).toBe('application/pdf'); + }); +}); + +// Helper to create a mock MessageMediaPoll instance +function mockPollMedia(overrides: any = {}) { + const defaults = { + poll: { + question: { text: 'Favorite color?' }, + answers: [ + { text: { text: 'Red' }, option: Buffer.from('0') }, + { text: { text: 'Blue' }, option: Buffer.from('1') }, + { text: { text: 'Green' }, option: Buffer.from('2') }, + ], + quiz: false, + publicVoters: false, + multipleChoice: false, + closed: false, + closePeriod: undefined, + closeDate: undefined, + }, + results: { + results: [], + totalVoters: 0, + solution: undefined, + }, + }; + + const merged = { + poll: { ...defaults.poll, ...overrides.poll }, + results: { ...defaults.results, ...overrides.results }, + }; + + // Merge answers if provided + if (overrides.poll?.answers) { + merged.poll.answers = overrides.poll.answers; + } + + return Object.assign(new MockMediaPoll(), merged); +} + +describe('extractPollData', () => { + it('returns null for non-MessageMediaPoll media', () => { + const photo = new MockMediaPhoto(); + expect(extractPollData(photo)).toBeNull(); + expect(extractPollData(null)).toBeNull(); + expect(extractPollData(undefined)).toBeNull(); + }); + + it('extracts basic poll with question and options', () => { + const media = mockPollMedia(); + const result = extractPollData(media); + expect(result).not.toBeNull(); + expect(result!.question).toBe('Favorite color?'); + expect(result!.options).toHaveLength(3); + expect(result!.options[0]).toEqual({ text: 'Red', voters: 0, chosen: false, correct: false }); + expect(result!.options[1]).toEqual({ text: 'Blue', voters: 0, chosen: false, correct: false }); + expect(result!.options[2]).toEqual({ text: 'Green', voters: 0, chosen: false, correct: false }); + expect(result!.isQuiz).toBe(false); + expect(result!.isPublic).toBe(false); + expect(result!.isMultiple).toBe(false); + expect(result!.isClosed).toBe(false); + expect(result!.totalVoters).toBe(0); + expect(result!.correctOption).toBeNull(); + expect(result!.solution).toBeNull(); + }); + + it('extracts poll with votes matched to options via option bytes', () => { + const media = mockPollMedia({ + results: { + results: [ + { option: Buffer.from('0'), voters: 5, chosen: false, correct: false }, + { option: Buffer.from('1'), voters: 3, chosen: true, correct: false }, + { option: Buffer.from('2'), voters: 1, chosen: false, correct: false }, + ], + totalVoters: 9, + }, + }); + const result = extractPollData(media); + expect(result!.options[0].voters).toBe(5); + expect(result!.options[0].chosen).toBe(false); + expect(result!.options[1].voters).toBe(3); + expect(result!.options[1].chosen).toBe(true); + expect(result!.options[2].voters).toBe(1); + expect(result!.totalVoters).toBe(9); + }); + + it('extracts quiz poll with correctOption as 1-based index', () => { + const media = mockPollMedia({ + poll: { + question: { text: 'Capital of France?' }, + answers: [ + { text: { text: 'London' }, option: Buffer.from('0') }, + { text: { text: 'Paris' }, option: Buffer.from('1') }, + { text: { text: 'Berlin' }, option: Buffer.from('2') }, + ], + quiz: true, + publicVoters: false, + multipleChoice: false, + closed: false, + }, + results: { + results: [ + { option: Buffer.from('0'), voters: 2, chosen: false, correct: false }, + { option: Buffer.from('1'), voters: 8, chosen: true, correct: true }, + { option: Buffer.from('2'), voters: 1, chosen: false, correct: false }, + ], + totalVoters: 11, + solution: 'Paris is the capital of France', + }, + }); + const result = extractPollData(media); + expect(result!.isQuiz).toBe(true); + expect(result!.correctOption).toBe(2); // 1-based: option index 1 -> position 2 + expect(result!.options[1].correct).toBe(true); + expect(result!.solution).toBe('Paris is the capital of France'); + }); + + it('extracts closed poll with closePeriod and closeDate', () => { + const closeTimestamp = 1710200000; // Unix timestamp + const media = mockPollMedia({ + poll: { + question: { text: 'Quick poll' }, + answers: [ + { text: { text: 'Yes' }, option: Buffer.from('0') }, + { text: { text: 'No' }, option: Buffer.from('1') }, + ], + quiz: false, + publicVoters: false, + multipleChoice: false, + closed: true, + closePeriod: 60, + closeDate: closeTimestamp, + }, + results: { + results: [], + totalVoters: 5, + }, + }); + const result = extractPollData(media); + expect(result!.isClosed).toBe(true); + expect(result!.closePeriod).toBe(60); + expect(result!.closeDate).toBe(new Date(closeTimestamp * 1000).toISOString()); + expect(result!.totalVoters).toBe(5); + }); + + it('extracts public and multiple-choice flags', () => { + const media = mockPollMedia({ + poll: { + question: { text: 'Multi poll' }, + answers: [ + { text: { text: 'A' }, option: Buffer.from('0') }, + { text: { text: 'B' }, option: Buffer.from('1') }, + ], + quiz: false, + publicVoters: true, + multipleChoice: true, + closed: false, + }, + }); + const result = extractPollData(media); + expect(result!.isPublic).toBe(true); + expect(result!.isMultiple).toBe(true); + }); + + it('handles missing results gracefully', () => { + const media = Object.assign(new MockMediaPoll(), { + poll: { + question: { text: 'New poll' }, + answers: [ + { text: { text: 'Yes' }, option: Buffer.from('0') }, + { text: { text: 'No' }, option: Buffer.from('1') }, + ], + quiz: false, + publicVoters: false, + multipleChoice: false, + closed: false, + }, + results: null, + }); + const result = extractPollData(media); + expect(result).not.toBeNull(); + expect(result!.options[0].voters).toBe(0); + expect(result!.totalVoters).toBe(0); + }); +}); + +describe('serializeMessage - poll field', () => { + it('populates poll field when message contains a poll', () => { + const media = mockPollMedia(); + const msg = mockMessage({ media }); + const result = serializeMessage(msg as any); + expect(result.mediaType).toBe('poll'); + expect(result.poll).toBeDefined(); + expect(result.poll!.question).toBe('Favorite color?'); + expect(result.poll!.options).toHaveLength(3); + }); + + it('does not include poll field for non-poll messages', () => { + const msg = mockMessage({ media: null }); + const result = serializeMessage(msg as any); + expect(result.poll).toBeUndefined(); + }); +}); + +describe('detectMedia - poll', () => { + it('returns mediaType "poll" for MessageMediaPoll', () => { + const media = new MockMediaPoll(); + expect(detectMedia(media).mediaType).toBe('poll'); + }); +}); + +describe('markedPeerId', () => { + it('marks channels with -100 prefix', () => { + expect(markedPeerId({ id: 123456, className: 'Channel' })).toBe('-100123456'); + }); + + it('marks basic chats with a leading minus', () => { + expect(markedPeerId({ id: 99, className: 'Chat' })).toBe('-99'); + }); + + it('marks Forbidden chat and channel classes', () => { + expect(markedPeerId({ id: 8, className: 'ChatForbidden' })).toBe('-8'); + expect(markedPeerId({ id: 9, className: 'ChannelForbidden' })).toBe('-1009'); + }); + + it('leaves users unmarked', () => { + expect(markedPeerId({ id: 42, className: 'User' })).toBe('42'); + }); + + it('does not double-mark an already negative id', () => { + expect(markedPeerId({ id: '-100123', className: 'Channel' })).toBe('-100123'); + }); +}); + +describe('messagePeerMarkedId', () => { + it('marks channel, chat, and user peers', () => { + expect(messagePeerMarkedId({ peerId: { channelId: 5 } })).toBe('-1005'); + expect(messagePeerMarkedId({ peerId: { chatId: 9 } })).toBe('-9'); + expect(messagePeerMarkedId({ peerId: { userId: 3 } })).toBe('3'); + }); + + it('returns empty when the update has no peer', () => { + expect(messagePeerMarkedId({ id: 1, message: 'x' })).toBe(''); + }); +}); + +describe('serializeChatPhoto / serializeBannedRights', () => { + it('returns hasPhoto for a real photo object', () => { + expect(serializeChatPhoto({ className: 'ChatPhoto' })).toEqual({ hasPhoto: true }); + }); + + it('returns null for empty photos', () => { + expect(serializeChatPhoto({ className: 'ChatPhotoEmpty' })).toBeNull(); + expect(serializeChatPhoto(null)).toBeNull(); + }); + + it('keeps only boolean permission flags', () => { + expect(serializeBannedRights({ sendMessages: true, className: 'X', flags: 3 })).toEqual({ + sendMessages: true, + }); + }); +}); diff --git a/cli/tests/unit/session-hold-cross-review.test.ts b/cli/tests/unit/session-hold-cross-review.test.ts new file mode 100644 index 0000000..d4e2d91 --- /dev/null +++ b/cli/tests/unit/session-hold-cross-review.test.ts @@ -0,0 +1,108 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { lock } from 'proper-lockfile'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { withClient } from '../../src/lib/client.js'; + +const mocks = vi.hoisted(() => ({ connect: vi.fn(), destroy: vi.fn() })); +vi.mock('teleproto', async () => ({ + ...await vi.importActual('teleproto'), + sessions: { StringSession: class {} }, + TelegramClient: class { connect = mocks.connect; destroy = mocks.destroy; }, +})); + +/** Independent composition checks: real profile lock, controlled SDK lifecycle. */ +describe('deferred ownership after request completion', () => { + let dir: string; + let store: SessionStore; + const releases: Array<() => Promise<void>> = []; + const opts = { apiId: 1, apiHash: 'synthetic', sessionString: 'synthetic' }; + + beforeEach(async () => { + mocks.connect.mockReset().mockResolvedValue(undefined); + mocks.destroy.mockReset().mockResolvedValue(undefined); + dir = await mkdtemp(join(tmpdir(), 'tg-hold-cross-')); + store = new SessionStore(dir); + const acquire = store.acquireLock.bind(store); + vi.spyOn(store, 'acquireLock').mockImplementation(async profile => { + const release = await acquire(profile); + releases.push(release); + return release; + }); + }); + + afterEach(async () => { + // Explicit fixture disposal also handles the intentionally fail-closed case; + // never remove a directory while proper-lockfile still has its heartbeat. + for (const release of releases.splice(0)) await release().catch(() => {}); + vi.restoreAllMocks(); + await rm(dir, { recursive: true, force: true }); + }); + + async function probe() { + const release = await lock(store.filePath('fixture'), { realpath: false, retries: 0 }); + await release(); + } + + it('an operation failure with successful cleanup releases ownership', async () => { + const operation = store.withLock('fixture', async (_session, holdUntil) => + withClient(opts, async () => { throw new Error('Read failed'); }, { holdUntil })); + await expect(operation).rejects.toThrow('Read failed'); + await vi.waitFor(async () => { await probe(); }); + expect(mocks.destroy).toHaveBeenCalledOnce(); + }); + + it('an already rejected teardown fails closed without losing the original operation result', async () => { + const result = await store.withLock('fixture', async (_session, holdUntil) => { + holdUntil(Promise.reject(new Error('Teardown failed'))); + return 'result'; + }); + expect(result).toBe('result'); + await expect(probe()).rejects.toMatchObject({ code: 'ELOCKED' }); + }); + + it('timeout retains ownership across late callback failure and its final destruction', async () => { + let failOperation!: (error: Error) => void; + let finishDestroy!: () => void; + const inFlight = new Promise<never>((_resolve, reject) => { failOperation = reject; }); + const finalDestroy = new Promise<void>(resolve => { finishDestroy = resolve; }); + mocks.destroy.mockResolvedValueOnce(undefined).mockReturnValueOnce(finalDestroy); + const operation = store.withLock('fixture', async (_session, holdUntil) => + withClient(opts, async () => inFlight, { timeout: 20, holdUntil })); + try { + await expect(operation).rejects.toMatchObject({ code: 'TIMEOUT' }); + await expect(probe()).rejects.toMatchObject({ code: 'ELOCKED' }); + failOperation(new Error('Late read failure')); + await vi.waitFor(() => expect(mocks.destroy).toHaveBeenCalledTimes(2)); + await expect(probe()).rejects.toMatchObject({ code: 'ELOCKED' }); + finishDestroy(); + await vi.waitFor(async () => { await probe(); }); + } finally { + failOperation(new Error('Fixture teardown')); + finishDestroy(); + } + }); + + it('multiple cleanup holds release only after the last successful teardown', async () => { + let finishFirst!: () => void; + let finishSecond!: () => void; + const first = new Promise<void>(resolve => { finishFirst = resolve; }); + const second = new Promise<void>(resolve => { finishSecond = resolve; }); + try { + await store.withLock('fixture', async (_session, holdUntil) => { + holdUntil(Promise.resolve()); + holdUntil(first); + holdUntil(second); + }); + finishFirst(); + await expect(probe()).rejects.toMatchObject({ code: 'ELOCKED' }); + finishSecond(); + await vi.waitFor(async () => { await probe(); }); + } finally { + finishFirst(); + finishSecond(); + } + }); +}); diff --git a/cli/tests/unit/session-ownership-process.test.ts b/cli/tests/unit/session-ownership-process.test.ts new file mode 100644 index 0000000..9799b55 --- /dev/null +++ b/cli/tests/unit/session-ownership-process.test.ts @@ -0,0 +1,267 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { build } from 'esbuild'; +import { fork, type ChildProcess } from 'node:child_process'; +import { createRequire } from 'node:module'; +import { mkdtempSync, rmSync, writeFileSync, existsSync, symlinkSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { SessionStore } from '../../src/lib/session-store.js'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; +import { DaemonClient } from '../../src/lib/daemon/client.js'; +import { createConnection } from 'node:net'; +import { once } from 'node:events'; + +const require = createRequire(import.meta.url); +interface Event { event: string; code?: string; message?: string } +class Worker { + readonly process: ChildProcess; + readonly events: Event[] = []; + stdout = ''; + stderr = ''; + private readonly waiters = new Set<() => void>(); + constructor(entry: string, role: string, dir: string, profile = 'test') { + this.process = fork(entry, [role, dir, profile], { + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + env: { ...process.env, TG_API_ID: '1234', TG_API_HASH: 'synthetic-api-hash' }, + }); + this.process.stdout!.on('data', (data) => { this.stdout += data; }); + this.process.stderr!.on('data', (data) => { this.stderr += data; }); + this.process.on('message', (message) => { + this.events.push(message as Event); + for (const notify of this.waiters) notify(); + }); + this.process.on('exit', () => { for (const notify of this.waiters) notify(); }); + } + send(command: string) { this.process.send(command); } + event(name: string): Promise<Event> { + return new Promise((resolve, reject) => { + const finish = () => { + const result = this.events.find((event) => event.event === name); + const failure = this.events.find((event) => event.event === 'failed'); + if (!result && !failure && this.process.exitCode == null && this.process.signalCode == null) return; + clearTimeout(timeout); + this.waiters.delete(finish); + if (result) resolve(result); + else reject(new Error(`Worker missed ${name}: ${JSON.stringify(failure)} ${this.stderr}`)); + }; + const timeout = setTimeout(() => { + this.waiters.delete(finish); + reject(new Error(`Worker timed out awaiting ${name}: ${JSON.stringify(this.events)} ${this.stderr}`)); + }, 5000); + this.waiters.add(finish); + finish(); + }); + } + async exit(): Promise<void> { + if (this.process.exitCode != null || this.process.signalCode != null) return; + await new Promise<void>((resolve) => this.process.once('exit', () => resolve())); + } +} + +/** IPC barriers hold precise lifecycle phases; no timing guesses or live Telegram. */ +describe('exclusive profile ownership across processes', () => { + let bundleDir: string; + let entry: string; + let dir: string; + const workers: Worker[] = []; + + beforeAll(async () => { + bundleDir = mkdtempSync(join(tmpdir(), 'tg-owner-build-')); + entry = join(bundleDir, 'worker.mjs'); + const telegramMock = resolve('tests/fixtures/daemon-telegram.ts'); + await build({ + entryPoints: [resolve('tests/fixtures/session-ownership.ts')], + outfile: entry, bundle: true, platform: 'node', format: 'esm', target: 'node20', logLevel: 'silent', + plugins: [{ name: 'offline-telegram-and-external-packages', setup(builder) { + builder.onResolve({ filter: /^teleproto$/ }, () => ({ path: telegramMock })); + builder.onResolve({ filter: /^[^./]/ }, (args) => { + if (args.path.startsWith('node:')) return { path: args.path, external: true }; + return { path: require.resolve(args.path), external: true }; + }); + } }], + }); + }); + afterAll(() => rmSync(bundleDir, { recursive: true, force: true })); + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'tg-owner-')); + writeFileSync(join(dir, 'config.json'), JSON.stringify({ profiles: {} })); + }); + afterEach(async () => { + for (const worker of workers) { + if (worker.process.exitCode == null && worker.process.signalCode == null) worker.process.kill('SIGKILL'); + } + await Promise.all(workers.map((worker) => worker.exit())); + workers.length = 0; + rmSync(dir, { recursive: true, force: true }); + }); + async function worker(role: string, path = dir, profile = 'test') { + const current = new Worker(entry, role, path, profile); + workers.push(current); + await current.event('ready'); + return current; + } + async function probeBlocked(path = dir, profile = 'test') { + const probe = await worker('probe', path, profile); + probe.send('run'); + expect(await probe.event('blocked')).toMatchObject({ code: 'ELOCKED' }); + await probe.exit(); + expect(probe.events.some((event) => event.event === 'acquired')).toBe(false); + } + async function probeFree() { + const probe = await worker('probe'); + probe.send('run'); + await probe.event('acquired'); + await probe.exit(); + } + async function releaseConnected(owner: Worker, role: string) { + if (role === 'direct') owner.send('operation'); + else if (role === 'foreground' || role === 'background') owner.process.kill('SIGTERM'); + await owner.event('destroying'); + await probeBlocked(); + owner.send('destroying'); + await owner.exit(); + await probeFree(); + } + + it.each(['direct', 'foreground', 'background'])('holds %s ownership before connect through destroy', async (role) => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const owner = await worker(role); + if (role === 'background') new DaemonPaths(dir, 'test').writePidExclusive(owner.process.pid!); + owner.send('run'); + await owner.event('connecting'); + await probeBlocked(); + owner.send('connecting'); + await owner.event('connected'); + if (role === 'direct') await owner.event('operation'); + await releaseConnected(owner, role); + }, 15000); + + it.each(['login', 'import'])('locks a missing profile for the entire %s operation', async (role) => { + const owner = await worker(role); + owner.send('run'); + await owner.event('connecting'); + const file = new SessionStore(dir).filePath('test'); + expect(existsSync(file)).toBe(false); + await probeBlocked(); + owner.send('connecting'); + await owner.event('destroying'); + await probeBlocked(); + owner.send('destroying'); + await owner.exit(); + expect(await new SessionStore(dir).load('test')).toMatch(/^synthetic-/); + await probeFree(); + }, 15000); + + it('prevents direct connect after its daemon check has already passed', async () => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const direct = await worker('direct-race'); + direct.send('run'); + await direct.event('before-lock'); + const daemon = await worker('background'); + new DaemonPaths(dir, 'test').writePidExclusive(daemon.process.pid!); + daemon.send('run'); + await daemon.event('connecting'); + direct.send('before-lock'); + await direct.event('done'); + await direct.exit(); + expect(direct.events.some((event) => event.event === 'connecting')).toBe(false); + expect(JSON.parse(direct.stdout.trim())).toMatchObject({ ok: false }); + daemon.send('connecting'); + await daemon.event('connected'); + await releaseConnected(daemon, 'background'); + }, 15000); + + it('keeps one lock across delete/recreate and symlinked config aliases', async () => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const alias = join(dir, 'alias'); + symlinkSync(dir, alias, 'dir'); + const owner = await worker('delete-recreate'); + owner.send('run'); + await owner.event('deleted'); + await probeBlocked(alias); + owner.send('deleted'); + await owner.event('saved'); + await probeBlocked(alias); + owner.send('saved'); + await owner.exit(); + expect(await new SessionStore(dir).load('test')).toBe('synthetic-recreated-session'); + await probeFree(); + }, 15000); + + it('permits a different profile while one connected profile is owned', async () => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const owner = await worker('direct'); + owner.send('run'); + await owner.event('connecting'); + const other = await worker('probe', dir, 'other'); + other.send('run'); + await other.event('acquired'); + await other.exit(); + owner.send('connecting'); + await owner.event('operation'); + await releaseConnected(owner, 'direct'); + }, 15000); + + it('keeps the background daemon alive after an oversized client frame', async () => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const owner = await worker('background'); + const paths = new DaemonPaths(dir, 'test'); + paths.writePidExclusive(owner.process.pid!); + owner.send('run'); + await owner.event('connecting'); + owner.send('connecting'); + await vi.waitFor(() => expect(paths.socketExists()).toBe(true)); + + const bad = createConnection(paths.socketPath); + bad.on('error', () => {}); + await once(bad, 'connect'); + const closed = new Promise<void>((resolve) => bad.once('close', () => resolve())); + bad.write(Buffer.alloc(1_100_000, 120)); + await closed; + + const healthy = new DaemonClient(paths.socketPath); + await expect(healthy.call('ping', {}, { timeoutMs: 1000 })).resolves.toBe('pong'); + healthy.close(); + expect(owner.process.exitCode).toBeNull(); + expect(owner.stderr).not.toMatch(/Unhandled|Message too large/); + await releaseConnected(owner, 'background'); + }, 15000); + + it('retains ownership after timeout until late connect and its destroy settle', async () => { + await new SessionStore(dir).save('test', 'synthetic-session'); + const owner = await worker('direct-timeout'); + owner.send('run'); + await owner.event('connecting'); + await owner.event('destroying-1'); + owner.send('destroying-1'); + await owner.event('timed-out'); + await vi.waitFor(() => expect(owner.stdout.endsWith('\n')).toBe(true)); + expect(JSON.parse(owner.stdout.trim())).toMatchObject({ ok: false, code: 'TIMEOUT' }); + await probeBlocked(); + + owner.send('connecting'); + await owner.event('connected'); + await owner.event('destroying-2'); + await probeBlocked(); + owner.send('destroying-2'); + await owner.event('destroyed-2'); + // The old process remains alive. Ownership is freed by successful cleanup, + // rather than the process exit handler or a stale-lock timeout. + await probeFree(); + expect(owner.events.some((event) => event.event === 'operation')).toBe(false); + expect(owner.stdout.trim().split('\n')).toHaveLength(1); + owner.send('finish'); + await owner.exit(); + }, 15000); + + it('keeps ownership after rejected cleanup until the owner process exits', async () => { + const owner = await worker('hold-reject'); + owner.send('run'); + await owner.event('cleanup-rejected'); + await probeBlocked(); + expect(owner.stderr).not.toMatch(/Unhandled|Synthetic cleanup failure/); + owner.send('finish'); + await owner.exit(); + await probeFree(); + }, 15000); +}); diff --git a/cli/tests/unit/session-store.test.ts b/cli/tests/unit/session-store.test.ts new file mode 100644 index 0000000..734d553 --- /dev/null +++ b/cli/tests/unit/session-store.test.ts @@ -0,0 +1,213 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { existsSync, rmSync, readFileSync, writeFileSync, chmodSync, statSync } from 'node:fs'; +import { SessionStore } from '../../src/lib/session-store.js'; + +const posix = process.platform !== 'win32'; + +function posixMode(p: string): number { + return statSync(p).mode & 0o777; +} + +describe('SessionStore', () => { + let tmpDir: string; + let store: SessionStore; + + beforeEach(() => { + tmpDir = join(tmpdir(), `tg-test-${randomUUID()}`); + store = new SessionStore(tmpDir); + }); + + afterEach(async () => { + // Small delay to let any proper-lockfile cleanup finish + await new Promise((r) => setTimeout(r, 50)); + try { + if (existsSync(tmpDir)) { + rmSync(tmpDir, { recursive: true, force: true }); + } + } catch { + // Ignore cleanup errors + } + }); + + it('creates sessions directory on construction', () => { + expect(existsSync(join(tmpDir, 'sessions'))).toBe(true); + }); + + it('save then load returns the session string', async () => { + await store.save('default', 'abc123'); + const loaded = await store.load('default'); + expect(loaded).toBe('abc123'); + }); + + it('load returns empty string for missing profile', async () => { + const loaded = await store.load('nonexistent'); + expect(loaded).toBe(''); + }); + + it('delete removes the session file', async () => { + await store.save('default', 'abc123'); + const filePath = join(tmpDir, 'sessions', 'default.session'); + expect(existsSync(filePath)).toBe(true); + + await store.delete('default'); + expect(existsSync(filePath)).toBe(false); + }); + + it('delete does not throw for missing profile', async () => { + await expect(store.delete('nonexistent')).resolves.not.toThrow(); + }); + + it('save overwrites existing session', async () => { + await store.save('default', 'first'); + await store.save('default', 'second'); + const loaded = await store.load('default'); + expect(loaded).toBe('second'); + }); + + it('sequential save/load with same profile does not throw', async () => { + await store.save('default', 'session1'); + const v1 = await store.load('default'); + await store.save('default', 'session2'); + const v2 = await store.load('default'); + expect(v1).toBe('session1'); + expect(v2).toBe('session2'); + }); + + it('filePath returns correct path', async () => { + const expectedPath = join(tmpDir, 'sessions', 'myprofile.session'); + await store.save('myprofile', 'data'); + expect(existsSync(expectedPath)).toBe(true); + expect(readFileSync(expectedPath, 'utf-8')).toBe('data'); + }); + + it('filePath sanitizes path traversal attempts', () => { + const safePath = store.filePath('../../etc/evil'); + expect(safePath).toBe(join(tmpDir, 'sessions', 'evil.session')); + expect(safePath).not.toContain('..'); + }); + + it('delete uses file locking (lockfile is created during delete)', async () => { + await store.save('locked', 'data'); + const file = store.filePath('locked'); + expect(existsSync(file)).toBe(true); + + // Delete should succeed with locking + await store.delete('locked'); + expect(existsSync(file)).toBe(false); + }); + + it('withLock returns empty string when session file does not exist', async () => { + const result = await store.withLock('missing', async (session) => { + return session; + }); + expect(result).toBe(''); + }); + + it('withLock provides session string and holds lock during callback', async () => { + await store.save('locked-profile', 'my-session'); + + const result = await store.withLock('locked-profile', async (session) => { + expect(session).toBe('my-session'); + // Session file should still be readable inside lock + const raw = readFileSync(store.filePath('locked-profile'), 'utf-8'); + expect(raw).toBe('my-session'); + return 'callback-result'; + }); + + expect(result).toBe('callback-result'); + }); + + it('withLock releases lock after callback completes', async () => { + await store.save('relock', 'data'); + + await store.withLock('relock', async () => { + // Lock is held here + }); + + // Should be able to acquire lock again + const loaded = await store.load('relock'); + expect(loaded).toBe('data'); + }); + + it('withLock releases lock even if callback throws', async () => { + await store.save('throw-profile', 'data'); + + await expect( + store.withLock('throw-profile', async () => { + throw new Error('callback failed'); + }), + ).rejects.toThrow('callback failed'); + + // Lock should be released — load should succeed + const loaded = await store.load('throw-profile'); + expect(loaded).toBe('data'); + }); + + it('deleteUnlocked removes file without acquiring lock', async () => { + await store.save('unlocked-del', 'data'); + const file = store.filePath('unlocked-del'); + expect(existsSync(file)).toBe(true); + + store.deleteUnlocked('unlocked-del'); + expect(existsSync(file)).toBe(false); + }); + + it('deleteUnlocked is a no-op for missing profile', () => { + // Should not throw + store.deleteUnlocked('nonexistent'); + }); + + it.skipIf(!posix)('sessions directory is created mode 0700', () => { + expect(posixMode(join(tmpDir, 'sessions'))).toBe(0o700); + }); + + it.skipIf(!posix)('tightens an existing 0755 sessions directory to 0700', () => { + const dir = join(tmpDir, 'sessions'); + chmodSync(dir, 0o755); + expect(posixMode(dir)).toBe(0o755); + + new SessionStore(tmpDir); + expect(posixMode(dir)).toBe(0o700); + }); + + it.skipIf(!posix)('save writes session files mode 0600', async () => { + await store.save('default', 'secret-session'); + expect(posixMode(store.filePath('default'))).toBe(0o600); + }); + + it.skipIf(!posix)('load chmods a legacy 0644 session file to 0600', async () => { + const file = store.filePath('legacy'); + writeFileSync(file, 'old-session', { encoding: 'utf-8', mode: 0o644 }); + chmodSync(file, 0o644); + expect(posixMode(file)).toBe(0o644); + + const loaded = await store.load('legacy'); + expect(loaded).toBe('old-session'); + expect(posixMode(file)).toBe(0o600); + }); + + it.skipIf(!posix)('save chmods a legacy 0644 session file to 0600', async () => { + const file = store.filePath('legacy-save'); + writeFileSync(file, 'old', { encoding: 'utf-8', mode: 0o644 }); + chmodSync(file, 0o644); + + await store.save('legacy-save', 'new-session'); + expect(posixMode(file)).toBe(0o600); + expect(readFileSync(file, 'utf-8')).toBe('new-session'); + }); + + it('deleteUnlocked works inside withLock without deadlock', async () => { + await store.save('nested-del', 'data'); + const file = store.filePath('nested-del'); + + await store.withLock('nested-del', async (session) => { + expect(session).toBe('data'); + // This would deadlock if it tried to acquire the lock + store.deleteUnlocked('nested-del'); + expect(existsSync(file)).toBe(false); + }); + }); +}); diff --git a/cli/tests/unit/session.test.ts b/cli/tests/unit/session.test.ts new file mode 100644 index 0000000..190ef0b --- /dev/null +++ b/cli/tests/unit/session.test.ts @@ -0,0 +1,467 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// Mock modules before imports +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn(), +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(), +})); + +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: vi.fn(), + outputError: vi.fn(), + logStatus: vi.fn(), +})); + +describe('session export', () => { + let exportAction: typeof import('../../src/commands/session/export.js').exportAction; + let SessionStore: any; + let createConfig: any; + let outputSuccess: any; + let outputError: any; + let stdoutSpy: ReturnType<typeof vi.spyOn>; + + beforeEach(async () => { + vi.resetModules(); + + // Re-mock after resetModules + vi.doMock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn(), + })); + vi.doMock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(), + })); + vi.doMock('../../src/lib/output.js', () => ({ + outputSuccess: vi.fn(), + outputError: vi.fn(), + logStatus: vi.fn(), + })); + + const sessionMod = await import('../../src/lib/session-store.js'); + const configMod = await import('../../src/lib/config.js'); + const outputMod = await import('../../src/lib/output.js'); + const exportMod = await import('../../src/commands/session/export.js'); + + SessionStore = sessionMod.SessionStore; + createConfig = configMod.createConfig; + outputSuccess = outputMod.outputSuccess; + outputError = outputMod.outputError; + exportAction = exportMod.exportAction; + + stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + }); + + afterEach(() => { + stdoutSpy?.mockRestore(); + vi.restoreAllMocks(); + }); + + it('outputs raw session string when json is default (not explicitly passed)', async () => { + const mockStore = { load: vi.fn().mockResolvedValue('abc123session') }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + get: vi.fn().mockReturnValue(undefined), + }; + (createConfig as any).mockReturnValue(mockConfig); + + // Simulate Commander context: json is true but source is 'default' (not explicitly passed) + const context = { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + }), + getOptionValueSourceWithGlobals: (name: string) => name === 'json' ? 'default' : undefined, + }; + + await exportAction.call(context as any); + + // Should output raw session string, NOT JSON envelope + expect(stdoutSpy).toHaveBeenCalledWith('abc123session\n'); + expect(outputSuccess).not.toHaveBeenCalled(); + }); + + it('outputs JSON envelope with metadata when --json explicitly passed', async () => { + const mockStore = { load: vi.fn().mockResolvedValue('abc123session') }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + get: vi.fn().mockReturnValue({ session: 'abc123session', phone: '+1234567890', created: '2026-01-01T00:00:00Z' }), + }; + (createConfig as any).mockReturnValue(mockConfig); + + // Simulate Commander context: json explicitly passed via CLI + const context = { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + }), + getOptionValueSourceWithGlobals: (name: string) => name === 'json' ? 'cli' : undefined, + }; + + await exportAction.call(context as any); + + expect(outputSuccess).toHaveBeenCalledWith({ + session: 'abc123session', + phone: '+1234567890', + created: '2026-01-01T00:00:00Z', + }); + }); + + it('refuses --daemon', async () => { + const mockStore = { load: vi.fn().mockResolvedValue('abc123session') }; + (SessionStore as any).mockImplementation(() => mockStore); + (createConfig as any).mockReturnValue({ path: '/tmp/tg-cli/config.json', get: vi.fn() }); + + const context = { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + daemon: true, + }), + getOptionValueSourceWithGlobals: () => 'default', + }; + + await exportAction.call(context as any); + expect(outputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + 'DAEMON_PROXY_UNAVAILABLE', + ); + }); + + it('uses outputSuccess for --toon instead of a raw session string', async () => { + const mockStore = { load: vi.fn().mockResolvedValue('abc123session') }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + get: vi.fn().mockReturnValue({ session: 'abc123session', phone: '+1', created: '2026-01-01T00:00:00Z' }), + }; + (createConfig as any).mockReturnValue(mockConfig); + + const context = { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + toon: true, + }), + getOptionValueSourceWithGlobals: () => 'default', + }; + + await exportAction.call(context as any); + + expect(outputSuccess).toHaveBeenCalledWith({ + session: 'abc123session', + phone: '+1', + created: '2026-01-01T00:00:00Z', + }); + expect(stdoutSpy).not.toHaveBeenCalledWith('abc123session\n'); + }); + + it('outputs error when no session exists', async () => { + const mockStore = { load: vi.fn().mockResolvedValue('') }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + get: vi.fn().mockReturnValue(undefined), + }; + (createConfig as any).mockReturnValue(mockConfig); + + const context = { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + }), + getOptionValueSourceWithGlobals: () => 'default', + }; + + await exportAction.call(context as any); + + expect(outputError).toHaveBeenCalledWith( + "No session found for profile 'default'", + 'NO_SESSION', + ); + }); +}); + +describe('session import', () => { + let importAction: typeof import('../../src/commands/session/import.js').importAction; + let SessionStore: any; + let createConfig: any; + let resolveCredentials: any; + let withClient: any; + let outputSuccess: any; + let outputError: any; + let logStatus: any; + + beforeEach(async () => { + vi.resetModules(); + + vi.doMock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn(), + })); + vi.doMock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(), + resolveCredentials: vi.fn(), + getCredentialsOrThrow: vi.fn().mockResolvedValue({ apiId: 123, apiHash: 'abc' }), + })); + vi.doMock('../../src/lib/output.js', () => ({ + outputSuccess: vi.fn(), + outputError: vi.fn(), + logStatus: vi.fn(), + })); + vi.doMock('../../src/lib/client.js', () => ({ + withClient: vi.fn(), + })); + vi.doMock('../../src/lib/errors.js', () => ({ + formatError: vi.fn((err: any) => ({ message: err?.message ?? String(err) })), + })); + + const sessionMod = await import('../../src/lib/session-store.js'); + const configMod = await import('../../src/lib/config.js'); + const outputMod = await import('../../src/lib/output.js'); + const clientMod = await import('../../src/lib/client.js'); + const importMod = await import('../../src/commands/session/import.js'); + + SessionStore = sessionMod.SessionStore; + createConfig = configMod.createConfig; + resolveCredentials = (configMod as any).resolveCredentials; + withClient = (clientMod as any).withClient; + outputSuccess = outputMod.outputSuccess; + outputError = outputMod.outputError; + logStatus = outputMod.logStatus; + importAction = importMod.importAction; + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + function makeContext(overrides: Record<string, any> = {}) { + return { + optsWithGlobals: () => ({ + json: true, + human: false, + verbose: false, + quiet: false, + profile: 'default', + skipVerify: true, + ...overrides, + }), + }; + } + + it('saves session string from argument to store (skip-verify)', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + + const context = makeContext(); + + await importAction.call(context as any, 'importedsession123'); + + expect(mockStore.saveUnlocked).toHaveBeenCalledWith('default', 'importedsession123'); + expect(mockConfig.set).toHaveBeenCalledWith( + 'profiles.default', + expect.objectContaining({ + created: expect.any(String), + }), + ); + }); + + it('outputs success envelope with verified field after import', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + + const context = makeContext(); + + await importAction.call(context as any, 'importedsession123'); + + expect(outputSuccess).toHaveBeenCalledWith({ + imported: true, + profile: 'default', + verified: false, + }); + }); + + it('validates session by default when credentials available', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + resolveCredentials.mockReturnValue({ apiId: 123, apiHash: 'abc' }); + withClient.mockImplementation(async (_opts: any, fn: any) => { + return fn({ checkAuthorization: vi.fn().mockResolvedValue(true) }); + }); + + const context = makeContext({ skipVerify: undefined }); + + await importAction.call(context as any, 'validsession'); + + expect(withClient).toHaveBeenCalledOnce(); + expect(mockStore.saveUnlocked).toHaveBeenCalledWith('default', 'validsession'); + expect(outputSuccess).toHaveBeenCalledWith({ + imported: true, + profile: 'default', + verified: true, + }); + }); + + it('rejects unauthorized session during verification', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + resolveCredentials.mockReturnValue({ apiId: 123, apiHash: 'abc' }); + withClient.mockImplementation(async (_opts: any, fn: any) => { + return fn({ checkAuthorization: vi.fn().mockResolvedValue(false) }); + }); + + const context = makeContext({ skipVerify: undefined }); + + await importAction.call(context as any, 'invalidsession'); + + expect(outputError).toHaveBeenCalledWith( + expect.stringContaining('not authorized'), + 'INVALID_SESSION', + ); + expect(mockStore.saveUnlocked).not.toHaveBeenCalled(); + }); + + it('rejects session when verification throws a connection error', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + resolveCredentials.mockReturnValue({ apiId: 123, apiHash: 'abc' }); + withClient.mockRejectedValue(new Error('Connection failed')); + + const context = makeContext({ skipVerify: undefined }); + + await importAction.call(context as any, 'badsession'); + + expect(outputError).toHaveBeenCalledWith( + expect.stringContaining('verification failed'), + 'VERIFY_FAILED', + ); + expect(mockStore.saveUnlocked).not.toHaveBeenCalled(); + }); + + it('skips verification with warning when no credentials configured and reports verified: false', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + + const mockConfig = { + path: '/tmp/tg-cli/config.json', + set: vi.fn(), + get: vi.fn(), + }; + (createConfig as any).mockReturnValue(mockConfig); + resolveCredentials.mockReturnValue(null); + + const context = makeContext({ skipVerify: undefined }); + + await importAction.call(context as any, 'somesession'); + + expect(logStatus).toHaveBeenCalledWith( + expect.stringContaining('Cannot verify session'), + false, + ); + expect(mockStore.saveUnlocked).toHaveBeenCalledWith('default', 'somesession'); + // Must NOT report verified: true when credentials were missing + expect(outputSuccess).toHaveBeenCalledWith({ + imported: true, + profile: 'default', + verified: false, + }); + }); + + it('refuses --daemon', async () => { + const mockStore = { saveUnlocked: vi.fn(), withLock: vi.fn(async (_profile, fn) => fn('')) }; + (SessionStore as any).mockImplementation(() => mockStore); + (createConfig as any).mockReturnValue({ path: '/tmp/tg-cli/config.json', set: vi.fn() }); + const context = makeContext({ daemon: true }); + await importAction.call(context as any, 'importedsession123'); + expect(outputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + 'DAEMON_PROXY_UNAVAILABLE', + ); + expect(mockStore.saveUnlocked).not.toHaveBeenCalled(); + }); + + it('verifies and saves using the profile preset while holding one lock', async () => { + let locked = false; + const mockStore = { + withLock: vi.fn(async (_profile, fn) => { + locked = true; + try { return await fn('previous-session'); } finally { locked = false; } + }), + saveUnlocked: vi.fn(() => { expect(locked).toBe(true); }), + }; + SessionStore.mockImplementation(() => mockStore); + const mockConfig = { path: '/tmp/tg-cli/config.json', get: vi.fn(key => key.endsWith('.client') ? 'desktop' : 'wss'), set: vi.fn() }; + createConfig.mockReturnValue(mockConfig); + resolveCredentials.mockReturnValue(null); + withClient.mockImplementation(async (_opts, fn) => { + expect(locked).toBe(true); + expect(_opts.transport).toBe('wss'); + return fn({ checkAuthorization: vi.fn().mockResolvedValue(true) }); + }); + await importAction.call(makeContext({ skipVerify: false }) as any, 'synthetic-import'); + const configModule = await import('../../src/lib/config.js'); + expect(configModule.getCredentialsOrThrow).toHaveBeenCalledWith(mockConfig, undefined, 'default'); + expect(mockStore.withLock).toHaveBeenCalledOnce(); + expect(mockStore.saveUnlocked).toHaveBeenCalledWith('default', 'synthetic-import'); + expect(mockConfig.set).toHaveBeenCalledWith('profiles.default', expect.objectContaining({ client: 'desktop', transport: 'wss' })); + expect(locked).toBe(false); + expect(outputSuccess).toHaveBeenCalledWith({ imported: true, profile: 'default', verified: true }); + }); +}); diff --git a/cli/tests/unit/teleproto-bridge.test.ts b/cli/tests/unit/teleproto-bridge.test.ts new file mode 100644 index 0000000..8f54ff5 --- /dev/null +++ b/cli/tests/unit/teleproto-bridge.test.ts @@ -0,0 +1,50 @@ +import { describe, it, expect, vi } from 'vitest'; +import { Api } from 'teleproto'; +import bigInt from 'big-integer'; +import { runBridge } from '../../src/commands/bridge/index.js'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +const user = new Api.User({id:bigInt('9007199254740993'),accessHash:bigInt(2),firstName:'Fixture'}); +const client = () => ({getEntity:vi.fn(async()=>user),getDialogs:vi.fn(async()=>[{entity:user}]),sendMessage:vi.fn(async()=>({id:7,entities:[new Api.MessageEntityBold({offset:0,length:4})]})),deleteMessages:vi.fn(async()=>[1])}); +describe('legacy bridge contracts using real Teleproto objects',()=>{ + it.each(['main','reserve'])('keeps HTML DTO and parse mode for %s',async account=>{ + const c=client();expect(await runBridge(c as any,'html',{account,chat:'fixture',text:'<b>Test</b>'})).toEqual({message_id:7,format:'html',entities:['MessageEntityBold']}); + expect(c.sendMessage).toHaveBeenCalledOnce();expect(c.sendMessage.mock.calls[0][1]).toMatchObject({parseMode:'html'}); + }); + it('validates schedules before invoking Telegram and preserves server scheduling',async()=>{ + const c=client();await expect(runBridge(c as any,'schedule',{account:'main',chat:'me',text:'fixture',when:'invalid'})).rejects.toThrow();expect(c.getEntity).not.toHaveBeenCalled(); + const when=new Date(Date.now()+60000).toISOString();const result:any=await runBridge(c as any,'schedule',{account:'main',chat:'me',text:'fixture',when}); + expect(result).toMatchObject({id:7,scheduled_for:when,account:'main'});expect(c.sendMessage.mock.calls[0][1].schedule).toBe(Math.floor(Date.parse(when)/1000)); + }); + it.each([true,false])('passes explicit delete revoke=%s',async revoke=>{ + const c=client();await runBridge(c as any,'delete',{account:'main',chat:'fixture',ids:'1,2',revoke});expect(c.deleteMessages).toHaveBeenCalledWith(user,[1,2],{revoke}); + }); + it('rejects absent revoke, invalid accounts and arbitrary operations without requests',async()=>{ + const c=client();for(const [op,p] of [['delete',{account:'main',chat:'me',ids:'1'}],['html',{account:'typo'}],['invoke',{account:'main'}]] as const)await expect(runBridge(c as any,op,p)).rejects.toThrow();expect(c.getEntity).not.toHaveBeenCalled(); + }); + it('never repeats a failed send or a missing send result',async()=>{ + for(const missing of [false,true]){ + const c=client();if(missing)c.sendMessage.mockResolvedValue(undefined as any);else c.sendMessage.mockRejectedValue(new Error('TIMEOUT')); + await expect(runBridge(c as any,'html',{account:'main',chat:'me',text:'fixture'})).rejects.toThrow();expect(c.sendMessage).toHaveBeenCalledOnce(); + } + }); + it('rejects ambiguous bare IDs rather than delivering to another peer kind',async()=>{ + const c=client();c.getDialogs.mockResolvedValue([{entity:user},{entity:user}]);await expect(runBridge(c as any,'send-dialog',{account:'main',chat:String(user.id),text:'fixture'})).rejects.toThrow('ambiguous');expect(c.sendMessage).not.toHaveBeenCalled(); + }); + it('preserves DM array fields and large IDs',async()=>{ + const c=client();c.getDialogs.mockResolvedValue([{entity:user,message:{date:100,message:'fixture'},unreadCount:2}] as any); + expect(await runBridge(c as any,'recent-dms',{account:'main',since:0})).toEqual([{user_id:'9007199254740993',username:null,first_name:'Fixture',last_name:null,last_msg_date:100,last_msg_preview:'fixture',unread_count:2,is_self:false}]); + }); + it('writes downloaded bytes and preserves the media DTO',async()=>{ + const dir=await mkdtemp(join(tmpdir(),'tg-bridge-')); + try {const path=join(dir,'media');const c={...client(),getMessages:vi.fn(async()=>[{media:{}}]),downloadMedia:vi.fn(async()=>Buffer.from('fixture'))}; + expect(await runBridge(c as any,'download-media',{account:'reserve',chat:'fixture',id:4,path})).toEqual({id:4,size:7,path});expect(await readFile(path,'utf8')).toBe('fixture'); + }finally{await rm(dir,{recursive:true,force:true});} + }); + it('refuses protected story media before download',async()=>{ + const story=new Api.StoryItem({id:1,date:100,expireDate:200,media:new Api.MessageMediaPhoto({photo:new Api.PhotoEmpty({id:bigInt(1)})}),noforwards:true}); + const c={getInputEntity:vi.fn(async()=>new Api.InputPeerSelf()),invoke:vi.fn(async()=>({stories:[story]})),downloadMedia:vi.fn()}; + await expect(runBridge(c as any,'stories',{account:'main',action:'download',chat:'fixture',story_id:1})).rejects.toThrow('MEDIA_PROTECTED');expect(c.downloadMedia).not.toHaveBeenCalled(); + }); +}); diff --git a/cli/tests/unit/teleproto-compat.test.ts b/cli/tests/unit/teleproto-compat.test.ts new file mode 100644 index 0000000..4aa36e0 --- /dev/null +++ b/cli/tests/unit/teleproto-compat.test.ts @@ -0,0 +1,34 @@ +import { describe, it, expect, vi } from 'vitest'; +import { Api, TelegramClient, sessions, errors } from 'teleproto'; +import { StringSession as GramSession } from 'gramjs-reference/sessions/index.js'; +import { AuthKey as GramKey } from 'gramjs-reference/crypto/AuthKey.js'; +import { Logger } from 'teleproto/extensions/Logger.js'; +import bigInt from 'big-integer'; +import { translateTelegramError } from '../../src/lib/errors.js'; +import { createRequestClient } from '../../src/lib/daemon/request-client.js'; + +describe('Teleproto offline compatibility against pinned GramJS reference',()=>{ + it.each([[2,'149.154.167.51',443],[4,'2001:db8::1',80]] as const)('round-trips a synthetic GramJS session for DC %s',async(dc,ip,port)=>{ + const old=new GramSession('');old.setDC(dc,ip,port);const key=new GramKey();await key.setKey(Buffer.alloc(256,7));old.setAuthKey(key); + const serialized=old.save();const next=new sessions.StringSession(serialized);await next.load(); + expect(next.dcId).toBe(dc);expect(next.serverAddress).toBe(ip);expect(next.port).toBe(port);expect(next.save()).toBe(serialized); + const back=new GramSession(next.save());await back.load();expect(back.authKey?.getKey()).toEqual(Buffer.alloc(256,7)); + }); + it('serializes layer-232 poll and forum requests with actual TL constructors',()=>{ + const poll=new Api.Poll({id:bigInt.zero,hash:bigInt.zero,question:new Api.TextWithEntities({text:'Question',entities:[]}),answers:[new Api.InputPollAnswer({text:new Api.TextWithEntities({text:'Answer',entities:[]})})],quiz:true}); + const media=new Api.InputMediaPoll({poll,correctAnswers:[0]});expect(media.getBytes().length).toBeGreaterThan(20); + const topics=new Api.messages.GetForumTopics({peer:new Api.InputPeerSelf(),offsetDate:0,offsetId:0,offsetTopic:0,limit:10});expect(topics.getBytes().length).toBeGreaterThan(12); + const personal=new Api.photos.UploadContactProfilePhoto({userId:new Api.InputUserSelf(),save:true,suggest:false,file:new Api.InputFile({id:bigInt(1),parts:1,name:'fixture.jpg',md5Checksum:''})});expect(personal.getBytes().length).toBeGreaterThan(20); + }); + it('preserves FloodWait mapping with actual Teleproto errors',()=>{ + const error=new errors.FloodWaitError({capture:30,request:new Api.help.GetConfig()});expect(translateTelegramError(error).code).toBe('FLOOD'); + }); + it('uses SDK reconnect catch-up without tying it to a cancelled command',async()=>{ + const client=new TelegramClient(new sessions.StringSession(''),1,'synthetic',{baseLogger:new Logger('none'),catchUp:true}); + const getMe=vi.spyOn(client,'getMe').mockResolvedValue(new Api.User({id:bigInt(1)})); + const catchUp=vi.spyOn((client as any).updateManager,'catchUp').mockResolvedValue(undefined); + const start=vi.spyOn((client as any)._updateLoop,'start').mockImplementation(()=>{}); + try {const controller=new AbortController();const view=createRequestClient(client,controller.signal);const recovering=(view.client as any)._handleReconnect();controller.abort();await recovering;await view.settled();expect(getMe).toHaveBeenCalledOnce();expect(catchUp).toHaveBeenCalledOnce();expect(start).toHaveBeenCalledOnce();} + finally{await client.destroy();} + }); +}); diff --git a/cli/tests/unit/toon-benchmark.test.ts b/cli/tests/unit/toon-benchmark.test.ts new file mode 100644 index 0000000..969deb5 --- /dev/null +++ b/cli/tests/unit/toon-benchmark.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { countTokens } from 'gpt-tokenizer'; +import { encodeToon } from '../../src/lib/toon.js'; + +const FIXTURE_DIR = join(import.meta.dirname, '..', 'fixtures', 'toon-benchmark'); + +function loadFixture(name: string): unknown { + return JSON.parse(readFileSync(join(FIXTURE_DIR, name), 'utf-8')); +} + +/** + * Measure token savings of TOON encoding vs JSON encoding. + * Returns the savings ratio (1 - toonTokens / jsonTokens). + */ +function measureSavings(name: string, data: unknown): number { + const envelope = { ok: true, data }; + const jsonStr = JSON.stringify(envelope); + const toonStr = encodeToon(envelope); + + const jsonTokens = countTokens(jsonStr); + const toonTokens = countTokens(toonStr); + const savings = 1 - toonTokens / jsonTokens; + + console.log( + `${name}: JSON=${jsonTokens} TOON=${toonTokens} savings=${(savings * 100).toFixed(1)}%`, + ); + + return savings; +} + +describe('TOON benchmark gate', () => { + it('achieves >= 20% token savings on 100+ messages', () => { + const fixture = loadFixture('messages-100.json'); + const savings = measureSavings('messages-100', fixture); + expect(savings).toBeGreaterThanOrEqual(0.20); + }); + + it('achieves >= 20% token savings on 50+ chat list items', () => { + const fixture = loadFixture('chat-list-50.json'); + const savings = measureSavings('chat-list-50', fixture); + expect(savings).toBeGreaterThanOrEqual(0.20); + }); + + it('achieves >= 20% token savings on 10 user profiles', () => { + const fixture = loadFixture('user-profiles-10.json'); + const savings = measureSavings('user-profiles-10', fixture); + expect(savings).toBeGreaterThanOrEqual(0.20); + }); + + it('achieves >= 20% token savings on 30 search results', () => { + const fixture = loadFixture('search-results-30.json'); + const savings = measureSavings('search-results-30', fixture); + expect(savings).toBeGreaterThanOrEqual(0.20); + }); + + it('achieves >= 15% token savings on mixed data shapes', () => { + const fixture = loadFixture('mixed-shapes.json'); + const savings = measureSavings('mixed-shapes', fixture); + expect(savings).toBeGreaterThanOrEqual(0.15); + }); +}); diff --git a/cli/tests/unit/toon.test.ts b/cli/tests/unit/toon.test.ts new file mode 100644 index 0000000..4618dd7 --- /dev/null +++ b/cli/tests/unit/toon.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect } from 'vitest'; +import { encodeToon } from '../../src/lib/toon.js'; + +describe('encodeToon', () => { + it('returns a string, not JSON-parseable as identical object', () => { + const input = { ok: true, data: { value: 42 } }; + const result = encodeToon(input); + expect(typeof result).toBe('string'); + // TOON is not valid JSON -- parsing it should not yield the identical object + try { + const parsed = JSON.parse(result); + expect(parsed).not.toEqual(input); + } catch { + // Expected: TOON is not valid JSON + } + }); + + it('output contains "ok: true" for success envelope', () => { + const result = encodeToon({ ok: true, data: { messages: [{ id: 1, text: 'hi' }] } }); + expect(result).toContain('ok: true'); + }); + + it('array data uses tabular format with tab delimiters', () => { + const result = encodeToon({ + ok: true, + data: { messages: [{ id: 1, text: 'hi' }, { id: 2, text: 'bye' }] }, + }); + // Tab characters should be present in tabular rows + expect(result).toContain('\t'); + }); + + it('handles null values without error', () => { + const result = encodeToon({ + ok: true, + data: { messages: [{ id: 1, text: null, mediaType: null }] }, + }); + expect(typeof result).toBe('string'); + expect(result).toContain('ok: true'); + // null values should be encoded (not omitted or throwing) + expect(result).toContain('null'); + }); + + it('handles empty arrays without error', () => { + const result = encodeToon({ ok: true, data: { messages: [], total: 0 } }); + expect(typeof result).toBe('string'); + expect(result).toContain('ok: true'); + }); + + it('error envelope encodes correctly (ok: false, error present)', () => { + const result = encodeToon({ ok: false, error: 'Not found', code: 'NOT_FOUND' }); + expect(result).toContain('ok: false'); + expect(result).toContain('Not found'); + expect(result).toContain('NOT_FOUND'); + }); +}); diff --git a/cli/tests/unit/topic-filter.test.ts b/cli/tests/unit/topic-filter.test.ts new file mode 100644 index 0000000..430dd23 --- /dev/null +++ b/cli/tests/unit/topic-filter.test.ts @@ -0,0 +1,47 @@ +import { describe, it, expect } from 'vitest'; +import { messageMatchesTopic } from '../../src/lib/daemon/topic-filter.js'; + +describe('messageMatchesTopic', () => { + it('always passes the topic-root message', () => { + expect(messageMatchesTopic({ id: 9 }, 9)).toBe(true); + expect(messageMatchesTopic({ id: 1 }, 1)).toBe(true); + }); + + it('passes General unthreaded and General replies (no forumTopic flag)', () => { + expect(messageMatchesTopic({ id: 8, message: 'hi' }, 1)).toBe(true); + expect(messageMatchesTopic({ + id: 12, + replyTo: { replyToMsgId: 8 }, + }, 1)).toBe(true); + }); + + it('drops named-topic messages when watching General', () => { + expect(messageMatchesTopic({ + id: 20, + replyTo: { forumTopic: true, replyToTopId: 9, replyToMsgId: 15 }, + }, 1)).toBe(false); + }); + + it('passes named-topic messages and nested replies for that topic', () => { + expect(messageMatchesTopic({ + id: 20, + replyTo: { forumTopic: true, replyToTopId: 9, replyToMsgId: 15 }, + }, 9)).toBe(true); + expect(messageMatchesTopic({ + id: 21, + replyTo: { forumTopic: true, replyToMsgId: 9 }, + }, 9)).toBe(true); + }); + + it('drops General and other topics when watching a named topic', () => { + expect(messageMatchesTopic({ id: 8 }, 9)).toBe(false); + expect(messageMatchesTopic({ + id: 12, + replyTo: { replyToMsgId: 8 }, + }, 9)).toBe(false); + expect(messageMatchesTopic({ + id: 30, + replyTo: { forumTopic: true, replyToTopId: 4 }, + }, 9)).toBe(false); + }); +}); diff --git a/cli/tests/unit/transport-diagnostics.test.ts b/cli/tests/unit/transport-diagnostics.test.ts new file mode 100644 index 0000000..c89fb1c --- /dev/null +++ b/cli/tests/unit/transport-diagnostics.test.ts @@ -0,0 +1,138 @@ +import 'teleproto'; +import { createServer, type Socket } from 'node:net'; +import { once } from 'node:events'; +import { inspect } from 'node:util'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { PromisedNetSockets } from 'teleproto/extensions/PromisedNetSockets.js'; +import { FullPacketCodec } from 'teleproto/network/connection/TCPFull.js'; +import { InvalidBufferError, InvalidChecksumError, TypeNotFoundError, SecurityError } from 'teleproto/errors/Common.js'; +import { describeTransportError, DiagnosticTCPFull } from '../../src/lib/transport-diagnostics.js'; +import { createGramjsLogger } from '../../src/lib/gramjs-logger.js'; +import { createClientForAuth } from '../../src/lib/client.js'; +import { connectOrThrow } from '../../src/lib/connect.js'; +import { setQuietMode, setVerboseMode } from '../../src/lib/cli-mode.js'; +import { MTProtoSender } from 'teleproto/network/MTProtoSender.js'; + +afterEach(() => { + setQuietMode(false); + setVerboseMode(false); + vi.restoreAllMocks(); +}); + +describe('safe transport diagnostics', () => { + it.each(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'ENETUNREACH'])('retains %s without error contents', code => { + const error = Object.assign(new Error('synthetic-secret'), { code, payload: 'synthetic-session' }); + expect(describeTransportError(error)).toBe(code); + }); + + it('classifies SDK errors without exposing their payloads or messages', () => { + const rateLimit = Buffer.alloc(4); + rateLimit.writeInt32LE(-429); + expect(describeTransportError(new InvalidBufferError(rateLimit))).toBe('INVALID_BUFFER (code=429)'); + expect(describeTransportError(new InvalidBufferError(Buffer.from('synthetic-secret')))).toBe('INVALID_BUFFER'); + expect(describeTransportError(new InvalidChecksumError(1, 2))).toBe('INVALID_CHECKSUM'); + expect(describeTransportError(new TypeNotFoundError(123, Buffer.from('synthetic-secret')))).toBe('UNKNOWN_CONSTRUCTOR'); + expect(describeTransportError(new SecurityError('synthetic-secret'))).toBe('SECURITY_CHECK_FAILED'); + expect(describeTransportError(new Error('NetSocket was closed'))).toBe('CONNECTION_CLOSED'); + expect(describeTransportError(new Error('TIMEOUT'))).toBe('TIMEOUT'); + }); + + it('does not evaluate getters, custom inspection or arbitrary strings', () => { + const getter = vi.fn(() => { throw new Error('synthetic-secret'); }); + const error = Object.defineProperties({}, { + code: { get: getter }, message: { get: getter }, [inspect.custom]: { value: getter }, + }); + expect(describeTransportError(error)).toBe('UNKNOWN_ERROR'); + expect(describeTransportError('synthetic-secret')).toBe('UNKNOWN_ERROR'); + expect(describeTransportError(new Error('synthetic-secret'))).toBe('UNKNOWN_ERROR'); + expect(getter).not.toHaveBeenCalled(); + }); + + it('handles hostile proxies without interrupting cleanup', () => { + const error = new Proxy({}, { getPrototypeOf() { throw new Error('synthetic-secret'); } }); + expect(describeTransportError(error)).toBe('UNKNOWN_ERROR'); + }); + + it.each([false, true])('preserves real SDK top-level diagnostics (quiet=%s)', async quiet => { + setQuietMode(quiet); + setVerboseMode(true); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const client = await createClientForAuth(1, 'synthetic-secret'); + try { + await client._errorHandler!(Object.assign(new Error('synthetic-secret'), { code: 'ECONNRESET' })); + } finally { await client.destroy(); } + const logged = stderr.mock.calls.flat().join(''); + expect(stdout).not.toHaveBeenCalled(); + expect(logged).not.toContain('synthetic-'); + if (quiet) expect(logged).toBe(''); + else expect(logged).toContain('Telegram client failed: ECONNRESET'); + }); +}); + +describe('real TCPFull receive loop against a local server', () => { + it.each([ + { failure: 'rate-limit', expected: 'INVALID_BUFFER (code=429)', quiet: false }, + { failure: 'checksum', expected: 'INVALID_CHECKSUM', quiet: false }, + { failure: 'eof', expected: 'CONNECTION_CLOSED', quiet: false }, + { failure: 'reset', expected: 'ECONNRESET', quiet: false }, + { failure: 'rate-limit', expected: '', quiet: true }, + ])('keeps the cause before gramjs discards it: $failure, quiet=$quiet', async ({ failure, expected, quiet }) => { + setQuietMode(quiet); + const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true); + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true); + const sockets = new Set<Socket>(); + const server = createServer(socket => { + sockets.add(socket); + socket.on('error', () => {}); + socket.once('data', () => { + if (failure === 'reset') { socket.resetAndDestroy(); return; } + if (failure === 'eof') { socket.end(); return; } + if (failure === 'rate-limit') { + const frame = Buffer.alloc(12); + for (const offset of [0, 4, 8]) frame.writeInt32LE(-429, offset); + socket.end(frame); + } else { + const frame = new FullPacketCodec(undefined as any).encodePacket(Buffer.from('synthetic-secret')); + frame[frame.length - 1] ^= 0xff; + socket.end(frame); + } + }); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + const port = (server.address() as { port: number }).port; + const connection = new DiagnosticTCPFull({ + ip: '127.0.0.1', port, dcId: 4, loggers: createGramjsLogger(), + socket: PromisedNetSockets, testServers: false, + }); + try { + await connection.connect(); + await connection.send(Buffer.alloc(20)); + await expect(connection.recv()).rejects.toThrow(); + const logged = stderr.mock.calls.flat().join(''); + expect(stdout).not.toHaveBeenCalled(); + expect(logged).not.toContain('synthetic-'); + if (quiet) expect(logged).toBe(''); + else expect(logged).toContain(`Transport receive failed: ${expected}`); + } finally { + await connection.disconnect(); + for (const socket of sockets) socket.destroy(); + await new Promise<void>(resolve => server.close(() => resolve())); + } + }); +}); + +describe('failed connection retries', () => { + it('detects the real SDK false return and allows destroy to clean up its loop', async () => { + vi.spyOn(MTProtoSender.prototype, 'connect').mockRejectedValue(new Error('synthetic connection failure')); + const client = await createClientForAuth(1, 'synthetic-secret'); + try { + await expect(connectOrThrow(client)).rejects.toThrow('synthetic connection failure'); + } finally { await client.destroy(); } + }); + + it('accepts false for a client that is already connected', async () => { + await expect(connectOrThrow({ connect: async () => false, connected: true } as any)).resolves.toBeUndefined(); + }); +}); diff --git a/cli/tests/unit/user-block.test.ts b/cli/tests/unit/user-block.test.ts new file mode 100644 index 0000000..dccf213 --- /dev/null +++ b/cli/tests/unit/user-block.test.ts @@ -0,0 +1,213 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(true), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + Block: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { userBlockAction } from '../../src/commands/user/block.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('userBlockAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(true); + }); + + it('blocks a user successfully', async () => { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + username: 'alice', + }); + + mockResolveEntity.mockResolvedValueOnce(user); + + const ctx = createMockCommandContext(); + await userBlockAction.call(ctx as any, '@alice'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledWith({ + userId: '100', + username: 'alice', + firstName: 'Alice', + action: 'blocked', + }); + }); + + it('errors with NOT_A_USER for channel entities', async () => { + const channel = new MockChannel({}); + Object.assign(channel, { id: BigInt(300) }); + + mockResolveEntity.mockResolvedValueOnce(channel); + + const ctx = createMockCommandContext(); + await userBlockAction.call(ctx as any, '@somechannel'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not a user: this is a group/channel', + 'NOT_A_USER', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('errors with NOT_A_USER for chat entities', async () => { + const chat = new MockChat({}); + Object.assign(chat, { id: BigInt(400) }); + + mockResolveEntity.mockResolvedValueOnce(chat); + + const ctx = createMockCommandContext(); + await userBlockAction.call(ctx as any, 'somechat'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not a user: this is a group/channel', + 'NOT_A_USER', + ); + }); + + it('translates RPCError via translateTelegramError', async () => { + const user = new MockUser({}); + Object.assign(user, { id: BigInt(100), firstName: 'Alice', username: 'alice' }); + mockResolveEntity.mockResolvedValueOnce(user); + + mockInvoke.mockRejectedValueOnce({ errorMessage: 'USER_BOT_INVALID' }); + + const ctx = createMockCommandContext(); + await userBlockAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Cannot block this bot', + 'USER_BOT_INVALID', + ); + }); + + it('handles idempotent blocking (already blocked succeeds)', async () => { + const user = new MockUser({}); + Object.assign(user, { id: BigInt(100), firstName: 'Alice', username: 'alice' }); + mockResolveEntity.mockResolvedValueOnce(user); + // Telegram returns true even if already blocked + mockInvoke.mockResolvedValueOnce(true); + + const ctx = createMockCommandContext(); + await userBlockAction.call(ctx as any, '@alice'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + userId: '100', + username: 'alice', + firstName: 'Alice', + action: 'blocked', + }); + }); +}); diff --git a/cli/tests/unit/user-blocked.test.ts b/cli/tests/unit/user-blocked.test.ts new file mode 100644 index 0000000..ec1a5dd --- /dev/null +++ b/cli/tests/unit/user-blocked.test.ts @@ -0,0 +1,210 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +// Mock output +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { + mockConnect, + mockDestroy, + mockInvoke, +} = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(undefined), +})); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + contacts: { + GetBlocked: vi.fn().mockImplementation((opts: any) => ({ ...opts, _type: 'GetBlocked' })), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock serialize (for bigIntToString) +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: bigint) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +// Import after mocks +import { userBlockedAction } from '../../src/commands/user/blocked.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + limit: '50', + offset: '0', + ...opts, + })), + }; +} + +describe('userBlockedAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('returns blocked users with correct structure', async () => { + mockInvoke.mockResolvedValueOnce({ + blocked: [ + { peerId: { userId: BigInt(100) } }, + { peerId: { userId: BigInt(200) } }, + ], + users: [ + { id: BigInt(100), firstName: 'Alice', lastName: 'Smith', username: 'alice', bot: false, className: 'User' }, + { id: BigInt(200), firstName: 'Bob', lastName: null, username: null, bot: true, className: 'User' }, + ], + count: 5, + className: 'contacts.BlockedSlice', + }); + + const ctx = createMockCommandContext(); + await userBlockedAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + users: [ + { id: '100', firstName: 'Alice', lastName: 'Smith', username: 'alice', isBot: false }, + { id: '200', firstName: 'Bob', lastName: null, username: null, isBot: true }, + ], + total: 5, + }); + }); + + it('returns empty list for no blocked users', async () => { + mockInvoke.mockResolvedValueOnce({ + blocked: [], + users: [], + className: 'contacts.Blocked', + }); + + const ctx = createMockCommandContext(); + await userBlockedAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + users: [], + total: 0, + }); + }); + + it('uses .count for BlockedSlice response type', async () => { + mockInvoke.mockResolvedValueOnce({ + blocked: [ + { peerId: { userId: BigInt(300) } }, + ], + users: [ + { id: BigInt(300), firstName: 'Carol', lastName: null, username: 'carol', bot: false, className: 'User' }, + ], + count: 42, + className: 'contacts.BlockedSlice', + }); + + const ctx = createMockCommandContext({ limit: '10', offset: '5' }); + await userBlockedAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + users: [ + { id: '300', firstName: 'Carol', lastName: null, username: 'carol', isBot: false }, + ], + total: 42, + }); + }); + + it('uses blocked.length for Blocked response type (no .count)', async () => { + mockInvoke.mockResolvedValueOnce({ + blocked: [ + { peerId: { userId: BigInt(400) } }, + { peerId: { userId: BigInt(500) } }, + ], + users: [ + { id: BigInt(400), firstName: 'Dave', lastName: null, username: null, bot: false, className: 'User' }, + { id: BigInt(500), firstName: 'Eve', lastName: null, username: 'eve', bot: false, className: 'User' }, + ], + className: 'contacts.Blocked', + }); + + const ctx = createMockCommandContext(); + await userBlockedAction.call(ctx as any); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + users: [ + { id: '400', firstName: 'Dave', lastName: null, username: null, isBot: false }, + { id: '500', firstName: 'Eve', lastName: null, username: 'eve', isBot: false }, + ], + total: 2, + }); + }); + + it('translates RPCError via translateTelegramError', async () => { + mockInvoke.mockRejectedValueOnce({ errorMessage: 'PEER_ID_INVALID' }); + + const ctx = createMockCommandContext(); + await userBlockedAction.call(ctx as any); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Peer not found', + 'PEER_ID_INVALID', + ); + }); +}); diff --git a/cli/tests/unit/user-profile.test.ts b/cli/tests/unit/user-profile.test.ts new file mode 100644 index 0000000..717e724 --- /dev/null +++ b/cli/tests/unit/user-profile.test.ts @@ -0,0 +1,475 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { + Object.assign(this, data); + } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { + Object.assign(this, data); + } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(undefined), + MockUser, + MockChannel, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + UserStatusOnline: class { className = 'UserStatusOnline'; }, + UserStatusOffline: class { + className = 'UserStatusOffline'; + wasOnline: number; + constructor(data: any) { this.wasOnline = data?.wasOnline ?? 0; } + }, + UserStatusRecently: class { className = 'UserStatusRecently'; }, + UserStatusLastWeek: class { className = 'UserStatusLastWeek'; }, + UserStatusLastMonth: class { className = 'UserStatusLastMonth'; }, + UserStatusEmpty: class { className = 'UserStatusEmpty'; }, + users: { + GetFullUser: vi.fn(), + }, + photos: { + GetUserPhotos: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { TgError } from '../../src/lib/errors.js'; + +import { userProfileAction } from '../../src/commands/user/profile.js'; + +// Create a mock Command context +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +// Helper to create a mock user entity returned by resolveEntity +function createMockUserEntity(overrides: Record<string, any> = {}) { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + lastName: 'Smith', + username: 'alice', + phone: '+1234567890', + bot: false, + status: { className: 'UserStatusRecently' }, + premium: false, + verified: false, + mutualContact: true, + langCode: 'en', + photo: null, + ...overrides, + }); + return user; +} + +// Helper to create a mock GetFullUser response +function createMockFullUserResult(user: any, overrides: Record<string, any> = {}) { + return { + fullUser: { + about: 'Hello world', + blocked: false, + commonChatsCount: 3, + botInfo: null, + ...overrides, + }, + users: [user], + }; +} + +describe('userProfileAction', () => { + const originalExitCode = process.exitCode; + afterEach(() => { process.exitCode = originalExitCode; }); + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('fetches a single user profile successfully', async () => { + const user = createMockUserEntity(); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 5, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.profiles).toHaveLength(1); + expect(result.notFound).toEqual([]); + + const profile = result.profiles[0]; + expect(profile.id).toBe('100'); + expect(profile.firstName).toBe('Alice'); + expect(profile.lastName).toBe('Smith'); + expect(profile.username).toBe('alice'); + expect(profile.phone).toBe('+1234567890'); + expect(profile.bio).toBe('Hello world'); + expect(profile.photoCount).toBe(5); + expect(profile.isBot).toBe(false); + expect(profile.blocked).toBe(false); + expect(profile.commonChatsCount).toBe(3); + expect(profile.premium).toBe(false); + expect(profile.verified).toBe(false); + expect(profile.mutualContact).toBe(true); + expect(profile.langCode).toBe('en'); + }); + + it('handles comma-separated multi-user input', async () => { + const user1 = createMockUserEntity({ id: BigInt(100), firstName: 'Alice', username: 'alice' }); + const user2 = createMockUserEntity({ id: BigInt(200), firstName: 'Bob', username: 'bob' }); + + mockResolveEntity.mockResolvedValueOnce(user1); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user1)); + mockInvoke.mockResolvedValueOnce({ count: 2, photos: [] }); + + mockResolveEntity.mockResolvedValueOnce(user2); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user2, { about: 'Hi' })); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice,@bob'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.profiles).toHaveLength(2); + expect(result.notFound).toEqual([]); + }); + + it('adds unresolvable users to notFound array', async () => { + const user1 = createMockUserEntity(); + mockResolveEntity.mockResolvedValueOnce(user1); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user1)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + mockResolveEntity.mockRejectedValueOnce(new TgError('Peer not found', 'PEER_NOT_FOUND')); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice,@nonexistent'); + + expect(mockOutputSuccess).toHaveBeenCalledOnce(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.profiles).toHaveLength(1); + expect(result.notFound).toEqual(['@nonexistent']); + }); + + it('rejects non-User entities (channels) as notFound', async () => { + const channel = new MockChannel({}); + Object.assign(channel, { id: BigInt(300) }); + + mockResolveEntity.mockResolvedValueOnce(channel); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@somechannel'); + + expect(mockOutputSuccess).toHaveBeenCalledWith(expect.objectContaining({ profiles: [], partial: true, errors: expect.any(Array) })); + expect(process.exitCode).toBe(1); + }); + + it('outputs NO_USERS_FOUND error when all inputs fail', async () => { + mockResolveEntity.mockRejectedValueOnce(new TgError('Peer not found', 'PEER_NOT_FOUND')); + mockResolveEntity.mockRejectedValueOnce(new TgError('Peer not found', 'PEER_NOT_FOUND')); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@bad1,@bad2'); + + expect(mockOutputSuccess).toHaveBeenCalledWith(expect.objectContaining({ profiles: [], partial: true, errors: expect.any(Array) })); + expect(process.exitCode).toBe(1); + expect(mockOutputError).not.toHaveBeenCalled(); + }); + + it('maps UserStatusOnline to "online"', async () => { + const user = createMockUserEntity({ status: { className: 'UserStatusOnline' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe('online'); + }); + + it('maps UserStatusOffline to ISO timestamp', async () => { + const wasOnline = Math.floor(Date.now() / 1000); + const user = createMockUserEntity({ status: { className: 'UserStatusOffline', wasOnline } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe(new Date(wasOnline * 1000).toISOString()); + }); + + it('maps UserStatusRecently to "recently"', async () => { + const user = createMockUserEntity({ status: { className: 'UserStatusRecently' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe('recently'); + }); + + it('maps UserStatusLastWeek to "within_week"', async () => { + const user = createMockUserEntity({ status: { className: 'UserStatusLastWeek' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe('within_week'); + }); + + it('maps UserStatusLastMonth to "within_month"', async () => { + const user = createMockUserEntity({ status: { className: 'UserStatusLastMonth' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe('within_month'); + }); + + it('maps UserStatusEmpty to "long_time_ago"', async () => { + const user = createMockUserEntity({ status: { className: 'UserStatusEmpty' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBe('long_time_ago'); + }); + + it('sets lastSeen to null for bots', async () => { + const user = createMockUserEntity({ + bot: true, + status: { className: 'UserStatusRecently' }, + }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user, { + botInfo: { placeholder: 'Search...', inlinePlaceholder: 'Search...' }, + })); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@botuser'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.lastSeen).toBeNull(); + expect(profile.isBot).toBe(true); + }); + + it('includes bot-specific fields when isBot is true', async () => { + const user = createMockUserEntity({ + bot: true, + botInlinePlaceholder: 'Search...', + }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user, { + botInfo: { placeholder: 'Type to search' }, + })); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@botuser'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.isBot).toBe(true); + expect(profile.botInlinePlaceholder).toBe('Search...'); + expect(profile.supportsInline).toBe(true); + }); + + it('does not include bot fields when isBot is false', async () => { + const user = createMockUserEntity({ bot: false }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.isBot).toBe(false); + expect(profile).not.toHaveProperty('botInlinePlaceholder'); + expect(profile).not.toHaveProperty('supportsInline'); + }); + + it('sets phone to "[restricted]" for non-bot users with missing phone', async () => { + const user = createMockUserEntity({ phone: undefined, bot: false }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.phone).toBe('[restricted]'); + }); + + it('sets phone to null for bots with missing phone', async () => { + const user = createMockUserEntity({ phone: undefined, bot: true }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user, { botInfo: null })); + mockInvoke.mockResolvedValueOnce({ count: 0, photos: [] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@botuser'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.phone).toBeNull(); + }); + + it('falls back to photo count from photos array length', async () => { + const user = createMockUserEntity(); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + // No .count property, but has photos array + mockInvoke.mockResolvedValueOnce({ photos: [{}, {}, {}] }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.photoCount).toBe(3); + }); + + it('handles photo count error gracefully', async () => { + const user = createMockUserEntity({ photo: { className: 'UserProfilePhoto' } }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(createMockFullUserResult(user)); + // GetUserPhotos throws + mockInvoke.mockRejectedValueOnce(new Error('Photos API error')); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + const profile = mockOutputSuccess.mock.calls[0][0].profiles[0]; + expect(profile.photoCount).toBeNull(); + const result = mockOutputSuccess.mock.calls[0][0]; + expect(result.partial).toBe(true); + expect(result.errors).toEqual([{ input: '@alice', error: 'Could not fetch profile photos: Photos API error', code: 'UNKNOWN_ERROR' }]); + expect(process.exitCode).toBe(1); + }); + + it('handles NOT_AUTHENTICATED when no session', async () => { + mockStoreWithLock.mockImplementationOnce(async (_profile: string, fn: (s: string | null) => Promise<any>) => { + return fn(null as any); + }); + + const ctx = createMockCommandContext(); + await userProfileAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not logged in. Run: tg auth login', + 'NOT_AUTHENTICATED', + ); + }); +}); diff --git a/cli/tests/unit/user-unblock.test.ts b/cli/tests/unit/user-unblock.test.ts new file mode 100644 index 0000000..fee5338 --- /dev/null +++ b/cli/tests/unit/user-unblock.test.ts @@ -0,0 +1,197 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +// ---- Mocks ---- + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), +})); + +// Hoisted mock state for telegram client and entity classes +const { mockConnect, mockDestroy, mockInvoke, MockUser, MockChannel, MockChat } = vi.hoisted(() => { + class MockUser { + className = 'User'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChannel { + className = 'Channel'; + constructor(data: any) { Object.assign(this, data); } + } + class MockChat { + className = 'Chat'; + constructor(data: any) { Object.assign(this, data); } + } + return { + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), + mockInvoke: vi.fn().mockResolvedValue(true), + MockUser, + MockChannel, + MockChat, + }; +}); + +const mockClientInstance = { + connect: mockConnect, + destroy: mockDestroy, + invoke: mockInvoke, +}; + +vi.mock('teleproto', () => ({ + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { + StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })), + }, + Api: { + User: MockUser, + Channel: MockChannel, + Chat: MockChat, + contacts: { + Unblock: vi.fn(), + }, + }, +})); + +// Mock config +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ + get: vi.fn(), + set: vi.fn(), + path: '/tmp/mock-config.json', + })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +// Mock session store +const mockStoreWithLock = vi.fn().mockImplementation(async (_profile: string, fn: (s: string) => Promise<any>) => { + return fn('test-session'); +}); + +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + filePath: (p: string) => `/mock/sessions/${p}.session`, + })), +})); + +// Mock client module +vi.mock('../../src/lib/client.js', () => ({ + withClient: vi.fn(async (_opts: any, fn: any) => fn(mockClientInstance)), +})); + +// Mock peer resolution +const mockResolveEntity = vi.fn(); +vi.mock('../../src/lib/peer.js', () => ({ + resolveEntity: (...args: any[]) => mockResolveEntity(...args), +})); + +// Mock serialize +vi.mock('../../src/lib/serialize.js', () => ({ + bigIntToString: (v: any) => String(v), +})); + +// Mock errors (use actual translateTelegramError) +vi.mock('../../src/lib/errors.js', async (importOriginal) => { + const actual = await importOriginal<typeof import('../../src/lib/errors.js')>(); + return { + ...actual, + translateTelegramError: actual.translateTelegramError, + }; +}); + +import { userUnblockAction } from '../../src/commands/user/unblock.js'; + +function createMockCommandContext(opts: Record<string, any> = {}) { + return { + optsWithGlobals: vi.fn(() => ({ + profile: 'default', + quiet: false, + config: undefined, + json: true, + human: false, + verbose: false, + ...opts, + })), + }; +} + +describe('userUnblockAction', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockInvoke.mockResolvedValue(true); + }); + + it('unblocks a user successfully', async () => { + const user = new MockUser({}); + Object.assign(user, { + id: BigInt(100), + firstName: 'Alice', + username: 'alice', + }); + + mockResolveEntity.mockResolvedValueOnce(user); + + const ctx = createMockCommandContext(); + await userUnblockAction.call(ctx as any, '@alice'); + + expect(mockInvoke).toHaveBeenCalledOnce(); + expect(mockOutputSuccess).toHaveBeenCalledWith({ + userId: '100', + username: 'alice', + firstName: 'Alice', + action: 'unblocked', + }); + }); + + it('errors with NOT_A_USER for channel entities', async () => { + const channel = new MockChannel({}); + Object.assign(channel, { id: BigInt(300) }); + + mockResolveEntity.mockResolvedValueOnce(channel); + + const ctx = createMockCommandContext(); + await userUnblockAction.call(ctx as any, '@somechannel'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'Not a user: this is a group/channel', + 'NOT_A_USER', + ); + expect(mockInvoke).not.toHaveBeenCalled(); + }); + + it('translates RPCError via translateTelegramError', async () => { + const user = new MockUser({}); + Object.assign(user, { id: BigInt(100), firstName: 'Alice', username: 'alice' }); + mockResolveEntity.mockResolvedValueOnce(user); + + mockInvoke.mockRejectedValueOnce({ errorMessage: 'INPUT_USER_DEACTIVATED' }); + + const ctx = createMockCommandContext(); + await userUnblockAction.call(ctx as any, '@alice'); + + expect(mockOutputError).toHaveBeenCalledWith( + 'User account deleted', + 'INPUT_USER_DEACTIVATED', + ); + }); + + it('handles idempotent unblocking (already unblocked succeeds)', async () => { + const user = new MockUser({}); + Object.assign(user, { id: BigInt(100), firstName: 'Bob', username: 'bob' }); + mockResolveEntity.mockResolvedValueOnce(user); + mockInvoke.mockResolvedValueOnce(true); + + const ctx = createMockCommandContext(); + await userUnblockAction.call(ctx as any, '@bob'); + + expect(mockOutputSuccess).toHaveBeenCalledWith({ + userId: '100', + username: 'bob', + firstName: 'Bob', + action: 'unblocked', + }); + }); +}); diff --git a/cli/tests/unit/validate.test.ts b/cli/tests/unit/validate.test.ts new file mode 100644 index 0000000..d0b09b3 --- /dev/null +++ b/cli/tests/unit/validate.test.ts @@ -0,0 +1,175 @@ +import { describe, it, expect } from 'vitest'; +import { validateProfile, validatePagination, parseMessageIds, parseMessageId, parseIsoDate, parseTopicId, parseIntegerOption, MAX_TL_INT } from '../../src/lib/validate.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +describe('validateProfile', () => { + it('accepts valid profile names', () => { + expect(validateProfile('default')).toBe('default'); + expect(validateProfile('my-profile_01')).toBe('my-profile_01'); + }); + + it('rejects empty string', () => { + expect(() => validateProfile('')).toThrow(); + }); + + it('rejects path traversal attempts', () => { + expect(() => validateProfile('../etc/passwd')).toThrow(); + expect(() => validateProfile('foo/bar')).toThrow(); + }); + + it('rejects special characters', () => { + expect(() => validateProfile('hello world')).toThrow(); + expect(() => validateProfile('name;rm -rf')).toThrow(); + }); + + it('rejects names longer than 64 characters', () => { + expect(() => validateProfile('a'.repeat(65))).toThrow(); + }); +}); + +describe('validatePagination', () => { + it('returns parsed limit and offset with defaults', () => { + expect(validatePagination({})).toEqual({ limit: 50, offset: 0 }); + }); + + it('parses string values', () => { + expect(validatePagination({ limit: '20', offset: '10' })).toEqual({ limit: 20, offset: 10 }); + }); + + it('rejects negative limit', () => { + expect(() => validatePagination({ limit: '-1' })).toThrow(); + }); + + it('rejects zero limit', () => { + expect(() => validatePagination({ limit: '0' })).toThrow(); + }); + + it('rejects negative offset', () => { + expect(() => validatePagination({ offset: '-5' })).toThrow(); + }); + + it('rejects non-numeric values', () => { + expect(() => validatePagination({ limit: 'abc' })).toThrow(); + }); + + it('uses a custom default limit', () => { + expect(validatePagination({}, 20)).toEqual({ limit: 20, offset: 0 }); + }); +}); + +describe('parseMessageIds', () => { + it('parses a single id', () => { + expect(parseMessageIds('42')).toEqual([42]); + }); + + it('parses comma-separated ids', () => { + expect(parseMessageIds('1, 2, 3')).toEqual([1, 2, 3]); + }); + + it('rejects 12abc (no silent parseInt truncation)', () => { + try { + parseMessageIds('12abc'); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.code).toBe(ErrorCode.INVALID_MESSAGE_ID); + } + }); + + it('rejects zero and negative', () => { + expect(() => parseMessageIds('0')).toThrow(); + expect(() => parseMessageIds('-1')).toThrow(); + }); + + it('rejects empty input', () => { + try { + parseMessageIds(''); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.code).toBe(ErrorCode.INVALID_MESSAGE_ID); + } + }); + + it('rejects more than max ids', () => { + const input = Array.from({ length: 101 }, (_, i) => String(i + 1)).join(','); + try { + parseMessageIds(input); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.code).toBe(ErrorCode.TOO_MANY_IDS); + } + }); +}); + +describe('parseIsoDate', () => { + it('parses ISO 8601', () => { + expect(parseIsoDate('2024-03-12T00:00:00Z', '--since').toISOString()).toBe('2024-03-12T00:00:00.000Z'); + }); + + it('rejects garbage', () => { + try { + parseIsoDate('not-a-date', '--since'); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.code).toBe(ErrorCode.INVALID_INPUT); + expect(err.message).toContain('--since'); + } + }); +}); + +describe('parseMessageId', () => { + it.each(['1,', ',1', '1,,', '1,2'])('rejects list syntax for a single ID: %s', (input) => { + expect(() => parseMessageId(input)).toThrow(); + }); + it('returns a single positive id', () => { + expect(parseMessageId('7')).toBe(7); + }); + + it('rejects a list', () => { + expect(() => parseMessageId('1,2')).toThrow(); + }); +}); + +describe('parseTopicId', () => { + it('parses a positive integer', () => { + expect(parseTopicId('12')).toBe(12); + }); + + it('rejects parseInt truncation like 12x', () => { + try { + parseTopicId('12x'); + throw new Error('expected throw'); + } catch (err: any) { + expect(err.code).toBe(ErrorCode.INVALID_TOPIC_ID); + } + }); + + it('rejects zero, negative, and floats', () => { + expect(() => parseTopicId('0')).toThrow(); + expect(() => parseTopicId('-1')).toThrow(); + expect(() => parseTopicId('1.5')).toThrow(); + }); +}); + +describe('integer boundaries', () => { + it.each(['12junk', '0', '-1', '1.5', '1e3', '2147483648', '9007199254740993', '9'.repeat(400)])('rejects unsafe message/topic ID %s', (input) => { + expect(() => parseMessageId(input)).toThrow(); + expect(() => parseTopicId(input)).toThrow(); + }); + + it('accepts the signed TL integer upper boundary', () => { + expect(parseMessageId(String(MAX_TL_INT))).toBe(MAX_TL_INT); + expect(parseTopicId(String(MAX_TL_INT))).toBe(MAX_TL_INT); + }); + + it.each(['', ' ', '1e3', '0x10', '1.5', '2147483648'])('rejects coercion or overflow in pagination: %s', input => { + expect(() => validatePagination({ limit: input })).toThrow(); + expect(() => validatePagination({ offset: input })).toThrow(); + }); + + it('allows zero only when the option domain permits it', () => { + expect(parseIntegerOption('0', 'timeout')).toBe(0); + expect(() => parseIntegerOption('0', 'ID', { min: 1 })).toThrow(); + expect(parseIntegerOption('2147483', 'seconds', { max: 2147483 })).toBe(2147483); + expect(() => parseIntegerOption('2147484', 'seconds', { max: 2147483 })).toThrow(); + }); +}); diff --git a/cli/tests/unit/with-auth-daemon.test.ts b/cli/tests/unit/with-auth-daemon.test.ts new file mode 100644 index 0000000..275f04e --- /dev/null +++ b/cli/tests/unit/with-auth-daemon.test.ts @@ -0,0 +1,10 @@ +import { describe, it, expect } from 'vitest'; +import { DaemonPaths } from '../../src/lib/daemon/pid.js'; + +describe('withAuth daemon detection', () => { + it('DaemonPaths correctly resolves socket path for profile', () => { + const paths = new DaemonPaths('/tmp/test-config', 'myprofile'); + expect(paths.socketPath).toContain('myprofile.sock'); + expect(paths.socketPath).toContain('daemon'); + }); +}); diff --git a/cli/tests/unit/with-auth.test.ts b/cli/tests/unit/with-auth.test.ts new file mode 100644 index 0000000..064a5a1 --- /dev/null +++ b/cli/tests/unit/with-auth.test.ts @@ -0,0 +1,247 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockOutputSuccess = vi.fn(); +const mockOutputError = vi.fn(); +const mockLogVerbose = vi.fn(); +const mockIsVerboseMode = vi.fn(() => false); +vi.mock('../../src/lib/output.js', () => ({ + outputSuccess: (...args: any[]) => mockOutputSuccess(...args), + outputError: (...args: any[]) => mockOutputError(...args), + logStatus: vi.fn(), + logVerbose: (...args: any[]) => mockLogVerbose(...args), +})); +vi.mock('../../src/lib/cli-mode.js', () => ({ + isVerboseMode: () => mockIsVerboseMode(), + isQuietMode: () => false, + setQuietMode: vi.fn(), + setVerboseMode: vi.fn(), +})); + +const { mockConnect, mockDestroy } = vi.hoisted(() => ({ + mockConnect: vi.fn().mockResolvedValue(undefined), + mockDestroy: vi.fn().mockResolvedValue(undefined), +})); + +const mockClientInstance = { connect: mockConnect, destroy: mockDestroy }; + +vi.mock('teleproto', async () => ({ + ...await vi.importActual('teleproto'), + TelegramClient: vi.fn().mockImplementation(() => mockClientInstance), + sessions: { StringSession: vi.fn().mockImplementation((s: string) => ({ _session: s })) }, +})); + +vi.mock('../../src/lib/config.js', () => ({ + createConfig: vi.fn(() => ({ get: vi.fn(), set: vi.fn(), path: '/tmp/mock-config.json' })), + getCredentialsOrThrow: vi.fn(() => ({ apiId: 12345, apiHash: 'testhash' })), +})); + +const mockStoreWithLock = vi.fn(); +vi.mock('../../src/lib/session-store.js', () => ({ + SessionStore: vi.fn().mockImplementation(() => ({ + withLock: mockStoreWithLock, + })), +})); + +const mockSocketExists = vi.fn(() => false); +const mockCleanup = vi.fn(); +const mockReadPid = vi.fn(() => null); +vi.mock('../../src/lib/daemon/pid.js', () => ({ + DaemonPaths: vi.fn().mockImplementation(() => ({ + socketExists: mockSocketExists, + cleanup: mockCleanup, + readPid: mockReadPid, + socketPath: '/tmp/mock.sock', + })), +})); + +const mockIsProcessAlive = vi.fn(() => false); +vi.mock('../../src/lib/daemon/lifecycle.js', () => ({ + isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args), + waitWhile: vi.fn(), + daemonChildEnv: vi.fn(), + installDaemonSignals: vi.fn(), +})); + +const mockDaemonCall = vi.fn(); +const mockDaemonClose = vi.fn(); +vi.mock('../../src/lib/daemon/client.js', () => ({ + DaemonClient: vi.fn().mockImplementation(() => ({ + call: mockDaemonCall, + close: mockDaemonClose, + })), +})); + +const { MockDaemonServer, mockServerStart } = vi.hoisted(() => { + const mockServerStart = vi.fn(); + const MockDaemonServer = vi.fn().mockImplementation(() => ({ + start: mockServerStart, + getClient: vi.fn(), + stop: vi.fn(), + })); + return { MockDaemonServer, mockServerStart }; +}); +vi.mock('../../src/lib/daemon/server.js', () => ({ + DaemonServer: MockDaemonServer, +})); + +import { withAuth } from '../../src/lib/with-auth.js'; +import { ErrorCode } from '../../src/lib/error-codes.js'; + +describe('withAuth', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockIsVerboseMode.mockReturnValue(false); + mockStoreWithLock.mockImplementation(async (_p: string, fn: (s: string) => Promise<any>) => fn('test-session')); + }); + + it('calls the callback with a connected client', async () => { + const fn = vi.fn().mockResolvedValue(undefined); + await withAuth({ profile: 'default', json: true, human: false, verbose: false, quiet: false }, fn); + expect(fn).toHaveBeenCalledWith(mockClientInstance); + }); + + it('outputs NOT_AUTHENTICATED when no session', async () => { + mockStoreWithLock.mockImplementation(async (_p: string, fn: (s: string) => Promise<any>) => fn('')); + const fn = vi.fn(); + await withAuth({ profile: 'default', json: true, human: false, verbose: false, quiet: false }, fn); + expect(fn).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith('Not logged in. Run: tg auth login', 'NOT_AUTHENTICATED'); + }); + + it('catches errors and outputs formatted error with UNKNOWN_ERROR', async () => { + const fn = vi.fn().mockRejectedValue(new Error('boom')); + await withAuth({ profile: 'default', json: true, human: false, verbose: false, quiet: false }, fn); + expect(mockOutputError).toHaveBeenCalledWith('boom', 'UNKNOWN_ERROR'); + }); + + it('translates gramjs RPC errors to a stable code', async () => { + const fn = vi.fn().mockRejectedValue({ errorMessage: 'PEER_ID_INVALID' }); + await withAuth({ profile: 'default', json: true, human: false, verbose: false, quiet: false }, fn); + expect(mockOutputError).toHaveBeenCalledWith('Peer not found', 'PEER_ID_INVALID'); + }); + + it('logs the raw error body when verbose mode is on', async () => { + mockIsVerboseMode.mockReturnValueOnce(true); + const fn = vi.fn().mockRejectedValue({ errorMessage: 'PEER_ID_INVALID' }); + await withAuth({ profile: 'default', json: true, human: false, verbose: true, quiet: false }, fn); + expect(mockLogVerbose).toHaveBeenCalledWith('PEER_ID_INVALID'); + expect(mockOutputError).toHaveBeenCalledWith('Peer not found', 'PEER_ID_INVALID'); + }); + + it('validates profile name and rejects invalid ones', async () => { + const fn = vi.fn(); + await withAuth({ profile: '../hack', json: true, human: false, verbose: false, quiet: false }, fn); + expect(fn).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalled(); + }); +}); + +const daemonOpts = { + profile: 'default', + json: true, + human: false, + verbose: false, + quiet: false, + daemon: true, +}; + +describe('withAuth --daemon', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockStoreWithLock.mockImplementation(async (_p: string, fn: (s: string) => Promise<any>) => fn('test-session')); + mockSocketExists.mockReturnValue(false); + mockReadPid.mockReturnValue(null); + mockIsProcessAlive.mockReturnValue(false); + }); + + it('errors CONNECTION_FAILED for --daemon when pid is alive but socket is gone', async () => { + mockSocketExists.mockReturnValue(false); + mockReadPid.mockReturnValue(4242); + mockIsProcessAlive.mockReturnValue(true); + const fn = vi.fn(); + await withAuth(daemonOpts, fn); + + expect(fn).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('not responding'), + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + }); + + it('errors DAEMON_NOT_RUNNING when no socket; does not start an in-process server', async () => { + const fn = vi.fn(); + await withAuth(daemonOpts, fn); + + expect(fn).not.toHaveBeenCalled(); + expect(MockDaemonServer).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon is not running. Start one with: tg daemon start', + ErrorCode.DAEMON_NOT_RUNNING, + ); + }); + + it('refuses a direct client when a daemon is already up (no --daemon flag)', async () => { + mockSocketExists.mockReturnValue(true); + mockDaemonCall.mockResolvedValueOnce('pong'); + const fn = vi.fn(); + await withAuth({ ...daemonOpts, daemon: false }, fn); + + expect(fn).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(MockDaemonServer).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('daemon is running'), + ErrorCode.DAEMON_ALREADY_RUNNING, + ); + }); + + it('does not open a second MTProto client when the daemon is already up', async () => { + mockSocketExists.mockReturnValue(true); + mockDaemonCall.mockResolvedValueOnce('pong'); + const fn = vi.fn(); + await withAuth(daemonOpts, fn); + + expect(fn).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(MockDaemonServer).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('--daemon'), + ErrorCode.DAEMON_PROXY_UNAVAILABLE, + ); + }); + + it('treats a stale socket as not running and does not fall through to withClient', async () => { + mockSocketExists.mockReturnValue(true); + mockReadPid.mockReturnValue(null); + mockDaemonCall.mockRejectedValueOnce(new Error('ECONNREFUSED')); + const fn = vi.fn(); + await withAuth(daemonOpts, fn); + + expect(mockCleanup).toHaveBeenCalled(); + expect(fn).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + 'Daemon is not running. Start one with: tg daemon start', + ErrorCode.DAEMON_NOT_RUNNING, + ); + }); + + it('does not unlink a live daemon socket when ping fails', async () => { + mockSocketExists.mockReturnValue(true); + mockReadPid.mockReturnValue(4242); + mockIsProcessAlive.mockReturnValue(true); + mockDaemonCall.mockRejectedValueOnce(new Error('timeout')); + const fn = vi.fn(); + await withAuth(daemonOpts, fn); + + expect(mockCleanup).not.toHaveBeenCalled(); + expect(fn).not.toHaveBeenCalled(); + expect(mockConnect).not.toHaveBeenCalled(); + expect(mockOutputError).toHaveBeenCalledWith( + expect.stringContaining('not responding'), + ErrorCode.DAEMON_CONNECTION_FAILED, + ); + }); +}); diff --git a/cli/tests/unit/wss.test.ts b/cli/tests/unit/wss.test.ts new file mode 100644 index 0000000..efe8998 --- /dev/null +++ b/cli/tests/unit/wss.test.ts @@ -0,0 +1,170 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { TelegramClient, sessions } from 'teleproto'; +import { PromisedWebSockets } from 'teleproto/extensions/PromisedWebSockets.js'; +import { Logger } from 'teleproto/extensions/Logger.js'; +import { DiagnosticWSS, WssSocket, wssHost } from '../../src/lib/wss.js'; +import { connectionOptions } from '../../src/lib/connection-options.js'; +import { resolveTransport } from '../../src/lib/transport.js'; +import { createClientForAuth } from '../../src/lib/client.js'; + +afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); }); + +const params = (dcId = 4) => ({ + ip: '149.154.167.91', port: 80, dcId, loggers: new Logger('none'), + socket: PromisedWebSockets, testServers: false, +}); + +describe('WSS routing', () => { + it.each(['pluto', 'venus', 'aurora', 'vesta', 'flora'])('maps the %s data center independently of the saved address', name => { + const dcId = ['pluto', 'venus', 'aurora', 'vesta', 'flora'].indexOf(name) + 1; + const connection = new DiagnosticWSS(params(dcId)); + expect(connection.ip).toBe(`${name}.web.telegram.org`); + expect(connection.port).toBe(443); + expect(connection.toString()).toBe(`${name}.web.telegram.org:443/WSS`); + }); + + it.each([0, -6, 6, 2.5, NaN, 203])('rejects unsupported DC %s before connecting', dcId => { + expect(() => wssHost(dcId)).toThrow('does not support'); + }); + + it('uses TLS, the binary WebSocket protocol and obfuscated framing', async () => { + const connect = vi.spyOn(PromisedWebSockets.prototype, 'connect').mockResolvedValue(undefined); + const write = vi.spyOn(PromisedWebSockets.prototype, 'write').mockImplementation(() => {}); + const connection = new DiagnosticWSS(params()); + await connection.connect(); + expect(connect).toHaveBeenCalledWith(443, 'vesta.web.telegram.org', false); + + expect(write.mock.calls[0][0]).toHaveLength(64); + }); + + it('closes the socket on a failed upgrade and logs no error payload', async () => { + vi.spyOn(PromisedWebSockets.prototype, 'connect').mockRejectedValue(new Error('private payload')); + const close = vi.spyOn(PromisedWebSockets.prototype, 'close').mockResolvedValue(); + const options = params(); + const log = vi.spyOn(options.loggers, 'error'); + await expect(new DiagnosticWSS(options).connect()).rejects.toThrow('private payload'); + expect(close).toHaveBeenCalled(); + expect(log).toHaveBeenCalledWith('Transport connect failed: UNKNOWN_ERROR'); + }); + + it('does not rewrite the address or key in an existing session', async () => { + const session = new sessions.StringSession(''); + session.setDC(2, '149.154.167.51', 80); + const client = new TelegramClient(session, 1, 'synthetic', { ...connectionOptions('wss'), baseLogger: new Logger('none') }); + try { + const connection = new (client as any)._transport.connection({ ...params(session.dcId), ip: session.serverAddress }); + expect(connection.ip).toBe('venus.web.telegram.org'); + expect(session.serverAddress).toBe('149.154.167.51'); + expect(session.dcId).toBe(2); + } finally { await client.destroy(); } + }); + + it('routes a real SDK DC migration through WSS and clears the old DC key', async () => { + const client = await createClientForAuth(1, 'synthetic', 'wss'); + const disconnect = vi.fn(async () => {}); + (client as any)._sender = { disconnect }; + vi.spyOn(client, 'getDC').mockResolvedValue({ id: 2, ipAddress: '149.154.167.51', port: 443 } as any); + vi.spyOn(client, 'connect').mockImplementation(async () => { + const connection = new (client as any)._transport.connection({ ...params(client.session.dcId), ip: client.session.serverAddress }); + expect(connection.ip).toBe('venus.web.telegram.org'); + expect((client as any)._transport.webSocket).toBe(true); + return true; + }); + try { + await client._switchDC(2); + expect(client.session.dcId).toBe(2); + expect(disconnect).toHaveBeenCalledOnce(); + expect(client.connect).toHaveBeenCalledOnce(); + } finally { (client as any)._sender = undefined; await client.destroy(); } + }); +}); + +describe('WSS lifetime', () => { + it('routes borrowed media DCs to their dedicated endpoint', () => { + expect(new DiagnosticWSS(params(-2)).ip).toBe('venus-1.web.telegram.org'); + }); + it('bounds an upgrade that never completes', async () => { + vi.useFakeTimers(); + vi.spyOn(PromisedWebSockets.prototype, 'connect').mockReturnValue(new Promise(() => {})); + const close = vi.spyOn(PromisedWebSockets.prototype, 'close').mockResolvedValue(); + const socket = new WssSocket(); + const rejected = expect(socket.connect(443, 'vesta.web.telegram.org')).rejects.toThrow('TIMEOUT'); + await vi.advanceTimersByTimeAsync(10_000); + await rejected; + expect(close).toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it.each([0, 5])('cancels an upgrade before readiness after %s microtasks', async ticks => { + vi.spyOn(PromisedWebSockets.prototype, 'connect').mockReturnValue(new Promise(() => {})); + vi.spyOn(PromisedWebSockets.prototype, 'close').mockResolvedValue(); + const connection = new DiagnosticWSS(params()); + const rejected = expect(connection.connect()).rejects.toThrow('WebSocket was closed'); + for (let i = 0; i < ticks; i++) await Promise.resolve(); + await connection.disconnect(); + await rejected; + expect(connection.isConnected()).toBe(false); + }); + + it('isolates late SDK events from a previous socket after reconnecting', async () => { + const instances: PromisedWebSockets[] = []; + vi.spyOn(PromisedWebSockets.prototype, 'connect').mockImplementation(async function () { + instances.push(this); + (this as any).closed = false; + }); + vi.spyOn(PromisedWebSockets.prototype, 'close').mockImplementation(async function () { + (this as any).closed = true; + }); + vi.spyOn(PromisedWebSockets.prototype, 'read').mockImplementation(async function () { + if ((this as any).closed) throw new Error('WebSocket was closed'); + return Buffer.from('new connection'); + }); + const socket = new WssSocket(); + await socket.connect(443, 'vesta.web.telegram.org'); + await socket.connect(443, 'vesta.web.telegram.org'); + expect(instances[0]).not.toBe(instances[1]); + await instances[0].close(); + await expect(socket.read(14)).resolves.toEqual(Buffer.from('new connection')); + await socket.close(); + }); +}); + +describe('transport selection', () => { + it('uses CLI, then the selected profile, then TCP', () => { + const config = { get: vi.fn(key => key === 'profiles.work.transport' ? 'wss' : undefined) } as any; + expect(resolveTransport(config, 'work')).toBe('wss'); + expect(resolveTransport(config, 'work', 'tcp')).toBe('tcp'); + expect(resolveTransport(config, 'default')).toBe('tcp'); + }); + + it('rejects malformed config values without echoing them', () => { + expect(() => resolveTransport({ get: () => 'private-config-value' } as any, 'work')) + .toThrow('Transport must be tcp or wss'); + expect(() => connectionOptions('https' as any)).toThrow('Transport must be tcp or wss'); + }); +}); + +describe('Node 20 WebSocket compatibility', () => { + it('connects without global WebSocket and reports received activity', async () => { + const { WebSocketServer } = await import('ws'); + const { once } = await import('node:events'); + const server = new WebSocketServer({ host: '127.0.0.1', port: 0 }); + await once(server, 'listening'); + server.on('connection', peer => { peer.on('message', bytes => peer.send(bytes)); }); + const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'WebSocket'); + Object.defineProperty(globalThis, 'WebSocket', { configurable: true, value: undefined }); + const socket = new WssSocket(); + try { + await socket.connect((server.address() as { port: number }).port, '127.0.0.1'); + socket.write(Buffer.from('fixture')); + await expect(socket.readExactly(7)).resolves.toEqual(Buffer.from('fixture')); + expect(socket.lastDataAt).toBeGreaterThan(0); + } finally { + await socket.close(); + for (const peer of server.clients) peer.terminate(); + await new Promise<void>(done => server.close(() => done())); + if (descriptor) Object.defineProperty(globalThis, 'WebSocket', descriptor); + else delete (globalThis as any).WebSocket; + } + }); +}); diff --git a/cli/tsconfig.json b/cli/tsconfig.json new file mode 100644 index 0000000..e8c5cca --- /dev/null +++ b/cli/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "declaration": true, + "sourceMap": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src"] +} diff --git a/cli/tsup.config.ts b/cli/tsup.config.ts new file mode 100644 index 0000000..be2eb4f --- /dev/null +++ b/cli/tsup.config.ts @@ -0,0 +1,31 @@ +import { defineConfig } from 'tsup'; + +const shared = { + format: ['esm'] as const, + target: 'node20' as const, + sourcemap: true, + shims: false, + external: ['teleproto'], +}; + +export default defineConfig([ + { + ...shared, + entry: { 'bin/tg': 'src/bin/tg.ts' }, + clean: true, + dts: false, + banner: { js: '#!/usr/bin/env node' }, + }, + { + ...shared, + entry: { 'lib/daemon/entry': 'src/lib/daemon/entry.ts' }, + clean: false, + dts: false, + }, + { + ...shared, + entry: { index: 'src/index.ts' }, + clean: false, + dts: true, + }, +]); diff --git a/cli/vitest.config.ts b/cli/vitest.config.ts new file mode 100644 index 0000000..73d72e8 --- /dev/null +++ b/cli/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + globals: true, + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + exclude: ['node_modules/', 'tests/', 'dist/'], + }, + }, +}); diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..6d37f60 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,21 @@ +# Документация + +- [Подключение и обслуживание](setup-development.md) +- [61 инструмент](tools.md) +- [Сценарии](../examples/scenarios.md) +- [Безопасность](../SECURITY.md) +- [Разработка](../CONTRIBUTING.md) +- [Происхождение](../UPSTREAM.md) +- [Отчёт проверки](verification.md) + +## Архитектура + +ИИ-клиент → stdio FastMCP из Python MCP SDK → локальная сборка tg-cli → профильный daemon → Teleproto → Telegram MTProto. + +`mcp_server/` содержит Python-обёртку и преобразование JSON в TOON. `cli/` содержит исходники Node/TypeScript и тесты. `scripts/manage.py` устанавливает зависимости и вычисляет пути для конкретного компьютера. `main` и `reserve` — имена профилей самого читателя, без предзаданных аккаунтов. + +Runtime не читает конфигурацию родительского workspace. `TG_MCP_STATE_DIR` выбирает отдельное хранилище, а не экспортирует сессию. Сервер запускается без credentials; они нужны только для реальных Telegram-вызовов. + +## Related + +- [README](../README.md) diff --git a/docs/dependency-licenses.json b/docs/dependency-licenses.json new file mode 100644 index 0000000..d9d2e2f --- /dev/null +++ b/docs/dependency-licenses.json @@ -0,0 +1,1442 @@ +[ + { + "name": "@ampproject/remapping", + "version": "2.3.0", + "license": "Apache-2.0", + "developmentOnly": true + }, + { + "name": "@babel/helper-string-parser", + "version": "7.27.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@babel/helper-validator-identifier", + "version": "7.28.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@babel/parser", + "version": "7.29.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@babel/types", + "version": "7.29.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@bcoe/v8-coverage", + "version": "1.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@cifrante/darwin-arm64", + "version": "0.8.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "@cryptography/aes", + "version": "0.1.1", + "license": "GPL-3.0-or-later", + "developmentOnly": true + }, + { + "name": "@esbuild/darwin-arm64", + "version": "0.28.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@isaacs/cliui", + "version": "8.0.2", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "@istanbuljs/schema", + "version": "0.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@jridgewell/gen-mapping", + "version": "0.3.13", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@jridgewell/resolve-uri", + "version": "3.1.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@jridgewell/sourcemap-codec", + "version": "1.5.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@jridgewell/trace-mapping", + "version": "0.3.31", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@pkgjs/parseargs", + "version": "0.11.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@rollup/rollup-darwin-arm64", + "version": "4.59.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@toon-format/toon", + "version": "2.3.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "@types/chai", + "version": "5.2.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/deep-eql", + "version": "4.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/estree", + "version": "1.0.8", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/node", + "version": "25.4.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/proper-lockfile", + "version": "4.1.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/retry", + "version": "0.12.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@types/ws", + "version": "8.18.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/coverage-v8", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/expect", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/mocker", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/pretty-format", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/runner", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/snapshot", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/spy", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "@vitest/utils", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "acorn", + "version": "8.16.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ajv", + "version": "8.18.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "ajv-formats", + "version": "3.0.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "ansi-regex", + "version": "5.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ansi-regex", + "version": "5.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ansi-regex", + "version": "5.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ansi-regex", + "version": "6.2.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ansi-styles", + "version": "4.3.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ansi-styles", + "version": "6.2.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "any-promise", + "version": "1.3.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "assertion-error", + "version": "2.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ast-v8-to-istanbul", + "version": "0.3.12", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "async-mutex", + "version": "0.3.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "atomically", + "version": "2.1.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "balanced-match", + "version": "1.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "balanced-match", + "version": "4.0.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "base64-js", + "version": "1.5.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "big-integer", + "version": "1.6.52", + "license": "Unlicense", + "developmentOnly": false + }, + { + "name": "brace-expansion", + "version": "2.1.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "brace-expansion", + "version": "5.0.9", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "buffer", + "version": "6.0.3", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "bufferutil", + "version": "4.1.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "bundle-require", + "version": "5.1.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "cac", + "version": "6.7.14", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "chai", + "version": "5.3.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "check-error", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "chokidar", + "version": "4.0.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "cifrante", + "version": "0.8.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "color-convert", + "version": "2.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "color-name", + "version": "1.1.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "commander", + "version": "14.0.3", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "commander", + "version": "4.1.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "conf", + "version": "15.1.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "confbox", + "version": "0.1.8", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "consola", + "version": "3.4.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "cross-spawn", + "version": "7.0.6", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "d", + "version": "1.0.2", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "debounce-fn", + "version": "6.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "debug", + "version": "2.6.9", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "debug", + "version": "4.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "debug", + "version": "4.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "debug", + "version": "4.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "debug", + "version": "4.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "debug", + "version": "4.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "deep-eql", + "version": "5.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "dom-serializer", + "version": "1.4.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "domelementtype", + "version": "2.3.0", + "license": "BSD-2-Clause", + "developmentOnly": true + }, + { + "name": "domhandler", + "version": "4.3.1", + "license": "BSD-2-Clause", + "developmentOnly": true + }, + { + "name": "domutils", + "version": "2.8.0", + "license": "BSD-2-Clause", + "developmentOnly": true + }, + { + "name": "dot-prop", + "version": "10.1.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "eastasianwidth", + "version": "0.2.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "emoji-regex", + "version": "8.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "emoji-regex", + "version": "8.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "emoji-regex", + "version": "9.2.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "entities", + "version": "2.2.0", + "license": "BSD-2-Clause", + "developmentOnly": true + }, + { + "name": "env-paths", + "version": "3.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "es-module-lexer", + "version": "1.7.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "es5-ext", + "version": "0.10.64", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "es6-iterator", + "version": "2.0.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "es6-symbol", + "version": "3.1.4", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "esbuild", + "version": "0.28.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "esniff", + "version": "2.0.1", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "estree-walker", + "version": "3.0.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "event-emitter", + "version": "0.3.7", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "expect-type", + "version": "1.4.0", + "license": "Apache-2.0", + "developmentOnly": true + }, + { + "name": "ext", + "version": "1.7.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "fast-deep-equal", + "version": "3.1.3", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "fast-uri", + "version": "3.1.9", + "license": "BSD-3-Clause", + "developmentOnly": false + }, + { + "name": "fdir", + "version": "6.5.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "fix-dts-default-cjs-exports", + "version": "1.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "foreground-child", + "version": "3.3.1", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "fsevents", + "version": "2.3.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "glob", + "version": "10.5.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "gpt-tokenizer", + "version": "3.4.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "graceful-fs", + "version": "4.2.11", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "has-flag", + "version": "4.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "html-escaper", + "version": "2.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "htmlparser2", + "version": "6.1.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ieee754", + "version": "1.2.1", + "license": "BSD-3-Clause", + "developmentOnly": false + }, + { + "name": "imurmurhash", + "version": "0.1.4", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "ip-address", + "version": "10.7.5", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "is-typedarray", + "version": "1.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "isexe", + "version": "2.0.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "istanbul-lib-coverage", + "version": "3.2.2", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "istanbul-lib-report", + "version": "3.0.1", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "istanbul-lib-source-maps", + "version": "5.0.6", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "istanbul-reports", + "version": "3.2.0", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "jackspeak", + "version": "3.4.3", + "license": "BlueOak-1.0.0", + "developmentOnly": true + }, + { + "name": "joycon", + "version": "3.1.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "js-tokens", + "version": "10.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "js-tokens", + "version": "9.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "json-schema-traverse", + "version": "1.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "json-schema-typed", + "version": "8.0.2", + "license": "BSD-2-Clause", + "developmentOnly": false + }, + { + "name": "lilconfig", + "version": "3.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "lines-and-columns", + "version": "1.2.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "load-tsconfig", + "version": "0.2.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "loupe", + "version": "3.2.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "lru-cache", + "version": "10.4.3", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "magic-string", + "version": "0.30.21", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "magicast", + "version": "0.3.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "make-dir", + "version": "4.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "mime", + "version": "3.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "mimic-function", + "version": "5.0.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "minimatch", + "version": "10.2.4", + "license": "BlueOak-1.0.0", + "developmentOnly": true + }, + { + "name": "minimatch", + "version": "9.0.9", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "minipass", + "version": "7.1.3", + "license": "BlueOak-1.0.0", + "developmentOnly": true + }, + { + "name": "mlly", + "version": "1.8.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ms", + "version": "2.1.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "mz", + "version": "2.7.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "nanoid", + "version": "3.3.18", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "next-tick", + "version": "1.1.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "node-gyp-build", + "version": "4.8.4", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "node-localstorage", + "version": "2.2.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "node-localstorage", + "version": "3.0.5", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "object-assign", + "version": "4.1.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "package-json-from-dist", + "version": "1.0.1", + "license": "BlueOak-1.0.0", + "developmentOnly": true + }, + { + "name": "pako", + "version": "2.2.0", + "license": "(MIT AND Zlib)", + "developmentOnly": true + }, + { + "name": "path-browserify", + "version": "1.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "path-key", + "version": "3.1.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "path-scurry", + "version": "1.11.1", + "license": "BlueOak-1.0.0", + "developmentOnly": true + }, + { + "name": "pathe", + "version": "2.0.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "pathval", + "version": "2.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "picocolors", + "version": "1.1.1", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "picomatch", + "version": "4.0.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "pirates", + "version": "4.0.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "pkg-types", + "version": "1.3.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "postcss", + "version": "8.5.28", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "postcss-load-config", + "version": "6.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "proper-lockfile", + "version": "4.1.2", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "readdirp", + "version": "4.1.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "real-cancellable-promise", + "version": "1.2.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "require-from-string", + "version": "2.0.2", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "resolve-from", + "version": "5.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "retry", + "version": "0.12.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "rollup", + "version": "4.59.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "semver", + "version": "7.7.4", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "shebang-command", + "version": "2.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "shebang-regex", + "version": "3.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "siginfo", + "version": "2.0.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "signal-exit", + "version": "3.0.7", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "signal-exit", + "version": "4.1.0", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "signal-exit", + "version": "4.1.0", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "slide", + "version": "1.1.6", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "smart-buffer", + "version": "4.2.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "socks", + "version": "2.8.7", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "source-map", + "version": "0.7.6", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "source-map-js", + "version": "1.2.1", + "license": "BSD-3-Clause", + "developmentOnly": true + }, + { + "name": "stackback", + "version": "0.0.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "std-env", + "version": "3.10.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "store2", + "version": "2.14.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "string-width", + "version": "5.1.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "strip-ansi", + "version": "7.2.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "strip-literal", + "version": "3.1.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "stubborn-fs", + "version": "2.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "stubborn-utils", + "version": "1.0.2", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "sucrase", + "version": "3.35.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "supports-color", + "version": "7.2.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tagged-tag", + "version": "1.0.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "telegram", + "version": "2.26.22", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "teleproto", + "version": "1.232.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "test-exclude", + "version": "7.0.2", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "thenify", + "version": "3.3.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "thenify-all", + "version": "1.6.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinybench", + "version": "2.9.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinyexec", + "version": "0.3.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinyglobby", + "version": "0.2.15", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinypool", + "version": "1.1.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinyrainbow", + "version": "2.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tinyspy", + "version": "4.0.6", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "tree-kill", + "version": "1.2.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ts-custom-error", + "version": "3.3.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "ts-interface-checker", + "version": "0.1.13", + "license": "Apache-2.0", + "developmentOnly": true + }, + { + "name": "tslib", + "version": "2.9.1", + "license": "0BSD", + "developmentOnly": true + }, + { + "name": "tsup", + "version": "8.5.1", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "type", + "version": "2.7.3", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "type-fest", + "version": "5.4.4", + "license": "(MIT OR CC0-1.0)", + "developmentOnly": false + }, + { + "name": "typedarray-to-buffer", + "version": "3.1.5", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "typescript", + "version": "5.9.3", + "license": "Apache-2.0", + "developmentOnly": true + }, + { + "name": "ufo", + "version": "1.6.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "uint8array-extras", + "version": "1.5.0", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "undici-types", + "version": "7.18.2", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "utf-8-validate", + "version": "5.0.10", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "vite", + "version": "6.4.3", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "vite-node", + "version": "3.2.4", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "vitest", + "version": "3.2.7", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "websocket", + "version": "1.0.35", + "license": "Apache-2.0", + "developmentOnly": true + }, + { + "name": "when-exit", + "version": "2.1.5", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "which", + "version": "2.0.2", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "why-is-node-running", + "version": "2.3.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "wrap-ansi", + "version": "7.0.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "wrap-ansi", + "version": "8.1.0", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "write-file-atomic", + "version": "1.3.4", + "license": "ISC", + "developmentOnly": true + }, + { + "name": "write-file-atomic", + "version": "5.0.1", + "license": "ISC", + "developmentOnly": false + }, + { + "name": "ws", + "version": "8.22.1", + "license": "MIT", + "developmentOnly": false + }, + { + "name": "yaeti", + "version": "0.0.6", + "license": "MIT", + "developmentOnly": true + }, + { + "name": "zod", + "version": "4.6.7", + "license": "MIT", + "developmentOnly": false + } +] diff --git a/docs/python-dependency-licenses.json b/docs/python-dependency-licenses.json new file mode 100644 index 0000000..ec6b955 --- /dev/null +++ b/docs/python-dependency-licenses.json @@ -0,0 +1,152 @@ +[ + { + "name": "annotated-types", + "version": "0.8.0", + "license": "MIT" + }, + { + "name": "anyio", + "version": "4.16.0", + "license": "MIT" + }, + { + "name": "attrs", + "version": "26.1.0", + "license": "MIT" + }, + { + "name": "certifi", + "version": "2026.10.23", + "license": "MPL-2.0" + }, + { + "name": "cffi", + "version": "2.1.1", + "license": "MIT-0" + }, + { + "name": "click", + "version": "8.5.0", + "license": "BSD-3-Clause" + }, + { + "name": "cryptography", + "version": "50.0.2", + "license": "Apache-2.0 OR BSD-3-Clause" + }, + { + "name": "h11", + "version": "0.16.0", + "license": "MIT" + }, + { + "name": "httpcore", + "version": "1.0.9", + "license": "BSD-3-Clause" + }, + { + "name": "httpx", + "version": "0.28.1", + "license": "BSD-3-Clause" + }, + { + "name": "httpx-sse", + "version": "0.4.3", + "license": "MIT" + }, + { + "name": "idna", + "version": "3.20", + "license": "BSD-3-Clause" + }, + { + "name": "jsonschema", + "version": "4.26.0", + "license": "MIT" + }, + { + "name": "jsonschema-specifications", + "version": "2025.9.1", + "license": "MIT" + }, + { + "name": "mcp", + "version": "1.26.0", + "license": "MIT" + }, + { + "name": "pip", + "version": "24.2", + "license": "MIT" + }, + { + "name": "pycparser", + "version": "3.12", + "license": "BSD-3-Clause" + }, + { + "name": "pydantic", + "version": "2.14.3", + "license": "MIT" + }, + { + "name": "pydantic-settings", + "version": "2.16.2", + "license": "MIT" + }, + { + "name": "pydantic_core", + "version": "2.50.4", + "license": "MIT" + }, + { + "name": "PyJWT", + "version": "2.15.1", + "license": "MIT" + }, + { + "name": "python-dotenv", + "version": "1.2.4", + "license": "BSD-3-Clause" + }, + { + "name": "python-multipart", + "version": "0.0.33", + "license": "Apache-2.0" + }, + { + "name": "referencing", + "version": "0.37.0", + "license": "MIT" + }, + { + "name": "rpds-py", + "version": "2026.9.1", + "license": "MIT" + }, + { + "name": "sse-starlette", + "version": "3.6.0", + "license": "BSD-3-Clause" + }, + { + "name": "starlette", + "version": "1.10.0", + "license": "BSD-3-Clause" + }, + { + "name": "typing-inspection", + "version": "0.4.5", + "license": "MIT" + }, + { + "name": "typing_extensions", + "version": "4.16.0", + "license": "PSF-2.0" + }, + { + "name": "uvicorn", + "version": "0.54.0", + "license": "BSD-3-Clause" + } +] diff --git a/docs/setup-development.md b/docs/setup-development.md new file mode 100644 index 0000000..fa62aeb --- /dev/null +++ b/docs/setup-development.md @@ -0,0 +1,71 @@ +# Подключение и обслуживание + +## Установка из исходников + +Скачайте [архив main](https://git.flowmasters.ru/vik/telegram-mcp/archive/main.zip) или клонируйте репозиторий: + +```sh +git clone https://git.flowmasters.ru/vik/telegram-mcp.git +cd telegram-mcp +``` + +В корне проекта: + +```sh +python3 scripts/manage.py setup +python3 scripts/manage.py check +python3 scripts/manage.py login +python3 scripts/manage.py config +``` + +`setup` создаёт `.venv`, устанавливает Python-зависимости из файла с SHA-256, выполняет `npm ci --ignore-scripts` по lockfile и явную сборку CLI. Нужен интернет к пакетным реестрам. Вызовов Telegram нет. + +`login` запускается человеком в терминале. По умолчанию используется профиль `main`, для второго аккаунта — `login --account reserve`. Номер, код и пароль не надо отправлять ИИ или вставлять в конфигурацию MCP. Пресет `desktop` использует существующий механизм CLI для получения параметров клиента; он требует доступа к upstream opentele. Пользовательская авторизация остаётся интерактивной. Профиль сохраняет выбранный транспорт; при необходимости укажите `--transport wss`. + +## MCP-клиент + +`config` печатает JSON с абсолютными путями, вычисленными на вашем компьютере. Скопируйте только секцию сервера в конфигурацию своего MCP-клиента, не заменяя остальные серверы. Формат верхнего уровня зависит от клиента. Общий [пример](../examples/mcp-client.json) — шаблон, а не готовые пути. + +- Команда: Python из `.venv/bin/python` этого проекта. +- Аргумент: `mcp_server/server.py` этого проекта. +- Транспорт: stdio. Shell-обёртка не нужна. +- После переноса папки повторите `setup`, сгенерируйте конфигурацию заново и переподключите клиент: виртуальное окружение не переносимо как бинарный артефакт. + +Не добавляйте сессии, API hash или телефон в MCP JSON. Сервер не загружает `.env`, не использует глобальную команду `tg` и очищает у дочернего процесса унаследованные переменные `TG_*`; авторизация берётся из выделенного CLI config/profile. + +## Хранилище аккаунтов + +По умолчанию: `~/.local/share/telegram-mcp/`. Внутри — config и sessions. Это **приватные данные**, не часть репозитория. Права каталога после `login`: 0700. Для отдельного экземпляра задайте абсолютный `TG_MCP_STATE_DIR` при login и в окружении MCP. `config` включит эту переменную, если она задана. Не указывайте каталог другого действующего tg-cli. + +Не запускайте два прямых клиента на одной сессии. MCP использует профильный daemon. Для ручных команд после входа используйте daemon: + +```sh +python3 scripts/manage.py cli -- --daemon user profile me +``` + +Для прямой авторизации/выхода остановите daemon соответствующего аккаунта: + +```sh +python3 scripts/manage.py cli -- daemon stop +python3 scripts/manage.py login +``` + +Внутри MCP старые 12 методов по умолчанию используют `main`; новые 49 требуют явный `account`. В примерах всегда выбирайте `main` или `reserve` явно. Возврата к другому аккаунту при ошибке нет. + +## Ошибки + +- Нет Node/Python: установите указанные версии, повторите setup. +- Нет авторизации: выполните login выбранного профиля. `check` вход не проверяет. +- Соединение не проходит: попробуйте login с `--transport wss` после остановки daemon. Это не обход блокировок и не обещание доступности Telegram. +- `FOLDER_CONFLICT`: перечитайте папки и повторите предпросмотр; не применяйте старую revision. +- `TIMEOUT` при отправке: проверьте историю или очередь. Не повторяйте отправку автоматически. + +## Обновление и откат + +Остановите daemon каждого используемого профиля и MCP-клиент. Сохраните предыдущий исходный комплект, замените код проверенной версией, выполните setup и check, обновите пути клиента при необходимости. Файлы авторизации не включайте в резервную копию кода. Для отката используйте предыдущий комплект и его lockfiles; не устанавливайте npm @latest поверх локальной сборки. Автоматического обновления здесь нет. + +## Related + +- [README](../README.md) +- [Документация](README.md) +- [Безопасность](../SECURITY.md) diff --git a/docs/tools.md b/docs/tools.md new file mode 100644 index 0000000..c5199c0 --- /dev/null +++ b/docs/tools.md @@ -0,0 +1,73 @@ +# Telegram MCP: каталог инструментов + +Каталог MCP (12 базовых + 49 расширенных). Базовые отправки send_message/send_html/send_file/schedule_message отправляют сразу; предпросмотр относится к новым операциям изменения. Новые инструменты требуют явный `account`; изменения по умолчанию возвращают `dry_run`. Предпросмотр не является разрешением на применение. + +| Инструмент | Назначение | +|---|---| +| `telegram_send_message` | Отправить текстовое сообщение в Telegram. | +| `telegram_send_html` | Отправить HTML-оформленное сообщение в Telegram. | +| `telegram_schedule_message` | Запланировать отправку текстового сообщения на конкретное время (server-side). | +| `telegram_send_file` | Отправить файл (документ или фото) в Telegram. | +| `telegram_read_history` | Прочитать последние сообщения из чата. | +| `telegram_get_messages` | Прочитать конкретные сообщения без загрузки истории. | +| `telegram_search_messages` | Поиск сообщений в доступных диалогах или одном chat; json/toon и выбор fields. | +| `telegram_list_stories` | Список сохранённых в профиле (pinned) или действующих (active) историй. | +| `telegram_get_story` | Прочитать метаданные и подпись одной истории по username и ID. | +| `telegram_download_story_media` | Скачать фото или видео истории во временную локальную папку (не более 30 МБ). | +| `telegram_wait_for_reply` | Ждать ответ от бота/собеседника в чате после сообщения с указанным id. | +| `telegram_auth_status` | Проверить авторизацию выбранного аккаунта в tg-cli. | +| `telegram_list_folders` | Read folder order, rules, included/excluded/pinned peer IDs and revision. Does not read messages. | +| `telegram_list_dialogs` | Read metadata from a resumable daemon snapshot; limit 1..500, offset 0..50000. Pass cursor/next_offset, honor retry_at; refresh starts a new scan. muted=null inherits defaults. | +| `telegram_update_folder` | Create or patch an ordinary folder. Omitted fields are preserved; supplied lists replace those lists. Preview first; apply requires preview revision. Shared folders are refused. | +| `telegram_delete_folder` | Delete an ordinary folder only, not its chats. Preview first; apply requires revision. | +| `telegram_reorder_folders` | Reorder folders; include every current ID exactly once, including All Chats when returned. Apply requires revision. | +| `telegram_set_archived` | Archive or unarchive one chat. | +| `telegram_set_chat_pinned` | Pin or unpin a dialog in its main/archive list. Folder pins use update_folder. | +| `telegram_set_unread` | Set or clear the manual unread mark; does not reset message read receipts. | +| `telegram_mark_read` | Mark messages read up to max_id; this changes read receipts. | +| `telegram_set_mute` | Set mute expiry Unix seconds: 0 unmute, 2147483647 indefinitely. Preserves other notification fields. | +| `telegram_save_draft` | Save a plain-text draft; empty text clears it. Does not send a message. | +| `telegram_get_notification_settings` | Read per-chat notification overrides. inherited=true means account defaults apply. | +| `telegram_list_scheduled_messages` | Read the server-side scheduled message queue. | +| `telegram_cancel_scheduled_messages` | Cancel selected scheduled messages. | +| `telegram_send_scheduled_now` | Send selected scheduled messages now. Never retry automatically after timeout. | +| `telegram_get_chat_info` | Read chat details. | +| `telegram_resolve_peer` | Resolve username or marked ID. | +| `telegram_get_invite_info` | Inspect invite without joining. | +| `telegram_get_user_profile` | Read accessible user profile. | +| `telegram_list_members` | List accessible members; Telegram may restrict completeness. | +| `telegram_list_topics` | List forum topics. | +| `telegram_list_pinned_messages` | Read pinned messages. | +| `telegram_list_contacts` | Read contacts. | +| `telegram_list_blocked_users` | Read blocked users. | +| `telegram_search_public_chats` | Search by name; does not join or contact anyone. | +| `telegram_search_contacts` | Search by name; does not join or contact anyone. | +| `telegram_get_history_page` | Read history with date bounds and topic selection; no read receipts. | +| `telegram_search_media` | Search messages by media type and optional text. | +| `telegram_get_replies` | Read replies/comments on a post. | +| `telegram_join_chat` | Join a group/channel. May send a join request. | +| `telegram_leave_chat` | Leave a group/channel. | +| `telegram_block_user` | Block a user. | +| `telegram_unblock_user` | Unblock a user. | +| `telegram_delete_contact` | Delete a contact from your address book. | +| `telegram_add_contact` | Add a contact; first_name is required for phone-number input. | +| `telegram_send_reply` | Send plain text, reply, forum message or channel comment. Do not retry a timed-out send. | +| `telegram_edit_message` | Edit a sent message. | +| `telegram_forward_messages` | Forward selected messages to destination. | +| `telegram_delete_messages` | Delete selected messages. Explicit for_everyone controls revocation; Telegram chat permissions still apply. | +| `telegram_react` | Add or remove a reaction. | +| `telegram_pin_message` | Pin a message, silent by default. | +| `telegram_unpin_message` | Unpin a message. | +| `telegram_download_media` | Download message attachments to an absolute local path. Existing files are not overwritten. | +| `telegram_download_profile_photo` | Download an accessible current profile photo; no overwrite. | +| `telegram_create_chat` | Create a supergroup or channel. | +| `telegram_edit_chat` | Change chat title/description with available administrator rights. | +| `telegram_send_poll` | Send an ordinary poll. Anonymous by default. | +| `telegram_audit_folders` | Read-only resumable folder audit: cursor/refresh, scan_limit up to 50000, category notification defaults, membership and overlap. Honor retry_at; audit_pending is not an empty audit. complete=false means partial scan. No message bodies/read receipts. | +| `telegram_get_folder_chats` | Compute folder membership using peers, rules and inherited mute settings. Inspect complete and note before interpreting counts. | + +## Related + +- [Документация](README.md) +- [README](../README.md) +- [Сценарии](../examples/scenarios.md) diff --git a/docs/verification.md b/docs/verification.md new file mode 100644 index 0000000..67ee1d3 --- /dev/null +++ b/docs/verification.md @@ -0,0 +1,52 @@ +# Проверка локального исходного комплекта + +Дата: 2026-11-05. Статус: владелец разрешил публикацию исходников в публичном репозитории `vik/telegram-mcp`. Этот отчёт фиксирует проверки подготовленного комплекта; бинарный релиз не выпускался. Проверки выполнялись на macOS, Python 3.13, с установленным Node, без пользовательского входа в Telegram. Linux/WSL заявлены как целевые окружения, но отдельный прогон на них ещё не выполнен. + +## Состав + +- CLI 0.6.1-teleproto.1, Teleproto 1.232.1: исходники и тесты, а не копия глобальной установки. +- Python MCP SDK 1.26.0; lockfile с хешами зависимостей. +- 61 MCP-инструмент, интерактивный login через bundled CLI, отдельное состояние main/reserve. +- Установка, запуск, генерация локальной MCP-конфигурации, четыре сценария, каталог, инструкция обновления и отката. + +## Выполненные проверки + +| Проверка | Результат | +|---|---| +| npm ci из lockfile и сборка | PASS | +| TypeScript typecheck | PASS | +| CLI suite | 107 файлов, 1373 теста — PASS | +| Python suite | 28 тестов — PASS | +| Настоящий MCP stdio | initialize, 61 схема, вызов предпросмотра — PASS | +| Отдельный распакованный каталог с пробелами в пути | setup, check, исходные 25 Python-тестов — PASS; три последующих теста экспорта отдельно прошли в основном checkout | +| Запуск без .env и без TG_SESSION | PASS | +| Удаление родительских TG_* из CLI environment | PASS | +| Поиск личных путей/профилей и credential-shaped строк | После очистки — PASS | +| Сравнение исходников с известными локальными credential values | После очистки — 0 совпадений; значения и источник проверки не включены в комплект | +| Экспорт исходников | Allowlist, запрет symlink/неожиданных расширений, manifest SHA-256 | + +Первый полный CLI-прогон с исходным автоматическим параллелизмом завершился 1372/1373: процессный тест detach превысил свой таймаут 2 секунды. При ограничении до двух workers все 1373 прошли без изменения самого теста. `manage.py test` использует этот ограниченный параллелизм. Это наблюдение о тестовом окружении, не замаскированный успешный первый прогон. + +SDK вместе с установленными Pydantic settings выводит предупреждение об аннотации lifespan; на stdio initialize/list_tools/call_tool оно не повлияло. Предупреждение не подавлено. В smoke нет реальных запросов Telegram. + +## Очистка и review + +Выполнено локальное ревью корректности, читаемости, границ модулей, конфиденциальности и запуска; независимый внешний review не заявляется. + +- Из MCP удалены личные аккаунты, фиксированные идентификаторы, профили прежней установки, поиск корневого workspace и загрузка .env. +- Глобальный tg не вызывается. Пути вычисляются относительно исходников и отдельного пользовательского хранилища. +- Живые значения Telegram client presets в upstream-тесте заменены синтетическими fixture-значениями; тесты сохранены. +- Исправлено разделение CLI-опций и текстовых аргументов базовой отправки и файлов; добавлены regression-тесты. +- Ожидание ответа получает self ID из выбранного профиля; при невозможности определить себя прекращает работу, а не принимает своё сообщение за ответ. +- Старые операционные документы, runtime, сессии и Git history не переносились. Реальная конфигурация MCP-клиента генерируется на машине пользователя и не включается в архив. +- Лицензия upstream MIT сохранена. Отдельно перечислены лицензии npm и Python-зависимостей; GPL-зависимость обнаружена в test-only reference SDK, исходники зависимостей не включены в экспорт. + +## Перед публикацией + +Название и адрес согласованы: [telegram-mcp](https://git.flowmasters.ru/vik/telegram-mcp). Порядок запроса приватного security-канала указан в SECURITY.md. Проверка с реальным Telegram-аккаунтом выполняется только по отдельному поручению. Не считать offline-тесты подтверждением всех live write-сценариев. + +## Related + +- [README](../README.md) +- [Разработка](../CONTRIBUTING.md) +- [Лицензии и происхождение](../UPSTREAM.md) diff --git a/examples/mcp-client.json b/examples/mcp-client.json new file mode 100644 index 0000000..1a4476b --- /dev/null +++ b/examples/mcp-client.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "telegram": { + "command": "/absolute/path/to/telegram-mcp/.venv/bin/python", + "args": ["/absolute/path/to/telegram-mcp/mcp_server/server.py"] + } + } +} diff --git a/examples/scenarios.md b/examples/scenarios.md new file mode 100644 index 0000000..fe2e812 --- /dev/null +++ b/examples/scenarios.md @@ -0,0 +1,32 @@ +# Четыре сценария + +Все люди и проекты в примерах вымышлены. Укажите свои выбранные чаты; примеры не запускаются автоматически. Для разовой работы явно выбирайте account="main". + +## Новости без повторов + +«Прочитай эти пять каналов за неделю. Объедини пересказы одного события, покажи разногласия авторов и ссылки на исходные посты. Не выдавай повторные перепечатки за независимые подтверждения». + +Инструменты: история за период, поиск, чтение конкретных сообщений и комментариев. ИИ сравнивает содержание. Регулярный утренний запуск требует отдельного расписания. + +## Где нужен ответ + +«Посмотри выбранные рабочие и личные чаты за сегодня. Найди вопросы ко мне, просьбы подтвердить время или принять решение. Покажи исходное сообщение и короткий контекст. Пока ничего не меняй». + +Результат — проверяемый список, а не гарантия обнаружения каждого важного сообщения. + +## Черновики + +«Подготовь ответы на выбранные вопросы, без обещаний, которых я не давал. Покажи формулировки. После моих правок сохрани черновики в этих чатах; не отправляй». + +Черновик может заменить существующий текст в чате. Перед сохранением согласуйте замену. Пустой текст очищает черновик. + +## Поездка + +«Разбери обсуждение поездки: даты, жильё, маршрут, ссылки. Раздели решения и предложения. Подготовь опрос по тому, что ещё надо выбрать. Пока покажи план». + +После одобрения: отправить опрос, закрепить выбранный итог, подготовить папку с чатами поездки. Удаление папки не удаляет чаты. Инструмента автоматического приглашения всех друзей в группу здесь нет. + +## Related + +- [README](../README.md) +- [Каталог](../docs/tools.md) diff --git a/mcp_server/extended.py b/mcp_server/extended.py new file mode 100644 index 0000000..bbf03d3 --- /dev/null +++ b/mcp_server/extended.py @@ -0,0 +1,335 @@ +"""Typed additive MCP surface. Transport/retry policy stays owned by server.py.""" +from __future__ import annotations +import json +from typing import Literal +from pathlib import Path +from pydantic import BaseModel, Field, ConfigDict +from mcp.types import ToolAnnotations + +Account = Literal["main", "reserve"] +class FolderRules(BaseModel): + model_config = ConfigDict(extra="forbid") + contacts: bool | None = None + nonContacts: bool | None = None + groups: bool | None = None + broadcasts: bool | None = None + bots: bool | None = None + excludeMuted: bool | None = None + excludeRead: bool | None = None + excludeArchived: bool | None = None + +class FolderPatch(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str | None = Field(default=None, min_length=1, max_length=12) + emoticon: str | None = None + color: int | None = Field(default=None, ge=0, le=6) + include: list[str] | None = Field(default=None, max_length=200) + exclude: list[str] | None = Field(default=None, max_length=200) + pinned: list[str] | None = Field(default=None, max_length=200) + rules: FolderRules | None = None + + +def register_tools(mcp, run, read): + def tool(write=False): + return mcp.tool(annotations=ToolAnnotations(readOnlyHint=not write, destructiveHint=write, idempotentHint=False, openWorldHint=True)) + + def error(message): + return {"ok": False, "code": "INVALID_INPUT", "error": message} + + def organize(action, account, **payload): + if account not in ("main", "reserve"): + return error("account must be main or reserve") + payload = {k: v for k, v in payload.items() if v is not None} + return run(["bridge", "call", "organize", json.dumps({"action": action, "account": account, **payload}, ensure_ascii=False)], account) + + def cli(group, action, account, positional=(), options=None, dry_run=False): + if account not in ("main", "reserve"): + return error("account must be main or reserve") + args = [group, action] + for key, value in (options or {}).items(): + if value is None or value is False: + continue + if key in ("limit",) and (type(value) is not int or not 1 <= value <= 100): + return error("limit must be 1..100") + if key == "offset" and (type(value) is not int or not 0 <= value <= 5000): + return error("offset must be 0..5000") + if value is True: + args.append("--" + key) + else: + for item in value if isinstance(value, list) else [value]: + args.append("--" + key + "=" + str(item)) + if any(not isinstance(s, str) or "\0" in s for s in positional): + return error("Arguments must be strings without NUL") + if positional: + args.extend(["--", *positional]) + if dry_run: + return {"ok": True, "data": {"dry_run": True, "account": account, "command": args}} + return run(args, account) + + def message_ids(values): + if not values or len(values) > 100 or any(type(v) is not int or v < 1 or v > 2147483647 for v in values): + raise ValueError("message_ids must contain 1..100 positive 32-bit IDs") + return ",".join(map(str, values)) + + @tool(write=False) + def telegram_list_folders(account: Account) -> dict: + """Read folder order, rules, included/excluded/pinned peer IDs and revision. Does not read messages.""" + return organize("folders", account) + + @tool(write=False) + def telegram_list_dialogs(account: Account, limit: int = 100, offset: int = 0, cursor: str | None = None, refresh: bool = False) -> dict: + """Read chat metadata without message bodies or read receipts. Cursor snapshot; pass next_offset and cursor. Wait retry_after_seconds on FloodWait. refresh starts a new snapshot. muted=null inherits defaults.""" + return organize("dialogs", account, limit=limit, offset=offset, cursor=cursor, refresh=refresh) + + @tool(write=True) + def telegram_update_folder(account: Account, folder_id: int, patch: FolderPatch, create: bool = False, revision: str | None = None, dry_run: bool = True) -> dict: + """Create or patch an ordinary folder. Omitted fields are preserved; supplied lists replace those lists. Preview first; apply requires preview revision. Shared folders are refused.""" + return organize("folder-put", account, id=folder_id, patch=patch.model_dump(exclude_none=True), create=create, revision=revision, dry_run=dry_run) + + @tool(write=True) + def telegram_delete_folder(account: Account, folder_id: int, revision: str | None = None, dry_run: bool = True) -> dict: + """Delete an ordinary folder only, not its chats. Preview first; apply requires revision.""" + return organize("folder-delete", account, id=folder_id, revision=revision, dry_run=dry_run) + + @tool(write=True) + def telegram_reorder_folders(account: Account, order: list[int], revision: str | None = None, dry_run: bool = True) -> dict: + """Reorder folders; include every current ID exactly once, including All Chats when returned. Apply requires revision.""" + return organize("folder-order", account, order=order, revision=revision, dry_run=dry_run) + + @tool(write=True) + def telegram_set_archived(account: Account, chat: str, archived: bool, dry_run: bool = True) -> dict: + """Archive or unarchive one chat.""" + return organize('archive', account, chat=chat, archived=archived, dry_run=dry_run) + + @tool(write=True) + def telegram_set_chat_pinned(account: Account, chat: str, pinned: bool, dry_run: bool = True) -> dict: + """Pin or unpin a dialog in its main/archive list. Folder pins use update_folder.""" + return organize('dialog-pin', account, chat=chat, pinned=pinned, dry_run=dry_run) + + @tool(write=True) + def telegram_set_unread(account: Account, chat: str, unread: bool, dry_run: bool = True) -> dict: + """Set or clear the manual unread mark; does not reset message read receipts.""" + return organize('unread', account, chat=chat, unread=unread, dry_run=dry_run) + + @tool(write=True) + def telegram_mark_read(account: Account, chat: str, max_id: int, dry_run: bool = True) -> dict: + """Mark messages read up to max_id; this changes read receipts.""" + return organize('read', account, chat=chat, max_id=max_id, dry_run=dry_run) + + @tool(write=True) + def telegram_set_mute(account: Account, chat: str, mute_until: int, dry_run: bool = True) -> dict: + """Set mute expiry Unix seconds: 0 unmute, 2147483647 indefinitely. Preserves other notification fields.""" + return organize('notify-set', account, chat=chat, mute_until=mute_until, dry_run=dry_run) + + @tool(write=True) + def telegram_save_draft(account: Account, chat: str, text: str, dry_run: bool = True) -> dict: + """Save a plain-text draft; empty text clears it. Does not send a message.""" + return organize('draft-save', account, chat=chat, text=text, dry_run=dry_run) + + @tool(write=False) + def telegram_get_notification_settings(account: Account, chat: str) -> dict: + """Read per-chat notification overrides. inherited=true means account defaults apply.""" + return organize("notify-get", account, chat=chat) + + @tool(write=False) + def telegram_list_scheduled_messages(account: Account, chat: str) -> dict: + """Read the server-side scheduled message queue.""" + return organize("scheduled-list", account, chat=chat) + + @tool(write=True) + def telegram_cancel_scheduled_messages(account: Account, chat: str, ids: list[int], dry_run: bool = True) -> dict: + """Cancel selected scheduled messages.""" + return organize('scheduled-delete', account, chat=chat, ids=ids, dry_run=dry_run) + + @tool(write=True) + def telegram_send_scheduled_now(account: Account, chat: str, ids: list[int], dry_run: bool = True) -> dict: + """Send selected scheduled messages now. Never retry automatically after timeout.""" + return organize('scheduled-send', account, chat=chat, ids=ids, dry_run=dry_run) + + @tool(write=False) + def telegram_get_chat_info(account: Account, chat: str) -> dict: + """Read chat details.""" + return cli('chat', 'info', account, [chat]) + + @tool(write=False) + def telegram_resolve_peer(account: Account, peer: str) -> dict: + """Resolve username or marked ID.""" + return cli('chat', 'resolve', account, [peer]) + + @tool(write=False) + def telegram_get_invite_info(account: Account, link: str) -> dict: + """Inspect invite without joining.""" + return cli('chat', 'invite-info', account, [link]) + + @tool(write=False) + def telegram_get_user_profile(account: Account, user: str) -> dict: + """Read accessible user profile.""" + return cli('user', 'profile', account, [user]) + + @tool(write=False) + def telegram_list_members(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict: + """List accessible members; Telegram may restrict completeness.""" + return cli('chat', 'members', account, [chat], {"limit": limit, "offset": offset}) + + @tool(write=False) + def telegram_list_topics(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict: + """List forum topics.""" + return cli('chat', 'topics', account, [chat], {"limit": limit, "offset": offset}) + + @tool(write=False) + def telegram_list_pinned_messages(account: Account, chat: str, limit: int = 50, offset: int = 0) -> dict: + """Read pinned messages.""" + return cli('message', 'pinned', account, [chat], {"limit": limit, "offset": offset}) + + @tool(write=False) + def telegram_list_contacts(account: Account, limit: int = 50, offset: int = 0) -> dict: + """Read contacts.""" + return cli('contact', 'list', account, [], {"limit": limit, "offset": offset}) + + @tool(write=False) + def telegram_list_blocked_users(account: Account, limit: int = 50, offset: int = 0) -> dict: + """Read blocked users.""" + return cli('user', 'blocked', account, [], {"limit": limit, "offset": offset}) + + @tool(write=False) + def telegram_search_public_chats(account: Account, query: str, limit: int = 20) -> dict: + """Search by name; does not join or contact anyone.""" + return cli('chat', 'search', account, [query], {"limit": limit}) + + @tool(write=False) + def telegram_search_contacts(account: Account, query: str, limit: int = 20) -> dict: + """Search by name; does not join or contact anyone.""" + return cli('contact', 'search', account, [query], {"limit": limit}) + + @tool(write=False) + def telegram_get_history_page(account: Account, chat: str, limit: int = 50, offset: int = 0, since: str | None = None, until: str | None = None, topic_id: int | None = None) -> dict: + """Read history with date bounds and topic selection; no read receipts.""" + return cli("message", "history", account, [chat], {"limit": limit, "offset": offset, "since": since, "until": until, "topic": topic_id}) + + @tool(write=False) + def telegram_search_media(account: Account, chat: str, media_type: Literal["photos", "videos", "documents", "urls", "voice", "music", "gifs", "round", "photo_video", "round_voice", "chat_photos", "phone_calls", "mentions", "geo", "contacts", "pinned"], query: str = "", limit: int = 50, offset: int = 0, topic_id: int | None = None) -> dict: + """Search messages by media type and optional text.""" + return cli("message", "search", account, options={"chat": chat, "filter": media_type, "query": query, "limit": limit, "offset": offset, "topic": topic_id}) + + @tool(write=False) + def telegram_get_replies(account: Account, chat: str, post_id: int, limit: int = 50, offset: int = 0) -> dict: + """Read replies/comments on a post.""" + if post_id < 1: return error("post_id must be positive") + return cli("message", "replies", account, [chat, str(post_id)], {"limit": limit, "offset": offset}) + + @tool(write=True) + def telegram_join_chat(account: Account, target: str, dry_run: bool = True) -> dict: + """Join a group/channel. May send a join request.""" + return cli('chat', 'join', account, [target], dry_run=dry_run) + + @tool(write=True) + def telegram_leave_chat(account: Account, chat: str, dry_run: bool = True) -> dict: + """Leave a group/channel.""" + return cli('chat', 'leave', account, [chat], dry_run=dry_run) + + @tool(write=True) + def telegram_block_user(account: Account, user: str, dry_run: bool = True) -> dict: + """Block a user.""" + return cli('user', 'block', account, [user], dry_run=dry_run) + + @tool(write=True) + def telegram_unblock_user(account: Account, user: str, dry_run: bool = True) -> dict: + """Unblock a user.""" + return cli('user', 'unblock', account, [user], dry_run=dry_run) + + @tool(write=True) + def telegram_delete_contact(account: Account, user: str, dry_run: bool = True) -> dict: + """Delete a contact from your address book.""" + return cli('contact', 'delete', account, [user], dry_run=dry_run) + + @tool(write=True) + def telegram_add_contact(account: Account, user: str, first_name: str | None = None, last_name: str | None = None, dry_run: bool = True) -> dict: + """Add a contact; first_name is required for phone-number input.""" + return cli("contact", "add", account, [user], {"first-name": first_name, "last-name": last_name}, dry_run) + + @tool(write=True) + def telegram_send_reply(account: Account, chat: str, text: str, reply_to: int | None = None, topic_id: int | None = None, comment_to: int | None = None, dry_run: bool = True) -> dict: + """Send plain text, reply, forum message or channel comment. Do not retry a timed-out send.""" + if not text or len(text) > 4096 or text == "-": return error("text must be 1..4096 characters, not a stdin marker") + if comment_to is not None and (reply_to is not None or topic_id is not None): return error("comment_to cannot be combined with reply_to/topic_id") + return cli("message", "send", account, [chat, text], {"reply-to": reply_to, "topic": topic_id, "comment-to": comment_to}, dry_run) + + @tool(write=True) + def telegram_edit_message(account: Account, chat: str, message_id: int, text: str, dry_run: bool = True) -> dict: + """Edit a sent message.""" + if message_id < 1 or not text or len(text) > 4096 or text == "-": return error("Invalid message_id or text") + return cli("message", "edit", account, [chat, str(message_id), text], dry_run=dry_run) + + @tool(write=True) + def telegram_forward_messages(account: Account, chat: str, ids: list[int], destination: str, dry_run: bool = True) -> dict: + """Forward selected messages to destination.""" + try: joined = message_ids(ids) + except ValueError as exc: return error(str(exc)) + return cli("message", "forward", account, [chat, joined, destination], dry_run=dry_run) + + @tool(write=True) + def telegram_delete_messages(account: Account, chat: str, ids: list[int], for_everyone: bool, dry_run: bool = True) -> dict: + """Delete selected messages. Explicit for_everyone controls revocation; Telegram chat permissions still apply.""" + try: joined = message_ids(ids) + except ValueError as exc: return error(str(exc)) + return cli("message", "delete", account, [chat, joined], {"revoke": for_everyone, "for-me": not for_everyone}, dry_run) + + @tool(write=True) + def telegram_react(account: Account, chat: str, message_id: int, emoji: str, remove: bool = False, dry_run: bool = True) -> dict: + """Add or remove a reaction.""" + if message_id < 1: return error("message_id must be positive") + return cli("message", "react", account, [chat, str(message_id), emoji], {"remove": remove}, dry_run) + + @tool(write=True) + def telegram_pin_message(account: Account, chat: str, message_id: int, notify: bool = False, dry_run: bool = True) -> dict: + """Pin a message, silent by default.""" + if message_id < 1: return error("message_id must be positive") + return cli("message", "pin", account, [chat, str(message_id)], {"notify": notify}, dry_run) + + @tool(write=True) + def telegram_unpin_message(account: Account, chat: str, message_id: int, dry_run: bool = True) -> dict: + """Unpin a message.""" + if message_id < 1: return error("message_id must be positive") + return cli("message", "unpin", account, [chat, str(message_id)], dry_run=dry_run) + + @tool(write=False) + def telegram_download_media(account: Account, chat: str, ids: list[int], output_path: str) -> dict: + """Download message attachments to an absolute local path. Existing files are not overwritten.""" + try: joined = message_ids(ids) + except ValueError as exc: return error(str(exc)) + if not Path(output_path).is_absolute(): return error("output_path must be absolute") + return cli("media", "download", account, [chat, joined], {"output": output_path}) + + @tool(write=False) + def telegram_download_profile_photo(account: Account, user: str, output_path: str) -> dict: + """Download an accessible current profile photo; no overwrite.""" + if not Path(output_path).is_absolute(): return error("output_path must be absolute") + return cli("user", "download-photo", account, [user], {"output": output_path}) + + @tool(write=True) + def telegram_create_chat(account: Account, title: str, chat_type: Literal["supergroup", "channel"] = "supergroup", description: str | None = None, dry_run: bool = True) -> dict: + """Create a supergroup or channel.""" + return cli("chat", "create", account, [title], {"type": chat_type, "description": description}, dry_run) + + @tool(write=True) + def telegram_edit_chat(account: Account, chat: str, title: str | None = None, description: str | None = None, dry_run: bool = True) -> dict: + """Change chat title/description with available administrator rights.""" + if title is None and description is None: return error("Provide title or description") + return cli("chat", "edit", account, [chat], {"title": title, "description": description}, dry_run) + + @tool(write=True) + def telegram_send_poll(account: Account, chat: str, question: str, options: list[str], multiple: bool = False, public: bool = False, dry_run: bool = True) -> dict: + """Send an ordinary poll. Anonymous by default.""" + if not 2 <= len(options) <= 10 or not question or len(question) > 300: return error("Expected question up to 300 characters and 2..10 options") + return cli("message", "poll", account, [chat], {"question": question, "option": options, "multiple": multiple, "public": public}, dry_run) + + + @tool() + def telegram_audit_folders(account: Account, scan_limit: int = 1000, cursor: str | None = None, refresh: bool = False) -> dict: + """Read-only folder audit: computed membership, overlap, uncategorized chats, bounded counts. complete=false means partial scan. No message bodies/read receipts.""" + return organize("audit", account, scan_limit=scan_limit, cursor=cursor, refresh=refresh) + + @tool() + def telegram_get_folder_chats(account: Account, folder_id: int, scan_limit: int = 1000, cursor: str | None = None, refresh: bool = False) -> dict: + """Compute folder membership using peers, rules and inherited mute settings. Inspect complete and note before interpreting counts.""" + return organize("audit", account, folder_id=folder_id, scan_limit=scan_limit, cursor=cursor, refresh=refresh) diff --git a/mcp_server/format_toon.mjs b/mcp_server/format_toon.mjs new file mode 100644 index 0000000..dc6cdd9 --- /dev/null +++ b/mcp_server/format_toon.mjs @@ -0,0 +1,8 @@ +// Local JSON -> TOON conversion using the already installed tg-cli dependency. +import { createRequire } from 'node:module'; +import { realpathSync, readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +const require = createRequire(realpathSync(process.argv[2])); +const { encode } = await import(pathToFileURL(require.resolve('@toon-format/toon')).href); +process.stdout.write(encode(JSON.parse(readFileSync(0, 'utf8'))) + '\n'); diff --git a/mcp_server/runtime.py b/mcp_server/runtime.py new file mode 100644 index 0000000..2592d7c --- /dev/null +++ b/mcp_server/runtime.py @@ -0,0 +1,34 @@ +"""Resolve portable paths; never load a workspace .env or a global tg install.""" +from pathlib import Path +import os +import shutil + +ROOT = Path(__file__).resolve().parents[1] + + +def resolve_account(account: str) -> str: + if account not in ("main", "reserve"): + raise ValueError("account must be main or reserve") + return account + + +def state_directory() -> Path: + configured = os.environ.get("TG_MCP_STATE_DIR") + path = Path(configured).expanduser() if configured else Path.home() / ".local" / "share" / "telegram-mcp" + if not path.is_absolute(): + raise ValueError("TG_MCP_STATE_DIR must be absolute") + return path + + +def child_environment(account: str) -> dict[str, str]: + resolve_account(account) + # Account identity and credentials come from this bundle's CLI profile. + # Never accidentally inherit another integration's Telegram credentials. + return {k: v for k, v in os.environ.items() if not k.startswith("TG_")} + + +def cli_command(account: str) -> list[str]: + resolve_account(account) + return [shutil.which("node") or "node", str(ROOT / "cli" / "dist" / "bin" / "tg.js"), + "--config", str(state_directory() / "config.json"), + "--quiet", "--profile", account] diff --git a/mcp_server/server.py b/mcp_server/server.py new file mode 100644 index 0000000..202a7db --- /dev/null +++ b/mcp_server/server.py @@ -0,0 +1,409 @@ +"""Portable Telegram MCP backed by the bundled Teleproto CLI.""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import time +from pathlib import Path +from urllib.parse import urlparse + +from mcp.server.fastmcp import FastMCP +from runtime import cli_command, child_environment, resolve_account + +mcp = FastMCP("telegram") +_resolve_account = resolve_account +_tg_env = child_environment + + +def _self_id(account: str) -> str: + result = _run(["user", "profile", "me"], account, 30) + profiles = result.get("data", {}).get("profiles", []) + if not result.get("ok") or not profiles or not profiles[0].get("id"): + raise ValueError("Cannot identify the selected account") + return str(profiles[0]["id"]) + + +def _invoke(args: list[str], account: str, timeout: int = 60) -> dict: + """One CLI invocation; never replay a potentially submitted operation.""" + try: + env = _tg_env(account) + except ValueError as e: + return {"ok": False, "error": str(e)} + + tg_cmd = cli_command(account) + args + try: + result = subprocess.run( + tg_cmd, + capture_output=True, + text=True, + timeout=timeout, + env=env, + ) + except FileNotFoundError: + return { + "ok": False, + "error": "Bundled CLI not available; run python3 scripts/manage.py setup", + } + except subprocess.TimeoutExpired: + return {"ok": False, "code": "TIMEOUT", "error": f"timeout {timeout}s; operation outcome may be unknown; verify before retrying"} + + stdout = (result.stdout or "").strip() + if not stdout: + return {"ok": False, "code": "CLI_NO_OUTPUT", "error": "tg returned no structured output"} + + json_lines = [ln for ln in stdout.splitlines() if ln.strip().startswith("{")] + if not json_lines: + return {"ok": False, "code": "CLI_INVALID_OUTPUT", "error": "tg returned no JSON envelope"} + try: + envelope = json.loads(json_lines[-1]) + if not isinstance(envelope, dict) or not isinstance(envelope.get("ok"), bool): + raise ValueError("invalid envelope") + if result.returncode: + # Upstream can return ok:true plus partial data and exit status 1. + envelope["ok"] = False + data = envelope.get("data") + partial = isinstance(data, dict) and data.get("partial") + envelope.setdefault("code", "PARTIAL_FAILURE" if partial else "CLI_FAILED") + envelope.setdefault("error", "Some operations failed; inspect data.errors" if envelope["code"] == "PARTIAL_FAILURE" else "CLI operation failed") + return envelope + except (ValueError, TypeError): + return {"ok": False, "code": "CLI_INVALID_OUTPUT", "error": "Invalid JSON envelope"} + + +def _ensure_daemon(account: str) -> dict: + status = _invoke(["daemon", "status"], account, 15) + if not status.get("ok"): + return status + if not status.get("data", {}).get("running"): + started = _invoke(["daemon", "start", "--idle-timeout", "300"], account, 25) + # Another MCP process may have started this profile concurrently. + if not started.get("ok") and started.get("code") != "DAEMON_ALREADY_RUNNING": + return started + status = _invoke(["daemon", "status"], account, 15) + data = status.get("data", {}) + if not status.get("ok") or not data.get("connected") or "execute" not in data.get("capabilities", []): + return {"ok": False, "code": "DAEMON_NOT_READY", "error": "Daemon is not connected or lacks execute; inspect daemon status"} + return status + + +def _run(args: list[str], account: str = "main", timeout: int = 60) -> dict: + result = _invoke(["--daemon", *args], account, timeout) + # This code is emitted before opening an API socket: nothing was submitted. + # Never retry timeouts, disconnected sockets, or any Telegram/API error. + if result.get("code") != "DAEMON_NOT_RUNNING": + return result + ready = _ensure_daemon(account) + if not ready.get("ok"): + return ready + return _invoke(["--daemon", *args], account, timeout) + + +def _read(args: list[str], account: str, fields: str | None, output_format: str) -> dict: + if output_format not in {"json", "toon"}: + return {"ok": False, "code": "INVALID_INPUT", "error": "output_format must be json or toon"} + if fields: + if not re.fullmatch(r"[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*(?:,[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)*", fields): + return {"ok": False, "code": "INVALID_INPUT", "error": "fields must be comma-separated field paths"} + args = ["--fields", fields, *args] + result = _run(args, account) + if output_format == "json": + return result + # Format locally after parsing JSON so errors and exit status stay structured. + try: + formatted = subprocess.run( + [cli_command(account)[0], str(Path(__file__).with_name("format_toon.mjs")), cli_command(account)[1]], + input=json.dumps(result, ensure_ascii=False), capture_output=True, text=True, timeout=10, + ) + if formatted.returncode: + raise ValueError("TOON conversion failed") + return {"ok": result["ok"], "format": "toon", "text": formatted.stdout.strip(), + **({"code": result.get("code"), "error": result.get("error")} if not result["ok"] else {})} + except (OSError, ValueError, subprocess.TimeoutExpired): + return {"ok": False, "code": "FORMAT_ERROR", "error": "TOON conversion failed", "result": result} + + +@mcp.tool() +def telegram_send_message(chat: str, text: str, account: str = "main") -> dict: + """Отправить текстовое сообщение в Telegram. + + Args: + chat: username (без @) или user_id или chat_id. Пример: "example_chat". + text: текст сообщения (до 4096 символов). + account: "main" (default) или "reserve". + Для main — только ad-hoc, не массовая рассылка (риск бана). + """ + return _run(["message", "send", "--", chat, text], account=account) + + +@mcp.tool() +def telegram_send_html(chat: str, html: str, account: str = "main") -> dict: + """Отправить HTML-оформленное сообщение в Telegram. + + Единственный форматированный режим этого MCP — HTML; Markdown не используется. + Поддерживаемые HTML-теги: b/strong, i/em, u, s/del, spoiler, + a, code, pre/code class="language-…", blockquote и blockquote expandable. + Символы <, > и & в данных, не являющихся тегами, необходимо экранировать. + """ + if len(html) > 4096: + return {"ok": False, "error": "Message too long (max 4096 chars before parsing)"} + return _bridge("html", {"chat": chat, "text": html}, account) + + +@mcp.tool() +def telegram_schedule_message( + chat: str, text: str, when_iso: str, account: str = "main" +) -> dict: + """Запланировать отправку текстового сообщения на конкретное время (server-side). + + Сообщение хранится у Telegram-сервера и доставляется в указанный момент — + мак может быть выключен/спать, доставка от этого не зависит. + + Args: + chat: username (без @) / user_id / chat_id. + text: текст сообщения (до 4096 символов). + when_iso: момент отправки в ISO 8601, желательно с таймзоной. + Пример: "2026-05-06T09:00:00+03:00" (9:00 МСК). + Минимум 10 секунд в будущем. + account: "main" (default) или "reserve". + + Возвращает {"ok": True, "data": {"id": <schedule_id>, "scheduled_for": <ISO>, ...}} + или {"ok": False, "error": "..."}. + + Операция выполняется через CLI bridge на соединении демона выбранного + профиля. После таймаута не повторять без проверки очереди Telegram. + """ + if len(text) > 4096: + return {"ok": False, "error": "Message too long (max 4096 chars)"} + + return _bridge("schedule", {"chat": chat, "text": text, "when": when_iso}, account) + + +@mcp.tool() +def telegram_send_file( + chat: str, file_path: str, caption: str | None = None, account: str = "main" +) -> dict: + """Отправить файл (документ или фото) в Telegram. + + Args: + chat: username (без @) или user_id / chat_id. + file_path: абсолютный путь к файлу. Форматы — любые; tg-cli сам определит тип. + caption: подпись к файлу (опционально). + account: "main" (default) или "reserve". + """ + if not Path(file_path).exists(): + return {"ok": False, "error": f"File not found: {file_path}"} + + args = ["media", "send"] + if caption: + args += ["--caption=" + caption] + args += ["--", chat, file_path] + return _run(args, account=account, timeout=120) + + +@mcp.tool() +def telegram_read_history(chat: str, limit: int = 5, account: str = "main", + fields: str | None = None, output_format: str = "json") -> dict: + """Прочитать последние сообщения из чата. + + Args: + chat: username или user_id. + limit: сколько сообщений вернуть (1–100). + account: "main" (default) или "reserve". + fields: поля через запятую, например id,text,date,senderId. По умолчанию все. + output_format: json (структура) или toon (компактный текст). + """ + limit = max(1, min(int(limit), 100)) + return _read(["message", "history", "--limit", str(limit), "--", chat], account, fields, output_format) + + +def _message_target(chat: str, message_ids: str | None) -> tuple[str, str]: + if chat.startswith(("https://", "http://")): + link = urlparse(chat) + if link.hostname not in {"t.me", "www.t.me", "telegram.me"} or message_ids: + raise ValueError("Use a Telegram post link alone, or chat plus message_ids") + parts = link.path.strip("/").split("/") + if parts[0] == "s": + parts = parts[1:] + if len(parts) in {3, 4} and parts[0] == "c" and parts[1].isdigit(): + chat, message_ids = "-100" + parts[1], parts[-1] + if len(parts) == 4 and not parts[2].isdigit(): + raise ValueError("Invalid topic ID") + elif len(parts) in {2, 3}: + chat, message_ids = parts[0], parts[-1] + if len(parts) == 3 and not parts[1].isdigit(): + raise ValueError("Invalid topic ID") + else: + raise ValueError("Expected a Telegram post link") + if not re.fullmatch(r"(?:@?[A-Za-z][A-Za-z0-9_]*|-?\d+)", chat): + raise ValueError("Invalid chat") + ids = (message_ids or "").split(",") + if not 1 <= len(ids) <= 100 or any(not x.isdigit() or not 0 < int(x) <= 2147483647 for x in ids): + raise ValueError("message_ids must contain 1–100 positive message IDs separated by commas") + return chat, ",".join(ids) + + +@mcp.tool() +def telegram_get_messages(chat: str, message_ids: str | None = None, account: str = "main", + fields: str | None = None, output_format: str = "json") -> dict: + """Прочитать конкретные сообщения без загрузки истории. + + chat: username/ID или ссылка https://t.me/channel/475 (также /c/ и темы). + message_ids: ID через запятую; при ссылке не указывать. + account: выбранный профиль main или reserve. + fields: поля через запятую, например id,text,date. output_format: json или toon. + """ + try: + chat, ids = _message_target(chat, message_ids) + except ValueError as error: + return {"ok": False, "code": "INVALID_INPUT", "error": str(error)} + return _read(["message", "get", chat, ids], account, fields, output_format) + + +@mcp.tool() +def telegram_search_messages(query: str, chat: str | None = None, limit: int = 10, + account: str = "main", fields: str | None = None, + output_format: str = "json") -> dict: + """Поиск сообщений в доступных диалогах или одном chat; json/toon и выбор fields.""" + args = ["message", "search", "--query", query, "--limit", str(max(1, min(int(limit), 100)))] + if chat: + args += ["--chat", chat] + return _read(args, account, fields, output_format) + + +def _bridge(operation: str, payload: dict, account: str) -> dict: + try: + key = _resolve_account(account) + except ValueError as error: + return {"ok": False, "code": "INVALID_INPUT", "error": str(error)} + return _run(["bridge", "call", operation, json.dumps({**payload, "account": key}, ensure_ascii=False)], key, 120) + + +def _stories_call(payload: dict, account: str) -> dict: + return _bridge("stories", payload, account) + + +def _story_chat(chat: str) -> str: + chat = chat.strip() + if chat.startswith("https://t.me/"): + chat = chat.removeprefix("https://t.me/").strip("/") + if not re.fullmatch(r"@?[A-Za-z][A-Za-z0-9_]{3,31}", chat): + raise ValueError("Use a Telegram username or https://t.me/username") + return chat.lstrip("@") + + +@mcp.tool() +def telegram_list_stories(chat: str, kind: str = "pinned", limit: int = 20, + offset_id: int = 0, account: str = "main") -> dict: + """Список сохранённых в профиле (pinned) или действующих (active) историй. + + chat: username или ссылка на канал/пользователя; limit 1–100. + Для pinned offset_id — ID последней истории предыдущей страницы. + Для active offset_id не поддерживается. Разовое чтение: account="main". + Содержимое картинок доступно отдельно через telegram_download_story_media. + """ + try: + chat = _story_chat(chat) + if kind not in {"pinned", "active"} or not 1 <= limit <= 100 or not 0 <= offset_id <= 2147483647 or (kind == "active" and offset_id): + raise ValueError("Invalid kind, limit or offset_id") + except (ValueError, TypeError) as error: + return {"ok": False, "code": "INVALID_INPUT", "error": str(error)} + return _stories_call({"action": "list", "chat": chat, "kind": kind, "limit": limit, "offset_id": offset_id}, account) + + +@mcp.tool() +def telegram_get_story(chat: str, story_id: int, account: str = "main") -> dict: + """Прочитать метаданные и подпись одной истории по username и ID.""" + try: + chat = _story_chat(chat) + if not 0 < story_id <= 2147483647: + raise ValueError("story_id must be positive") + except (ValueError, TypeError) as error: + return {"ok": False, "code": "INVALID_INPUT", "error": str(error)} + return _stories_call({"action": "get", "chat": chat, "story_id": story_id}, account) + + +@mcp.tool() +def telegram_download_story_media(chat: str, story_id: int, account: str = "main") -> dict: + """Скачать фото или видео истории во временную локальную папку (не более 30 МБ). + + Возвращает абсолютный путь для просмотра или распознавания; OCR не выполняется. + Нет автоматического распознавания, отметки прочтения или инкремента просмотров. + """ + try: + chat = _story_chat(chat) + if not 0 < story_id <= 2147483647: + raise ValueError("story_id must be positive") + except (ValueError, TypeError) as error: + return {"ok": False, "code": "INVALID_INPUT", "error": str(error)} + return _stories_call({"action": "download", "chat": chat, "story_id": story_id}, account) + + +@mcp.tool() +def telegram_wait_for_reply( + chat: str, + after_id: int, + timeout: int = 60, + poll_interval: int = 5, + account: str = "main", +) -> dict: + """Ждать ответ от бота/собеседника в чате после сообщения с указанным id. + + Args: + chat: username или user_id. + after_id: id сообщения, после которого ждём ответа. + timeout: максимальное время ожидания в секундах. + poll_interval: интервал опроса истории (в секундах). + account: "main" (default) или "reserve". + """ + try: + self_id = _self_id(account) + except ValueError as error: + return {"ok": False, "code": "AUTH_CHECK_FAILED", "error": str(error)} + deadline = time.time() + max(1, int(timeout)) + while time.time() < deadline: + history = _run( + ["message", "history", "--limit", "3", "--json", "--", chat], + account=account, + timeout=15, + ) + if history.get("ok") and "data" in history: + messages = history["data"] + if isinstance(messages, dict): + messages = messages.get("messages", []) + for msg in messages: + msg_id = int(msg.get("id", 0) or 0) + sender = str(msg.get("senderId", "") or "") + if msg_id > int(after_id) and sender != self_id: + return {"ok": True, "data": msg} + time.sleep(max(1, int(poll_interval))) + return {"ok": False, "error": "timeout, no reply received"} + + +@mcp.tool() +def telegram_auth_status(account: str = "main") -> dict: + """Проверить авторизацию выбранного аккаунта в tg-cli. + + Args: + account: "main" (default) или "reserve". + """ + # auth status opens a direct session and cannot run beside the daemon. + result = _run(["user", "profile", "me"], account=account, timeout=30) + if not result.get("ok"): + return result + profiles = result.get("data", {}).get("profiles", []) + if not profiles: + return {"ok": False, "code": "AUTH_CHECK_FAILED", "error": "No self profile returned"} + user = profiles[0] + return {"ok": True, "data": {"authorized": True, "user": { + key: user.get(key) for key in ("id", "phone", "username", "firstName") + }}} + + +from extended import register_tools +register_tools(mcp, _run, _read) + + +if __name__ == "__main__": + mcp.run() diff --git a/requirements.in b/requirements.in new file mode 100644 index 0000000..9bc0194 --- /dev/null +++ b/requirements.in @@ -0,0 +1 @@ +mcp==1.26.0 diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 0000000..d331e6f --- /dev/null +++ b/requirements.lock @@ -0,0 +1,568 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile requirements.in --generate-hashes -o requirements.lock --python-version 3.11 +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 + # via pydantic +anyio==4.16.0 \ + --hash=sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb \ + --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026 + # via + # httpx + # mcp + # sse-starlette + # starlette +attrs==26.1.0 \ + --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \ + --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32 + # via + # jsonschema + # referencing +certifi==2026.10.23 \ + --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \ + --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1 + # via + # httpcore + # httpx +cffi==2.1.1 \ + --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \ + --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \ + --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \ + --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \ + --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \ + --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \ + --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \ + --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \ + --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \ + --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \ + --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \ + --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \ + --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \ + --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \ + --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \ + --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \ + --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \ + --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \ + --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \ + --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \ + --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \ + --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \ + --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \ + --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \ + --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \ + --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \ + --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \ + --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \ + --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \ + --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \ + --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \ + --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \ + --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \ + --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \ + --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \ + --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \ + --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \ + --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \ + --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \ + --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \ + --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \ + --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \ + --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \ + --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \ + --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \ + --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \ + --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \ + --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \ + --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \ + --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \ + --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \ + --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \ + --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \ + --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \ + --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \ + --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \ + --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \ + --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \ + --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \ + --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \ + --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \ + --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \ + --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \ + --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \ + --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \ + --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \ + --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \ + --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \ + --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \ + --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \ + --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \ + --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \ + --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \ + --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \ + --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \ + --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \ + --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \ + --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \ + --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \ + --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \ + --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \ + --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \ + --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \ + --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \ + --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \ + --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \ + --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \ + --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \ + --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \ + --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \ + --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \ + --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \ + --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \ + --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \ + --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \ + --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \ + --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \ + --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \ + --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \ + --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264 + # via cryptography +click==8.5.0 \ + --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ + --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 + # via uvicorn +cryptography==50.0.2 \ + --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \ + --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \ + --hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \ + --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \ + --hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \ + --hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \ + --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \ + --hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \ + --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \ + --hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \ + --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \ + --hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \ + --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \ + --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \ + --hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \ + --hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \ + --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \ + --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \ + --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \ + --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \ + --hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \ + --hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \ + --hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \ + --hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \ + --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \ + --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \ + --hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \ + --hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \ + --hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \ + --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \ + --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \ + --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \ + --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \ + --hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \ + --hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \ + --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \ + --hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \ + --hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \ + --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \ + --hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \ + --hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \ + --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \ + --hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \ + --hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \ + --hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \ + --hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \ + --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \ + --hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \ + --hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \ + --hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \ + --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \ + --hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \ + --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \ + --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \ + --hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \ + --hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \ + --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \ + --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \ + --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b + # via pyjwt +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via + # httpcore + # uvicorn +httpcore==1.0.9 \ + --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ + --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + # via httpx +httpx==0.28.1 \ + --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ + --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad + # via mcp +httpx-sse==0.4.3 \ + --hash=sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc \ + --hash=sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d + # via mcp +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # anyio + # httpx +jsonschema==4.26.0 \ + --hash=sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326 \ + --hash=sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce + # via mcp +jsonschema-specifications==2025.9.1 \ + --hash=sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe \ + --hash=sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d + # via jsonschema +mcp==1.26.0 \ + --hash=sha256:904a21c33c25aa98ddbeb47273033c435e595bbacfdb177f4bd87f6dceebe1ca \ + --hash=sha256:db6e2ef491eecc1a0d93711a76f28dec2e05999f93afd48795da1c1137142c66 + # via -r requirements.in +pycparser==3.12 \ + --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \ + --hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6 + # via cffi +pydantic==2.14.3 \ + --hash=sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d \ + --hash=sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8 + # via + # mcp + # pydantic-settings +pydantic-core==2.50.4 \ + --hash=sha256:0001d6920e3a5d92758cda460d6dc9f918a78ad6d5d092f1c8b5395e6b775356 \ + --hash=sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444 \ + --hash=sha256:09450778e3ab58d3f565899fcfbf6c82926e31af29e28e799d1d50941316e0cb \ + --hash=sha256:0af56dbf8822ba9f4efcbbfdc15478f8b6fb08f1609860cb50aa2cc8476b3c34 \ + --hash=sha256:0b059a7968b1911be5a2d9a8234827ab0bef9d1e465d4b42da525894143550e8 \ + --hash=sha256:0ec20aca2b067369913716847f7dfe5f4dddf16a46965b7a70bbad5defaaba86 \ + --hash=sha256:0f87ae9db5ba8d8de40dcb93982cf8dd544e6552a80d3345af51941cc2146b80 \ + --hash=sha256:1239daaf063e62213ca1f34d96663900bd7510c42a786e843fd328af70e46445 \ + --hash=sha256:13b6dd62b5279f5b9d72f3bf918a35443ee8bd549241d9dc52d79a2c3b6d7016 \ + --hash=sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f \ + --hash=sha256:16902a147b3da4840612164a5e67947104d63e978f7a57c395877a5e26690b9c \ + --hash=sha256:1afefe44ec042fbabfb4483ea258c04cf75ff4ff328d754f09b321fdaa232aca \ + --hash=sha256:1de7be9a66fc8536770481ab64a05aae5067c725f2b29a09543af00e6a417b97 \ + --hash=sha256:1e20cbde2b6deb33a51d08cd168454dd9044ec7d4474056f4d98d63f51578783 \ + --hash=sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317 \ + --hash=sha256:219114f8dcdcbe4720d82ef016b1287ce5a0a67d7c69ca61524eb72e82aac344 \ + --hash=sha256:22e874666bdbd96d6bf629d32cd8ab376fedf1fd62585b52a42b9fa9fa6c20b6 \ + --hash=sha256:23a9ba564b2db709ff16eca990992ba95a19069972b34bff87c81d4b473cd755 \ + --hash=sha256:25e7e1080f9f7ce7cd9d114b31470ce912771bd02f38c824721d3c35d312abff \ + --hash=sha256:26cb012c4b8ca9f847bd0ac15978bd3d0f55b050bfbe6c47355edfc7e945029b \ + --hash=sha256:29358a8ca74e7d81158d14e2b10c904bd18773293ae3788716c0626fe0342347 \ + --hash=sha256:2980a701be88f9128a7470189fa3bcda5387f76c298a6f8e000fc29eb2a6f4e7 \ + --hash=sha256:2a60ec2a57ac3ef3767e526e9bf706ec75aa3d79c4ea134d9d4fcf7c62a297a7 \ + --hash=sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372 \ + --hash=sha256:2f5cc5bcb94063fbbdfd285a2b302da34af07491337c10bb35de1d5220fa1583 \ + --hash=sha256:2f6767122b37c780bb756a720a4eef2bc6a050a0a1143428834b3cbc89448bd2 \ + --hash=sha256:300753f71c73302e218124baf995f00058e085cd01869bd9610bcbd0bd4500c1 \ + --hash=sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b \ + --hash=sha256:32a991aebd165f227b7c7c60bb9d66c2c7de9c24308552da264c9938fde0f8d6 \ + --hash=sha256:32d6dda86383645ec428ea64dfc277036f5cbc60a72238eab28b91a3fdb9a113 \ + --hash=sha256:33b21f69540a12c2053cd1d95766d8bd9667a3897f7c712a642de8aa37eb0865 \ + --hash=sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe \ + --hash=sha256:3a48a5254d15a0ad050318bfc7a9566d4ec740118187e8f303e47a6840287eb7 \ + --hash=sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882 \ + --hash=sha256:3de6c2a4df2af0ac9ab4dc1488746fe8b1a90e27955d870d9edda3187d20092b \ + --hash=sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519 \ + --hash=sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf \ + --hash=sha256:41b2cd8b29dbb5a4c9828a70f50d1abfc92011115c813213d3a91205c6f731b3 \ + --hash=sha256:41f4f8ae714e4fea1d635880f8a1af715ecf080eed4d13c5b04a0f3210f9c61a \ + --hash=sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b \ + --hash=sha256:477af785d1846e4e96bf56983b92ea7553aaeccdeb8acdaa55c7cee9eda0ae32 \ + --hash=sha256:49eb1241a969a5994db6880c18c012b6cbe2340343d8f529721571806583e500 \ + --hash=sha256:4c29b8f2d6417069bb1f257e6b9113f5d64dc2f554cc200ea90b4fe2c5cdb733 \ + --hash=sha256:4eb15be588407148ef5937dc8d9256a71f6b115e6cddadb7aa20b6ee384680dc \ + --hash=sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20 \ + --hash=sha256:523466eba8ee10f7480f3c2057563145978011c583130d2cc01fb1e7af808e25 \ + --hash=sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69 \ + --hash=sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7 \ + --hash=sha256:5bc1811ef2b4d4ba63e8e452f6e332b6374bd1d2cbbfdf66826c8cb1f71dd10d \ + --hash=sha256:5c074454dc6d4f6f4ba6561a56bf33a14db7651d882a5a5321ba3ae8868e082d \ + --hash=sha256:5c1013647be741647895c102831dcf79c34209662dbb683df9efb864417ed7d5 \ + --hash=sha256:601fce6cea9ddeaa85329e12e7f351def38d233075f42a3012b9c48071b02941 \ + --hash=sha256:6118e5a5550e36582e19bac1a403711a748f9f18251b054c326d3db02aaa7a18 \ + --hash=sha256:629eae995185540406e3635df5d5cf1d44f19ea240840b835d3f44541ff694d8 \ + --hash=sha256:6348ad12fa741bcc9c2f173e99fbf27cbc038826d8c31a4a7d836eca27878ba2 \ + --hash=sha256:65376dbe1ab4dbc768ca2b72b7c13993562c035f5925fd3bc7ff9c8c585c515d \ + --hash=sha256:6619d49a89a15cd04334f76fec530c155923bfc60da74ff5d815a52629e1aa6c \ + --hash=sha256:664e74848c2f5fc27db8505fe24e1ecd3ac669412913bf73d176916f86cc08e2 \ + --hash=sha256:67f7cc397e1d5556a801d1cba74de0d27d827eb242e6c036c0ca273c745414f1 \ + --hash=sha256:696613a0c0e7b2b35356e389ba4195ce20cfe7a2fc2e992c87d974d973eabec7 \ + --hash=sha256:6c5687b59b6ba0f663c4f2f15470f68507d6b45ccd3a19ee6d224f95cbee70d8 \ + --hash=sha256:6c7d7b0b596319e9ce79ef96ce57a14054a2eac629c0588a0539187a218be799 \ + --hash=sha256:70dbc9f83c41f37a4faa62dae5203853847223a891da446f48ef2efcfd5df806 \ + --hash=sha256:71395a43da5584bb70556f380387e15f845c0dcf76373c1afbfa0025737576ac \ + --hash=sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03 \ + --hash=sha256:71e03d2ea1a221d020cfc5b6cc8bbbedef23a06704c70fcf4d0afb42965b22d1 \ + --hash=sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43 \ + --hash=sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c \ + --hash=sha256:7646353a5a7c553c04167aca628e2550b538f492765b03ccf34321a560acc43c \ + --hash=sha256:76e0065998159244ff4c097a6c05ff08019c6fbb6e597a85846e73044f0215b3 \ + --hash=sha256:789a6453e5ffd18a7ab6b8c3a0dd8403053829197ec258ecb90c604c21ffcc99 \ + --hash=sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c \ + --hash=sha256:7ac2769a7ddd661e07e26c12220adc31b17014c48234b2a5a88993b8d4109e09 \ + --hash=sha256:817953730e4a73a09008b010c4a42396cefe799616a22df2ac21d3927b3080cf \ + --hash=sha256:83d2beac85b757bfc404c5c0612df51c4ef33bbb7be65cf4a96b4da7cbc4ff4f \ + --hash=sha256:86c7c4615634b5c57a79770f5b738354e45ae219a89949aeae84f19169a05283 \ + --hash=sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2 \ + --hash=sha256:8cceae48ae7f94990c2f4e36291e9ec9868735e8b0f19e4489a17b0422338466 \ + --hash=sha256:92f8f63df729061bb14558ed740e7a222f6e2aa6c2e6a5bcfb4e706676562049 \ + --hash=sha256:930ad463d3fb7a340d323bcc496ec32dae469ec9974c29ff569f19806b6b03b4 \ + --hash=sha256:94733cb447c37b0ce6f71b39ca1288d5f966a084023a5617b4cc35a852586859 \ + --hash=sha256:9be1cfe715ecaa060ffd5d599ef410b94ef2697a0eed4cee562f788a2aa2175b \ + --hash=sha256:a0c5210d038418a115e7cf8706bfa611bd14add2f5787274dba45aadca3155e0 \ + --hash=sha256:a2f8716344bbbd10443391be0b1f2003b34949e3c4e6883005c2bc498ab6b64b \ + --hash=sha256:a4bb174bd65f795c39ad6642d9d5bdc43351b306b7d0a654ab0d0abb38be245f \ + --hash=sha256:a70d5effebd81ebd8e15a8aabdc7980832367b2b00c36543bac378977004cc80 \ + --hash=sha256:a9ee990bf2cfbd81574c5d4f9f6c9d480a14b5b43d2c4f2ca13f4c6f48089394 \ + --hash=sha256:ab2822bcdcefb54d1e8ca29f5e3ec3afe160fb794bb3a3a73b09d11ed2671104 \ + --hash=sha256:ad92d255a165cde5f9882ff69699eaf5495e0a1f32e97566bbbb80f11e46781f \ + --hash=sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6 \ + --hash=sha256:aeb2e123cbf978a905e9f55155c1b8316fbbfa7cf64d04521fe174bab302d100 \ + --hash=sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914 \ + --hash=sha256:b0cdb655fbd1562c2dfc9986f9103a106f7058cd0915afc6e656d4b1d73f3387 \ + --hash=sha256:b26f39a5be3cd91a2035818be3d0ffdf5282c3e1f5f53d3b80b7024021acee52 \ + --hash=sha256:b2f2d13239487cecaae98c9f4d5904ad0737643cdf8873c88ec6a78b12214f20 \ + --hash=sha256:b300a30304c4c6aeab03ed06809819d9eceacdd58441d3c7dffe41edfd006091 \ + --hash=sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949 \ + --hash=sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c \ + --hash=sha256:b867f9fd183d76977f810c626d539265183c25b2284762893a31e8d6cacc81c0 \ + --hash=sha256:b99bed995ed7c41515c11fe2beb86f8a6cc298e5537cae2f736de2f982f74ef0 \ + --hash=sha256:bd46bcc28ed85d3cf71581b42d90b4ebd1f2062f81879519fed209f8a4d1cfc6 \ + --hash=sha256:bee28aab5a580eec673f7b68dfa8dece3dd37bd207ef8d22fafe23a8e9837296 \ + --hash=sha256:c04e9d920e2674f54651fd260a15c5d2843526c73d5242ee4311325ddc9573b3 \ + --hash=sha256:c4c5a1770ecfe8bdb6c6f09f8d81ea4de04f7efb012fac1efa4ad315dccc1fd1 \ + --hash=sha256:c733087ecf7dde06b1d071679bfd5f3ba03266ba77814c1c7253bc48c9adedd9 \ + --hash=sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969 \ + --hash=sha256:c81d98e27d9d9261909dcccab1ba5d6ea1c98b0bb9470e368604614fd1d36ddd \ + --hash=sha256:c81e35862aced259177a537ce1a6264c3a97bae1ced184ca9dc10ea754563688 \ + --hash=sha256:c856e439a9d54d514e81a7131229ba151cdf81df7c408e0f6c89340e5003dfe2 \ + --hash=sha256:c9e70012926e97069cdd09221861aff412aa94e4cac2e019055cdb79485b150c \ + --hash=sha256:ca83a32b2b41653d89f09a3d22b770bca96da72273bef8f7a68136bdd1e8b823 \ + --hash=sha256:cbf0777d54672990b10cb8ca9b0523499e182d7e2ea39f86b138519a902aa601 \ + --hash=sha256:d49127f137f871cde3c5650af33bbbdcee02679dae76e020902fa106f522b8ae \ + --hash=sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4 \ + --hash=sha256:d6a166978f22f10cb91413f70519861605219346decf65bc79008f9257c94afe \ + --hash=sha256:d6e3485a5e5c01fb5339c1ee3d4b9e21e2135a2a9d44caafb71acd994487ee7c \ + --hash=sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f \ + --hash=sha256:d8201c9f9035520cdcc7dcad383b039ec8123969b87e01cf27c3dd883c02313b \ + --hash=sha256:da779ae50b46f3f7d1e1b5f362fdc0ad376a49fd55f6f3122dc2b6149936cdf7 \ + --hash=sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8 \ + --hash=sha256:dd8bed00731a21e3106e5dd6bbffb6c775a2c0bbc7c0c9face534d830057bdc9 \ + --hash=sha256:df1c174796cd63eb6b139f7daf783affe1f3ed659605850e843b24764c21bfc5 \ + --hash=sha256:dfcf6e51000b34f7026322cd9ea9bc340d745637e27e0bbc22f504b4f6b967ee \ + --hash=sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a \ + --hash=sha256:e512c75ec5cf4475c1aa50ad975ecdf253f4963b06e152e1a11edd6de4010753 \ + --hash=sha256:e5bd109d095aaae989a0463d5ef0fcc43e9ddd5de125e656d3c119a79e466380 \ + --hash=sha256:e6b4b08d09054310a4dc389fa61ee22a7a5a292cb23ab8a985136ca8828bf924 \ + --hash=sha256:e6da138a1ecc1341c8b788a5ee822670b03788e1f5decf7af9d461de6e508b8e \ + --hash=sha256:ea2f61b0bc12f3592288503961b764579dea0658852d96a0b3d823614d808821 \ + --hash=sha256:ed9c0b6f236648dbf30d57e9f57e1f74878caafa04833a19f529b5ba5164b7a8 \ + --hash=sha256:edbca8789fd10f0de534b660a6b4c71f1fd18039679c918dad392ab044bb37e4 \ + --hash=sha256:edc17549ab592e33cfcaf285f047bb75fcd98f608aa9309af1187fd736ce9641 \ + --hash=sha256:ef8a9ddb2e2a4eae4abb72dc0710eca6c2726779b0664bd10c3ce9fcfaed8c4e \ + --hash=sha256:f08ee8248aad2d054e5bc4c73554d4505464698f6d754f16198dbc5764e9821d \ + --hash=sha256:f1d62fb172db35c6478c9323da34ff37d1f3d37d7d44337a9d94ba8c583e5730 \ + --hash=sha256:f8fd23653a252cefabea11cd041efd7b80bdf403e43a36dea53f9cb0aaa21f0f \ + --hash=sha256:faa4e96385c820ce9d7f7a623486e23d4134ae3c9ba2071e44e0ab5a5a5002c4 \ + --hash=sha256:fb2bb5b557080da398b866408117d98fe9731a12334afd0cdff221b458cdc5dc \ + --hash=sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa \ + --hash=sha256:ffb616d8d55965839670301dc3bae3abacff560a7e137a89056058a8a9da4d96 + # via pydantic +pydantic-settings==2.16.2 \ + --hash=sha256:3dc08ffabed2bbd5dc2dd55ead7b78b4e4c5cd776aecd04310db5f1224caaf46 \ + --hash=sha256:8d523e5c129b097686bde019bd6109bff53f4c8c3f63f1ddf9933ffa42e5ab4f + # via mcp +pyjwt==2.15.1 \ + --hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193 \ + --hash=sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8 + # via mcp +python-dotenv==1.2.4 \ + --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \ + --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0 + # via pydantic-settings +python-multipart==0.0.33 \ + --hash=sha256:8f16c07b36add9da6b2ee87d3efcaf0a45a6de9c3d0a5dd94e9ccf7675a7bc45 \ + --hash=sha256:b8112424a6abd162ec08d390565dd113ad699f2fe6fef3c987b8bbcbfe9e390d + # via mcp +referencing==0.37.0 \ + --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231 \ + --hash=sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8 + # via + # jsonschema + # jsonschema-specifications +rpds-py==2026.9.1 \ + --hash=sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25 \ + --hash=sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68 \ + --hash=sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495 \ + --hash=sha256:0483515261947e4e8b8e1375bf7463e7eb6ccfb3d86e7b554d90cd5285f20f32 \ + --hash=sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96 \ + --hash=sha256:074a4d198bc34d9a8ea425114fc3ded6d11ec01f6a314a8db67454a5152d8834 \ + --hash=sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0 \ + --hash=sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6 \ + --hash=sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e \ + --hash=sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa \ + --hash=sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759 \ + --hash=sha256:136a1c3fe4402b7008bc81cb62ee538481795b61a7e83df88dff3b3f02b726ff \ + --hash=sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7 \ + --hash=sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c \ + --hash=sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903 \ + --hash=sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d \ + --hash=sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9 \ + --hash=sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e \ + --hash=sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b \ + --hash=sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a \ + --hash=sha256:270bdcdaac5d5b6f73c5e22e7e135c7f2a50e789f71d9e241d5be8d90026e19a \ + --hash=sha256:2711d29b653b3bce48a63d18b9c6b53274669e6d6c4094dddeb4d9a0e45128b2 \ + --hash=sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945 \ + --hash=sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91 \ + --hash=sha256:3231c4c0e521dafa5be0c9f114ee2c2ad46650836f2d72caa86801950c3e7044 \ + --hash=sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69 \ + --hash=sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e \ + --hash=sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3 \ + --hash=sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4 \ + --hash=sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33 \ + --hash=sha256:3e524c7874ac72884d28e16dd5b8d839fd09e0fe76b020d3fbca23212a7b8c52 \ + --hash=sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9 \ + --hash=sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb \ + --hash=sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35 \ + --hash=sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299 \ + --hash=sha256:44b32a7c4f0da3d28af31c259e38ddcff096f855e205ed0671d02fcf44f1ea1c \ + --hash=sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063 \ + --hash=sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a \ + --hash=sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6 \ + --hash=sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12 \ + --hash=sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14 \ + --hash=sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0 \ + --hash=sha256:4c0d2cb595a420b34d5086db0add011e26e2c09d6a024afbac4228bf8f863a30 \ + --hash=sha256:4cfaf02209061880210819934de2f4f6aa83dc04dafe6770276acc240a56da31 \ + --hash=sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02 \ + --hash=sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af \ + --hash=sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef \ + --hash=sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0 \ + --hash=sha256:56cd8b3f77d7b6812f533b662186a1f28316931166ddc00fb893b1b0db7e9888 \ + --hash=sha256:57492a550a1d88d29d003247e5f78dd8cf04a701fac0e4c8db8745a6d2504e0a \ + --hash=sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c \ + --hash=sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b \ + --hash=sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86 \ + --hash=sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f \ + --hash=sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531 \ + --hash=sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6 \ + --hash=sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82 \ + --hash=sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d \ + --hash=sha256:6b723eb406dec5bc9ec516c73ab9c3239a3284e017f7eb89ee2b3258bd504fb7 \ + --hash=sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448 \ + --hash=sha256:6beb738155fe8ab8091afdfa5a3226b21c2b1593f1e50ebb90eb25b44dbc0391 \ + --hash=sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb \ + --hash=sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4 \ + --hash=sha256:6eae33003518fd4cb4f83a218d5371469dd3001aa3b87128c005b07762f7fe5e \ + --hash=sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c \ + --hash=sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15 \ + --hash=sha256:761fdae6728ceb99ab182fad2f0cc1e262f610834dc891aea1d1a2a2e634776f \ + --hash=sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297 \ + --hash=sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36 \ + --hash=sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d \ + --hash=sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b \ + --hash=sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237 \ + --hash=sha256:8171b44a054e5c67fd748ada04187f1250bf35b95f85e52ab64bcf3331a923bb \ + --hash=sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477 \ + --hash=sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c \ + --hash=sha256:839dde845559254f34885267c6878f60d61d5205180226d976fe488d45fa128e \ + --hash=sha256:84a6ecc0c940169190d2c23bd969debd48c94dbc855acd60188a68d71d421608 \ + --hash=sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07 \ + --hash=sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c \ + --hash=sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35 \ + --hash=sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0 \ + --hash=sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785 \ + --hash=sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad \ + --hash=sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc \ + --hash=sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9 \ + --hash=sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025 \ + --hash=sha256:a3dbc5ed9514908d5046107d7b1346bde71eea61de6e0e4919c19354f97e769f \ + --hash=sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009 \ + --hash=sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d \ + --hash=sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118 \ + --hash=sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db \ + --hash=sha256:ab4b2fda7c2b542f7f9d886cc6a838c5079d2b76f72e6081411faba11adde2c9 \ + --hash=sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab \ + --hash=sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37 \ + --hash=sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d \ + --hash=sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc \ + --hash=sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9 \ + --hash=sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3 \ + --hash=sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569 \ + --hash=sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69 \ + --hash=sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b \ + --hash=sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018 \ + --hash=sha256:ce4d4f52e2a4324396caddbd45a97d8d7be5f42edd25d2355282a9c34f9b2f7f \ + --hash=sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c \ + --hash=sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f \ + --hash=sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5 \ + --hash=sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445 \ + --hash=sha256:d95a354e02393eada6d7351184671aced9d4cce109dabf927cb7aa99624352a1 \ + --hash=sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e \ + --hash=sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429 \ + --hash=sha256:e01b3c878c8641913e688edd1b3f08658c6783d29cf6b826bd3c0d1ae7a1ffaa \ + --hash=sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b \ + --hash=sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250 \ + --hash=sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e \ + --hash=sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83 \ + --hash=sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f \ + --hash=sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd \ + --hash=sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346 \ + --hash=sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858 \ + --hash=sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871 \ + --hash=sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da \ + --hash=sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0 \ + --hash=sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f \ + --hash=sha256:f3d6ed6a98cfd19155996605474982cc470d7601746a6439078f1a5a3fa8b050 \ + --hash=sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31 \ + --hash=sha256:fda1d96e542c37b6c804547dbf489c129fe7c97183a76a5ec275909ba1a063df \ + --hash=sha256:fdcd198979b4ecffcc1beba366a7fbcf4eb41243691a82fe52ceb0b902f09c12 \ + --hash=sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567 + # via + # jsonschema + # referencing +sse-starlette==3.6.0 \ + --hash=sha256:623151d6c20dc0eebf1b3379c27faae91fff883bac7ab6665f16f46440a88b3a \ + --hash=sha256:e4dfa4d237d2712cb2b4d4918eda9b457cd6b44bbecdc838af75de836565bafd + # via mcp +starlette==1.10.0 \ + --hash=sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4 \ + --hash=sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b + # via + # mcp + # sse-starlette +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # mcp + # pydantic + # pydantic-core + # pydantic-settings + # referencing + # starlette + # typing-inspection +typing-inspection==0.4.5 \ + --hash=sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7 \ + --hash=sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39 + # via + # mcp + # pydantic + # pydantic-settings +uvicorn==0.54.0 \ + --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ + --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 + # via mcp diff --git a/scripts/export_source.py b/scripts/export_source.py new file mode 100644 index 0000000..4885015 --- /dev/null +++ b/scripts/export_source.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Export reviewed source only; fail closed for runtime or unexpected files.""" +from pathlib import Path +import hashlib +import io +import json +import re +import sys +import tarfile + +ROOT = Path(__file__).resolve().parents[1] +FILES = ['README.md', 'LICENSE', 'UPSTREAM.md', 'SECURITY.md', 'CONTRIBUTING.md', + '.gitignore', 'requirements.in', 'requirements.lock', + 'cli/package.json', 'cli/package-lock.json', 'cli/LICENSE', + 'cli/tsconfig.json', 'cli/tsup.config.ts', 'cli/vitest.config.ts'] +DIRECTORIES = ['cli/src', 'cli/tests', 'mcp_server', 'scripts', 'tests', 'docs', 'examples'] +SUFFIXES = {'.py', '.mjs', '.ts', '.json', '.md'} +PATTERNS = [ + ('private-key', re.compile(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----')), + ('bot-token', re.compile(r'\b\d{8,12}:[A-Za-z0-9_-]{30,}\b')), + ('access-token', re.compile(r'\b(?:ghp_|github_pat_|sk-proj-)[A-Za-z0-9_-]{20,}\b')), + ('credential-url', re.compile(r'https?://[^\s/@:]+:[^\s/@]+@')), + ('personal-path', re.compile(r'/(?:Users|home)/(?!(?:user|example|test|runner)(?:/|\b))[^\s/]+/')), +] + + +def source_files(): + paths = [ROOT / p for p in FILES] + for path in paths + [ROOT / d for d in DIRECTORIES]: + if path.is_symlink(): + raise ValueError(f"Symlink is not permitted: {path.relative_to(ROOT)}") + for directory in DIRECTORIES: + for p in (ROOT / directory).rglob('*'): + if '__pycache__' in p.parts: + continue + if p.is_symlink(): + raise ValueError(f'Symlink is not permitted: {p.relative_to(ROOT)}') + if not p.is_file(): + continue + if p.suffix not in SUFFIXES: + raise ValueError(f'Unexpected source file: {p.relative_to(ROOT)}') + paths.append(p) + return sorted(paths) + + +def validate(paths): + findings = [] + for path in paths: + text = path.read_text() + for kind, pattern in PATTERNS: + for match in pattern.finditer(text): + findings.append(f'{path.relative_to(ROOT)}:{text.count(chr(10), 0, match.start()) + 1}: {kind}') + if path.suffix == '.md': + for target in re.findall(r'\]\(([^)]+)\)', text): + if '://' not in target and not target.startswith('#'): + if not (path.parent / target.split('#')[0]).exists(): + findings.append(f'{path.relative_to(ROOT)}: broken local link') + if findings: + raise ValueError('\n'.join(findings)) + + +def main(): + if len(sys.argv) != 2: + raise SystemExit('Usage: python3 scripts/export_source.py /outside/checkout/source.tar.gz') + output = Path(sys.argv[1]).resolve() + if output == ROOT or ROOT in output.parents: + raise SystemExit('Export outside the source checkout') + if output.exists(): + raise SystemExit('Destination exists; choose a new filename') + paths = source_files() + validate(paths) + manifest = {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths} + with tarfile.open(output, 'w:gz') as archive: + for p in paths: + data = p.read_bytes() + info = tarfile.TarInfo('telegram-mcp/' + str(p.relative_to(ROOT))) + info.size = len(data) + info.mode = 0o644 + archive.addfile(info, io.BytesIO(data)) + data = (json.dumps(manifest, indent=2) + '\n').encode() + info = tarfile.TarInfo('telegram-mcp/SOURCE-MANIFEST.json') + info.size = len(data) + info.mode = 0o644 + archive.addfile(info, io.BytesIO(data)) + print(f'Exported {len(paths)} source files; SHA-256 {hashlib.sha256(output.read_bytes()).hexdigest()}') + + +if __name__ == '__main__': + main() diff --git a/scripts/manage.py b/scripts/manage.py new file mode 100644 index 0000000..1acf074 --- /dev/null +++ b/scripts/manage.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Local installation and launch. No global npm install or automatic client edits.""" +from __future__ import annotations +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import venv + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "mcp_server")) +from runtime import cli_command, child_environment, state_directory + + +def python() -> Path: + return ROOT / ".venv" / "bin" / "python" + + +def run(command, **kwargs): + subprocess.run([str(x) for x in command], check=True, **kwargs) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=["setup", "login", "run", "config", "check", "test", "cli"]) + parser.add_argument("--account", choices=["main", "reserve"], default="main") + parser.add_argument("--transport", choices=["tcp", "wss"], default="tcp") + args, extra = parser.parse_known_args() + if args.action != "cli" and extra: + parser.error("unexpected arguments") + if os.name != "posix": + parser.error("Use macOS, Linux or WSL; native Windows is not supported") + if args.action == "setup": + if sys.version_info < (3, 11): + parser.error("Python 3.11+ is required") + for name in ("node", "npm"): + if not shutil.which(name): + parser.error(f"Install {name} first (Node 20+)") + version = subprocess.check_output(["node", "--version"], text=True) + if int(version.lstrip("v").split('.')[0]) < 20: + parser.error("Node 20+ is required") + if not python().exists(): + venv.EnvBuilder(with_pip=True).create(ROOT / ".venv") + run([python(), "-m", "pip", "install", "--require-hashes", "-r", ROOT / "requirements.lock"]) + run(["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"], cwd=ROOT / "cli") + run(["npm", "run", "build"], cwd=ROOT / "cli") + print("Installed locally. Next: python3 scripts/manage.py login") + elif args.action == "config": + env = {} + if "TG_MCP_STATE_DIR" in os.environ: + env["TG_MCP_STATE_DIR"] = str(state_directory()) + server = {"command": str(python()), "args": [str(ROOT / "mcp_server" / "server.py")]} + if env: + server["env"] = env + print(json.dumps({"mcpServers": {"telegram": server}}, indent=2)) + elif args.action == "run": + os.execv(str(python()), [str(python()), str(ROOT / "mcp_server" / "server.py")]) + elif args.action == "login": + state = state_directory() + state.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(state, 0o700) + # Interactive terminal only: credentials and codes are never MCP arguments. + if not sys.stdin.isatty(): + parser.error("Run login yourself in an interactive terminal") + os.umask(0o077) + run(cli_command(args.account) + ["--transport", args.transport, "auth", "login", "--client", "desktop"], + env=child_environment(args.account)) + elif args.action == "cli": + run(cli_command(args.account) + (extra[1:] if extra[:1] == ["--"] else extra), + env=child_environment(args.account)) + elif args.action == "check": + run([python(), ROOT / "scripts" / "smoke.py"]) + elif args.action == "test": + run(["npm", "run", "typecheck"], cwd=ROOT / "cli") + run(["npm", "test", "--", "--maxWorkers=2", "--minWorkers=1"], cwd=ROOT / "cli") + env = dict(os.environ, PYTHONPATH=str(ROOT / "mcp_server")) + run([python(), "-m", "unittest", "discover", "-s", ROOT / "tests", "-v"], env=env) + run([python(), ROOT / "scripts" / "smoke.py"]) + + +if __name__ == "__main__": + main() diff --git a/scripts/smoke.py b/scripts/smoke.py new file mode 100644 index 0000000..94376d5 --- /dev/null +++ b/scripts/smoke.py @@ -0,0 +1,32 @@ +"""Offline real stdio handshake. Does not call Telegram or require a login.""" +import asyncio +import json +from pathlib import Path +import sys +import tempfile +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + +ROOT = Path(__file__).resolve().parents[1] + + +async def main(): + with tempfile.TemporaryDirectory(prefix="telegram-mcp-smoke-") as state: + params = StdioServerParameters(command=sys.executable, + args=[str(ROOT / "mcp_server" / "server.py")], env={"TG_MCP_STATE_DIR": state}) + async with stdio_client(params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = (await session.list_tools()).tools + assert len(tools) == 61, len(tools) + result = await session.call_tool("telegram_send_reply", { + "account": "main", "chat": "me", "text": "offline preview"}) + assert not result.isError + data = json.loads(result.content[0].text) + assert data["data"]["dry_run"] is True + assert not list(Path(state).iterdir()), "Offline check touched account state" + print("PASS: 61 tool schemas; stdio initialize/list_tools/call_tool; offline preview") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/test_export.py b/tests/test_export.py new file mode 100644 index 0000000..f9a66cc --- /dev/null +++ b/tests/test_export.py @@ -0,0 +1,38 @@ +"""Public source export must not silently include runtime artifacts.""" +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import export_source + + +class SourceExportContracts(unittest.TestCase): + def test_unexpected_file_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp) + (root/'code').mkdir() + (root/'code'/'account.session').write_text('synthetic') + with patch.object(export_source,'ROOT',root), patch.object(export_source,'FILES',[]), patch.object(export_source,'DIRECTORIES',['code']): + with self.assertRaises(ValueError):export_source.source_files() + + def test_symlink_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp) + (root/'code').mkdir() + (root/'private').write_text('synthetic') + (root/'code'/'innocent.py').symlink_to(root/'private') + with patch.object(export_source,'ROOT',root), patch.object(export_source,'FILES',[]), patch.object(export_source,'DIRECTORIES',['code']): + with self.assertRaises(ValueError):export_source.source_files() + + def test_secret_finding_never_prints_value(self): + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp) + path=root/'fixture.py' + token='123456789'+':'+'a'*35 + path.write_text('token = '+repr(token)) + with patch.object(export_source,'ROOT',root): + with self.assertRaises(ValueError) as caught:export_source.validate([path]) + self.assertNotIn(token,str(caught.exception)) + self.assertIn('bot-token',str(caught.exception)) diff --git a/tests/test_extended.py b/tests/test_extended.py new file mode 100644 index 0000000..248dcd5 --- /dev/null +++ b/tests/test_extended.py @@ -0,0 +1,67 @@ +from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "mcp_server")) +import asyncio +import json +import unittest +from unittest.mock import Mock +from mcp.server.fastmcp import FastMCP +from extended import register_tools + +class ExtendedContracts(unittest.TestCase): + def setUp(self): + self.mcp = FastMCP('test') + self.run = Mock(return_value={'ok': True, 'data': {}}) + register_tools(self.mcp, self.run, Mock()) + + def call(self, name, **kwargs): + tool = self.mcp._tool_manager.get_tool('telegram_' + name) + return asyncio.run(tool.run(kwargs)) + + def test_all_tools_have_explicit_accounts_and_annotations(self): + tools = asyncio.run(self.mcp.list_tools()) + self.assertEqual(len(tools), 49) + for tool in tools: + self.assertIn('account', tool.inputSchema['required'], tool.name) + self.assertIsNotNone(tool.annotations, tool.name) + if not tool.annotations.readOnlyHint: + self.assertTrue(tool.inputSchema['properties']['dry_run']['default'], tool.name) + + def test_local_write_preview_does_not_connect(self): + self.call('send_reply', account='main', chat='me', text='--help') + self.call('delete_messages', account='main', chat='me', ids=[1], for_everyone=False) + self.run.assert_not_called() + + def test_option_injection_is_data(self): + self.call('send_reply', account='main', chat='me', text='--schedule=tomorrow', dry_run=False) + args, account = self.run.call_args.args + self.assertEqual(args, ['message', 'send', '--', 'me', '--schedule=tomorrow']) + self.assertEqual(account, 'main') + + def test_timeout_is_not_retried(self): + self.run.return_value = {'ok': False, 'code': 'TIMEOUT'} + self.assertFalse(self.call('send_reply', account='main', chat='me', text='synthetic', dry_run=False)['ok']) + self.run.assert_called_once() + + def test_folder_patch_is_typed_and_preserves_omitted_fields(self): + self.call('update_folder', account='main', folder_id=2, patch={'title': 'New'}) + args, account = self.run.call_args.args + payload = json.loads(args[-1]) + self.assertEqual(payload['patch'], {'title': 'New'}) + self.assertTrue(payload['dry_run']) + self.assertEqual(account, 'main') + + def test_invalid_ids_and_pagination_never_connect(self): + for ids in [[], [0], [True], list(range(1, 102))]: + # Direct helper validation is also checked through the callable below. + if ids == [True]: continue # MCP int validation may coerce booleans. + self.assertFalse(self.call('delete_messages', account='main', chat='me', ids=ids, for_everyone=False, dry_run=False)['ok']) + self.assertFalse(self.call('list_contacts', account='main', limit=10000)['ok']) + self.run.assert_not_called() + + def test_revoke_mode_is_explicit(self): + self.call('delete_messages', account='main', chat='me', ids=[2], for_everyone=False, dry_run=False) + self.assertEqual(self.run.call_args.args[0], ['message', 'delete', '--for-me', '--', 'me', '2']) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_portable.py b/tests/test_portable.py new file mode 100644 index 0000000..38fb51d --- /dev/null +++ b/tests/test_portable.py @@ -0,0 +1,58 @@ +"""Regression tests for portable account isolation and command boundaries.""" +from pathlib import Path +import os +import sys +import subprocess +import tempfile +import unittest +from unittest.mock import patch +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'mcp_server')) +import runtime +import server + + +class PortableContracts(unittest.TestCase): + def test_no_credentials_leak_from_parent(self): + with patch.dict(os.environ, {'TG_SESSION': 'synthetic', 'TG_API_HASH': 'synthetic', + 'TG_MAIN_SESSION': 'synthetic', 'TG_DAEMON_PROFILE': 'other'}): + env = runtime.child_environment('main') + self.assertFalse(any(k.startswith('TG_') for k in env)) + + def test_profile_and_config_are_explicit(self): + with tempfile.TemporaryDirectory(prefix='profile test ') as state: + with patch.dict(os.environ, {'TG_MCP_STATE_DIR': state}): + for account in ['main', 'reserve']: + cmd = runtime.cli_command(account) + self.assertEqual(cmd[cmd.index('--profile') + 1], account) + self.assertEqual(cmd[cmd.index('--config') + 1], str(Path(state) / 'config.json')) + self.assertTrue(Path(cmd[1]).is_absolute()) + with patch.dict(os.environ, {'TG_MCP_STATE_DIR': 'relative'}): + with self.assertRaises(ValueError): runtime.cli_command('main') + with self.assertRaises(ValueError): runtime.cli_command('unknown') + + def test_server_import_does_not_load_dotenv(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, '.env').write_text('TG_SESSION=should-not-load\n') + env = {k: v for k, v in os.environ.items() if not k.startswith('TG_')} + env['PYTHONPATH'] = str(runtime.ROOT / 'mcp_server') + result = subprocess.run([sys.executable, '-c', + 'import server, os; assert "TG_SESSION" not in os.environ'], cwd=directory, + env=env, capture_output=True) + self.assertEqual(result.returncode, 0) + + def test_self_identity_failure_stops_wait(self): + with patch.object(server, '_run', return_value={'ok': False}) as run: + result = server.telegram_wait_for_reply('me', 1, timeout=1, account='main') + self.assertEqual(result['code'], 'AUTH_CHECK_FAILED') + self.assertEqual(run.call_count, 1) + + def test_send_text_cannot_become_cli_option(self): + with patch.object(server, '_run', return_value={'ok': True}) as run: + server.telegram_send_message('me', '--schedule=tomorrow', account='main') + self.assertEqual(run.call_args.args[0], ['message', 'send', '--', 'me', '--schedule=tomorrow']) + + def test_file_caption_is_option_value_and_targets_are_positional(self): + with tempfile.NamedTemporaryFile() as f: + with patch.object(server, '_run', return_value={'ok': True}) as run: + server.telegram_send_file('me', f.name, '--help', account='main') + self.assertEqual(run.call_args.args[0], ['media', 'send', '--caption=--help', '--', 'me', f.name]) diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..6e68a29 --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,120 @@ +"""Contract checks without Telegram writes or credentials in test output.""" +import importlib.util +import json +from pathlib import Path +import subprocess +import unittest +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "mcp_server")) +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location("telegram_server", Path(__file__).resolve().parents[1] / "mcp_server" / "server.py") +server = importlib.util.module_from_spec(spec) +spec.loader.exec_module(server) + + +class TelegramContracts(unittest.TestCase): + def test_story_validation_and_dispatch(self): + with patch.object(server, "_stories_call", return_value={"ok": True}) as call: + self.assertTrue(server.telegram_list_stories("https://t.me/example_channel", limit=5, account="main")["ok"]) + self.assertEqual(call.call_args.args[0]["chat"], "example_channel") + self.assertEqual(call.call_args.args[1], "main") + call.reset_mock() + for kwargs in [{"chat": "--help"}, {"chat": "example_channel", "kind": "active", "offset_id": 1}, + {"chat": "example_channel", "limit": 101}]: + self.assertFalse(server.telegram_list_stories(**kwargs)["ok"]) + self.assertFalse(server.telegram_get_story("example_channel", 0)["ok"]) + self.assertFalse(server.telegram_download_story_media("example_channel", -1)["ok"]) + call.assert_not_called() + + def test_story_worker_uses_owning_daemon(self): + with patch.object(server, "_run", return_value={"ok": True, "data": {"stories": []}}) as call: + self.assertTrue(server._stories_call({"action": "list"}, "main")["ok"]) + self.assertEqual(call.call_args.args[0][:3], ["bridge", "call", "stories"]) + self.assertEqual(call.call_args.args[1], "main") + + def test_html_and_schedule_keep_account_and_single_run(self): + with patch.object(server, "_run", return_value={"ok": False, "code": "TIMEOUT"}) as call: + self.assertFalse(server.telegram_send_html("me", "<b>Test</b>", "main")["ok"]) + call.assert_called_once() + call.reset_mock() + self.assertFalse(server.telegram_schedule_message("me", "fixture", "2030-01-01T00:00:00Z", "reserve")["ok"]) + call.assert_called_once() + self.assertEqual(call.call_args.args[1], "reserve") + + def test_post_links(self): + for link, expected in [ + ("https://t.me/example_channel/475", ("example_channel", "475")), + ("https://t.me/s/example_channel/475?single", ("example_channel", "475")), + ("https://t.me/c/12345/99", ("-10012345", "99")), + ("https://t.me/c/12345/7/99", ("-10012345", "99")), + ("https://t.me/forum/7/99", ("forum", "99")), + ]: + self.assertEqual(server._message_target(link, None), expected) + + def test_bad_targets_never_connect(self): + with patch.object(server, "_run") as run: + for chat, ids in [("https://evil.test/a/1", None), ("https://t.me/a", None), + ("--help", "1"), ("example_channel", "0"), ("example_channel", "1,abc"), + ("https://t.me/a/1", "2")]: + self.assertFalse(server.telegram_get_messages(chat, ids)["ok"]) + run.assert_not_called() + + def test_partial_failure_keeps_successes(self): + body = {"ok": True, "data": {"messages": [{"id": 1}], "partial": True, + "errors": [{"input": "2", "code": "NOT_FOUND"}]}} + with patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \ + patch.object(server.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, json.dumps(body), "")): + result = server._invoke(["message", "get", "me", "1,2"], "main") + self.assertFalse(result["ok"]) + self.assertEqual(result["code"], "PARTIAL_FAILURE") + self.assertEqual(result["data"], body["data"]) + + def test_send_timeout_is_never_replayed(self): + with patch.object(server, "_ensure_daemon", return_value={"ok": True}), \ + patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \ + patch.object(server.subprocess, "run", side_effect=subprocess.TimeoutExpired("tg", 1)) as run: + result = server.telegram_send_message("me", "synthetic", account="main") + self.assertEqual(result["code"], "TIMEOUT") + self.assertEqual(run.call_count, 1) + self.assertIn("--daemon", run.call_args.args[0]) + + def test_dead_daemon_does_not_send(self): + with patch.object(server, "_ensure_daemon", return_value={"ok": False, "code": "DAEMON_NOT_READY"}), \ + patch.object(server, "_invoke", return_value={"ok": False, "code": "DAEMON_NOT_RUNNING"}) as invoke: + self.assertFalse(server.telegram_send_message("me", "synthetic", "main")["ok"]) + self.assertEqual(invoke.call_count, 1) + + def test_only_proven_nondispatch_starts_daemon(self): + with patch.object(server, "_ensure_daemon", return_value={"ok": True}) as ensure, \ + patch.object(server, "_invoke", side_effect=[ + {"ok": False, "code": "DAEMON_NOT_RUNNING"}, {"ok": True, "data": {"id": 1}}, + ]) as invoke: + self.assertTrue(server.telegram_send_message("me", "synthetic", "main")["ok"]) + self.assertEqual(invoke.call_count, 2) + ensure.assert_called_once_with("main") + + def test_daemon_start_race_rechecks_status(self): + ready = {"ok": True, "data": {"running": True, "connected": True, "capabilities": ["execute"]}} + with patch.object(server, "_invoke", side_effect=[ + {"ok": True, "data": {"running": False}}, + {"ok": False, "code": "DAEMON_ALREADY_RUNNING"}, ready, + ]): + self.assertEqual(server._ensure_daemon("main"), ready) + + def test_fields_validation_before_network(self): + with patch.object(server, "_run") as run: + self.assertFalse(server.telegram_read_history("me", fields="id;rm")["ok"]) + self.assertFalse(server.telegram_read_history("me", output_format="xml")["ok"]) + run.assert_not_called() + + def test_no_unstructured_output_leak(self): + with patch.object(server, "_tg_env", return_value={"TG_SESSION": "test"}), \ + patch.object(server.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, "private payload", "private error")): + result = server._invoke(["daemon", "status"], "main") + self.assertNotIn("private", json.dumps(result)) + + + +if __name__ == "__main__": + unittest.main()