# Основы API (/docs/bots/api) ## Запрос [#запрос] ``` POST https://<домен федерации>/bot/v1/<метод> Authorization: Bearer <токен> Content-Type: application/json { ...параметры... } ``` - Тело — JSON-объект, не больше 1 МиБ. Пустое тело означает «без параметров». - Можно и `GET` с параметрами в строке запроса (`?offset=10&timeout=30`): целые числа распознаются сами. Сложные параметры (кнопки, команды) передавайте только в `POST`. - Имена методов чувствительны к регистру: `sendMessage`, а не `sendmessage`. - Адрес — тот же домен, что у федерации в приложении. Отдельного домена для API нет. ## Ответ [#ответ] Успех — код 200: ```json { "ok": true, "result": <результат метода> } ``` Ошибка — код HTTP из таблицы ниже и: ```json { "ok": false, "error_code": 409, "description": "Refused: bot_stopped", "parameters": { "reason": "bot_stopped" } } ``` `parameters` есть не всегда: в нём `retry_after` (секунды, для 429) и `reason` (машинная причина отказа). ## Ошибки [#ошибки] | Код | Когда | |---|---| | 400 | Неверные параметры: нет обязательного, не тот тип, текст слишком длинный, неизвестная сущность или кнопка. `description` объясняет, что не так. | | 401 | Нет токена, токен неверный или уже заменён новым, бот удалён или заблокирован вместе с владельцем. | | 403 | Действие запрещено правами или модерацией (см. `reason` ниже). | | 404 | Неизвестный метод, чат не найден или бот в нём не состоит, взаимодействие старше 15 минут. | | 405 | Метод HTTP не `POST` и не `GET`. | | 409 | Состояние не позволяет: человек остановил бота, закрылось окно ответа, задан вебхук при вызове `getUpdates`, данные изменились одновременно (повторите). | | 413 | Тело больше 1 МиБ. | | 429 | Слишком часто. Подождите `parameters.retry_after` секунд. | | 500 | Ошибка сервера. Подробности — в журнале сервера. | | 503 | Сервер временно недоступен. Повторите позже. | ### Причины (`parameters.reason`) [#причины-parametersreason] | Причина | Код | Что значит | |---|---|---| | `bot_stopped` | 409 | Человек остановил бота. Ждите обновления `my_chat_member` со статусом `member`. | | `reply_window_closed` | 409 | Личный бот отвечает позже 24 часов после последнего сообщения собеседника. | | `storage_quota` | 409 | У отправителя закончилась квота хранимых сообщений. | | `chat_closed` | 403 | Модераторы закрыли чат. | | `content_filtered` | 403 | Текст задевает фильтр федерации. | | `privacy_restricted` | 403 | Настройки приватности человека этого не разрешают. | | `profile_restricted` | 403 | Бот ограничен модераторами. | | `profile_suspended` | 403 | Профиль заблокирован. | Ошибки 403 — решение федерации, а не временное состояние: не повторяйте такой запрос в цикле. ## Повторы и идемпотентность [#повторы-и-идемпотентность] Сеть может оборваться после того, как сервер уже выполнил запрос. Чтобы повтор `sendMessage` не отправил сообщение дважды, передавайте `idempotency_key` (от 1 до 128 символов): повтор с тем же ключом вернёт то же сообщение. ```json { "chat_id": "…", "text": "Сборка №42 готова", "idempotency_key": "build-42" } ``` Ключ действует в пределах одного бота. Удобно брать ID события, на которое бот отвечает. ## Частота [#частота] Отправка, правка и удаление сообщений тратят тот же бюджет, что у человека: 30 действий сразу, затем 5 в секунду. При превышении приходит 429 с `retry_after`. Ничего не записывается, пока запрос не принят. ## Журнал сервера [#журнал-сервера] Сервер пишет строку `[bots]` в свой журнал на каждый ответ 4xx и 5xx (бот, метод, код), на каждую ошибку вебхука (бот, хост, код или ошибка), на нажатие или подсказку, на которую бот не ответил, и на первое обновление каждого вида, отброшенное фильтром `allowed_updates`. Токен, секрет и путь адреса вебхука в журнал не попадают. Если что-то не работает, спросите администратора федерации. # Кнопки (/docs/bots/buttons) Кнопки — часть сообщения бота, а не отдельная клавиатура: они стоят под текстом, и правка сообщения заменяет их вместе с ним. Писать кнопки могут только боты. ## Добавить кнопки [#добавить-кнопки] `buttons` — массив рядов, ряд — массив кнопок. У каждой кнопки `text` и ровно одно действие: ```json { "chat_id": "…", "text": "Развернуть сборку 42?", "buttons": [ [ { "text": "Да", "callback_data": "deploy:42" }, { "text": "Нет", "callback_data": "cancel:42" } ], [ { "text": "Журнал", "url": "https://ci.example.org/42" }, { "text": "Скопировать хеш", "copy_text": "9f2c1e7" } ] ] } ``` | Действие | Что происходит при нажатии | |---|---| | `callback_data` | До 64 байт. Бот получает `callback_query` и отвечает. | | `url` | Приложение открывает адрес, как обычную ссылку, с подтверждением. | | `copy_text` | До 256 символов. Приложение копирует текст и говорит «Скопировано». | До 8 рядов, до 8 кнопок в ряду, до 32 кнопок в сообщении; подпись — до 64 символов. Кнопки не пересылаются вместе с сообщением. Личный бот, отвечающий от имени человека, кнопок не пишет. Старые версии приложения видят вместо кнопок строку `🔘 Да · Нет`. ## Нажатие [#нажатие] Нажатие кнопки с `callback_data` приходит обновлением: ```json { "update_id": 15, "callback_query": { "id": "…", "from": { "id": "…", "is_bot": false, "first_name": "Анна" }, "chat": { "id": "…", "type": "group", "title": "Релизы" }, "message": { "message_id": "…", "text": "Развернуть сборку 42?", ... }, "button_id": "…", "data": "deploy:42" } } ``` Пока бот думает, кнопка показывает загрузку. ## Ответ на нажатие [#ответ-на-нажатие] Ответьте `answerCallbackQuery` за **10 секунд**. Что увидит человек, решает бот: | Ответ | Что видит человек | |---|---| | `{"callback_query_id": "…", "text": "Готово"}` | Всплывающее уведомление приложения: на телефоне внизу над строкой ввода, на компьютере справа сверху. Новое заменяет предыдущее, так что быстрые нажатия не копятся. | | `{"callback_query_id": "…", "text": "Нет прав", "show_alert": true}` | Диалог, который человек закрывает сам. | | `{"callback_query_id": "…", "url": "https://…"}` | Открывается адрес. | | `{"callback_query_id": "…"}` | Ничего. | Если бот не ответил за 10 секунд, нажатие заканчивается пустым ответом и ничего не показывает. Текст ответа — до 200 символов. Часто вместе с ответом бот меняет само сообщение — например, убирает кнопки после выбора: ```json { "chat_id": "…", "message_id": "…", "text": "Сборка 42 развёрнута ✅" } ``` (`editMessage` без `buttons` убирает кнопки.) Вместо всплывающего сообщения можно ответить [временным сообщением](./ephemeral.mdx), которое увидит только нажавший. # Команды (/docs/bots/commands) Команды — это `/имя` с описанием, которые приложение показывает, когда человек набирает `/` в чате с ботом. Как в Discord, у команды могут быть **параметры** с типами, вариантами и подсказками от бота. ## Задать команды [#задать-команды] ```sh curl -s -X POST "$API/setMyCommands" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' -d @- <<'JSON' { "commands": [ { "command": "start", "description": "Начать" }, { "command": "weather", "description": "Погода в городе", "options": [ { "name": "город", "description": "Где", "required": true, "autocomplete": true }, { "name": "дней", "type": "integer", "min_value": 1, "max_value": 7 } ] } ] } JSON ``` - Имя — строчные латинские буквы, цифры и `_`; описание — до 256 символов. - До 100 команд в одной области, все вместе не больше 64 КиБ. - `setMyCommands` заменяет все команды области; пустой список их удаляет. Приложение запоминает список команд чата на пять минут, но видит изменения сразу, как только бот их меняет. ## Области [#области] | `scope` | Где действует | |---|---| | `{"type": "default"}` (по умолчанию) | Везде. | | `{"type": "all_private_chats"}` | Во всех личных чатах. | | `{"type": "all_group_chats"}` | Во всех группах и комнатах. | | `{"type": "chat", "chat_id": "…"}` | В одном чате, где бот состоит. | Действует самая точная область. У бота может быть до 64 областей с командами. ## Как команда доходит до бота [#как-команда-доходит-до-бота] **Обычная команда.** Приложение отправляет текст команды как сообщение человека, его видят все в чате. Бот получает обновление `message`, а если команда запущена из списка, ещё и разобранные параметры: ```json "command": { "name": "weather", "options": { "город": "Алматы", "дней": 3 } } ``` Команду, набранную вручную, бот получает как текст, без `options`. В группах команды доходят до бота и в режиме приватности; `/команда@имя_бота` — только тому боту, чьё это имя. **Временная команда** (`"ephemeral": true`). В чат ничего не пишется, никто другой не видит вызова, а бот получает `ephemeral_command` с ID взаимодействия и отвечает временным сообщением ([временные сообщения](./ephemeral.mdx#временные-команды)). ## Параметры [#параметры] | Поле | Тип | | |---|---|---| | `name` | строка | Имя параметра. | | `description` | строка | Подсказка. | | `required` | логическое | Обязательный. Обязательные без условия идут первыми. | | `type` | строка | `string` (по умолчанию), `integer`, `number`, `boolean`, `user`, `date`. | | `choices` | массив | До 25 вариантов `{"name", "value"}`; другие значения не принимаются. | | `autocomplete` | логическое | Бот подсказывает значения по мере ввода (вместо `choices`). | | `min_value`, `max_value` | число | Границы для `integer` и `number`. | | `min_length`, `max_length` | целое | Длина для `string`, до 1024. | | `shown_when` | объект | Условие: параметр существует, только пока другой имеет одно из значений. | Значения приходят боту по имени параметра: | Тип | Значение в JSON | Как выбирает человек | |---|---|---| | `string` | строка | Вводит текст. | | `integer`, `number` | число | Вводит число. | | `boolean` | `true` / `false` | «Да» или «Нет». | | `user` | ID профиля | Выбирает участника чата. | | `date` | строка `ГГГГ-ММ-ДД` | Выбирает дату. | Сервер сам отклоняет неизвестный параметр, значение не того типа, вне границ или не из вариантов, участника не из чата и пропущенный обязательный параметр: бот получает только проверенные значения. ### Условия [#условия] Параметр с `shown_when` появляется, только пока более ранний параметр имеет одно из значений: ```json { "command": "event", "description": "Событие", "options": [ { "name": "вид", "required": true, "choices": [ { "name": "Разовое", "value": "once" }, { "name": "Еженедельное", "value": "weekly" } ] }, { "name": "дата", "type": "date", "required": true, "shown_when": { "option": "вид", "values": ["once"] } } ] } ``` Здесь дата обязательна только для разового события. Значение скрытого параметра сервер не примет. ## Подсказки [#подсказки] Для параметра с `"autocomplete": true` приложение спрашивает бота, что предложить. Бот получает `autocomplete_query`: ```json { "id": "…", "from": {...}, "chat": {...}, "command": "weather", "options": {"дней": 3}, "focused": "город", "query": "Ал" } ``` и отвечает до 25 вариантами за **3 секунды**, иначе список будет пустым: ```sh curl -s -X POST "$API/answerAutocompleteQuery" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"autocomplete_query_id": "…", "choices": [{"name": "Алматы", "value": "Алматы"}, {"name": "Алтай", "value": "Алтай"}]}' ``` `value` должен подходить параметру по типу и границам. ## Как это выглядит у человека [#как-это-выглядит-у-человека] Параметры пишутся прямо в поле ввода: `/weather город:Алматы дней:3`. Над полем показывается команда с плашкой на каждый параметр и подсказки к тому, где стоит курсор: варианты, ответы бота, «Да»/«Нет», участники или календарь. Неверное значение подсвечивается красным, и отправка не пройдёт, пока его не исправить. # Временные сообщения (/docs/bots/ephemeral) Временное сообщение видит только один человек. Оно стоит в истории чата среди обычных сообщений с пометкой «Только вы видите это» и кнопкой «Скрыть», как ephemeral-ответы в Discord. Временное сообщение не сохраняется в истории, не попадает в поиск, уведомления и счётчики непрочитанного, на него нельзя ответить, закрепить или переслать. Живёт оно 24 часа с первой отправки, пока его не удалит бот, не скроет человек или не закроется приложение. ## Когда бот может так ответить [#когда-бот-может-так-ответить] Только в ответ на действие человека, в том же чате и не позже чем через **15 минут**: - на [временную команду](#временные-команды) — `id` из `ephemeral_command`; - на нажатие кнопки — `id` из `callback_query`. ```json { "chat_id": "…", "text": "Ваш баланс: 1 200 ₸", "ephemeral": { "interaction_id": "" } } ``` Ответ: ```json { "ok": true, "result": { "ephemeral_message_id": "…", "chat": {...}, "receiver": {...}, "expires_at": 1793136400 } } ``` Временное сообщение проходит те же проверки, что обычное (закрытый чат, блокировки, фильтр) и тратит тот же бюджет частоты. У одного бота может жить до 20 временных сообщений для одного человека: двадцать первое удаляет самое старое. ## Временные команды [#временные-команды] Команда с `"ephemeral": true` в `setMyCommands` не пишет ничего в чат: никто другой не видит её вызова, а бот получает ```json { "update_id": 31, "ephemeral_command": { "id": "…", "from": {...}, "chat": {...}, "text": "/balance", "command": "balance", "args": "", "date": 1793050000 } } ``` Приложение заранее говорит человеку «Ответ увидите только вы». ## Правка на месте [#правка-на-месте] У кнопок временного сообщения тоже есть нажатия: обновление `callback_query` с `ephemeral_message_id`. Ответить можно, заменив само временное сообщение: ```json { "chat_id": "…", "text": "Счётчик: 2", "ephemeral": { "interaction_id": "", "replace": true } } ``` - Нажали кнопку **временного** сообщения: `replace` меняет его на месте (тот же ID, та же дата истечения). - Нажали кнопку **обычного** сообщения: `replace` показывает временное сообщение на месте этого сообщения, но только у нажавшего. Остальные видят прежнее. - `replace_message_id` заменяет конкретное временное сообщение этого бота. Без нажатий временное сообщение меняют `editEphemeralMessage` и удаляют `deleteEphemeralMessage`. Сервер хранит временные сообщения только в памяти, а приложение не сохраняет их на устройстве. # Примеры (/docs/bots/examples) Оба примера делают одно и то же: задают команды, отвечают на `/start` сообщением с кнопками, отвечают на нажатия и повторяют любой другой текст. Они получают обновления через long polling и не требуют ничего, кроме стандартной библиотеки. ```sh export COMON_API='https://comon.chat/bot/v1' # адрес вашей федерации export COMON_TOKEN='cbt_...' ``` Python 3.9 или новее. ```python title="echo_bot.py" import json import os import time import urllib.error import urllib.request API = os.environ["COMON_API"] TOKEN = os.environ["COMON_TOKEN"] def call(method, **params): request = urllib.request.Request( f"{API}/{method}", data=json.dumps(params).encode(), headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}, ) try: with urllib.request.urlopen(request, timeout=60) as response: return json.load(response)["result"] except urllib.error.HTTPError as error: body = json.load(error) retry = body.get("parameters", {}).get("retry_after") if retry: time.sleep(retry) return call(method, **params) raise RuntimeError(f"{method}: {body['error_code']} {body['description']}") def on_message(message): chat = message["chat"]["id"] text = message.get("text", "") if text.startswith("/start"): call("sendMessage", chat_id=chat, text="Привет! Нажми кнопку.", buttons=[[{"text": "Подбросить монету", "callback_data": "coin"}], [{"text": "Сайт Comon", "url": "https://comon.chat"}]]) elif text: call("sendMessage", chat_id=chat, text=text, reply_to_message_id=message["message_id"]) def on_callback(query): if query["data"] == "coin": side = "Орёл" if time.time_ns() % 2 else "Решка" call("answerCallbackQuery", callback_query_id=query["id"], text=side) else: call("answerCallbackQuery", callback_query_id=query["id"]) def main(): call("setMyCommands", commands=[{"command": "start", "description": "Начать"}]) offset = None while True: params = {"timeout": 50, "allowed_updates": ["message", "callback_query"]} if offset is not None: params["offset"] = offset for update in call("getUpdates", **params): offset = update["update_id"] + 1 if "message" in update: on_message(update["message"]) elif "callback_query" in update: on_callback(update["callback_query"]) if __name__ == "__main__": main() ``` Node.js 18 или новее. ```js title="echo_bot.mjs" const API = process.env.COMON_API; const TOKEN = process.env.COMON_TOKEN; async function call(method, params = {}) { const response = await fetch(`${API}/${method}`, { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); const body = await response.json(); if (body.ok) return body.result; const retry = body.parameters?.retry_after; if (retry) { await new Promise((resolve) => setTimeout(resolve, retry * 1000)); return call(method, params); } throw new Error(`${method}: ${body.error_code} ${body.description}`); } async function onMessage(message) { const chat = message.chat.id; const text = message.text ?? ''; if (text.startsWith('/start')) { await call('sendMessage', { chat_id: chat, text: 'Привет! Нажми кнопку.', buttons: [ [{ text: 'Подбросить монету', callback_data: 'coin' }], [{ text: 'Сайт Comon', url: 'https://comon.chat' }], ], }); } else if (text) { await call('sendMessage', { chat_id: chat, text, reply_to_message_id: message.message_id }); } } async function onCallback(query) { const text = query.data === 'coin' ? (Math.random() < 0.5 ? 'Орёл' : 'Решка') : undefined; await call('answerCallbackQuery', { callback_query_id: query.id, text }); } await call('setMyCommands', { commands: [{ command: 'start', description: 'Начать' }] }); let offset; for (;;) { const updates = await call('getUpdates', { timeout: 50, offset, allowed_updates: ['message', 'callback_query'], }); for (const update of updates) { offset = update.update_id + 1; if (update.message) await onMessage(update.message); else if (update.callback_query) await onCallback(update.callback_query); } } ``` ## Что дальше [#что-дальше] - Перейти на вебхук и проверять подпись: [обновления](./updates.mdx#вебхук-setwebhook). - Команды с параметрами и подсказками: [команды](./commands.mdx). - Ответы, которые видит только нажавший: [временные сообщения](./ephemeral.mdx). - Не отправлять дважды при обрыве сети: [`idempotency_key`](./api.mdx#повторы-и-идемпотентность). # Как устроены боты (/docs/bots/how-bots-work) ## Бот — это профиль [#бот--это-профиль] Бот — обычный профиль федерации с пометкой «бот». У него нет устройств, и в приложение он не входит: за него действует ваша программа с токеном. В чатах у бота пометка «бот», а его владелец виден только самому владельцу. - **Имя пользователя** заканчивается на `bot` (регистр не важен) и занимает то же пространство имён, что люди и публичные чаты. - **Токен** — `cbt__<43 символа>`. Сервер хранит только его хеш. Новый токен сразу отключает старый: незавершённые запросы старого получают 401, его вебхук удаляется, его long poll завершается, а неполученные обновления остаются для нового токена. - **Удаление бота** отзывает токен, убирает бота из всех групп и сообществ и помечает профиль удалённым. Открыть личный чат с удалённым ботом нельзя. ## Где бот бывает [#где-бот-бывает] - **Личный чат.** Его всегда начинает человек, обычно кнопкой «Запустить» (бот получает `/start`). Человек может остановить бота («Остановить бота» или удалив чат): тогда бот не может ему писать, пока его не перезапустят. Об остановке и перезапуске бот узнаёт обновлением [`my_chat_member`](./updates.mdx#my_chat_member). - **Группы и каналы.** Только если у бота включено «Можно добавлять в группы» и его добавил тот, кто вправе добавлять участников. Бот узнаёт ID чата из `my_chat_member` при добавлении и из каждого полученного сообщения. Владельцем группы, канала или сообщества бот не становится. - **Каналы.** В канале бот сначала подписчик. Чтобы он публиковал, назначьте его редактором в списке подписчиков; тогда он пишет в канал через `sendMessage`, а новые посты приходят ему как `channel_post`. - **Сообщества.** Бота добавляет участник с правом управлять сообществом («Добавить в сообщество»). Бот получает собственную роль с выбранными правами: её нельзя удалить или выдать кому-то ещё, она исчезает, когда бот уходит. Права комнат действуют на бота как на любого участника. ## Что бот слышит [#что-бот-слышит] В личке и каналах бот получает всё. В группах и комнатах сообществ действует **режим приватности**: бот получает только - команды (`/команда`, а `/команда@имя_бота` — только если это его имя); - сообщения, где его упомянули; - ответы на его сообщения. Всё остальное бот получает, если у него включено «Читает все сообщения в группах» или если его права в чате позволяют удалять сообщения. Бот **никогда** не получает свои сообщения и сообщения других ботов. Служебные сообщения («X добавил Y») ботам не приходят. Личные чаты с ботом не создают контактов. ## Ограничения [#ограничения] - Бот не начинает личный чат и не пишет тем, кто его остановил (ошибка `bot_stopped`). - Бот проходит те же проверки, что и человек: закрытый модератором чат, фильтр слов, блокировки, настройки приватности получателя. Такие отказы приходят как 403 ([ошибки](./api.mdx#ошибки)). - Отправка тратит тот же бюджет частоты, что у людей: 30 сообщений сразу, затем 5 в секунду. - Удалённый бот, а также бот, чей владелец заблокирован или удалён модераторами, не проходит проверку токена и не получает обновлений. # Боты (/docs/bots) Бот — это профиль федерации, которым управляет ваша программа. Программа работает где угодно и обращается к серверу федерации по HTTP: получает обновления (сообщения, нажатия кнопок, команды) и вызывает методы (отправить сообщение, ответить на нажатие, задать команды). Запросы устроены как в Telegram Bot API: `POST /bot/v1/<метод>`, токен в заголовке, ответ `{"ok": true, "result": …}`. } title="Основы API" href="/bots/api"> Запросы, токен, ответы и ошибки. } title="Обновления" href="/bots/updates"> Long polling, вебхуки с подписью и все виды обновлений. } title="Методы" href="/bots/methods"> Все 17 методов: параметры и результат. } title="Команды" href="/bots/commands"> Команды с типизированными параметрами и подсказками. } title="Кнопки" href="/bots/buttons"> Кнопки в сообщениях и ответы на нажатия. } title="Личные боты" href="/bots/personal"> Бот, который отвечает в личных чатах от имени человека. ## Что умеют боты [#что-умеют-боты] - **Общаться в личке.** Человек находит бота по @имени и нажимает «Запустить». Бот отвечает обычными сообщениями с форматированием и кнопками. - **Работать в группах, каналах и сообществах.** Бота добавляют как участника; в канале он может публиковать посты, в сообществе получает свою роль. - **Команды** со списком подсказок, типизированными параметрами (число, дата, участник, выбор из вариантов) и подсказками от самого бота по мере ввода. - **Кнопки** в сообщениях: ответ ботом во всплывающем сообщении, диалоге или ссылкой, открытие адреса, копирование текста. - **Временные сообщения**, которые видит только один человек, как ephemeral-ответы в Discord. - **Личные боты**: человек подключает бота к своим личным чатам, и тот отвечает от его имени. Бот не может начать личный чат первым, не видит сообщений других ботов и своих собственных. ## Быстрый старт [#быстрый-старт] ### Создайте бота [#создайте-бота] В приложении откройте **Настройки › Боты › Мои боты › Создать бота**. Задайте имя и имя пользователя — оно должно заканчиваться на `bot`, например `weather_bot`. Приложение покажет **токен** вида `cbt__<секрет>`. Скопируйте его сразу: он показывается один раз. Кто знает токен, управляет ботом. Потеряли — выпустите новый в карточке бота («Выпустить новый токен»), старый перестанет работать сразу. ### Проверьте токен [#проверьте-токен] ```sh export TOKEN='cbt_...' export API='https://comon.chat/bot/v1' # адрес вашей федерации curl -s -X POST "$API/getMe" -H "Authorization: Bearer $TOKEN" ``` ```json {"ok": true, "result": {"id": "…", "is_bot": true, "first_name": "Погода", "username": "weather_bot", "can_join_groups": false, "reads_all_messages": false, "supports_personal": false}} ``` ### Получите первое сообщение [#получите-первое-сообщение] Найдите бота в приложении по @имени, нажмите «Запустить» и напишите ему что-нибудь. Затем: ```sh curl -s -X POST "$API/getUpdates" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' -d '{"timeout": 30}' ``` В ответе будет обновление `message` с `chat.id`. ### Ответьте [#ответьте] ```sh curl -s -X POST "$API/sendMessage" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"chat_id": "", "text": "Привет!", "buttons": [[{"text": "Ещё", "callback_data": "more"}]]}' ``` Полные примеры на Python и Node.js — в [примерах](./examples.mdx). Посмотреть все возможности вживую можно у встроенного `@demo_bot`, если его не выключили на вашем сервере. ## Настройки бота [#настройки-бота] В карточке бота в **Мои боты** владелец меняет имя, описание, строку «О боте», аватар и три переключателя: | Переключатель | Что значит | |---|---| | Можно добавлять в группы | Бота можно добавить в группу, канал или сообщество. Без него бот живёт только в личке. | | Читает все сообщения в группах | Бот получает все сообщения групп и комнат, а не только команды, упоминания и ответы ему ([приватность](./how-bots-work.mdx#что-бот-слышит)). | | Может быть личным ботом | Люди могут подключить бота как [личного](./personal.mdx). | Сколько ботов можно создать, решает федерация: по умолчанию 20 на человека ([политика ботов](../selfhost/bots-and-bridges.mdx)). # Лимиты ботов (/docs/bots/limits) ## Боты [#боты] | Что | Сколько | |---|---:| | Ботов у одного человека | 20, федерация может изменить ([политика](../selfhost/bots-and-bridges.mdx)) | | Имя пользователя | 3–32 символа, заканчивается на `bot` | | Описание / строка «О боте» | 512 / 120 символов | | Тело запроса | 1 МиБ | | Частота отправки, правки и удаления | 30 сразу, затем 5 в секунду | ## Обновления [#обновления] | Что | Сколько | |---|---:| | Хранение обновлений | 24 часа, не больше 100 000 на бота | | `getUpdates`: `limit` / `timeout` | 1–100 / 0–50 секунд | | Секрет вебхука | 16–256 символов | | Ожидание ответа вебхука | 10 секунд | | Пауза между повторами вебхука | растёт до 1 минуты | ## Сообщения [#сообщения] | Что | Сколько | |---|---:| | Текст | 32 768 символов | | Блоков в документе | 256 | | Документ целиком | 512 КиБ | | Удаление за раз | 100 сообщений | | `idempotency_key` | 1–128 символов | ## Команды [#команды] | Что | Сколько | |---|---:| | Команд в одной области | 100, вместе до 64 КиБ | | Областей с командами | 64 | | Описание команды | 256 символов | | Параметров у команды | 10 | | Вариантов у параметра, подсказок в ответе | 25 | | Название варианта | 100 символов | | Текстовый параметр, `max_length` | 1024 символа | | Ответ на подсказку | 3 секунды | | Текст запуска команды | 4096 символов | ## Кнопки [#кнопки] | Что | Сколько | |---|---:| | Рядов / кнопок в ряду / кнопок в сообщении | 8 / 8 / 32 | | Подпись кнопки | 64 символа | | `callback_data` | 64 байта | | `copy_text` | 256 символов | | Ответ на нажатие | 10 секунд | | Текст ответа на нажатие | 200 символов | ## Временные сообщения [#временные-сообщения] | Что | Сколько | |---|---:| | Сколько ждёт взаимодействие | 15 минут | | Срок жизни | 24 часа | | Живых у одного бота для одного человека | 20, новое удаляет самое старое | ## Личные боты [#личные-боты] | Что | Сколько | |---|---:| | Окно ответа после последнего сообщения собеседника | 24 часа | | Людей в списке «только» или «кроме» | 100 | # Сообщения (/docs/bots/messages) Бот пишет сообщение одним из двух способов: `text` с `entities` для обычного текста или `document` для богатого сообщения. К обоим можно добавить `buttons` и `reply_to_message_id`. ## Текст [#текст] ```json { "chat_id": "…", "text": "Привет, мир" } ``` До 32 768 символов. Пустой текст или текст из одних пробелов не принимается. ### Оформление [#оформление] `entities` размечают отрезки `text`. `offset` и `length` — в единицах UTF-16 ([Entity](./objects.mdx#entity)). ```json { "chat_id": "…", "text": "Сборка 42 готова: открыть", "entities": [ { "type": "bold", "offset": 0, "length": 9 }, { "type": "text_link", "offset": 18, "length": 7, "url": "https://ci.example.org/42" } ] } ``` Разметка Markdown или HTML в тексте не разбирается: звёздочки останутся звёздочками. ## Документ [#документ] Сообщения Comon — это документы из блоков: абзацы, заголовки, списки, цитаты, код, таблицы, колонки, выноски, раскрывающиеся блоки ([форматирование](../features/formatting.mdx)). Бот может прислать документ целиком в поле `document`. Его форма — JSON сообщения `InputDocument` из `protocol/comon/federation/document.proto` с полями в camelCase. ```json { "chat_id": "…", "document": { "schemaVersion": 1, "blocks": [ { "id": "0000000000000000000000000000000a", "heading": { "level": 2, "content": { "id": "0000000000000000000000000000000b", "text": "Сборка 42" } } }, { "id": "0000000000000000000000000000000c", "code": { "content": { "id": "0000000000000000000000000000000d", "text": "flutter build web" }, "language": "sh" } }, { "id": "0000000000000000000000000000000e", "list": { "kind": "DOCUMENT_LIST_KIND_BULLET", "items": [ { "id": "0000000000000000000000000000000f", "blocks": [ { "id": "00000000000000000000000000000010", "paragraph": { "id": "00000000000000000000000000000011", "text": "тесты прошли" } } ] } ] } } ] }, "buttons": [[{ "text": "Открыть", "url": "https://ci.example.org/42" }]] } ``` - ID блоков и текстов — 32 шестнадцатеричных символа в нижнем регистре, уникальные внутри документа. Порядок значения не имеет: можно нумеровать подряд. - Заголовки — уровней 1–3. - Ограничения документа: до 256 блоков, вложенность списков и цитат до 4 уровней, до 512 КиБ ([лимиты](./limits.mdx)). - Неверный документ вернёт 400 с описанием ошибки. ## Ответ на сообщение [#ответ-на-сообщение] ```json { "chat_id": "…", "text": "Принято", "reply_to_message_id": "" } ``` Сообщение должно быть из того же чата. ## Правка и удаление [#правка-и-удаление] `editMessage` заменяет содержимое целиком, вместе с кнопками: чтобы убрать кнопки, пришлите сообщение без `buttons`. Бот правит свои сообщения: в личках и группах в течение 48 часов, в каналах и комнатах сообществ без ограничения. `deleteMessage` удаляет одно (`message_id`) или до 100 сообщений (`message_ids`) у всех. ## Повторная отправка [#повторная-отправка] Чтобы повтор после обрыва сети не отправил сообщение дважды, передавайте `idempotency_key` ([повторы](./api.mdx#повторы-и-идемпотентность)). ## Медиа [#медиа] Отправка файлов, фото и голосовых через Bot API пока не поддерживается. Бот получает входящие медиа в `document` как блоки с вложениями и может ссылаться на внешние адреса кнопками и ссылками. # Методы (/docs/bots/methods) Все методы вызываются как `POST /bot/v1/<метод>` с токеном ([основы](./api.mdx)). Обязательные параметры отмечены **жирным**. Объекты `User`, `Chat`, `Message` описаны в [объектах](./objects.mdx). | Метод | Что делает | |---|---| | [`getMe`](#getme) | Профиль бота | | [`getUpdates`](#getupdates) | Получить обновления | | [`setWebhook`](#setwebhook), [`deleteWebhook`](#deletewebhook), [`getWebhookInfo`](#getwebhookinfo) | Вебхук | | [`sendMessage`](#sendmessage) | Отправить сообщение или временное сообщение | | [`editMessage`](#editmessage) | Изменить сообщение | | [`deleteMessage`](#deletemessage) | Удалить сообщения | | [`answerCallbackQuery`](#answercallbackquery) | Ответить на нажатие кнопки | | [`answerAutocompleteQuery`](#answerautocompletequery) | Подсказать значения параметра | | [`setMyCommands`](#setmycommands), [`getMyCommands`](#getmycommands), [`deleteMyCommands`](#deletemycommands) | Команды | | [`editEphemeralMessage`](#editephemeralmessage), [`deleteEphemeralMessage`](#deleteephemeralmessage) | Временные сообщения | | [`getChat`](#getchat) | Сведения о чате | | [`readPersonalMessages`](#readpersonalmessages) | Отметить прочитанным за человека | ## getMe [#getme] Без параметров. Результат — [`User`](./objects.mdx#user) бота и его переключатели: ```json { "id": "…", "is_bot": true, "first_name": "Погода", "username": "weather_bot", "can_join_groups": true, "reads_all_messages": false, "supports_personal": false } ``` ## getUpdates [#getupdates] | Параметр | Тип | | |---|---|---| | `offset` | целое | Первый нужный `update_id`; меньшие удаляются. | | `limit` | целое | 1–100, по умолчанию 100. | | `timeout` | целое | Ожидание в секундах, 0–50, по умолчанию 0. | | `allowed_updates` | строки | Виды обновлений. Запоминаются. | Результат — массив обновлений. 409, если задан вебхук. Подробно — в [обновлениях](./updates.mdx). ## setWebhook [#setwebhook] | Параметр | Тип | | |---|---|---| | **`url`** | строка | HTTPS на публичном адресе. | | `secret` | строка | 16–256 символов `A-Z a-z 0-9 _ -`; включает подпись `X-Comon-Signature`. | | `allowed_updates` | строки | Виды обновлений. | | `drop_pending_updates` | логическое | Удалить накопленные обновления. | Результат — `true`. Повторный вызов заменяет вебхук и сбрасывает последнюю ошибку. ## deleteWebhook [#deletewebhook] | Параметр | Тип | | |---|---|---| | `drop_pending_updates` | логическое | Удалить накопленные обновления. | Результат — `true`. ## getWebhookInfo [#getwebhookinfo] Без параметров. Результат: | Поле | Тип | | |---|---|---| | `url` | строка | Пустая, если вебхука нет. | | `has_secret` | логическое | Задан ли секрет. | | `pending_update_count` | целое | Сколько обновлений ждёт. | | `last_error_date` | целое | Время последней ошибки, Unix-секунды. | | `last_error_message` | строка | Последняя ошибка: `HTTP status 502`, `Timed out`, `Connection failed: …`. | ## sendMessage [#sendmessage] | Параметр | Тип | | |---|---|---| | **`chat_id`** | строка | Куда. Бот должен состоять в чате, а в личке человек должен был запустить бота. | | `text` | строка | Текст. Нужен `text` или `document`. | | `entities` | массив | Оформление `text` ([сообщения](./messages.mdx#оформление)). | | `document` | объект | Документ с заголовками, списками, кодом и другими блоками ([сообщения](./messages.mdx#документ)). Вместо `text`. | | `buttons` | массив рядов | Кнопки ([кнопки](./buttons.mdx)). | | `reply_to_message_id` | строка | Ответ на сообщение этого чата. | | `idempotency_key` | строка | 1–128 символов; повтор с тем же ключом вернёт то же сообщение. | | `on_behalf_of` | строка | ID человека: личный бот отвечает от его имени ([личные боты](./personal.mdx)). | | `ephemeral` | объект | Отправить [временное сообщение](./ephemeral.mdx) вместо обычного. | Результат — отправленное [`Message`](./objects.mdx#message). С `ephemeral` результат другой: ```json { "ephemeral_message_id": "…", "chat": {...}, "receiver": {...}, "expires_at": 1793136400 } ``` ## editMessage [#editmessage] | Параметр | Тип | | |---|---|---| | **`chat_id`** | строка | | | **`message_id`** | строка | Сообщение бота (или человека, если бот личный и передан `on_behalf_of`). | | `text`, `entities`, `document`, `buttons`, `reply_to_message_id` | | Новое содержимое, как в `sendMessage`. Кнопки заменяются целиком. | | `on_behalf_of` | строка | ID человека для личного бота. | Результат — изменённое `Message` или `true`. ## deleteMessage [#deletemessage] | Параметр | Тип | | |---|---|---| | **`chat_id`** | строка | | | `message_id` | строка | Одно сообщение. | | `message_ids` | строки | Или до 100 сообщений сразу. | | `on_behalf_of` | строка | ID человека для личного бота. | Результат — `true`. Бот удаляет свои сообщения, а чужие — если в чате у него есть право удалять. ## answerCallbackQuery [#answercallbackquery] | Параметр | Тип | | |---|---|---| | **`callback_query_id`** | строка | `id` из обновления `callback_query`. | | `text` | строка | До 200 символов: всплывающее сообщение. | | `show_alert` | логическое | Показать `text` диалогом, который человек закроет сам. | | `url` | строка | Открыть адрес. | Результат — `true`. Без `text` и `url` ничего не показывается. Отвечайте за 10 секунд; позже — 400. ## answerAutocompleteQuery [#answerautocompletequery] | Параметр | Тип | | |---|---|---| | **`autocomplete_query_id`** | строка | `id` из обновления `autocomplete_query`. | | `choices` | массив | До 25 вариантов `{"name": "Алматы", "value": "almaty"}`; `value` — того же типа, что параметр. | Результат — `true`. Отвечайте за 3 секунды. ## setMyCommands [#setmycommands] | Параметр | Тип | | |---|---|---| | **`commands`** | массив | До 100 команд ([команды](./commands.mdx)). Пустой массив удаляет команды области. | | `scope` | объект | Область: `{"type": "default"}` (по умолчанию), `all_private_chats`, `all_group_chats` или `{"type": "chat", "chat_id": "…"}`. | Результат — `true`. ## getMyCommands [#getmycommands] | Параметр | Тип | | |---|---|---| | `scope` | объект | Как в `setMyCommands`. | Результат — массив команд этой области в том же виде, в каком они заданы. ## deleteMyCommands [#deletemycommands] | Параметр | Тип | | |---|---|---| | `scope` | объект | Как в `setMyCommands`. | Результат — `true`. ## editEphemeralMessage [#editephemeralmessage] | Параметр | Тип | | |---|---|---| | **`ephemeral_message_id`** | строка | Временное сообщение этого бота. | | `text`, `entities`, `document`, `buttons` | | Новое содержимое. | Результат — `{"ephemeral_message_id": "…"}`. Срок жизни не продлевается. ## deleteEphemeralMessage [#deleteephemeralmessage] | Параметр | Тип | | |---|---|---| | **`ephemeral_message_id`** | строка | | Результат — `true`. ## getChat [#getchat] | Параметр | Тип | | |---|---|---| | **`chat_id`** | строка | Чат, где бот состоит. | Результат — [`Chat`](./objects.mdx#chat), у личных чатов и групп ещё `member_count`. 404, если чата нет или бот в нём не состоит. ## readPersonalMessages [#readpersonalmessages] | Параметр | Тип | | |---|---|---| | **`owner_id`** | строка | Человек, подключивший бота. | | **`chat_id`** | строка | Его личный чат. | | **`read_through_order`** | целое | `order` последнего прочитанного сообщения. | Результат — `true`. Нужно право «Отмечать сообщения прочитанными» ([личные боты](./personal.mdx)). # Объекты (/docs/bots/objects) Все ID в Comon — непрозрачные строки: не разбирайте их и не превращайте в числа. Время — Unix-секунды. ## User [#user] Профиль человека или бота. | Поле | Тип | | |---|---|---| | `id` | строка | ID профиля. | | `is_bot` | логическое | Бот ли это. | | `first_name` | строка | Имя. | | `last_name` | строка | Фамилия, если есть. | | `username` | строка | @имя без `@`, если есть. | ```json { "id": "…", "is_bot": false, "first_name": "Анна", "last_name": "Ким", "username": "anna" } ``` ## Chat [#chat] | Поле | Тип | | |---|---|---| | `id` | строка | ID чата. | | `type` | строка | `private` (личный), `group`, `channel`, `community`, `room` (комната сообщества). | | `user` | `User` | У `private`: собеседник бота. | | `title` | строка | У остальных: название. | | `username` | строка | @имя публичного чата, если есть. | | `community_id` | строка | У `room`: сообщество, которому принадлежит комната. | ```json { "id": "…", "type": "room", "title": "релизы", "community_id": "…" } ``` ## Message [#message] | Поле | Тип | | |---|---|---| | `message_id` | строка | ID сообщения в чате. | | `chat` | `Chat` | Чат. | | `from` | `User` | Автор, если он есть. | | `date` | целое | Время отправки. | | `edited` | `true` | Есть, если сообщение редактировали. | | `order` | целое | Порядковый номер в чате; нужен для `readPersonalMessages`. | | `text` | строка | Весь текст сообщения: абзацы, заголовки, код, подписи и ячейки таблиц, по строке на блок. | | `entities` | массив | Оформление и упоминания в `text`. | | `reply_to_message_id` | строка | На какое сообщение это ответ. | | `document` | объект | Полный документ сообщения со всеми блоками и вложениями. | | `command` | объект | Только в обновлении `message`: `{"name", "options"}` обычной команды, запущенной из приложения ([команды](./commands.mdx)). | Для простых ботов достаточно `text`. `document` нужен, если важна структура: медиа, списки, таблицы, цитаты. Его форма описана в `protocol/comon/federation/document.proto`, в JSON поля пишутся в camelCase. ## Entity [#entity] Отрезок `text` с оформлением. `offset` и `length` считаются в единицах UTF-16, как в JavaScript и Telegram: эмодзи вне базовой плоскости занимает две единицы. | `type` | Дополнительно | Что значит | |---|---|---| | `bold`, `italic`, `underline`, `strikethrough`, `code`, `spoiler` | | Оформление. | | `text_link` | `url` | Ссылка под текстом. | | `mention` | `user_id` | Упоминание человека. Только во входящих сообщениях. | | `mention_all` | | Упоминание всех участников. Только во входящих. | ```json { "type": "text_link", "offset": 0, "length": 7, "url": "https://comon.chat" } ``` ## BotCommand [#botcommand] | Поле | Тип | | |---|---|---| | `command` | строка | Имя без `/`: строчные латинские буквы, цифры и `_`. | | `description` | строка | До 256 символов. | | `ephemeral` | логическое | [Временная команда](./ephemeral.mdx#временные-команды). | | `options` | массив | Параметры ([команды](./commands.mdx#параметры)). | # Личные боты (/docs/bots/personal) Человек может подключить одного бота как **личного**: бот читает выбранные личные чаты этого человека и действует в них от его имени — например, отвечает клиентам, пока человек занят. Для собеседника ответ бота — обычное сообщение человека; сам человек видит под ним «Отправил <бот>». ## Подключение [#подключение] Бот должен разрешать это: переключатель «Может быть личным ботом» в его настройках. Человек открывает **Настройки › Боты › Личный бот**, вводит @имя бота и выбирает: - **Чаты**: контакты, остальные, только перечисленные люди или все, кроме перечисленных. Чаты с ботами и со служебным профилем федерации не охватываются никогда. - **Что может бот**: «Отвечать на сообщения», «Отмечать сообщения прочитанными», «Удалять свои ответы», «Удалять любые сообщения», «Ставить реакции». В каждом охваченном чате человек видит плашку «<бот> управляет этим чатом» с кнопками «Приостановить» и «Возобновить». ## Обновления [#обновления] | Вид | Когда | |---|---| | `personal_connection` | Человек подключил или отключил бота. | | `personal_message` | Новое сообщение в охваченном чате, в том числе от самого человека. | | `edited_personal_message` | Его отредактировали. | | `deleted_personal_messages` | Сообщения удалили. | ```json { "personal_connection": { "owner": { "id": "…", "is_bot": false, "first_name": "Анна" }, "connected": true, "rights": { "reply": true, "mark_read": true, "delete_sent": true, "delete_all": false, "react": false }, "date": 1793050000 } } ``` ```json { "personal_message": { "message_id": "…", "chat": {...}, "from": {...}, "date": 1793050000, "order": 512, "text": "Здравствуйте, вы работаете в субботу?", "owner_id": "…", "outgoing": false } } ``` - `owner_id` — человек, подключивший бота; `chat` показан с его стороны. - `outgoing: true` — сообщение написал сам человек (или бот от его имени, тогда ещё `sent_by_bot: true`). - Отключение (в том числе подключение другого бота или удаление аккаунта) забирает из очереди ещё не полученные обновления этого человека; пауза в чате — обновления этого чата. ## Ответ от имени человека [#ответ-от-имени-человека] ```json { "chat_id": "…", "text": "Да, с 10 до 16.", "on_behalf_of": "" } ``` - Нужно право «Отвечать на сообщения». - Ответить можно только в течение **24 часов** после последнего сообщения собеседника, иначе 409 `reply_window_closed`. - Кнопки в таких сообщениях запрещены. - `deleteMessage` с `on_behalf_of` удаляет только ответы самого бота (право «Удалять свои ответы») или любые сообщения (право «Удалять любые сообщения»). - `readPersonalMessages` с `owner_id`, `chat_id` и `read_through_order` (поле `order` сообщения) отмечает чат прочитанным за человека. Если владелец заблокирован или удалён, личный бот читает, но ничего не может сделать. # Обновления (/docs/bots/updates) Всё, что происходит с ботом, приходит **обновлениями**. Сервер хранит их в очереди бота, поэтому они переживают перезапуск сервера и бота. Получать их можно двумя способами — long polling или вебхук, но не обоими сразу. Каждое обновление — объект с номером и ровно одним полем вида: ```json { "update_id": 42, "message": { ... } } ``` Номера растут по порядку. Очередь хранит обновления **24 часа** и не больше **100 000** на бота; старые отбрасываются первыми. ## Long polling: `getUpdates` [#long-polling-getupdates] ```sh curl -s -X POST "$API/getUpdates" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"offset": 43, "timeout": 50, "allowed_updates": ["message", "callback_query"]}' ``` | Параметр | Тип | Что значит | |---|---|---| | `offset` | целое | Номер первого нужного обновления. Все с меньшими номерами считаются полученными и удаляются. Передавайте `update_id` последнего обработанного + 1. | | `limit` | целое | Сколько вернуть, от 1 до 100. По умолчанию 100. | | `timeout` | целое | Сколько секунд ждать, если очередь пуста, от 0 до 50. По умолчанию 0 (ответить сразу). | | `allowed_updates` | список строк | Какие виды получать. Запоминается для следующих запросов и для вебхука. Без него действует прошлый список, а если его не задавали, все виды. | Результат — массив обновлений (может быть пустым). Новый `getUpdates` того же бота завершает предыдущий ожидающий запрос пустым ответом, поэтому держите один цикл опроса на бота. Если задан вебхук, `getUpdates` отвечает 409: удалите вебхук (`deleteWebhook`), чтобы опрашивать. ## Вебхук: `setWebhook` [#вебхук-setwebhook] Сервер сам отправляет каждое обновление `POST`-запросом на адрес бота. ```sh curl -s -X POST "$API/setWebhook" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"url": "https://bot.example.org/comon", "secret": "a-long-random-secret-0123"}' ``` | Параметр | Тип | Что значит | |---|---|---| | `url` | строка | Адрес HTTPS на публичном сервере. Обязателен. | | `secret` | строка | От 16 до 256 символов: латиница, цифры, `_` и `-`. С ним каждый запрос подписан. | | `allowed_updates` | список строк | Какие виды получать. | | `drop_pending_updates` | `true` | Удалить накопившиеся обновления. | Как сервер доставляет: - одно обновление на запрос, по порядку: следующее уходит, только когда предыдущее принято; - тело — JSON обновления, `Content-Type: application/json`; - ответ 2xx — доставлено. Любой другой код, перенаправление 3xx, ошибка соединения или 10 секунд без ответа — ошибка; сервер повторяет с растущей паузой до минуты, пока не получится или пока обновление не устареет; - адрес должен вести на публичный IP: частные адреса, `localhost` и IPv6-формы с IPv4 внутри (NAT64, 6to4, Teredo) запрещены. Имя проверяется при `setWebhook` и перед каждой отправкой: если оно стало указывать на частный адрес, обновление ждёт. Сертификат проверяется по имени из адреса. `deleteWebhook` (с необязательным `drop_pending_updates`) убирает вебхук. `getWebhookInfo` показывает текущее состояние: ```json { "url": "https://bot.example.org/comon", "has_secret": true, "pending_update_count": 0, "last_error_date": 1793050000, "last_error_message": "HTTP status 502" } ``` ### Проверка подписи [#проверка-подписи] С `secret` каждый запрос несёт заголовок: ``` X-Comon-Signature: t=1793050000,v1=5f2b… ``` `v1` — HMAC-SHA256 от строки `.<тело запроса>` с ключом `secret`, в шестнадцатеричном виде. Проверяйте по сырым байтам тела, до разбора JSON, и отвергайте старые `t`, чтобы чужой перехват нельзя было отправить повторно. ```python import hashlib, hmac, time def verify(secret: str, header: str, body: bytes, tolerance: int = 300) -> bool: parts = dict(item.split("=", 1) for item in header.split(",")) t, v1 = parts.get("t", ""), parts.get("v1", "") if not t.isdigit() or abs(time.time() - int(t)) > tolerance: return False expected = hmac.new(secret.encode(), t.encode() + b"." + body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, v1) ``` ```js import { createHmac, timingSafeEqual } from 'node:crypto'; export function verify(secret, header, body, tolerance = 300) { const parts = Object.fromEntries(header.split(',').map((p) => p.split('=', 2))); const t = Number(parts.t); if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > tolerance) return false; const expected = createHmac('sha256', secret).update(`${t}.`).update(body).digest('hex'); const given = Buffer.from(parts.v1 ?? '', 'utf8'); return given.length === expected.length && timingSafeEqual(Buffer.from(expected), given); } ``` ## Виды обновлений [#виды-обновлений] | Вид | Когда приходит | |---|---| | `message` | Новое сообщение в личке, группе или комнате, которое бот слышит. | | `edited_message` | Его отредактировали. | | `deleted_messages` | Сообщения удалили. | | `channel_post` | Новый пост в канале, где бот состоит. | | `callback_query` | Человек нажал кнопку с `callback_data`. | | `ephemeral_command` | Человек запустил временную команду. | | `autocomplete_query` | Человек заполняет параметр с подсказками. | | `my_chat_member` | Бота добавили или убрали из чата, остановили или перезапустили. | | `personal_connection` | Человек подключил или отключил бота как личного. | | `personal_message` | Новое сообщение в личном чате человека, подключившего бота. | | `edited_personal_message` | Его отредактировали. | | `deleted_personal_messages` | Сообщения в таком чате удалили. | Формы объектов `User`, `Chat` и `Message` — в [объектах](./objects.mdx). ### message, edited_message, channel_post [#message-edited_message-channel_post] Объект [`Message`](./objects.mdx#message). Правка поста в канале тоже приходит как `channel_post`, с `"edited": true`. Если это обычная команда с параметрами, запущенная из приложения, в нём есть ещё `command`: ```json { "update_id": 7, "message": { "message_id": "…", "chat": {"id": "…", "type": "group", "title": "Команда"}, "from": {"id": "…", "is_bot": false, "first_name": "Анна"}, "date": 1793050000, "order": 118, "text": "/remind когда:2026-11-01 что:релиз", "command": {"name": "remind", "options": {"когда": "2026-11-01", "что": "релиз"}} } } ``` ### deleted_messages [#deleted_messages] ```json { "chat": {"id": "…", "type": "private", "user": {...}}, "message_ids": ["…", "…"] } ``` ### callback_query [#callback_query] ```json { "id": "…", "from": {...}, "chat": {...}, "message": {...}, "ephemeral_message_id": "…", "button_id": "…", "data": "more" } ``` `message` — сообщение с кнопкой (если нажата кнопка обычного сообщения), `ephemeral_message_id` — если нажата кнопка временного сообщения. Ответьте `answerCallbackQuery` за **10 секунд** ([кнопки](./buttons.mdx)). ### ephemeral_command [#ephemeral_command] ```json { "id": "…", "from": {...}, "chat": {...}, "text": "/secret привет", "command": "secret", "args": "привет", "options": {"кому": ""}, "date": 1793050000 } ``` `id` — ID взаимодействия: ответьте временным сообщением в течение 15 минут ([временные сообщения](./ephemeral.mdx)). ### autocomplete_query [#autocomplete_query] ```json { "id": "…", "from": {...}, "chat": {...}, "command": "weather", "options": {"страна": "KZ"}, "focused": "город", "query": "Ал" } ``` Ответьте `answerAutocompleteQuery` за **3 секунды** ([команды](./commands.mdx#подсказки)). ### my_chat_member [#my_chat_member] ```json { "chat": {...}, "from": {...}, "status": "member", "date": 1793050000 } ``` | `status` | Когда | |---|---| | `member` | Бота добавили в группу, канал или сообщество, или человек перезапустил бота в личке. | | `left` | Бота убрали из группы, канала или сообщества. `chat` тогда содержит только `id`. | | `stopped` | Человек остановил бота в личке. | `from` есть только у остановки и перезапуска в личке: это человек, который это сделал. ### personal_connection, personal_message [#personal_connection-personal_message] См. [личные боты](./personal.mdx#обновления). # Сборка из исходников (/docs/develop/build) ## Что понадобится [#что-понадобится] - [mise](https://mise.jdx.dev), который установит инструменты из `mise.toml` и `mise.lock`. - PostgreSQL: сервер федерации хранит всё в нём. - Для сборки под iOS и macOS нужен Xcode, под Android нужен Android SDK, под Windows нужна Visual Studio с компонентами для C++. ## Тестовая федерация [#тестовая-федерация] ### Исходники [#исходники] ```sh git clone https://github.com/serezhia/chat_playground.git cd chat_playground mise trust mise install --locked mise run setup ``` ### База [#база] Создайте пустую базу и запишите строку подключения libpq в файл, например `host=localhost user=postgres password=postgres dbname=comon_local` в `.local/conninfo`. Затем создайте в ней схемы: ```sh cd backend/comon_federation_server mise exec -- dart run bin/migrate_database.dart --postgres-conninfo-file=../../.local/conninfo ``` ### Сервер [#сервер] ```sh mise exec -- dart run bin/comon_federation_server.dart --postgres-conninfo-file=../../.local/conninfo ``` Сервер слушает `https://localhost:8443` с тестовым сертификатом, хранит файлы в `.local/comon-federation` текущего каталога и впускает под любым именем через встроенную страницу входа. Для настоящих пользователей он не подходит, для них есть [полный стек](../selfhost/quick-start.mdx). Приложению нужно сказать, что тестовому сертификату можно доверять. На Windows это делает сценарий `mise run run:local`, он же запускает пару пользователей для проверки переписки, см. [инструкцию](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/local-development.md). На macOS и Linux проще поднять [полный стек](../selfhost/quick-start.mdx) и собрать приложение для него. ## Приложение для своей федерации [#приложение-для-своей-федерации] `tools/mvp-stack.py up` записывает файл `.local/mvp/client.json` с адресом федерации и, если сертификат выпустил внутренний центр Caddy, с этим сертификатом. Передайте его сборке: ```sh cd frontend/comon_client mise exec -- flutter run --dart-define-from-file=../../.local/mvp/client.json ``` Подписанные сборки для магазинов и тестировщиков описаны в инструкциях для [Apple](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/apple-release.md), [Android](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/android-release.md) и [Windows](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/windows-flavors.md). ## Проверки [#проверки] Перед отправкой изменений запустите те же проверки, что и CI: ```sh mise run verify ``` Как запускать их только для изменённых пакетов, написано в [`AGENTS.md`](https://github.com/serezhia/chat_playground/blob/master/AGENTS.md). # История изменений (/docs/develop/changelog) Главное в каждом выпуске и что сделать на сервере при обновлении. Полный список изменений на английском ведётся в [`docs/releases/CHANGELOG.md`](https://github.com/serezhia/chat_playground/blob/master/docs/releases/CHANGELOG.md), выпуски и установщики лежат на [GitHub](https://github.com/serezhia/chat_playground/releases). «Обязательное обновление» значит, что старые приложения перестают подключаться и показывают экран обновления ([версии приложений](../selfhost/app-updates.mdx)). Данные людей при этом остаются. ## 0.3.1, 22 ноября 2026 [#031-22-ноября-2026] Обычное обновление: протокол не менялся, приложения 0.3.0 продолжают работать с сервером 0.3.1. - Чат меньше дёргается при прокрутке во время синхронизации. - История чатов больше не зависает после наплыва событий и не требует переподключения федерации. - [Календарь](../features/calendar.mdx): после дневного лимита событий отказ сохраняется, а остальные изменения продолжают отправляться. - На iOS приложение быстрее открывается после накопившихся уведомлений. - Почта: при переключении вкладок «Входящих» видны сохранённые письма, поиск помнит положение во всех вкладках. **На сервере.** Ничего делать не нужно: обновляются только приложения. ## 0.3.0, 16 ноября 2026 [#030-16-ноября-2026] Протокол сменил поколение основного соединения: приложения 0.2.9 не подключатся к серверу 0.3.0 и покажут экран обновления. Приложения 0.3.0 с сервером 0.2.9 тоже покажут экран обновления, хотя устарел сервер. Обновите федерацию и сразу после неё опубликуйте приложения. - Новый интерфейс на всех экранах: оболочка, список чатов, чат, почта, календарь, звонки, сообщества, настройки, группы, каналы и ссылки. Загрузка показывается шиммером, а ошибки, которые проходят сами, повторяются без кнопки «Повторить». - [Группы](../features/chats.mdx): создание в два шага, описание группы, ссылки-приглашения со сроком, лимитом и одобрением, заявки на вступление. - Напоминание, поставленное на компьютере, звенит на телефоне будильником, даже если приложение на телефоне не открывали. - [Звонки](../features/calls.mdx): новые экраны разговора и конференции; при переходе по приложению звонок сворачивается. - [Стикеры](../features/stickers.mdx): жалобы на наборы попадают в общую очередь жалоб федерации; анимированные стикеры больше не перерисовываются на каждом круге. - Роли федерации меняют порядок перетаскиванием. - [Веб](../selfhost/web.mdx): WebAssembly в свежих Chrome, Safari и Firefox, запуск без сети и баннер «Обновить» после нового выпуска. **На сервере.** Сначала бэкап. Перед запуском федерации выполните `migrate_database`: без него сервер не запустится, он переносит открытые жалобы на стикеры в общую очередь. Схемы календаря (50) и сообщений (53) обновляются на месте. После федерации перезапустите push relay, потом публикуйте приложения. Серверные образы собираются на `dart:3.14.0`; для веба нужен новый `deploy/web/Caddyfile`. ## 0.2.9, 10 ноября 2026 [#029-10-ноября-2026] Обновление не обязательное: минимальный уровень клиента остаётся 29, рекомендуемый 30, и приложения 0.2.8 предложат обновиться. Если в приложении 0.2.9 выбрать напоминание «до начала» при дороге, приложения 0.2.8 этого аккаунта не прочитают настройки напоминаний до обновления. Приложения 0.2.9 передают медиа кусками, которые сервер 0.2.8 не принимает, поэтому сначала обновите федерацию, потом публикуйте приложения. - [Медиа](../features/media.mdx) загружаются и скачиваются быстрее: куски по 1 МиБ и 512 КиБ, несколько запросов сразу, соединения в фоновом потоке. - [Звонки](../features/calls.mdx): камера в H.264 через аппаратный кодер, 1080p на компьютере и 720p на телефоне, в тишине микрофон почти ничего не отправляет. Шумоподавление можно менять прямо во время звонка. - Приложение меньше работает в фоне и реже пишет на диск, быстрее догружает чаты после подключения и шифрует соединение нативным кодом (кроме веба). - Письмо из уведомления ждёт связи вместо ошибки, а возврат в приложение сразу переподключает. - [Календарь](../features/calendar.mdx): месяцы листаются без загрузки; с дорогой можно выбрать напоминание до выезда или до начала события. - [Почта](../features/mail.mdx): если ящиков несколько, в уведомлении видно, в какой пришло письмо; на значке инициалы отправителя. Для каждого ящика можно задать название и выбрать, о каких разделах и папках уведомлять, или выключить уведомления совсем. **На сервере.** Сначала бэкап. Почтовая схема сервера переходит на версию 12 на месте. Сначала федерация, после неё перезапустите push relay, потом публикуйте приложения. ## 0.2.8, 10 ноября 2026 [#028-10-ноября-2026] Минимальный уровень клиента 29: приложения подписывают запросы к push relay для своего relay. Новые приложения работают и с сервером 0.2.7, поэтому сначала опубликуйте их, потом обновите федерацию и перезапустите push relay. - [Календарь](../features/calendar.mdx): свои календари можно создавать и удалять вместе с событиями. Можно выбрать, кто видит вашу занятость и кто видит подробности каждого календаря; открытые вам календари включаются в профиле человека. Помощники могут вести календарь за владельца: создавать и менять события и отвечать на приглашения от его имени. - На iOS 26 будильник, снятый на другом устройстве, гаснет и без запущенного приложения. - [Почта](../features/mail.mdx): новые письма во «Входящих» приходят за секунды, папки и письма открываются без загрузки, последние письма читаются без сети, ящики на устройстве работают офлайн. - Уведомление о письме исчезает на всех устройствах, когда письмо прочитали, перенесли или удалили. На Windows появились уведомления о письмах. - Исправлены падения из отчётов 0.2.7, Android снова отправляет видео из галереи. **На сервере.** Сначала бэкап. Данные сервера и устройств переходят на новые схемы на месте. В `federation-push.json` relay перечисляются в `relays` ([push](../selfhost/push.mdx)); старые поля `relay_origin` на верхнем уровне останавливают сервер. После федерации перезапустите push relay. ## 0.2.7, 8 ноября 2026 [#027-8-ноября-2026] Минимальный уровень клиента 28: время в пути и второе напоминание у встреч. Опубликуйте новые приложения и проверьте ссылки на обновление, потом обновите федерацию и бридж Telegram. - Пространства: у каждого свои вкладки чатов, календаря и почты, источники и цвет. Пространство федерации хранится на ней, пространство устройства может собрать чаты, календари и ящики разных федераций ([папки и пространства](../features/organization.mdx)). - Почта: боковая панель папок и ящиков, карточки приглашений с видом дня, отдельный редактор, предложение времени из свободных слотов календаря, приглашения из вложенных файлов .ics. - Почтовый ящик федерации создаётся без пароля; для почтовых программ есть пароли приложений ([почтовый сервер](../selfhost/mail.mdx)). - Календарь на телефоне открывает событие в листе с выбором даты и времени на месте; у событий есть время в пути, второе напоминание и напоминание-будильник там, где устройство умеет. - Поиск открывается отдельной страницей с фильтрами по ящику и папке. **На сервере.** Сначала бэкап. Минимальный уровень клиента 28. Данные на устройствах переходят на новую схему на месте. ## 0.2.6, 7 ноября 2026 [#026-7-ноября-2026] Минимальный уровень клиента 27. Сначала обновляется сервер, потом приложения. - [Календарь](../features/calendar.mdx): личные события и встречи, общие расписания групп и сообществ, звонки во встречах, импорт .ics, календари Google, CalDAV и устройства, праздники, подписки по ссылке, ссылки для других приложений, поиск времени, переговорные и страница «Запись ко мне». - Подключённые аккаунты Google, Яндекса и любых серверов по паролю приложения — для календаря и почты ([внешние аккаунты](../selfhost/external-accounts.mdx)). - Чаты, история которых уже есть на устройстве, открываются сразу; пачка новых сообщений в открытом чате больше не теряет середину; правки в длинном чате видны сразу. - Стикеры: исправлены уязвимости Lottie, сервер проверяет и пересобирает загруженные анимации. - Медиа могут лежать в S3-совместимом хранилище; несколько основных процессов на одной базе (экспериментально). **На сервере.** Сначала бэкап. Базы переходят на новые схемы на месте, появляются схемы модулей календаря и внешних аккаунтов. Откат на 0.2.5 — только из бэкапа. ## 0.2.5, 28 октября 2026 [#025-28-октября-2026] Минимальный уровень клиента 12: события каналов пишутся от имени канала, и приложения 0.2.4 на них перестают читать канал. Сначала обновляется сервер, потом приложения. - Действия собеседника в шапке и списке чатов: кроме «печатает…» — запись и отправка голосовых и кружков, отправка фото, видео и файлов, выбор стикера, у каждого своя анимация. - [Системные сообщения](../features/messages.mdx#системные-сообщения): имена открывают профиль, «Вы …» для своих действий, закреп цитирует сообщение, одна строка на добавление, способ вступления, длительность звонка, фото группы в строке, события каналов и комнат, меню строки. - Поиск в чате по системным сообщениям и по одному участнику. - [Журнал действий сообщества](../features/communities.mdx#журнал-действий) показывает, что именно изменилось, и фильтруется по виду и по человеку. - Одно всплывающее уведомление для всего приложения вместо прежних плашек, с отменой там, где её можно сделать. - Удаление чата и выход из группы или сообщества подтверждаются на карточке поверх экрана. - Фото и обложки видео в непрочитанных чатах загружаются заранее, кружки запускаются сразу. - [Голосовые и кружки играют подряд](../features/voice.mdx#воспроизведение), в том числе свои и уже прослушанные. - В карточке человека, открытой не из чата с ним, есть кнопка «Чат». - Windows: значок в трее снова открывает окно и меню, прочитанные на другом устройстве сообщения не всплывают после пробуждения. - Android: иконка Comon вместо стандартной, звонок больше не прерывается при соединении. **На сервере.** База переходит на схему 38 на месте. Минимальный уровень клиента 12. ## 0.2.4, 26 октября 2026 [#024-26-октября-2026] Минимальный уровень клиента 11. Сначала обновляется сервер, потом приложения. - Новые экраны звонков на телефонах и компьютерах, голосовые комнаты, звонки по ссылке с гостями и общим чатом звонка. - Удаление личных чатов и выход из групп и сообществ. - Повтор неотправленных сообщений, мгновенная отправка кружков. - Установщик и обновление внутри приложения на Windows и Linux, ссылки `/u/`, `/join/`, `/call/`, которые открываются в приложении. - Android 8.0 или новее. **На сервере.** База переходит на схему 36 на месте. Шлюзы обновляются вместе с основным сервером или раньше него, сервер и SFU вместе. Новые необязательные настройки отчётов об ошибках ([эксплуатация](../selfhost/operations.mdx)). ## 0.2.3, 24 октября 2026 [#023-24-октября-2026] - Аватарки, превью и стикеры из кэша появляются сразу при запуске. - Новые панели профиля, группы и канала, анимация удаления, спойлеры в уведомлениях. - Масштаб при записи кружков. **На сервере.** Без миграций. Сделайте резервную копию и пересоберите сервер, чтобы спойлеры скрывались и в push-уведомлениях. ## 0.2.2, 22 октября 2026 [#022-22-октября-2026] - Стикеры не пропадают при плохой сети, медиа из Telegram сразу показывают превью. - Контекстные меню в новом стиле. **На сервере.** Без миграций. Обновите сервер и мост Telegram, затем приложения. ## 0.2.1, 21 октября 2026 [#021-21-октября-2026] - Приложение открывается, не дожидаясь уборки после прошлого запуска. **На сервере.** Схемы базы обновляются на месте: сначала проверьте миграцию на копии ([обновление](../selfhost/upgrading.mdx)). Федерация, которая ещё на SQLite, сначала переводится версией 0.2.0. Сервер больше не принимает `--store`, `--messaging` и `--sync`. ## 0.2.0, 19 октября 2026 [#020-19-октября-2026] Минимальный уровень клиента 9. Перед запуском сервер переводит данные 0.1.x отдельным конвертером. - Отложенные и тихие сообщения, упоминания каналов, расшифровка голосовых и кружков, импорт контактов из телефонной книги, необязательное имя пользователя. - Федерация может сменить домен: приложение, в которое встроен новый адрес, переносит на него сохранённую учётную запись само. **На сервере.** PostgreSQL вместо файлов SQLite. Неизвестный флаг останавливает запуск. Сервер и SFU обновляются вместе, потом приложения. # Где что лежит (/docs/develop) Этот сайт — для тех, кто пользуется Comon, держит свой сервер и пишет ботов ([Bot API](/bots)). Документация для тех, кто меняет сам Comon, живёт рядом с кодом в [репозитории](https://github.com/serezhia/chat_playground) и пишется на английском. ## Документация в репозитории [#документация-в-репозитории] | Что | Где | |---|---| | С чего начать: процессы, карта кода, общие правила | [`docs/ARCHITECTURE.md`](https://github.com/serezhia/chat_playground/blob/master/docs/ARCHITECTURE.md) | | Словарь терминов | [`docs/glossary.md`](https://github.com/serezhia/chat_playground/blob/master/docs/glossary.md) | | Устройство подсистем | [`docs/architecture/`](https://github.com/serezhia/chat_playground/blob/master/docs/architecture) | | Протокол и правила совместимости | [`docs/contracts/`](https://github.com/serezhia/chat_playground/blob/master/docs/contracts), исходники в [`protocol/`](https://github.com/serezhia/chat_playground/blob/master/protocol) | | Архитектурные решения | [`docs/decisions/`](https://github.com/serezhia/chat_playground/blob/master/docs/decisions) | | Безопасность | [`docs/security/`](https://github.com/serezhia/chat_playground/blob/master/docs/security) | | Инструкции: сборка, выпуск, проверка на устройствах, эксплуатация | [`docs/runbooks/`](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks) | | Правила работы в репозитории | [`AGENTS.md`](https://github.com/serezhia/chat_playground/blob/master/AGENTS.md) | | Правила ревью изменений | [`REVIEW.md`](https://github.com/serezhia/chat_playground/blob/master/REVIEW.md) | У каждого пакета есть свой README: назначение, слой, точки входа и команда для тестов. ## Как устроен код [#как-устроен-код] Всё написано на Dart и Flutter и лежит в одном репозитории: - `frontend/comon_client`: приложение; - `frontend/packages/cdlib_*`: CDLib, клиентская библиотека, которая хранит данные и синхронизирует их с сервером (как TDLib у Telegram); - `backend/comon_federation_server`: сервер федерации, а рядом `comon_push_relay` и `comon_bridge`; - `packages/comon_*`: общий код клиента и сервера: протокол, шифрованный транспорт, модели; - `protocol/`: описание протокола в Protobuf; - `deploy/`: стеки Docker Compose, по которым написан раздел [«Свой сервер»](/selfhost). ## Как устроен этот сайт [#как-устроен-этот-сайт] Сайт собирается [Fumadocs](https://fumadocs.dev) из MDX-файлов в каталоге [`site/`](https://github.com/serezhia/chat_playground/blob/master/site): русские страницы в `content/docs/ru`, английские в `content/docs/en`. Как запустить его локально и куда добавлять страницы, написано в [`site/README.md`](https://github.com/serezhia/chat_playground/blob/master/site/README.md). # Календарь (/docs/features/calendar) Вкладка **Календарь** появляется, когда федерация включила модуль календаря и ваша роль даёт право им пользоваться. Все календари хранятся на устройстве, как чаты: неделя, месяц или список открываются сразу и без сети, а изменения уходят на сервер по очереди, когда связь появится. ## События и встречи [#события-и-встречи] - Событие можно создать в календаре или из личного чата и небольшой группы: тогда это встреча, и её участники получают приглашение. Ответить можно на всю серию или на одну встречу. - Повторяющиеся события раскрываются на устройстве. **Это и следующие** отделяет продолжение серии в новую, связанную с прежней: история, гости, ответы и настройки сохраняются. - У события есть **Время в пути**, два напоминания и напоминание-будильник там, где устройство это умеет. Напоминания приходят и с устройства, и с сервера. - Вид **День**, **Неделя**, **Месяц** и список; быстрый ввод по-русски и по-английски; на компьютере календарем можно управлять с клавиатуры, Ctrl+K или ⌘K ищет событие. ## Звонок во встрече [#звонок-во-встрече] Во встречу можно добавить звонок. За пять минут до начала появляется кнопка **Присоединиться**, а над чатами — полоса **Сегодня**. У каждой встречи серии своя комната; гости без аккаунта входят по ссылке после того, как организатор их впустит. ## Общие расписания [#общие-расписания] У групп и сообществ есть общее расписание. Владелец группы решает, кто создаёт события и кто ими управляет; в сообществе это отдельные права ролей. Карточка события в чате не приглашает его участников: **Следить** добавляет событие в ваш календарь. ## Время коллег и переговорные [#время-коллег-и-переговорные] - **Подобрать время** в форме встречи показывает, когда вы и гости заняты в этот день, но не чем, и предлагает ближайшее свободное время. Кто видит вашу занятость (все, ваши контакты или никто, с исключениями), выбирается в **Настройки › Конфиденциальность › Занятость в календаре**. - **Доступ** в настройках календаря (или **Настройки › Конфиденциальность › Подробности календарей**) открывает другим, что за события в этом календаре: всем, контактам или никому, с исключениями. Личные события они всё равно видят только как «Занято». Открытые вам календари появляются в списке в группе **Доступные мне**, а в профиле человека — в разделе **Календарь**. Их можно только читать. - **Переговорные** перечисляет администратор федерации; встреча бронирует свободную, а занятая или переезд на её бронь отклоняется. - **Запись ко мне** — страница с днями и часами, когда вы принимаете встречи, и ссылка, по которой коллеги выбирают свободное время. Запись становится встречей в обоих календарях и в вашем чате. ## Другие календари [#другие-календари] - Импорт файла .ics в новый или существующий календарь. - Календари подключённого аккаунта Google или CalDAV: те, что можно менять, редактируются в Comon, и изменения уходят в аккаунт ([подключённые аккаунты](../selfhost/external-accounts.mdx)). - Календари телефона или компьютера (Android, iOS, macOS) видны рядом с календарями Comon на этом устройстве. **Копировать в Comon** делает копию для других ваших устройств. Без этого выбора с устройства ничего не уходит. - **Праздники** страны с переносами дней, **Подписка по ссылке** на адрес webcal или .ics и **Ссылка для других приложений** для Google, Apple или Outlook — со всеми подробностями или только с занятостью. Что из этого доступно, решает администратор федерации. ## Пространства и почта [#пространства-и-почта] Пространство показывает свои календари ([папки и пространства](./organization.mdx)). Приглашения из почты попадают в календарь, а в письме можно предложить время из свободных слотов ([почта](./mail.mdx)). # Звонки по ссылке (/docs/features/call-links) Звонок по ссылке — конференция без чата: постоянный адрес вида `https://<адрес федерации>/call/<код>`. По ссылке входят участники федерации под своим профилем и, если разрешено, гости без аккаунта, указав только имя. ## Создать ссылку [#создать-ссылку] «Звонок по ссылке» в меню над списком чатов или **Настройки › Звонки › Ссылки на звонки**. У ссылки есть: | Настройка | Варианты | |---|---| | Название | Необязательно, до 64 символов. | | Гости без аккаунта | Разрешены по умолчанию. Если выключить, войти смогут только участники федерации. | | Кто ждёт вашего одобрения | Никто, гости (по умолчанию) или все. | | Ссылка действует | Пока не отозвана, 1 день или 1 неделя. | Ссылку можно скопировать, отправить, изменить или отозвать. Отозванная ссылка перестаёт работать, а её звонок завершается. Кто может создавать ссылки, решает владелец федерации через роли; по умолчанию могут все. ## Как войти [#как-войти] Откройте ссылку. В приложении, где вы вошли в эту федерацию, можно войти под своим профилем. Без аккаунта нужно ввести имя и нажать «Войти как гость»: в приложении или в браузере, если у федерации есть веб-версия. Перед входом открывается **предпросмотр**: камера, микрофон и звук, чтобы проверить их и включить или выключить заранее. Камера изначально выключена, микрофон включён, если в звонке не больше шести человек. Первый вошедший начинает звонок. Звонок заканчивается, когда в нём не осталось ни участников, ни ждущих, или когда ссылку отозвали. ## Зал ожидания [#зал-ожидания] Тех, кому нужно одобрение, организатор (владелец ссылки) видит в зале ожидания над звонком и в разделе «Люди»: кнопки «Впустить», «Отклонить» и «Впустить всех». Пока человека не впустили, он не видит и не слышит звонок. Организатор сам никогда не ждёт. ## Что может организатор [#что-может-организатор] - впускать и отклонять ждущих; - выключать микрофон участникам и отключать их; - позвать в звонок людей из федерации: им позвонит, как при личном звонке, и они войдут без ожидания; - скопировать ссылку и поделиться ей. ## Чат звонка [#чат-звонка] У каждого звонка по ссылке есть свой настоящий чат, как в группе: сообщения, файлы, реакции и упоминания. Кнопка чата со счётчиком непрочитанных есть в шапке конференции, а на телефоне — в панели управления рядом с микрофоном. - В чате все, кого впустили, включая гостей. Ждущие в зале ожидания его не видят. - Кто вышел из звонка, остаётся в чате до конца звонка. Кого отключил организатор, теряет его. - Уведомления приходят только об упоминаниях, остальное видно по счётчику на экране звонка. - **Когда звонок заканчивается, чат удаляется у всех вместе с файлами.** Новый звонок по той же ссылке получает новый чат. ## Гости [#гости] Гость — временный профиль с введённым именем. Он видит только этот звонок и его чат и людей из этого чата. Поиск, контакты и публичные чаты федерации ему недоступны. Когда гость выходит из звонка или звонок заканчивается, его временный профиль удаляется вместе с сообщениями и файлами. | Что | Сколько у гостя | |---|---| | Сообщений | 500, не чаще одного в секунду после первых десяти | | Файлов | 100 МБ всего, до 25 МБ каждый | Владелец федерации может запретить гостей во всей федерации: **Управление федерацией › Гости в звонках**. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Ссылок у одного человека | 50 | | Участников в списке звонка (в звонке, ждут, приглашены) | 64 | | Позвать за один раз | 32 человека | | Гостей во всей федерации одновременно | 1024 | | Входов гостей и просмотров страниц ссылок с одного адреса | 10 и 60 в минуту | # Звонки (/docs/features/calls) Звонки идут через WebRTC. Сервер федерации только соединяет участников: личный звонок идёт напрямую между устройствами или через TURN-сервер федерации, групповой — через её медиасервер (SFU). Посторонние сервисы в звонке не участвуют. ## Личный звонок [#личный-звонок] В личном чате есть кнопки аудио- и видеозвонка. - Звонок звонит на всех устройствах собеседника, отвечает одно. На остальных видно, что звонок принят на другом устройстве. - Если собеседник не ответил за 45 секунд, звонок считается пропущенным. Если он уже в другом звонке, вы увидите «Занято». - Входящий звонок показывается системным экраном: на iPhone через CallKit, на Android уведомлением на весь экран, на Mac и Windows уведомлением с кнопками «Принять» и «Отклонить». - Если звонящий с камерой, звонок можно принять сразу с видео. - После окончания звонок ещё три секунды показывает итог и длительность, с кнопками «Перезвонить» и «Закрыть». Кто может вам звонить, выбирается в **Настройки › Конфиденциальность › Звонки**: все, только контакты или никто. Ботам и служебному чату федерации позвонить нельзя. ## Видео [#видео] - Камера собеседника на весь экран, ваша — в маленьком окне, которое можно перетащить в любой угол. Нажатие на маленькое окно меняет камеры местами. - На телефоне есть переключение фронтальной и основной камеры. Ваша фронтальная камера у вас показывается зеркально (выключается в настройках звонков), собеседник видит её как есть. - Включение камеры на телефоне переводит звук на громкую связь, если не подключена гарнитура. - Если система остановила камеру (например, приложение свернули на старом iPhone), собеседник видит аватар с пометкой «Камера на паузе», а не застывший кадр. - Над видео кнопки сами прячутся через 4 секунды, нажатие возвращает их. ## Демонстрация экрана [#демонстрация-экрана] Показывать экран можно в любом звонке, одновременно с камерой. | Где | Как | |---|---| | macOS, Windows | Выбор экрана или окна в окне приложения, с живыми превью. Источник можно сменить, не прекращая показ. | | Android | Системное разрешение на запись экрана. Остановить можно из уведомления. | | iPhone | Системное окно трансляции экрана. Остановить можно в Пункте управления. | | Браузер на компьютере | Окно выбора браузера: экран, окно или вкладка. | | Браузер на телефоне | Не поддерживается. | Показанный экран можно приближать щипком, колёсиком мыши или двойным нажатием, до 5×. Звук компьютера при показе экрана пока не передаётся. ## Групповые звонки [#групповые-звонки] В группе кнопка звонка начинает групповой звонок или подключает к уже идущему. Никому не звонит: в чате появляется сообщение «начал(а) групповой звонок», которое уведомляет участников по их обычным настройкам, а под шапкой группы — панель для входа. - **Сетка**: все участники, по 9 на странице на телефоне и по 16 на большом экране. - **Докладчик**: говорящий крупно, остальные полосой. Показанный экран занимает главное место; если экран показывают несколько человек, между ними можно переключаться. - У говорящего светится рамка, у выключенного микрофона — значок. - На телефоне есть режим списка: участники без видео, только кто говорит и у кого что включено. Показанный экран там начинает приходить, только когда вы нажмёте «Смотреть». - Нажатие на участника открывает меню: профиль, написать и **громкость этого участника только у вас**, от 0 до 200%. - Кнопку микрофона можно нажать, чтобы включить или выключить, или держать, чтобы говорить только пока держите. Если вас удалили из группы или вы вышли, вы выходите и из её звонка. Звонок заканчивается, когда из него вышел последний. ## Голосовые комнаты [#голосовые-комнаты] Голосовая комната сообщества — это постоянный групповой звонок. Нажмите на комнату, чтобы войти, и на другую, чтобы перейти. На телефоне в голосовую комнату всегда входят с выключенным микрофоном. Права и модерация описаны на странице [Сообщества](./communities.mdx#голосовые-комнаты). ## Звонок в фоне [#звонок-в-фоне] Звонок не прерывается, когда вы уходите из приложения: | Где | Что видно | |---|---| | iPhone | Системное окно «картинка в картинке». Камера продолжает работать на iOS 18, на iOS 16–17 ставится на паузу. | | Android | Окно «картинка в картинке» с кнопками микрофона и завершения, постоянное уведомление о звонке. | | Компьютер | Маленькое перетаскиваемое окно с последним говорящим поверх приложения. | | Браузер на компьютере | Окно «картинка в картинке» (Chrome, Edge). | Окно «картинка в картинке» выключается в **Настройки › Звонки**. Пока идёт звонок, экран телефона не гаснет, а при разговоре у уха без видео экран выключается датчиком приближения. Свёрнутый звонок виден полосой вверху приложения, нажатие на неё возвращает к звонку. ## Перенос на другое устройство [#перенос-на-другое-устройство] Если звонок идёт на одном вашем устройстве, на другом появляется панель с кнопкой «Перенести сюда». Звонок переходит на это устройство без разрыва. На телефоне такая карточка приходит и в уведомлениях. ## Качество связи [#качество-связи] Звук защищён от потерь пакетов: каждый пакет несёт копию предыдущего, кодек сам добавляет избыточность, когда сеть теряет данные. Если речь доходит плохо, под именем собеседника или в шапке конференции появляется пометка, с какой стороны проблема. ## Настройки звонков [#настройки-звонков] В **Настройки › Звонки**: - микрофон, динамик и камера этого устройства; - шумоподавление: выключено, стандартное или улучшенное (RNNoise, работает на устройстве, звук никуда не отправляется); - на Windows — приглушать ли другие приложения во время звонка; - «картинка в картинке» и зеркальное отображение своей камеры; - ваши ссылки на звонки, см. [Звонки по ссылке](./call-links.mdx). ## Где работают звонки [#где-работают-звонки] iPhone, Android, macOS, Windows и браузеры. В сборке для Linux звонки есть, но без камеры, и на устройствах они ещё не проверялись. Групповые звонки и голосовые комнаты работают, только если владелец федерации запустил медиасервер, см. [Звонки, SFU и TURN](../selfhost/calls.mdx). ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Участников группового звонка | 32 | | Ожидание ответа | 45 секунд | | Возвращение после обрыва связи | 20 секунд в личном звонке, 60 в групповом | | Звонков одновременно у одного человека, с входящими | 8 | # Каналы (/docs/features/channels) Канал — лента постов для большой аудитории. Посты выходят от имени канала, подписчики их читают, ставят реакции и пересылают. Комментариев, обсуждений и «написать каналу» нет. ## Создание [#создание] Нажмите «Создать канал» в меню над списком чатов, задайте название, описание и выберите подписчиков из контактов. Добавленные подписываются сразу. Пока у канала нет @имени, он закрытый: в него попадают только по добавлению или по ссылке-приглашению. ## Роли [#роли] | Действие | Владелец | Публикатор | Подписчик | |---|:-:|:-:|:-:| | Читать, пересылать из канала, ставить реакции | да | да | да | | Свои уведомления, архив, папки | да | да | да | | Публиковать, пересылать в канал | да | да | | | Править и удалять посты, закреплять | да | да | | | Видеть список подписчиков | да | да | | | Менять название и описание, добавлять и удалять подписчиков, назначать публикаторов | да | | | | Передать владение, закрыть канал | да | | | - Публикаторы правят посты друг друга: автором для подписчиков всегда остаётся канал, кто именно написал пост, подписчики не видят. - В постах нет ответов на сообщения и нет «удалить у меня». - Владелец может выйти, только передав владение (тогда он станет публикатором) или закрыв канал. ## Для подписчика [#для-подписчика] Вместо строки ввода у подписчика кнопка «Выключить уведомления» (или «Включить уведомления»). Под постом видно число просмотров и время. - **Просмотры** — приблизительное число показов поста. Один человек с нескольких устройств считается один раз за четверо суток. Это не число прочитавших. - **Реакции** анонимны: видны только их количества, и уведомлений о них нет. - Подписчики не видят друг друга, их список видят только владелец и публикаторы. - Новый подписчик видит всю прошлую историю, но не получает уведомлений о старых постах. ## Для публикатора [#для-публикатора] - Посты можно отложить: очередь отложенных у канала общая для всех публикаторов, см. [Отложенные и тихие сообщения](./scheduled.mdx). - **Тихая публикация** в настройках канала отправляет посты по умолчанию без звука. - Бот может публиковать в канале, если назначить его публикатором в списке подписчиков. - Переслать сообщение в канал можно, только если вы в нём публикуете: канал появляется в списке пересылки только тогда. ## Публичные каналы [#публичные-каналы] Владелец может дать каналу @имя. Публичный канал находится в глобальном поиске, его можно читать до подписки и открывать по ссылке `/u/<имя>`. Для закрытого канала есть ссылки-приглашения и заявки на вступление, которые одобряет владелец. Всё это описано на странице [Публичные чаты и приглашения](./public-chats.mdx). ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Подписчиков в канале, с владельцем и публикаторами | нет продуктового лимита; сервер держит до 10 000 | | Каналов, в которых состоит один человек | 500 | | Описание | 255 символов | | Добавить подписчиков за раз | 255 | # Личные чаты и группы (/docs/features/chats) Чаты бывают пяти видов: | Вид | Для чего | |---|---| | Личный чат | Переписка двух человек или человека с ботом. | | Группа | Общий чат до 256 участников. | | [Канал](./channels.mdx) | Лента публикаций для большой аудитории. | | [Сообщество](./communities.mdx) | Пространство с комнатами, категориями и ролями. | | Чат звонка | Временный чат конференции по ссылке, см. [Звонки по ссылке](./call-links.mdx). | Создать группу, канал или сообщество, вступить в сообщество или создать ссылку на звонок можно из меню создания над списком чатов. ## Личные чаты [#личные-чаты] Чтобы написать человеку, найдите его в поиске по имени или @имени или откройте его профиль и нажмите «Написать». Кто может начать с вами личный чат, вы выбираете в **Настройки › Конфиденциальность › Сообщения**: все, только контакты или никто. Уже начатые чаты продолжают работать. Подробнее на странице [Приватность и блокировка](./privacy.mdx). ### Если пишет незнакомый [#если-пишет-незнакомый] Если вам впервые написал человек не из ваших контактов, под шапкой чата появляются кнопки «Заблокировать» и «Добавить в контакты». Фото и видео от него размыты, пока вы их не откроете. Пожаловаться можно из меню чата. ### Сколько новых чатов в день [#сколько-новых-чатов-в-день] Чтобы не было спама, у каждого есть дневной лимит новых личных чатов с людьми, у которых вас нет в контактах. Для роли `@everyone` это 50 в день, владелец федерации может изменить его через роли. Чаты с теми, у кого вы в контактах, с ботами и со служебным чатом федерации не считаются. ### Служебный чат федерации [#служебный-чат-федерации] У каждого есть чат с профилем федерации. В него приходят ответы модераторов на жалобы, предупреждения и уведомления сервера. Если написать в этот чат, сообщение попадёт в поддержку федерации. Служебный чат нельзя заблокировать, пожаловаться на него или позвонить в него. ## Группы [#группы] Группа — закрытый чат для людей одной федерации. Вступление сразу, без приглашения: участник сразу появляется в группе. ### Создание [#создание] Нажмите «Новая группа», задайте название и выберите участников из контактов. Группу можно создать и для себя одного, а людей добавить позже. ### Кто что может [#кто-что-может] | Действие | Владелец | Участник | |---|:-:|:-:| | Писать, ставить реакции | да | да | | Добавлять участников из своих контактов | да | да | | Переименовать, сменить аватар | да | | | Удалять участников | да | | | Удалять чужие сообщения | да | | | Закреплять сообщения | да | | | Упоминать всех (`@all`) | да | | | Править свои сообщения без ограничения по времени | да | | | Передать владение | да | | | Удалить группу | да | | Добавить человека в группу можно, только если его настройки это разрешают: в **Настройки › Конфиденциальность › Группы и каналы** каждый выбирает, кто может его добавлять (все или только контакты). Добавление людей, у которых вас нет в контактах, тоже ограничено дневным лимитом: 50 в день для `@everyone`. ### История [#история] Новый участник видит всю историю группы. Непрочитанные для него начинаются с момента добавления. ### Прочтение [#прочтение] Две галочки у вашего сообщения в группе значат, что его прочитал хотя бы один участник. В меню сообщения видно число прочитавших и их список. ### Публичные группы [#публичные-группы] Группе можно дать @имя: тогда её найдут в поиске и откроют по ссылке. А ещё можно создавать ссылки-приглашения. См. [Публичные чаты и приглашения](./public-chats.mdx). ### Выйти или удалить [#выйти-или-удалить] Участник может выйти из группы. Владелец сначала передаёт владение другому участнику, а если он в группе один, то может выйти, и группа закроется. Владелец может удалить группу целиком. См. [Выход и удаление чатов](./leave-and-delete.mdx). ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Участников группы, с владельцем | 256 | | Добавить за один раз | 255 | | Название группы или канала | до 128 символов | | Новых личных чатов с незнакомыми в день | 50 для `@everyone`, до 10 000 для роли | | Добавлений незнакомых в группы и каналы в день | 50 для `@everyone`, до 10 000 для роли | # Сообщества (/docs/features/communities) Сообщество — один чат в списке, внутри которого баннер и комнаты по категориям. Комната работает как обычный чат: история, строка ввода, реакции, закрепы и поиск. ## Комнаты [#комнаты] | Комната | Что это | |---|---| | Текстовая | Обычный чат участников. | | Объявления | Текстовая комната, в которой по умолчанию пишут только те, кому это разрешено. | | Голосовая | Постоянный звонок со своим текстовым чатом. Заходят и выходят свободно, без звонка участникам. | Комнаты собраны в **категории**, которые каждый может свернуть у себя: свёрнутые категории одинаковы на всех ваших устройствах. Комната без категории стоит над всеми категориями. **Закрытая комната** — комната, которую `@everyone` не видит: её видят только роли, которым это разрешено. **Медленный режим** в комнате ограничивает, как часто участник может писать (до одного сообщения в 6 часов). На тех, кто может управлять сообщениями или комнатами, он не действует. В списке чатов сообщество занимает одну строку: последняя комната с новым сообщением, автор, счётчик непрочитанных и отдельный значок упоминаний. Меню сообщества: прочитать всё, уведомления, пригласить, настройки, выйти. ## Роли и права [#роли-и-права] У сообщества один **владелец**: у него все права, его нельзя исключить. Каждый участник получает роль **@everyone**, а ещё есть встроенная роль **Администратор** с правом «Администратор (всё)». Свои роли создаются выше @everyone; чем выше роль, тем она сильнее. | Право | Что даёт | |---|---| | Видеть комнаты | Видеть комнату и читать её. | | Писать сообщения | Писать в текстовых комнатах. | | Прикреплять файлы | Отправлять медиа и пересылать. | | Ставить реакции | Ставить реакции. | | Упоминать @everyone | Уведомлять всех участников комнаты. | | Удалять чужие сообщения | Удалять и закреплять чужие сообщения, без медленного режима. | | Заходить в голосовые комнаты | Входить в голосовые комнаты. | | Говорить | Включать микрофон в голосовой комнате. | | Камера и экран | Включать камеру и показывать экран. | | Выключать микрофон другим | Выключать микрофон участникам голосовой комнаты. | | Переводить и отключать других | Переводить участника в другую голосовую комнату или отключать его. | | Управлять комнатами | Создавать, менять и удалять комнаты и категории. | | Управлять ролями | Создавать роли ниже своей и выдавать права, которые есть у вас. | | Управлять сообществом | Название, описание, баннер, видимость, @имя, приглашения других. | | Исключать участников | Исключать тех, кто ниже вас. | | Блокировать участников | Банить тех, кто ниже вас, с удалением их сообщений за последние 7 дней. | | Создавать приглашения | Создавать коды приглашения. | | Просматривать журнал | Читать журнал действий сообщества. | | Администратор (всё) | Все права сразу. | Новое сообщество даёт `@everyone` права видеть, писать, прикреплять файлы, ставить реакции, заходить в голосовые комнаты, говорить, включать камеру и создавать приглашения. **Права в комнате.** Для категории и для комнаты можно переопределить права: для @everyone, для роли или для конкретного человека. Сначала применяются права всего сообщества, потом переопределения категории, потом комнаты. Без права «Видеть комнаты» остальные права в комнате не действуют. Комната, где можно читать, но нельзя писать, открывается только для чтения. Права считает только сервер: приложение показывает действие, если право есть, но проверяет его всё равно сервер. ## Вступление [#вступление] - **Закрытое сообщество** — вступление только по приглашению. - **Публичное** — его находят в поиске, в него вступают сразу; можно дать ему @имя. Приглашение — это ссылка со сроком действия и лимитом вступлений (по желанию). Её создаёт любой, у кого есть право «Создавать приглашения», а отзывает автор или тот, кто управляет сообществом. Ссылка открывает приложение; её можно и вставить в поиск. До вступления видна карточка: название, вид, число участников и описание, кнопка «Вступить». Публичные сообщества ваших федераций собраны во вкладке «Сообщества» поиска над списком чатов: без запроса там самые большие. Забаненный участник не может вернуться никаким способом, пока его не разбанят. Кто может создавать сообщества и в скольких можно состоять, решает владелец федерации через роли. По умолчанию создавать могут все. ## Уведомления [#уведомления] У сообщества и у каждой комнаты свои настройки уведомлений. Комната по умолчанию наследует их от сообщества, а сообщество — от его настройки по умолчанию. Новое сообщество уведомляет **только об упоминаниях**: когда вас упомянули, ответили вам или упомянули @everyone. Уведомление выглядит как «Сообщество › комната» с именем автора. ## Голосовые комнаты [#голосовые-комнаты] - Нажмите на голосовую комнату, чтобы войти. Под комнатой в списке видно, кто в ней сейчас. - Без права «Говорить» вы входите с выключенным микрофоном, без права «Камера и экран» не можете включить камеру и показ экрана. - У комнаты может быть лимит участников (до 99). Тем, кто может переводить других, лимит не мешает. - Модератор может выключить микрофон участнику (это сохраняется после перезахода), перевести его в другую голосовую комнату или отключить. - Нажатие на другую голосовую комнату выводит из текущего звонка. Подробнее о звонках — на странице [Звонки](./calls.mdx). ## Журнал действий [#журнал-действий] Сервер записывает, что делают управляющие сообществом: изменения комнат, категорий, ролей и настроек, выдачу ролей, исключения, баны и разбаны, приглашения, передачу владения. Журнал видят владелец, администраторы и роли с правом «Просматривать журнал». Записи хранятся год. Запись показывает, что именно изменилось: «Название: lobby → hall», медленный режим, цвет роли, выданные и снятые права, права комнаты для роли или участника, выданные и снятые роли, за какой срок удалены сообщения при бане. Журнал фильтруется по виду (сообщество, комнаты, роли, участники, ссылки-приглашения) и по человеку: его действия или действия с ним. Имя в записи открывает профиль, название комнаты — комнату. ## Владение и удаление [#владение-и-удаление] Владелец выходит только после передачи владения, если в сообществе есть кто-то ещё. Удалить сообщество может только владелец, вместе со всеми комнатами. Жалобы на сообщество и его комнаты уходят модераторам федерации. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Комнат в сообществе | 500 | | Категорий | 50, до 50 комнат в каждой | | Своих ролей | 100 | | Сообществ у одного человека | 100 (владелец федерации может уменьшить) | | Действующих приглашений | 100 | | Описание сообщества, тема комнаты | 1024 символа | | Медленный режим | до 6 часов | | Участников голосовой комнаты | до 99 | # Форматирование и блоки (/docs/features/formatting) Сообщение в Comon — документ: простой текст или заголовки, списки, таблицы и колонки. «Привет» — документ из одного абзаца. ## Два режима ввода [#два-режима-ввода] - **Строка ввода** внизу чата — для обычной переписки. В ней работает оформление текста, упоминания, вложения, ответ и цитаты, карточки ссылок. - **Полный редактор** открывается кнопкой «+» и занимает весь чат. В нём доступны все блоки: заголовки, списки, цитаты, код, таблицы, колонки и подписи к фото. Оба режима работают с одним и тем же черновиком: переключение не сбрасывает текст, курсор и историю отмены. ## Оформление текста [#оформление-текста] Выделите текст, и над ним появится панель: тип блока, жирный, курсив, подчёркнутый, зачёркнутый, моноширинный, спойлер, ссылка, цвет текста и фона, сброс оформления. На телефоне панель открывается через «Формат» в меню выделения. Markdown применяется при наборе: | Наберите | Получится | |---|---| | `**текст**` | **жирный** | | `*текст*` | *курсив* | | `~~текст~~` | ~~зачёркнутый~~ | | `` `текст` `` | `моноширинный` | | `\|\|текст\|\|` | спойлер | В полном редакторе ещё и в начале строки: | Наберите | Получится | |---|---| | `# `, `## `, `### ` | заголовок трёх уровней | | `- ` | маркированный список | | `1. ` | нумерованный список | | `[] ` | чек-лист | | `> ` | цитата | | ```` ``` ```` | блок кода | | `---` | разделитель | Отмена (Ctrl/Cmd+Z) возвращает набранные символы, если преобразование не нужно. **Цвета.** Текст и фон можно покрасить в один из девяти цветов: серый, коричневый, оранжевый, жёлтый, зелёный, синий, фиолетовый, розовый и красный. **Спойлер** скрывает слова под облаком точек. Нажатие на точки открывает спойлеры этого абзаца. В списке чатов и уведомлениях вместо скрытого текста видны точки, слова туда не попадают. ## Блоки [#блоки] В полном редакторе на компьютере «/» в начале пустой строки открывает меню блоков, а «/turn» превращает текущий блок в другой. Слева от каждого блока есть «+» и ручка для перетаскивания; нажатие на ручку открывает меню блока: превратить, дублировать (Ctrl/Cmd+D), переместить, удалить и настройки самого блока. На телефоне блоки добавляются кнопкой «+» на панели над клавиатурой. | Блок | Что это | |---|---| | Заголовок | Три уровня. | | Список | Маркированный, нумерованный или чек-лист. Вложенность до четырёх уровней, Tab и Shift+Tab меняют уровень. | | Чек-лист | Галочки ставит только автор, правкой сообщения. Читатели видят отметки, но не меняют их. | | Цитата | Свой текст с необязательной подписью автора внизу. Это не ссылка на сообщение, а обычный блок. | | Код | Моноширинный текст с подсветкой по выбранному языку. | | Разделитель | Горизонтальная линия. | | Сворачиваемый блок | Первая строка видна всегда, остальное открывается стрелкой. Каждый читатель открывает его у себя, изначально он свёрнут. | | Выноска | Тонированная рамка с эмодзи и цветом. | | Таблица | До 50 строк и 10 столбцов, строка и столбец заголовков, цвет ячеек. Tab переходит между ячейками, Tab в последней добавляет строку. | | Колонки | От двух до четырёх колонок рядом. На узком экране они встают друг под другом. | | Медиа | Фото, видео или файл, с подписью или без. | Enter на пустой строке выходит из блока: из списка, цитаты, выноски или таблицы. Так после любого блока всегда можно продолжить обычным текстом. ## Упоминания [#упоминания] Наберите `@` в начале слова, и появится список участников чата: сначала те, кто недавно писал. Упомянутый получает уведомление, даже если чат у него без звука. - `@all` уведомляет всех участников. Его могут использовать владелец группы, владелец и публикаторы канала и роли сообщества с правом упоминать всех. - В комнате сообщества `#` в начале слова вставляет ссылку на другую комнату. Такая ссылка никого не уведомляет. - Упоминания внутри цитат, кода, подписей и пересланных сообщений не уведомляют. - Если в группе или комнате вас упомянули или ответили вам, а вы ещё не прочитали, над кнопкой прокрутки вниз появляется «@». Нажатие ведёт к самому раннему такому сообщению. ## Ссылки и карточки [#ссылки-и-карточки] Ссылки в тексте распознаются сами. Явную ссылку под словом можно поставить через панель оформления. Если текст ссылки не совпадает с адресом или это не веб-адрес, приложение сначала спросит «Открыть ссылку?» и покажет полный адрес. Ссылки на чаты и звонки Comon открываются прямо в приложении. Для первой ссылки в тексте строка ввода показывает **карточку**: сайт, заголовок, описание и картинку. Карточку можно убрать, поставить над или под текстом, выбрать маленькую или большую картинку и ссылку, для которой она показывается. Карточку собирает сервер федерации при отправке, а не устройство получателя, так что читатели не обращаются к чужому сайту. | Что | Сколько | |---|---| | Карточек в одном сообщении | 5 | | Картинка карточки | JPEG до 64 КБ, до 320 пикселей по длинной стороне | | Новых запросов карточек | 20 сразу, дальше 1 в 2 секунды | Сервер загружает только публичные адреса по http и https и хранит готовую карточку час. ## Чего нет [#чего-нет] Формул, опросов, GIF и стикеров внутри документа пока нет. Стикеры, голосовые и кружки отправляются отдельными сообщениями. # Возможности (/docs/features) Что можно сделать в Comon, кто имеет на это право, что видят другие и какие есть ограничения. Лимиты на этих страницах — значения по умолчанию; часть из них владелец федерации меняет через роли. } title="Сообщения" href="/features/messages"> Отправка без сети, ответы и цитаты, пересылка, правка, удаление, закрепы, прочтение. } title="Медиа" href="/features/media"> Фото, видео и файлы, голосовые и кружки с расшифровкой, стикеры и свои эмодзи. } title="Чаты" href="/features/chats"> Личные чаты, группы, каналы, сообщества с комнатами и ролями, публичные чаты. } title="Звонки" href="/features/calls"> Личные и групповые звонки, демонстрация экрана, голосовые комнаты, звонки по ссылке с гостями. } title="Приватность" href="/features/privacy"> Кто может писать и звонить, блокировка, жалобы, модерация. } title="Безопасность" href="/features/security"> Что шифруется, что видит сервер, устройства и облачный пароль. ## Все страницы [#все-страницы] **Сообщения** - [Сообщения](./messages.mdx): отправка, черновики, неотправленные, ответы, пересылка, правка, удаление, закрепление, прочтение. - [Форматирование и блоки](./formatting.mdx): оформление текста, Markdown при наборе, таблицы, колонки, упоминания, карточки ссылок. - [Отложенные и тихие сообщения](./scheduled.mdx): по времени, по расписанию, когда собеседник в сети, без звука. - [Реакции](./reactions.mdx). **Медиа** - [Фото, видео и файлы](./media.mdx). - [Голосовые и кружки](./voice.mdx): запись, воспроизведение, расшифровка речи. - [Стикеры и эмодзи](./stickers.mdx): наборы, создание, импорт из Telegram. **Чаты** - [Личные чаты и группы](./chats.mdx). - [Каналы](./channels.mdx). - [Сообщества](./communities.mdx): комнаты, роли, права, голосовые комнаты. - [Публичные чаты и приглашения](./public-chats.mdx). - [Выход и удаление чатов](./leave-and-delete.mdx). **Звонки** - [Звонки](./calls.mdx): личные, групповые, видео, экран, звонок в фоне. - [Звонки по ссылке](./call-links.mdx): гости, зал ожидания, чат звонка. **Люди и безопасность** - [Профиль, контакты и статус](./people.mdx). - [Приватность и блокировка](./privacy.mdx). - [Модерация](./moderation.mdx): роли федерации, жалобы, действия модераторов. - [Безопасность и данные](./security.mdx). **Приложение** - [Уведомления](./notifications.mdx). - [Поиск](./search.mdx). - [Папки, пространства и архив](./organization.mdx). - [Настройки](./settings.mdx). - [Ссылки Comon](./links.mdx). # Выход и удаление чатов (/docs/features/leave-and-delete) Долгое нажатие (или правый клик) на чате в списке открывает меню. В его конце, после черты, — действие, которое убирает чат: | Чат | Действие | |---|---| | Личный, с ботом, служебный | Удалить чат | | Группа | Выйти из группы; владельцу ещё и «Удалить группу» | | Канал | Отписаться | | Сообщество | Выйти из сообщества | Действие подтверждается на карточке поверх размытого экрана: аватар чата, вопрос с его названием и красные кнопки над «Отмена». Отписка от канала ничего не спрашивает, кроме случая, когда вы его единственный участник и владелец. После подтверждения чат на пять секунд прячется, а внизу появляется уведомление с кнопкой «Отменить». Если не отменить, действие выполняется. Если сервер откажет, чат вернётся в список с объяснением. Те же действия есть в профиле собеседника и в информации о группе. Там подтверждение на той же карточке, но без пятисекундной отмены. ## Удалить личный чат [#удалить-личный-чат] Приложение спросит, у кого удалить: - **Только у вас.** Собеседник сохранит чат и историю. - **У обоих.** История пропадёт у вас обоих, восстановить её нельзя. На телефоне это две кнопки. В широком окне (компьютер, планшет) в карточке одна кнопка «Удалить» и флажок «Также удалить для…»: без флажка чат удалится только у вас, с флажком у обоих. Чат исчезает из списка и вернётся пустым со следующим сообщением. Черновик остаётся. Служебный чат федерации можно удалить только у себя. Удаление чата с ботом ещё и останавливает бота. Чтобы снова с ним говорить, нажмите «Запустить» в его профиле. ## Выйти из группы [#выйти-из-группы] Участник выходит в любой момент. Владелец группы, в которой есть кто-то ещё, сначала передаёт владение другому участнику. Если владелец остался один, он выходит, и группа закрывается. ## Удалить группу [#удалить-группу] Только владелец. Группа и её история пропадут у всех участников, приглашения перестанут работать, идущий звонок группы закончится. Это нельзя отменить. ## Отписаться от канала [#отписаться-от-канала] Канал пропадёт из списка. Вернуться можно по ссылке-приглашению или через поиск, если канал публичный. Владелец канала с подписчиками сначала передаёт владение или закрывает канал. ## Выйти из сообщества [#выйти-из-сообщества] Комнаты сообщества пропадут из списка. Владелец выходит только после передачи владения в настройках сообщества. ## Что ещё удаляется [#что-ещё-удаляется] При выходе из группы, канала или сообщества с устройства удаляются его история, закрепы, черновики и отложенные сообщения в нём. Уже отправленные вами сообщения остаются у остальных участников. # Ссылки Comon (/docs/features/links) ## Виды ссылок [#виды-ссылок] | Ссылка | Что открывает | |---|---| | `https://<адрес федерации>/u/<имя>` | Человека, бота или публичный чат по @имени | | `https://<адрес федерации>/join/<код>` | Приглашение в группу, канал или сообщество | | `https://<адрес федерации>/call/<код>` | Звонок по ссылке | Старые ссылки вида `/@имя` и `/+код` тоже работают: сервер перенаправляет их на новые. «Поделиться» и «Копировать ссылку» в приложении дают ссылки именно такого вида. ## Как открывается ссылка [#как-открывается-ссылка] **В приложении.** Нажатие на ссылку в сообщении открывает чат или звонок прямо в приложении. Если ссылка ведёт в федерацию, которой у вас ещё нет, приложение проверит, что по адресу действительно федерация Comon, и предложит подключиться; после входа откроется то, на что вела ссылка. Ссылку, `@имя` или `+код` можно вставить и в поиск. **В браузере.** Федерация показывает страницу без скриптов, на русском или английском: что открывает ссылка (имя человека, название и размер чата, звонок и его организатор) и кнопки: - открыть в приложении; - открыть веб-версию, если она есть у федерации; - скачать приложение для вашей платформы. Страницы приглашений и звонков не попадают в поисковики. **Сразу в приложении из любого места.** На iPhone, Mac и Android ссылки `comon.chat` открывают приложение напрямую, минуя браузер. Для федерации на своём домене это возможно, только если приложение собрано с этим доменом; иначе ссылка открывает страницу федерации, а она уже передаёт ссылку в приложение. На Windows и Linux ссылки всегда идут через страницу: установщик регистрирует схему `comon://`, через которую страница открывает приложение. # Почта (/docs/features/mail) ## Подключение ящика [#подключение-ящика] Comon показывает почту ящиков, которые у вас уже есть. Откройте **Настройки → Подключённые аккаунты** и подключите аккаунт Google или Яндекса либо любой почтовый сервер по паролю приложения. Как только федерация разрешает почту, в навигации появляется вкладка **Почта**. Почту синхронизирует сервер вашей федерации, поэтому новые письма приходят, даже когда устройства выключены, а о новом письме во «Входящих» приходит уведомление. Если ящик просит войти снова, над письмами появляется кнопка **Войти**. Имя отправителя, подпись, проверка новых отправителей, коды и уведомления каждого ящика — в **Настройки → Почта**. Туда же ведёт пункт **Настройки почты** во вкладке почты. ## Письма [#письма] - Меню над списком выбирает ящик и папку: «Входящие», «Отправленные», «Архив» и папки с сервера. - Письмо открывается справа или поверх списка на телефоне и сразу отмечается прочитанным. - Картинки из интернета скрыты, пока вы не нажмёте **Показать**: так отправитель не узнаёт, что письмо прочитано. Картинки, вложенные в само письмо, видны сразу. - Долгое нажатие или правый клик по письму: прочитано или нет, флажок, отложить, переместить, выбрать, архив, удалить. - Несколько писем: **Выбрать** в меню письма, затем нажатия выбирают другие. На компьютере — Ctrl или ⌘ с кликом, Shift для диапазона, Ctrl+A или ⌘A для всех. Выбранные письма можно переместить, отложить, архивировать, удалить, отметить прочитанными или флажком разом, а мышью — перетащить на папку. - **Новая папка** в меню папок или при перемещении создаёт папку на почтовом сервере. - **Отложить** прячет письмо до выбранного времени: позже сегодня, завтра утром, в понедельник утром или в свою дату. Отложенные письма собраны в меню папок в «Отложенных»; в срок письмо возвращается наверх своей папки с уведомлением. - Поиск ищет по отправителям, получателям, темам и началу текста писем на устройстве. Действия видны сразу и уходят на почтовый сервер по очереди; без связи они ждут подключения. Если почтовый сервер отказал, Comon скажет об этом. ## Ответ и новое письмо [#ответ-и-новое-письмо] Кнопки **Ответить**, **Ответить всем** и **Переслать** открывают редактор с цитатой письма; **Новое письмо** — пустой. Вложения одного письма — до 1,5 МБ вместе; при пересылке вложения исходного письма уходят сами. Письмо без связи ждёт на устройстве и уходит, когда связь появится. Отправленное письмо 5 секунд можно вернуть кнопкой **Отменить** в подсказке внизу. **Отправить позже** (кнопка с часами в редакторе) отправит письмо в выбранное время, даже если устройства выключены; до этого его можно открыть снова кнопкой **Изменить** над письмами. Отложенные письма и отправка позже работают в Comon: в других почтовых программах этого ящика они не видны. Если соединение оборвалось после передачи письма серверу, Comon не отправит его второй раз сам и попросит проверить «Отправленные». Администратор федерации может разрешить почту только для чтения: тогда письма видны, а действия и отправка недоступны. # Фото, видео и файлы (/docs/features/media) ## Как отправить [#как-отправить] - Кнопка вложения в строке ввода открывает выбор фото и видео, до десяти за раз. - «Файлы» в меню «+» отправляют что угодно как файл, без сжатия. - Файлы можно перетащить в чат или вставить из буфера обмена. - На телефоне можно поделиться в Comon из другого приложения через системное меню «Поделиться». Сообщение можно отправить сразу, не дожидаясь подготовки и загрузки: фото и видео готовятся и загружаются в фоне, а в чате уже видна их миниатюра с прогрессом. Загрузка продолжается после выхода из чата и возобновляется после перезапуска приложения. Несколько фото и видео, выбранных вместе, уходят одним сообщением-альбомом. Несколько файлов — одним сообщением со списком файлов. У альбома одна общая подпись. ## Фото [#фото] Перед отправкой приложение само готовит фото: - поворачивает по данным камеры и переводит в цвета sRGB; - **удаляет EXIF и геолокацию**; - сохраняет три размера: до 320, 1280 и 2560 пикселей по длинной стороне. Маленькое фото никогда не увеличивается. Пока фото грузится, на его месте видно размытое превью. ## Видео [#видео] Видео пересобирается в MP4 (H.264, до 1280 пикселей по длинной стороне, до 30 кадров в секунду), метаданные стираются. Если видео уже подходит, оно отправляется без перекодирования. В чате видео проигрывается без звука само, если его разрешает автозагрузка и оно хотя бы на 60% на экране. Нажатие открывает просмотр: перемотка, ±10 секунд, звук. Фото и видео одного чата листаются в одном просмотрщике. ## Файлы [#файлы] Файл отправляется как есть, с именем, размером и контрольной суммой. Получатель скачивает его по нажатию, приложение проверяет контрольную сумму перед открытием. GIF всегда отправляется файлом, чтобы сохранить анимацию. Правый клик (или долгое нажатие) на строке файла предлагает «Сохранить как…». ## Автозагрузка и память [#автозагрузка-и-память] В **Настройки › Данные и память** можно: - включить или выключить автозагрузку для мобильной сети и Wi-Fi, выбрать уровень (низкий, средний, высокий) или настроить отдельно фото, видео и файлы для личных чатов, групп, каналов и сообществ, с ограничением размера; - посмотреть, сколько места занимают медиа и файлы по категориям и чатам, и очистить их; - задать, сколько хранить медиа и максимальный размер кеша; - на телефоне — сохранять полученные фото и видео в галерею; - посмотреть расход трафика. Очистка удаляет копии на устройстве, на сервере ничего не удаляется: открытое снова скачается. **Загрузка заранее.** Пока приложение на связи, фото, обложки видео и кружков из непрочитанных входящих сообщений скачиваются до открытия чата, по тем же правилам автозагрузки: в первых 20 чатах с непрочитанными вне архива, до 30 в каждом. Открытый чат загружается первым. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Фото | 64 МБ, до 10 000 пикселей по стороне и 50 мегапикселей | | Видео | 128 МБ после подготовки, до 10 минут | | Файл | 1 ГБ (владелец федерации может уменьшить) | | Имя файла | 255 символов | | Фото и видео в одном сообщении | 10 | | Место под ваши медиа на сервере | 50 ГБ (владелец может изменить) | Место на сервере считается только по вашим загрузкам, которые ещё используются в сообщениях или аватарах. Удалённое у всех освобождает место. # Сообщения (/docs/features/messages) ## Отправка [#отправка] На компьютере Enter отправляет сообщение, а Shift+Enter переносит строку. Если удобнее отправлять по Ctrl+Enter (на Mac — Cmd+Enter), это меняется в **Настройки › Чаты**. Сообщение появляется в чате сразу, ещё до ответа сервера. Если сети нет, оно ждёт в очереди отправки на устройстве и уходит само, когда связь вернётся, в том числе после перезапуска приложения. Порядок сообщений в чате при этом сохраняется. У долгого нажатия (или правого клика) на кнопке «Отправить» есть ещё три варианта: «Отправить без звука», «Отправить позже» и в личном чате «Отправить, когда будет в сети». Они описаны на странице [Отложенные и тихие сообщения](./scheduled.mdx). ### Черновики [#черновики] Начатое сообщение сохраняется как черновик чата: вместе с вложениями, ответом и цитатами. Черновик переживает перезапуск приложения и возвращается, когда вы снова открываете чат. ### Если сообщение не ушло [#если-сообщение-не-ушло] Сообщение, которое сервер не принял или судьба которого неизвестна, помечается «Не отправлено». Нажатие на него открывает короткое меню: | Действие | Что делает | |---|---| | Повторить | Отправляет сообщение ещё раз и ставит его в конец чата. | | Повторить все | Повторяет все неотправленные сообщения этого чата. | | Отправить заново | Для сообщения, о котором неизвестно, дошло ли оно: отправляет его как новое. | | Копировать | Копирует текст. | | Удалить | Убирает сообщение из очереди. На сервере его нет, поэтому спрашивать «у кого удалить» не нужно. | У фото или видео, которое не загрузилось, на плитке есть своя кнопка повтора. Пока вложение загружается, крестик на нём убирает только это вложение. Если файл удалили с устройства до загрузки, приложение об этом скажет, и повтор не предлагается. ## Ответы и цитаты [#ответы-и-цитаты] - **Ответ.** Проведите по сообщению влево, дважды кликните мышью рядом с текстом или выберите «Ответить» в меню. Над вашим сообщением будет видно, на что оно отвечает. Нажатие на эту плашку переносит к исходному сообщению. - **Цитата части текста.** Выделите слова в сообщении и выберите «Цитировать». В сообщение вставится блок цитаты с этим фрагментом и автором. Цитата не считается ответом и не уведомляет автора. В одном сообщении может быть один ответ и до восьми цитат. Если исходное сообщение потом удалят, плашка ответа останется с последним известным текстом, но перейти к нему будет нельзя. ## Пересылка [#пересылка] Выберите одно или несколько сообщений (до 100 за раз) и нажмите «Переслать», затем отметьте один или несколько чатов. В параметрах пересылки можно: - **Скрыть имя автора.** Сообщение придёт как ваше, без плашки «Пересланное сообщение». - **Убрать подписи к фото.** Если пересылаете уже пересланное сообщение, в плашке останется исходный автор. При пересылке ответ на другое сообщение не переносится, упоминания никого не уведомляют. Пересылать можно только внутри одной федерации. ## Правка [#правка] Своё сообщение можно изменить: «Изменить» в меню или стрелка вверх в пустом поле ввода на компьютере (правится последнее ваше текстовое сообщение). Правка идёт в том же поле ввода, начатый черновик при этом не теряется. У исправленного сообщения рядом со временем появляется пометка «изм.». | Где | Кто правит | Сколько времени | |---|---|---| | Личный чат, группа | автор | 48 часов | | Группа | владелец группы | без ограничения | | Канал | владелец и публикаторы | без ограничения | | Комната сообщества | автор | без ограничения | Пересланное сообщение с указанием автора и карточку контакта изменить нельзя. Правка не уведомляет заново тех, кого упомянули. ## Удаление [#удаление] Выберите сообщения (до 100 за раз) и нажмите «Удалить». Варианты зависят от чата: - **Личный чат:** «Удалить у меня» или «Удалить у меня и у собеседника». Когда оба удалили сообщение у себя, сервер стирает его совсем. - **Группа:** только «Удалить у всех». Своё сообщение удаляет автор, чужое — владелец группы. - **Канал:** удаляют владелец и публикаторы, у всех подписчиков сразу. - **Комната сообщества:** своё удаляет автор, чужое — те, кому роль даёт право управлять сообщениями. Удалённое сообщение исчезает с экрана сразу. По умолчанию оно «утекает» в чёрную дыру; в **Настройки › Чаты** можно выбрать обычное исчезновение, а в браузере оно выбрано изначально. Если сервер удаление не примет, сообщение вернётся на место. ## Закрепление [#закрепление] Закреплённое сообщение показывается на панели над чатом, нажатие на неё ведёт к сообщению. Если закреплённых несколько, на панели виден номер текущего. - В **личном чате** сообщение закрепляют у себя или у обоих. - В **группе** закрепляет у всех только владелец. - В **канале** закрепляют владелец и публикаторы. - В **комнате сообщества** — те, кому это разрешает роль. О закреплении в чате появляется [системная строка](#системные-сообщения). ## Системные сообщения [#системные-сообщения] Строки посреди чата сообщают о событиях: кто кого добавил, кто вступил или вышел, что изменилось в названии, описании или фото, что закрепили, когда шёл звонок. - Имена в строке показываются текущими и открывают профиль. Ваши действия читаются «Вы …», действия над вами — «… вас». - Одно добавление — одна строка со всеми добавленными: «Анна добавила Бориса, Веру и Глеба». - Вступление говорит, как человек попал в группу: по ссылке-приглашению или по заявке, и кто её одобрил. - Строка группового звонка, пока он идёт, предлагает «Присоединиться», а после — показывает, сколько он длился. - Новое фото группы показывается в самой строке и открывается нажатием. Оно остаётся в строке, даже когда фото снова сменят. - Строка закрепления цитирует начало сообщения и ведёт к нему. Если сообщение удалили, в строке «удалённое сообщение». Закрепление только у себя видите только вы. - В **канале** строки создания, нового названия, описания и фото пишутся от имени канала. - В **комнате сообщества** строки о новом названии, теме и медленном режиме называют того, кто их изменил. Долгое нажатие, правый клик, Shift+F10 или клавиша меню открывают меню строки: точное время, «Перейти к сообщению» (у закрепления), «Выбрать» и «Удалить». Удаление убирает строку, но не отменяет событие. Системные строки нельзя изменить, переслать, закрепить, отметить реакцией или отправить в жалобу. ## Прочтение [#прочтение] - В **личном чате** две галочки у вашего сообщения значат, что собеседник его прочитал. - В **группе** две галочки появляются, когда сообщение прочитал хотя бы один участник. В меню сообщения видно, сколько человек его прочитали, и их список. Времени прочтения нет. - В **каналах** подписчики не видят, кто прочитал пост. Сообщение считается прочитанным, когда оно действительно попало на экран. Счётчик непрочитанных у чата в списке и разделитель «Непрочитанные» в чате показывают, с чего продолжить. ## Выделение и копирование [#выделение-и-копирование] - **Телефон.** Долгое нажатие поднимает сообщение над чатом и открывает меню. Слова можно выделить прямо в поднятом сообщении; «Копировать» в меню копирует сообщение целиком. - **Компьютер.** Обычный текст выделяется мышью, в том числе через несколько сообщений сразу. Правый клик открывает меню сообщения с реакциями; если что-то выделено, первыми идут «Цитировать» и «Копировать выделенное». - **Escape** по очереди снимает выделение сообщений, завершает правку и убирает ответ. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Текст одного сообщения | 32 768 символов | | Фото и видео в одном сообщении | 10 | | Ответ и цитаты | 1 ответ и до 8 цитат | | Удаление или пересылка за раз | 100 сообщений | | Окно правки своего сообщения | 48 часов | | Отправка подряд | 30 сообщений сразу, дальше 5 в секунду | Символы считаются в единицах UTF-16, как в Telegram: большинство эмодзи занимают два. Все лимиты сервера собраны в справочнике [Лимиты](../selfhost/limits.mdx). # Модерация (/docs/features/moderation) Модерацией федерации занимаются люди с ролями. Всё делается в приложении: **Настройки › Управление федерацией**. Этот раздел виден владельцу и тем, у кого есть право на панель управления; рядом с ним счётчик открытых жалоб. ## Роли федерации [#роли-федерации] У каждого есть встроенная роль `@everyone`. При создании федерации появляются ещё четыре: | Роль | Что может | |---|---| | Поддержка | Видит жалобы, отвечает от имени федерации, отклоняет их и передаёт модераторам, удаляет сообщения из жалоб | | Модератор | То же, плюс ограничивает и блокирует людей, закрывает чаты, видит журнал | | Администратор | Всё, включая роли и настройки федерации | | Владелец | Всё. Владелец один, передать владение можно, назначив роль владельца другому человеку. | Администраторы создают свои роли. Роль может давать права, лимиты (реакции, наборы стикеров, сообщества, новые личные чаты в день, добавления в группы в день, минуты распознавания речи) и значок: значки ролей видны в профиле, так участники отличают настоящих модераторов. | Право | Что даёт | |---|---| | Открывать панель федерации | Видеть «Управление федерацией», роли и профили | | Разбирать жалобы | Читать жалобы, отклонять и передавать модераторам | | Модерировать контент | Удалять сообщения из жалоб, скрывать и блокировать наборы стикеров, писать без фильтра слов | | Ограничивать профили | Предупреждать, ограничивать, блокировать, восстанавливать | | Закрывать чаты | Закрывать и открывать группы, каналы и сообщества | | Смотреть журнал действий | Читать журнал действий федерации | | Управлять ролями | Создавать, менять и назначать роли ниже своей | | Управлять федерацией | Менять настройки федерации и номера телефонов | | Создавать сообщества, ссылки на звонки и стикерпаки; публиковать и импортировать стикерпаки | По умолчанию есть у `@everyone` | | Отвечать от имени федерации | Писать людям из служебного чата | | Администратор | Все права, кроме действий владельца | **Старшинство.** Действовать против человека и менять его роли может только тот, чья самая высокая роль выше. Владельца не может тронуть никто. ## Жалобы [#жалобы] Жалобы на одно и то же (сообщения одного автора в одном чате, профиль, чат, сообщество или набор стикеров) собираются в одно **дело**. В очереди дела идут по важности, затем от старых к новым. Жалобы о вреде детям отмечены срочными, о насилии и самоповреждении — высокой важностью. О новом деле всем, кто разбирает жалобы, приходит сообщение в служебный чат, срочное — с пометкой. В деле видно, кто и почему пожаловался, копии сообщений на момент жалобы, текущее состояние профиля и доступные действия. ## Действия модератора [#действия-модератора] | Действие | Что происходит | |---|---| | Отклонить | Дело закрыто, авторам жалоб приходит, что нарушения нет. | | Передать модератору | Дело помечается и получает как минимум высокую важность. | | Ответить | Сообщение человеку из служебного чата. | | Удалить сообщения | Удаляются у всех. Вне публичных чатов — только сообщения из жалобы. | | Предупредить | Человеку приходит предупреждение с причиной, оно учитывается в профиле. | | Ограничить | До срока или до снятия человек пишет только в чаты, где уже есть: не создаёт, не вступает, не добавляет, новые личные чаты — только со взаимными контактами. Другие этого не видят. | | Заблокировать | Все устройства выходят, вход запрещён, в профиле видно «Аккаунт заблокирован». | | Восстановить | Снимает ограничение или блокировку. | | Закрыть чат, Открыть чат | Группа, канал или сообщество становится только для чтения, в него нельзя вступить и позвонить, оно пропадает из поиска. «Открыть чат» возвращает как было. | | Скрыть стикерпак, Заблокировать стикерпак, Оставить стикерпак | Скрыть набор из поиска, заблокировать его или вернуть как было. | К действию можно указать причину и заметку для других модераторов, и сразу закрыть дело. ## Служебный чат [#служебный-чат] У федерации есть свой профиль с её названием. В чат с ним приходят итоги жалоб, предупреждения, ограничения и ответы модераторов, на языке получателя. Сообщение, которое человек пишет в служебный чат, открывает дело поддержки: модераторы отвечают в тот же чат. ## Фильтры [#фильтры] Владелец федерации может задать стоп-слова (до 500) и запрещённые домены (до 500, вместе с поддоменами). Сообщение, в тексте или ссылках которого они есть, не отправится. На модераторов и служебный профиль фильтр не действует. ## Ограничения против спама [#ограничения-против-спама] - Новые личные чаты с теми, у кого вас нет в контактах: 50 в день для `@everyone`. - Добавление в группы и каналы тех, у кого вас нет в контактах: 50 в день. - Отправка, реакции, жалобы и изменения профиля ограничены по частоте. Лимиты меняются через роли, до 10 000 в день. ## Журнал и хранение [#журнал-и-хранение] Каждое действие модератора, изменение ролей, передача владения и изменение настроек записываются в журнал федерации. Его можно фильтровать по тому, кто действовал, и над кем. Журнал и закрытые дела с доказательствами хранятся год, открытые дела — пока не закрыты. ## Настройки федерации [#настройки-федерации] В **Управление федерацией › Правила и политики**: название федерации, контакт поддержки, правила на русском и английском, фильтры, дерево причин жалоб, гости в звонках, новые личные чаты в день, распознавание речи, режим контактов, номера телефонов и добавления в группы в день. Все они подробно описаны в разделе [Свой сервер](../selfhost/federation-settings.mdx). # Уведомления (/docs/features/notifications) ## Где приходят [#где-приходят] | Платформа | Как | После закрытия приложения | |---|---|---| | iPhone, iPad, Mac | Push через Apple, текст расшифровывается на устройстве | Да | | Android | Push через Google, текст расшифровывается на устройстве | Да, кроме принудительной остановки в настройках системы | | Windows | Уведомления системы от работающего приложения | Пока приложение запущено или в трее | | Браузер | Web Push через сервис браузера | Пока запущен браузер; на iPhone — если веб-версия добавлена на экран «Домой» | | Linux | Нет | — | Разрешение на уведомления приложение спрашивает один раз после первого входа. Если отказаться, уведомлений не будет, пока вы не включите их в **Настройки › Уведомления и звуки**. Текст уведомлений шифруется ключом устройства: ни сервис доставки, ни Apple, ни Google его не видят. Если расшифровать не удалось, приходит просто «Новое сообщение». ## Что приходит [#что-приходит] - Новые сообщения в личных чатах, группах, каналах и комнатах сообществ. - Упоминания и ответы вам — даже из чатов с выключенным звуком. - Реакции на ваши сообщения (в личных чатах и группах; кто может их присылать, настраивается). - Входящие звонки: на телефоне системным экраном звонка. - Отказ отложенного сообщения. Если вы прочитали сообщение на одном устройстве, уведомление пропадает и на других. Если сообщение удалили, его уведомление тоже убирается. Исправленное сообщение не уведомляет повторно. **Устройства по очереди.** Сначала уведомление получает устройство, которым вы пользовались последним, остальные — через 10–30 секунд, если вы ещё не прочитали. Если приложение открыто и вы им пользуетесь, вместо системного уведомления показывается баннер внутри приложения. В открытом чате уведомлений о нём нет. ## Выключить уведомления чата [#выключить-уведомления-чата] В меню чата или в его информации: «Выключить на час» или «Выключить бессрочно». Сообщения из выключенного чата приходят и считаются непрочитанными, но без уведомления, кроме упоминаний. В сообществе уведомления настраиваются для всего сообщества и отдельно для каждой комнаты. По умолчанию сообщество уведомляет только об упоминаниях и ответах вам. ## Расписание [#расписание] В **Настройки › Уведомления и звуки › Расписание** можно задать часы, когда уведомления разрешены, например рабочее время по будням. Вне этих часов сообщения приходят без уведомлений и остаются непрочитанными. Расписание задаётся в выбранном часовом поясе и не меняется, если вы переехали. Своё расписание может быть и у пространства (см. [Папки и пространства](./organization.mdx)). Уведомление приходит, только если его разрешают и федерация, и все пространства, где есть чат, и сам чат не выключен. Упоминания обходят выключенный чат, но не расписание. ## Архив [#архив] Если в архивном чате новое сообщение и уведомление о нём разрешено, чат сам выходит из архива. Если чат выключен или сейчас тихие часы, он остаётся в архиве. ## Звуки [#звуки] В **Настройки › Уведомления и звуки**: - **Звуки в приложении**: сообщения, звонки, голосовые комнаты, микрофон и звук; - **Рингтон** на телефоне: системный или Comon; - **Уведомления о реакциях**: от всех, от контактов или ни от кого. Сообщение, отправленное «без звука», приходит с уведомлением, но тихо. См. [Отложенные и тихие сообщения](./scheduled.mdx#тихие-сообщения). # Папки, пространства и архив (/docs/features/organization) Папки, пространства, архив и закреплённые чаты видны только вам, одинаковы на всех ваших устройствах и ничего не меняют в самих чатах. Папки свои в каждой федерации. ## Все чаты [#все-чаты] Если у вас несколько федераций, вверху можно выбрать «Все чаты» (чаты всех федераций вместе) или одну федерацию. Порядок чатов — по последнему сообщению; правка, прочтение, переименование или черновик чат не поднимают. Счётчик непрочитанных у папки считает чаты, а не сообщения. Белый счётчик значит, что в непрочитанных есть чат с уведомлениями, серый — что все непрочитанные чаты выключены. ## Папки [#папки] Папка — сохранённая выборка чатов, её вкладка видна над списком. Создаются в **Настройки › Чаты › Папки с чатами**; если папок ещё нет, там предлагаются готовые «Личные» и «Непрочитанные». В папке можно задать: - **виды чатов**: личные чаты с контактами, остальные личные чаты, группы, каналы; - **только непрочитанные**; - **архив**: только входящие, только архив или всё; - **всегда включать** выбранные чаты, даже если они не подходят под правила; - **исключать** выбранные чаты. Исключение сильнее включения. Папки можно переставлять, менять и удалять: удаление папки не трогает чаты. ## Пространства [#пространства] Пространство — отдельное рабочее место, например «Работа» или «Семья»: свои разделы на панели (чаты, календарь, почта) и свои источники в каждом из них. Создаются и настраиваются в **Настройки › Чаты › Пространства**; переключаются кнопкой пространства на панели. - **Чаты**: для каждой федерации — все её чаты, свои папки пространства или выбранные чаты. - **Календари** и **почта**: выбранные календари и ящики. Если всё взято из одной федерации, пространство хранится на ней и есть на всех ваших устройствах, вместе со своим [расписанием уведомлений](./notifications.mdx#расписание). Если источники из нескольких федераций, пространство хранится только на этом устройстве; перед таким переносом приложение предупреждает. Выключенное в пространстве не пропадает: оно остаётся в других пространствах и в «Все». Пространство не создаёт новых чатов и не меняет, от чьего имени вы пишете. Вложенных пространств нет. Когда пространства есть, настройки открываются из переключателя пространств; вернуть их вкладкой можно переключателем «Настройки отдельной вкладкой» там же. ## Архив [#архив] Архив убирает чат из основного списка. Архив — не то же самое, что выключить уведомления, прочитать, удалить или покинуть чат: история, черновик, счётчик непрочитанных и уведомления сохраняются. Чат сам выходит из архива, когда в нём новое сообщение, о котором вам пришло бы уведомление. Если чат выключен или сейчас тихие часы, он остаётся в архиве. ## Закреплённые чаты [#закреплённые-чаты] Чат можно закрепить вверху списка: «Закрепить чат» в его меню. Закрепление своё для каждого пространства и каждой папки. Закрепление не достаёт чат из архива. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Пространств | 32 | | Папок | 64 | | Название папки или пространства | до 64 символов | | Чатов, включённых или исключённых папкой | по 1000 | | Элементов в пространстве | 256 | | Закреплённых чатов в одной группе | 100 | | Окон в расписании уведомлений | 64 | # Профиль, контакты и статус (/docs/features/people) ## Профиль [#профиль] В каждой федерации у вас свой профиль: имя, фамилия (необязательно), @имя и аватар. Изменения профиля в одной федерации не затрагивают другие. - **@имя** — от 3 до 32 символов: латинская буква, затем буквы, цифры, `_` или `-`. @имя можно добавить и позже. Если @имени нет, незнакомые люди вас не найдут, а ссылки `/u/<имя>` у вас не будет; контакты находят вас по имени. - **Аватар** — квадратное фото, которое кадрируется под круглую маску: можно двигать, менять масштаб и поворачивать. Его можно заменить, посмотреть целиком или удалить. - **Телефон** виден, только если федерация использует номера. Номер приходит из сервиса входа организации или его задаёт владелец федерации, сам человек его не меняет. Профиль редактируется в **Настройки**, нажатием на свой профиль вверху. Для изменений нужна связь с сервером: без сети профиль не меняется. ## Профиль другого человека [#профиль-другого-человека] Профиль открывается из контактов, поиска, шапки чата, списка участников, аватара или имени автора сообщения. Ряд кнопок зависит от того, откуда открыт профиль: | Откуда | Кнопки | |---|---| | Из чата с этим человеком | Звонок, Видео, Звук, Поиск, Ещё | | Из другого места, переписка есть | Чат, Звонок, Звук, Поиск, Ещё | | Из другого места, переписки нет | Чат, Звонок, Видео, Звук, Ещё | «Чат» открывает переписку или начинает её, «Звук» — уведомления от этого чата, «Ещё» — добавить в контакты, задать своё имя для контакта, заблокировать, пожаловаться. Просмотр профиля не создаёт чат: он появится, только когда вы напишете или позвоните. ## Поиск людей [#поиск-людей] Что находит поиск, зависит от режима контактов, который выбрал владелец федерации: | Режим | Список контактов | Поиск незнакомых | |---|---|---| | Записная книжка | Только те, кого вы добавили | По части имени или @имени | | Все участники (по умолчанию) | Все участники федерации | Все, по части имени | | Скрытый | Только те, кого вы добавили | Только по точному @имени | В режиме «Все участники» все друг для друга контакты, и добавлять в контакты не нужно. Если у вас несколько федераций, поиск во вкладке «Все» идёт по каждой из них, а незнакомых ищет только по точному @имени. ## Контакты [#контакты] - Контакт односторонний: если вы добавили человека, у него ничего не меняется. В профиле видно, взаимный ли контакт и добавил ли он вас. - Переписка не добавляет в контакты сама. - Контакту можно задать своё имя: его видите только вы, а в профиле под ним видно имя, которое человек указал сам. - Блокировка не удаляет из контактов. - Во вкладке «Контакты» список сортируется по времени последнего визита или по имени. - Контакт можно отправить в чат карточкой: «Контакт» в меню вложений. Получатель видит аватар, имя и @имя и может сразу написать или добавить в контакты. ### Телефонная книга [#телефонная-книга] На iPhone и Android, если федерация использует номера телефонов и у вас есть номер, во вкладке «Контакты» появится предложение найти знакомых по телефонной книге. Найденные люди сразу становятся вашими контактами, с именем из вашей книги. Потом приложение повторяет поиск не чаще раза в день. Когда кто-то из вашей книги зарегистрируется, в чате с ним появится сообщение об этом. Загруженную телефонную книгу можно удалить с сервера: **Настройки › Конфиденциальность › Удалить загруженные контакты**. Сами контакты при этом остаются. Кто видит ваш номер и кто может найти вас по номеру, выбирается в настройках конфиденциальности. ## Статус «в сети» [#статус-в-сети] | Где | Что видно | |---|---| | Шапка личного чата | «в сети», «был(а) недавно», «был(а) 5 минут назад», «был(а) вчера в 12:12» или действие собеседника | | Список чатов | Точка «в сети» на аватаре; действие вместо последнего сообщения | | Шапка группы и комнаты | Действие с именем участника: «Вера выбирает стикер…» | | Профиль | То же, что в шапке, с точным временем | Действия: печатает, записывает или отправляет голосовое, записывает или отправляет видеосообщение, отправляет фото, видео или файл, выбирает стикер. У каждого своя анимация перед текстом. Пока приложение подключается, в шапке написано «соединение», а не статус собеседника. Статус «в сети» горит, пока приложение открыто и видно на экране. На компьютере он гаснет после пяти минут бездействия. ### Кто видит ваш статус [#кто-видит-ваш-статус] **Настройки › Конфиденциальность › Последняя активность**: все, мои контакты или никто, плюс исключения «Всегда показывать» и «Никогда не показывать» для людей и групп. Правило взаимное: если вы скрыли точное время от человека, вы не видите и его точного времени. Вместо него видно приблизительное: недавно, на этой неделе, в этом месяце или давно. Когда вы пишете кому-то или печатаете, вы видны в сети этому человеку ещё 30 секунд, даже если статус скрыт. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Имя и фамилия | по 64 символа | | Аватар | квадрат до 1024 пикселей и 8 МБ | | Контактов | 1000 | | Телефонная книга | до 5000 номеров, до 1000 новых номеров в день | # Приватность и блокировка (/docs/features/privacy) ## Настройки приватности [#настройки-приватности] **Настройки › Конфиденциальность** (настройки свои в каждой федерации): | Настройка | Варианты | По умолчанию | |---|---|---| | Последняя активность | Все, мои контакты, никто, плюс исключения | Все | | Сообщения: кто может начать с вами чат | Все, мои контакты, никто | Все | | Звонки: кто может вам звонить | Все, мои контакты, никто | Все | | Группы и каналы: кто может вас добавлять | Все, мои контакты | Все | | Номер телефона: кто его видит | Все, мои контакты, никто | Мои контакты | | Кто может найти меня по номеру | Все, мои контакты | Все | - «Сообщения» решает только, кто может **начать** чат. Уже начатые чаты продолжают работать. - Строки про телефон есть только в федерациях, которые используют номера. - В федерации в режиме «Все участники» все участники считаются контактами, поэтому «Мои контакты» там не предлагается. - На iPhone, Android и Mac здесь же выключаются подсказки чатов в системном меню «Поделиться». Если ваши настройки кому-то отказывают, он не узнаёт, почему: отказ из-за блокировки и из-за настроек выглядит одинаково. ## Блокировка [#блокировка] Заблокировать можно из профиля человека, из меню личного чата или кнопкой «Заблокировать», когда пишет незнакомый. Список заблокированных — **Настройки › Конфиденциальность › Заблокированные**, там же разблокировка. Блокировка действует в обе стороны: - нельзя начать личный чат и писать в существующий; - нельзя позвонить; - нельзя добавить друг друга в группу или канал; - вы не видите статуса друг друга, заблокированный не видит ваш аватар. Заблокированный не получает об этом уведомления. В общих группах и сообществах блокировка не мешает переписке, но сообщения заблокированного свёрнуты в «Сообщение от заблокированного пользователя»: нажатие показывает его. Служебный чат федерации заблокировать нельзя. ## Жалобы [#жалобы] Пожаловаться можно на сообщения (одно или несколько выбранных), человека, группу, канал, сообщество и набор стикеров: «Пожаловаться» в меню сообщения, профиля, чата или набора. 1. Выберите причину. Причины задаёт владелец федерации, они бывают вложенными. 2. Если причина требует, добавьте комментарий. 3. Для человека и чата можно сразу отметить «Также заблокировать пользователя». Модераторы видят только то, что видели вы в момент жалобы: копию выбранных сообщений и несколько последних сообщений чата. Остальная переписка им недоступна. Результат придёт в служебный чат федерации: были ли приняты меры или нарушения не нашлось. Списка своих жалоб нет. Подробнее о том, что делают модераторы, — на странице [Модерация](./moderation.mdx). ## Правила федерации [#правила-федерации] Если у федерации есть правила, их нужно принять при первом входе и заново, когда владелец их меняет. Правила, контакт поддержки и публичные страницы федерации есть в **Настройки › Помощь**, там же «Написать в поддержку». ## Удаление аккаунта [#удаление-аккаунта] **Настройки › Конфиденциальность › Удалить аккаунт**. Что при этом происходит, описано на странице [Федерации и аккаунты](../guide/federations.mdx#удаление-аккаунта). # Публичные чаты и приглашения (/docs/features/public-chats) ## @имена [#имена] У людей, групп, каналов и сообществ одной федерации общее пространство @имён: имя, занятое кем-то одним, занято для всех. В разных федерациях одинаковые имена не мешают друг другу. - Длина от 3 до 32 символов: латинская буква, затем буквы, цифры, `_` или `-`. - Регистр не важен при поиске, но имя показывается так, как его написал владелец. - Когда чат закрывают или удаляют, его @имя и коды приглашений освобождаются. ## Публичный или закрытый [#публичный-или-закрытый] | Что | Когда публичное | Кто даёт @имя | |---|---|---| | Группа, канал | Когда у неё есть @имя. Убрали имя — стала закрытой. | Владелец | | Сообщество | Когда в настройках выбрано «публичное». @имя необязательно. | Роли с правом управлять сообществом | Посторонний видит у публичного чата карточку: название, описание, число участников, аватар, обложку и @имя. ## Ссылки [#ссылки] | Ссылка | Что открывает | |---|---| | `https://<адрес федерации>/u/<имя>` | Человека или публичный чат | | `https://<адрес федерации>/join/<код>` | Приглашение в чат или сообщество | «Поделиться» и «Копировать ссылку» в приложении дают именно такие адреса. Если открыть ссылку в браузере, федерация покажет страницу с превью и кнопками: открыть в приложении, открыть веб-версию или скачать приложение для вашей платформы. Как ссылки открываются на разных устройствах, описано на странице [Ссылки Comon](./links.mdx). В приложении ссылку можно вставить в поиск, как и просто `@имя` или `+код`. Если ссылка ведёт в федерацию, которой у вас ещё нет, приложение предложит подключиться к ней и после входа откроет чат. ## Чтение до вступления [#чтение-до-вступления] Публичную группу или публичный канал можно читать, не вступая: сообщения, фото, видео и файлы видны, а внизу кнопка «Вступить в группу» или «Подписаться». Ничего не помечается прочитанным, и чат не появляется в списке, пока вы не вступили. У публичного сообщества до вступления видна только карточка. ## Ссылки-приглашения [#ссылки-приглашения] У каждой группы и каждого канала есть основная ссылка: она не истекает и не имеет лимита использований. Владелец может её перевыпустить, тогда старая перестанет работать. Дополнительные ссылки создаются в информации о чате. У них бывают: - название, чтобы понимать, кому вы её дали; - срок действия; - лимит вступлений; - одобрение: вступить по такой ссылке можно только после одобрения заявки. Ссылками управляет владелец группы или канала. У сообществ свои приглашения, см. [Сообщества](./communities.mdx). ## Заявки на вступление [#заявки-на-вступление] Если владелец включил одобрение заявок для чата или человек пришёл по ссылке с одобрением, вместо вступления кнопка «Подать заявку». Заявку можно отозвать. Владелец видит заявки в информации о чате, от самой ранней, и принимает или отклоняет каждую. Заявка не истекает и переживает выключение одобрения. ## Глобальный поиск [#глобальный-поиск] Поиск в списке чатов находит публичные группы, каналы и сообщества по @имени или части названия. Результаты, где вы ещё не состоите, показываются в разделе «Глобальный поиск». Запрос, начинающийся с `@`, ищет только по именам. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Рабочих ссылок-приглашений у чата | 100 | | Название ссылки | 32 символа | | Заявок, ждущих одобрения | 1000 | | Страниц превью ссылок с одного адреса в минуту | 60, дальше без превью | # Реакции (/docs/features/reactions) ## Как поставить [#как-поставить] - **Двойное касание** сообщения на телефоне ставит или снимает быструю реакцию. - **Долгое нажатие** (или правый клик) показывает над меню ряд реакций. На телефоне можно, не отпуская палец, провести на реакцию и отпустить. - Кнопка раскрытия в конце ряда открывает панель эмодзи: недавние, весь набор федерации и установленные вами наборы эмодзи. Реакции видны под сообщением или внутри него, рядом со временем. Пока реакций у сообщения не больше трёх, вместо счётчика видны аватары тех, кто их поставил. Долгое нажатие на реакцию из эмодзи-набора открывает этот набор. Реакцией может быть эмодзи из набора федерации или любой эмодзи-стикер федерации. ## Сколько можно [#сколько-можно] Количество задаёт владелец федерации через [роли](./moderation.mdx). По умолчанию: | Что | По умолчанию | Максимум для роли | |---|---:|---:| | Реакций одного человека на сообщение | 1 | 3 | | Разных реакций на одном сообщении | 11 | 11 | Если можно только одну реакцию, новая заменяет старую. Если несколько, при достижении предела снимается самая ранняя. ## Свои настройки [#свои-настройки] В **Настройки › Стикеры и эмодзи** можно выбрать «Быструю реакцию» для двойного касания и «Панель реакций»: до семи реакций, которые идут первыми в меню. Настройки общие для всех ваших устройств. ## Кто узнаёт о реакции [#кто-узнаёт-о-реакции] - В **личном чате и группе** автор сообщения получает уведомление о реакции. Чьи реакции присылать, выбирается в **Настройки › Уведомления и звуки › Уведомления о реакциях**: от всех (по умолчанию), только от контактов или ни от кого. Если реакцию сняли до отправки уведомления, оно не придёт. - Новые реакции на ваши сообщения отмечаются сердечком у счётчика непрочитанных в списке чатов. В самом чате над кнопкой прокрутки вниз появляется кнопка с сердечком: она ведёт к самому раннему сообщению с непрочитанной реакцией. - В **канале** реакции анонимны: никто не видит, кто их поставил, и уведомлений о них нет. Реакция не считается новым сообщением: она не поднимает чат в списке и не увеличивает счётчик непрочитанных. На системные сообщения реакции не ставятся. При удалении сообщения у всех его реакции тоже пропадают. # Отложенные и тихие сообщения (/docs/features/scheduled) Долгое нажатие или правый клик на кнопке «Отправить» открывает меню: - **Отправить без звука** — получатели увидят сообщение, но телефон не зазвонит. - **Отправить позже** — выбрать дату, время и повтор. - **Отправить, когда будет в сети** — только в личном чате. Так же отправляются стикеры (из их предпросмотра) и записи голосовых и кружков (с кнопки отправки записи). Отложить можно всё, что отправляется из строки ввода: текст, документ, фото, файлы, стикеры, голосовые и кружки. Пересылку отложить нельзя. ## Отправить позже [#отправить-позже] Выберите день и время. Время ближе десяти секунд отправляет сообщение сразу, а дальше года вперёд выбрать нельзя. **Повтор:** никогда, каждый день, каждую неделю, каждые 2 недели, каждый месяц, каждые 3 месяца, каждые 6 месяцев или каждый год. Повторяющееся сообщение после отправки остаётся в очереди со следующей датой. Отправляет сообщение сервер федерации, поэтому телефон может быть выключен. ## Когда будет в сети [#когда-будет-в-сети] Сообщение уйдёт, как только собеседник появится в сети. Если он в сети прямо сейчас, сообщение уходит сразу. Вариант недоступен, если собеседник скрыл от вас, когда бывает в сети. ## Очередь отложенных [#очередь-отложенных] Если в чате есть отложенные сообщения, в строке ввода появляется значок. Он открывает страницу «Отложенные сообщения», где каждое можно: - отправить сейчас; - перенести на другое время или изменить повтор; - изменить текст; - удалить. Очередь видна на всех ваших устройствах. Получатели не видят ни очереди, ни пометки, что сообщение было отложенным. В **канале** очередь общая для всех публикаторов: каждый видит и может менять запланированные посты остальных. ### Если отправить не удалось [#если-отправить-не-удалось] Отложенное сообщение не отправится, если к его времени вы больше не можете писать в этот чат, закончилось место для ваших сообщений или сервер был выключен дольше суток после назначенного времени. Тогда сообщение остаётся в очереди с причиной, а вам приходит одно уведомление. Его можно отправить ещё раз, перенести или удалить. Если вы вышли из чата или вас удалили, ваши отложенные сообщения в нём пропадают сразу, даже если вы вернётесь до их времени. ## Тихие сообщения [#тихие-сообщения] Сообщение «без звука» приходит как обычно: с уведомлением, счётчиком непрочитанных и упоминаниями, но без звука и вибрации. Получатель не видит, что сообщение было тихим. В канале публикатор может включить «тихую публикацию»: тогда все его посты по умолчанию уходят без звука, а меню кнопки «Отправить» предлагает один раз отправить со звуком. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Отложенных в одном чате | 100 у каждого автора; в канале 100 на всех публикаторов | | Насколько вперёд | 365 дней | | Опоздание, после которого сообщение не отправляется | 24 часа | | «Отправить сейчас» за раз | 32 сообщения | # Поиск (/docs/features/search) ## Глобальный поиск [#глобальный-поиск] Поле поиска над списком чатов (Ctrl/Cmd+K) ищет сразу везде: | Вкладка | Что ищет | |---|---| | Все | До трёх чатов и трёх людей, затем сообщения | | Чаты | Ваши чаты по названию | | Люди | Людей федерации, см. [Профиль, контакты и статус](./people.mdx#поиск-людей) | | Сообщения | Текст во всех ваших чатах | | Медиа, Ссылки, Файлы, Голосовые | Сообщения с таким содержимым; без запроса — последние | Публичные группы, каналы и сообщества, где вас ещё нет, показываются в разделе «Глобальный поиск». Если у вас несколько федераций, поиск идёт по всем сразу, а если одна недоступна, её можно повторить отдельно. Нажатие на результат открывает чат на этом сообщении. Назад возвращает к поиску с тем же запросом и местом в списке. ## Поиск в чате [#поиск-в-чате] Ctrl/Cmd+F или «Поиск» в меню чата. Чат сразу переходит к самому новому совпадению, а внизу видно «3 из 27» и стрелки. Enter и Shift+Enter листают совпадения, Escape закрывает поиск. Совпадения подсвечиваются в тексте, но не внутри нераскрытых спойлеров. Результаты можно показать списком. Кнопка фильтров в строке поиска: - **Системные сообщения** — показать события чата; ищутся, например, по новому названию или по человеку. - **От участника** — искать только сообщения одного участника или свои. В каналах этого фильтра нет: все посты там от имени канала. ## Как ищутся слова [#как-ищутся-слова] - Сообщение находится, если **каждое** слово запроса — начало какого-то слова в сообщении. «прив мир» найдёт «Привет, мир». Морфологии нет: «кот» не найдёт «кошка». - Регистр не важен, «ё» и «е» считаются одной буквой, латинские буквы с диакритикой — как без неё. - Ищется текст, заголовки, списки, цитаты, код, подписи к медиа, имена файлов и расшифровки голосовых. Текст из плашек ответа на чужие сообщения не ищется. - В запросе учитываются до 16 слов, длина — до 256 символов. Поиск идёт на сервере федерации, без сети он не работает. ## Общие медиа [#общие-медиа] Внизу профиля человека, информации о группе или канале — вкладки: Медиа (фото и видео), Файлы, Ссылки, Голосовые (голосовые и кружки) и, у человека, Общие группы. Показываются только вкладки, где что-то есть. Долгое нажатие или правый клик на элементе — «Перейти к сообщению». ## Чего пока нет [#чего-пока-нет] Истории поиска, поиска по кешу без сети, фильтров по чату и дате в глобальном поиске. # Безопасность и данные (/docs/features/security) ## Модель доверия [#модель-доверия] Comon — мессенджер для организаций, которые держат сервер у себя. Сервер федерации — доверенная сторона: - **сервер федерации может читать сохранённые сообщения**. Сквозного шифрования между людьми (как в «секретных чатах») в Comon нет; - зато данные не уходят никуда, кроме сервера федерации: федерации не связаны между собой, и написать в другую нельзя. Если нужно, чтобы владелец сервера не мог прочитать переписку, Comon для этого сейчас не подходит. ## Соединение с сервером [#соединение-с-сервером] - Приложение подключается к федерации по TLS, а поверх него открывает отдельную сессию по протоколу **Noise** с ключом сервера. - При первом подключении приложение проверяет, что по адресу действительно работает федерация, и запоминает её ключ. Если потом сервер подменят, приложение не подключится. - Каждое устройство получает свой ключ. Закрытая часть ключа хранится в защищённом хранилище системы (Keychain, Android Keystore и аналогах), а не в базе приложения. ## Вход [#вход] Вход идёт через сервис входа вашей организации (OIDC): приложение открывает его страницу в системном браузере или во встроенной системной сессии входа, но никогда во встроенном веб-просмотре. Comon не видит ваш пароль от этого сервиса. ### Облачный пароль [#облачный-пароль] Облачный пароль — второй шаг входа с нового устройства, на случай если учётную запись в сервисе входа захватят. Он не шифрует сообщения. - От 10 до 128 символов, пробелы разрешены. - Хранится на сервере только как стойкий хеш (PBKDF2-SHA256, 600 000 итераций). - После каждых пяти неверных попыток подряд вход блокируется: на минуту, потом каждый раз вдвое дольше, но не больше суток. - Забытый пароль сбрасывает владелец федерации на сервере. ## Устройства [#устройства] В **Настройки › Устройства** видны все устройства, с которых выполнен вход: название, платформа, версия приложения, когда последний раз были активны. Любое другое устройство можно отключить, или все сразу. Выход на одном устройстве не трогает другие. ## Данные на устройстве [#данные-на-устройстве] - База приложения и кеш медиа **зашифрованы** (SQLite с шифром ChaCha20, ключи в защищённом хранилище системы). - Если ключ недоступен, приложение не стирает данные, а ждёт, пока хранилище станет доступно. - Выход из федерации удаляет с устройства её данные и ключ входа. ## Что видит сервер федерации [#что-видит-сервер-федерации] | Видит | Не видит | |---|---| | Сообщения, файлы, профили, участников чатов | Ваш пароль от сервиса входа организации | | Время входа устройств и их названия | Закрытые ключи устройств | | Кто кому пишет | Ваш облачный пароль (только хеш) | Модераторы при этом видят не всё: только то, что приложено к жалобе. См. [Модерация](./moderation.mdx). ## Push-уведомления [#push-уведомления] Уведомления на телефоне и в браузере идут через **push relay** — отдельный сервис, который передаёт их в Apple, Google или браузер. - Текст уведомления **зашифрован** ключом устройства. Relay, Apple и Google видят только зашифрованный блок, время и объём. - Федерация не хранит токены Apple и Google, у неё есть только непрозрачные идентификаторы relay. Relay, в свою очередь, не знает ключей, которыми зашифрован текст. - Без relay приложение всё равно получает сообщения, когда открыто; не приходят только уведомления в фоне. Подробности для администратора — на странице [Push-уведомления](../selfhost/push.mdx). ## Распознавание речи [#распознавание-речи] Расшифровка голосовых идёт на распознавателе, который выбрал владелец федерации. Если он работает вне федерации, приложение пишет, куда уходит звук. Подробнее на странице [Голосовые и кружки](./voice.mdx#расшифровка-речи). ## Отчёты об ошибках [#отчёты-об-ошибках] Приложение может отправлять отчёты о сбоях, только если в сборке указан свой сервер отчётов (Sentry); переключатель «Отправлять отчёты об ошибках» есть в **Настройки › Помощь**. Отправить журнал вручную можно через «Сообщить о проблеме» там же. # Настройки (/docs/features/settings) Вверху настроек — ваш профиль: аватар, имя и `@имя · федерация`. Если федераций несколько, там же можно выбрать, настройки какого профиля показывать, или добавить федерацию. Разделы собраны в группы «Аккаунт», «Приложения» и «Общие». «Федерации», «Язык», «Оформление», вид чатов, вкладка календаря и переключатели устройства (уведомления, звуки, устройства звонка, напоминания) действуют на всём устройстве. Остальные — для профиля, выбранного вверху, и одинаковы на всех ваших устройствах. | Раздел | Что внутри | |---|---| | Устройства | Ваши устройства, завершение других сеансов. См. [Безопасность](./security.mdx#устройства). | | Чаты | Папки с чатами и пространства, вид сообщений, крупные эмодзи, клавиша отправки. См. [Чаты](#чаты). | | Почта | Ящики: имя отправителя, подпись, проверка новых отправителей, коды; подключение ящика; какие письма присылают уведомления. См. [Почта](./mail.mdx). | | Календарь | Вкладка календаря в навигации, начало недели, второй часовой пояс, календарь этой федерации, напоминания на этом устройстве. См. [Календарь](#календарь). | | Звонки | Микрофон, динамик, камера, шумоподавление, «картинка в картинке», зеркальная камера, ссылки на звонки. См. [Звонки](./calls.mdx#настройки-звонков). | | Боты | Мои боты и личный бот. См. [Боты](../bots/index.mdx). | | Уведомления и звуки | Системные уведомления, расписание, уведомления о реакциях, звуки, рингтон. См. [Уведомления](./notifications.mdx). | | Конфиденциальность | Заблокированные, облачный пароль, последняя активность, кто может писать, звонить и добавлять в группы, телефон, удаление аккаунта. См. [Приватность](./privacy.mdx). | | Данные и память | Использование памяти и сети, автозагрузка, сохранение в галерею, история сообщений на устройстве. | | Оформление | Тема и масштаб интерфейса. | | Стикеры и эмодзи | Быстрая реакция, панель реакций, наборы эмодзи и стикеров. См. [Стикеры и эмодзи](./stickers.mdx). | | Язык | Русский или английский. | | Федерации | Все ваши федерации, их подключение, очередь отправки, выход. См. [Федерации и аккаунты](../guide/federations.mdx). | | Помощь | Сообщить о проблеме, отчёты об ошибках, правила и поддержка федерации. | | Журнал | Просмотр журнала приложения (только в тестовых сборках). | | Управление федерацией | Для владельца и модераторов. См. [Модерация](./moderation.mdx). | ## Чаты [#чаты] - **Папки с чатами**: папки федерации и свои папки пространства. См. [Папки, пространства и архив](./organization.mdx). - **Пространства**: пространства, их разделы и источники, «Настройки отдельной вкладкой». См. [Пространства](./organization.mdx#пространства). - **Цвет своих сообщений**, **размер текста сообщений** и **фон чата** с узорами — с живым предпросмотром чата. - **Удаление сообщений**: «чёрная дыра» или растворение. - **Крупные эмодзи**: сообщения только из эмодзи без пузыря. - **Клавиша отправки** (если есть клавиатура): Enter или Ctrl/Cmd+Enter. ## Календарь [#календарь] - **Показывать календарь в навигации**: скрытие вкладки не меняет приглашения и напоминания. - **Вид**: начало недели, второй часовой пояс и, если на устройстве есть свои календари, показ обеих копий. - **Календари**: календарь этой федерации, куда приходят приглашения. - **Напоминания**: работают ли напоминания на этом устройстве, разрешение на точное время. См. [Календарь](./calendar.mdx). ## Оформление [#оформление] - **Тема**: системная (по умолчанию), светлая или тёмная. - **Масштаб интерфейса**. ## Данные и память [#данные-и-память] - **Использование памяти**: диаграмма по категориям, очистка, сколько хранить медиа (с исключениями для отдельных чатов), предельный размер кеша, вкладки «Чаты», «Медиа», «Файлы», «Музыка». - **Использование сети**: сколько трафика ушло на что, отдельно для мобильной сети и Wi-Fi. - **Автозагрузка медиа** для мобильной сети и Wi-Fi. - **Сохранять в галерею** полученные фото и видео (только в приложении на телефоне). - **История сообщений на устройстве** для каждой федерации: размер базы и очистка. Очистка не выход: вход, черновики, очередь отправки и список чатов сохранятся, история загрузится снова, когда вы откроете чаты. ## Помощь [#помощь] - **Сообщить о проблеме**: форма с описанием, снимком экрана, журналом приложения и данными об устройстве. «Отправить» открывает системное меню «Поделиться», и вы сами выбираете, куда отправить: в чат, на почту или в файл. Никуда автоматически отчёт не уходит. Форму можно открывать встряхиванием телефона, это включается здесь же. - **Отправлять отчёты об ошибках**: есть в сборках, где указан сервер отчётов. - Правила федерации, контакт поддержки, публичные страницы и «Написать в поддержку». # Стикеры и эмодзи (/docs/features/stickers) ## Панель эмодзи и стикеров [#панель-эмодзи-и-стикеров] Кнопка со смайликом слева от «Отправить» открывает панель с двумя вкладками: «Эмодзи» и «Стикеры». Панель открывается на той вкладке, где вы были в прошлый раз. В ней есть недавние, избранные стикеры, установленные наборы и поиск. - **Стикер** отправляется отдельным сообщением, без пузыря. Нажатие на стикер в чате открывает его набор: его можно добавить себе. - **Свои эмодзи** вставляются прямо в текст и рисуются вместо обычного эмодзи того же смысла. У тех, у кого набора нет, и в уведомлениях виден обычный эмодзи. В меню сообщения есть «Эмодзи из набора …»: оттуда набор добавляется к себе. - **Анимированные эмодзи.** Если владелец федерации установил набор анимированных эмодзи, сообщение из одного такого эмодзи проигрывается как маленький стикер. Нажатие проигрывает его снова. - **Крупные эмодзи.** Сообщение только из эмодзи показывается крупно и без пузыря. Это выключается в **Настройки › Чаты**. ## Наборы [#наборы] Наборы бывают двух видов: стикеры и эмодзи. Наборы общие для всей федерации: у каждого есть автор и ссылка по короткому имени. Публичные наборы находятся поиском, неопубликованные открываются только по ссылке. Владелец федерации также может установить **системные наборы**, которые есть у всех. В **Настройки › Стикеры и эмодзи**: - менять порядок установленных наборов перетаскиванием и удалять их; - добавить набор по ссылке или короткому имени; - найти публичные наборы федерации; - создать свой набор; - импортировать набор из Telegram; - включить или выключить повтор анимации и подсказки стикеров по эмодзи. Установленные наборы, недавние и избранное хранятся в вашем профиле и одинаковы на всех устройствах. ## Свой набор [#свой-набор] Создайте набор, задайте название и короткое имя, затем добавляйте стикеры: к каждому нужно хотя бы одно эмодзи. Набор можно переименовать, сменить обложку, переставить и заменить стикеры, сделать публичным или удалить. | Формат | Что загружать | |---|---| | Картинка | PNG или WEBP до 512 КБ | | Анимация Lottie | TGS до 64 КБ, только вектор, до 60 кадров в секунду, по правилам Telegram (без масок, эффектов, повторителей и звёзд) | | Видео | WEBM (VP9 с прозрачностью) до 256 КБ, до 30 кадров в секунду | Стикер вписывается в 512 пикселей, эмодзи — в квадрат 100 × 100. Анимация длится не дольше трёх секунд. Сервер сам проверяет и приводит файлы к нужному виду. Анимацию Lottie он разбирает, пересобирает и прорисовывает целиком в изолированном процессе, поэтому приложения получают только проверенный файл, а не тот, что загрузили. Если набор удалить, уже отправленные стикеры из него продолжают показываться. ## Импорт из Telegram [#импорт-из-telegram] Вставьте ссылку `t.me/addstickers/…` или `t.me/addemoji/…` в «Добавить по ссылке» или выберите «Импорт из Telegram». Сервер скачает набор через бота федерации и создаст его копию от вашего имени. Файлы, которые не прошли проверку, пропускаются, приложение покажет, сколько их. - Импорт работает, только если владелец федерации подключил Telegram-бота. - Импортированный набор нельзя сделать публичным, он доступен по ссылке. - Один набор Telegram импортируется в федерацию один раз: повторный импорт сразу откроет уже существующую копию. ## Жалобы [#жалобы] На чужой набор можно пожаловаться. Модераторы федерации могут скрыть набор из поиска или заблокировать его: тогда его стикеры перестают показываться везде, а его файлы нельзя загрузить снова. ## Лимиты [#лимиты] Владелец федерации может менять их через роли. В скобках — значения роли `@everyone` по умолчанию. | Что | Максимум | |---|---| | Своих наборов стикеров / эмодзи | 100 (20 / 10) | | Установленных наборов стикеров / эмодзи | 500 (200 / 100) | | Стикеров / эмодзи в наборе | 120 / 200 | | Избранных стикеров | 50 (5) | | Импортов из Telegram в день | 100 (10) | | Своих эмодзи в одном сообщении | 512 | # Голосовые и кружки (/docs/features/voice) ## Запись [#запись] Когда поле ввода пустое, вместо кнопки отправки стоит микрофон. Короткое нажатие переключает его на камеру для кружка и обратно. | Жест | Что происходит | |---|---| | Удерживать | Идёт запись. | | Отпустить | Запись отправляется. | | Провести влево | Отмена. | | Провести вверх | Запись закрепляется: руки свободны, есть кнопки «Отмена», «Стоп» и «Отправить». | | Пробел / Escape на компьютере | Пауза / отмена закреплённой записи. | После «Стоп» запись можно прослушать, обрезать голосовое с двух сторон, удалить или отправить. Если запись прервал звонок, сворачивание приложения или ошибка камеры, записанное сохраняется для предпросмотра. Запись работает и без сети: голосовое загружается на сервер прямо во время записи, когда связь есть, а иначе уходит из очереди отправки. Голосовое короче полсекунды и кружок короче секунды не отправляются. ### Кружки [#кружки] Кружок снимается фронтальной или основной камерой, есть кнопка подсветки. Масштаб меняется щипком или колёсиком мыши. На паузе кружок завершает фрагмент, а после продолжения записывает следующий: при отправке они склеиваются. На отметке 60 секунд кружок отправляется сам. ## Воспроизведение [#воспроизведение] - **Голосовое** показывает волну: нажмите или проведите по ней, чтобы перемотать. - **Кружок** в чате крутится без звука, пока он на экране. Нажатие включает звук и воспроизведение с начала, повторное — паузу. На паузе проведите пальцем по кругу, чтобы перемотать. - **Скорость** переключается нажатием: 1×, 1,5×, 2×. Долгое нажатие открывает ползунок от 0,5× до 2,5×. Скорость одна для голосовых и кружков и запоминается на устройстве. - Голосовые и кружки играют подряд: после записи само включается следующее более новое голосовое или кружок чата, своё или чужое, прослушанное или нет. Пауза цепочку не рвёт. Пока играет одна запись, следующая уже загружается, в пределах настроек автозагрузки. - Если у следующего кружка нет пузыря на экране, он играет в плавающем кружке и садится в пузырь, когда до него доскроллили. Если следующий кружок виден, чат ставит его по центру. - На телефоне с датчиком приближения звук переходит в разговорный динамик, когда телефон у уха. Плеер общий для приложения: при выходе из чата запись не останавливается. Её панель видна над списком чатов и в шапке чата, нажатие на название ведёт к сообщению. Если кружок со звуком уходит с экрана, он продолжает играть в плавающем окне, которое можно перетащить в угол или смахнуть. Точка у записи означает, что вы её ещё не слушали. Автор видит, прослушал ли запись кто-нибудь. В каналах этой отметки нет. ## Расшифровка речи [#расшифровка-речи] Если владелец федерации включил распознавание речи, у голосовых и кружков есть кнопка «Расшифровать». Текст появляется под записью и виден всем в чате, его можно свернуть. По расшифровке работает поиск. - Распознавание запускается только по нажатию, само при отправке или получении ничего не распознаётся. - Во время записи голосового можно включить «Aa»: речь распознаётся на лету, и вместо голосового отправляется обычный текст, который можно поправить перед отправкой. - Если распознаватель работает вне федерации, приложение пишет, куда уходит звук: «Распознано через …». - У каждого есть время распознавания на день. По умолчанию это час, владелец федерации меняет его через роли. Одна и та же запись распознаётся один раз: пересланное или повторно отправленное голосовое получает готовую расшифровку бесплатно. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Голосовое | до 2 часов и 64 МБ, Opus 48 кГц моно | | Кружок | до 60 секунд и 16 МБ, отправляется 400 × 400 пикселей | | Распознаётся запись длиной | до 30 минут (владелец может поднять до 2 часов) | | Время распознавания в день | 1 час (владелец может поднять до 24 часов) | # Приложения и платформы (/docs/guide/apps) Comon — одно приложение на Flutter для всех платформ. Возможности почти везде одинаковые, различия собраны ниже. ## Что работает где [#что-работает-где] | Платформа | Чаты, фото, файлы | Голосовые, кружки, видео | Звонки | Уведомления в фоне | |---|---|---|---|---| | iPhone и iPad | да | да | да, с системным экраном звонка | да | | Android | да | да | да, с уведомлением о звонке на весь экран | да | | macOS | да | да | да | да | | Windows | да | да | да | пока приложение запущено или свёрнуто в трей | | Linux | да | нет | см. ниже | нет | | Браузер | да | да | да | да, пока браузер запущен | ### Особенности платформ [#особенности-платформ] - **iPhone.** Новые сообщения подгружаются в фоне по push-уведомлению, поэтому чат открывается уже с ними, даже если приложение было закрыто. Поделиться в Comon можно из любого приложения через системное меню «Поделиться». - **Android.** Входящий звонок показывается на весь экран, даже на заблокированном телефоне. Работает «Поделиться» и импорт телефонной книги. - **Windows.** Закрытие окна сворачивает Comon в трей. Клик по значку в трее открывает окно, правый клик — меню «Открыть Comon» и «Завершить». После завершения уведомления не приходят. - **Linux.** Работают переписка, фото и файлы. Воспроизведения и записи голосовых, кружков и видео, камеры и системных уведомлений пока нет. Звонки в сборке для Linux есть, но без камеры, и на устройствах они ещё не проверялись. - **Браузер.** Веб-версия открывается по адресу федерации с `/app` на конце, если владелец её включил. Comon можно держать открытым только в одной вкладке. На iPhone уведомления работают, только если добавить веб-приложение на экран «Домой». Демонстрация экрана доступна в браузерах на компьютере. ## Языки [#языки] Интерфейс есть на русском и английском. Язык меняется в **Настройки › Язык**. ## Где взять приложение [#где-взять-приложение] Ссылки на сборки для всех платформ собраны на странице [comon.chat/download](https://comon.chat/download). - **iPhone, iPad и macOS** — через TestFlight по приглашению. - **Android** — файлом APK. - **Windows** — установщик без прав администратора. - **Linux** — файл AppImage. - **Браузер** — по адресу федерации с `/app` на конце. В App Store и Google Play приложения пока нет. Приложение можно собрать и самостоятельно, см. [Сборка из исходников](../develop/build.mdx). ## Обновления [#обновления] ### Когда федерация просит обновиться [#когда-федерация-просит-обновиться] Каждая федерация сообщает приложению, какие версии она поддерживает. - Если приложение слишком старое, вместо списка чатов появится экран «Нужно обновить приложение» со ссылкой на новую версию. Уже загруженные чаты при этом можно открыть для чтения. - Если вышла рекомендуемая версия, над списком чатов появится баннер с предложением обновиться. Его можно закрыть. ### Windows, Linux и macOS из установщика [#windows-linux-и-macos-из-установщика] Версия, установленная через установщик, обновляется сама: 1. При запуске и потом раз в час приложение проверяет, нет ли новой версии, и скачивает её в фоне. 2. Когда загрузка готова, над списком чатов появляется «Версия X готова к установке · Обновить». 3. «Обновить» перезапускает приложение уже в новой версии. Если идёт звонок, перезапуск ждёт его окончания. Без вашего нажатия обновление не ставится. Скачанная, но не установленная версия будет предложена при следующем запуске. Чаты и настройки хранятся отдельно от программы и переживают и обновление, и удаление приложения. ### Остальные платформы [#остальные-платформы] iPhone, iPad и macOS из TestFlight обновляются через TestFlight. Android-сборку из APK нужно скачать заново по ссылке из баннера. Веб-версия всегда последняя. # Федерации и аккаунты (/docs/guide/federations) ## Что такое федерация [#что-такое-федерация] Федерация — это сервер Comon вместе с его пользователями, чатами и правилами. Её запускает владелец: компания для сотрудников, сообщество для участников или один человек для друзей. Владелец решает, кто может войти, какие правила действуют и где физически лежат данные. Несмотря на название, каждая федерация — отдельный закрытый мир. Написать человеку из другой федерации нельзя, общих чатов между федерациями нет. Так данные одной организации никогда не попадают на чужой сервер. ## Как войти [#как-войти] ### Узнайте адрес [#узнайте-адрес] Адрес федерации даёт её владелец, например `chat.example.org`. ### Добавьте федерацию [#добавьте-федерацию] На первом экране приложения или в **Настройки › Федерации** нажмите «Добавить федерацию» и введите адрес. Приложение сначала проверяет, что по этому адресу действительно сервер Comon, и запоминает его ключ. Подменить сервер незаметно потом не получится. ### Войдите [#войдите] Приложение откроет страницу входа вашей организации: корпоративный вход или учётную запись, которую выдал владелец. Если федерация требует облачный пароль, приложение попросит его задать. ### Заполните профиль [#заполните-профиль] При первом входе укажите имя. @имя можно выбрать сразу или добавить позже. Если у федерации есть правила, их нужно принять. Когда владелец меняет правила, их принимают заново. ## Несколько федераций в одном приложении [#несколько-федераций-в-одном-приложении] Если вы состоите в нескольких федерациях, второе приложение не нужно. Добавьте каждую в **Настройки › Федерации**, и в каждой у вас будет свой профиль. Чаты всех федераций собраны в «Все чаты», а чаты одной федерации — в «Все чаты федерации». Если одна федерация недоступна, остальные работают как обычно. В **Настройки › Федерации** у каждой федерации есть действия: | Действие | Что происходит | |---|---| | Отключиться | Соединение ставится на паузу. Загруженные чаты, черновики и очередь отправки остаются на устройстве. Пауза сохраняется и после перезапуска. | | Подключиться | Соединение возобновляется, очередь отправки уходит на сервер. | | Войти снова | Вход в ту же федерацию и тот же профиль, если сеанс закончился. | | Выйти | С устройства удаляются данные этой федерации и ключ входа. На сервере переписка остаётся, вернуться можно, войдя заново. Неотправленные сообщения при выходе пропадают. | ## Облачный пароль [#облачный-пароль] Облачный пароль Comon — второй шаг входа, его спрашивают при входе с нового устройства. Задать, сменить или отключить его можно в **Настройки › Конфиденциальность › Облачный пароль**. - Обязателен ли он, решает владелец федерации. Если он обязателен, отключить его нельзя. - Пароль — от 10 до 128 символов. - Восстановить забытый пароль самостоятельно нельзя, его сбрасывает владелец федерации. ## Устройства [#устройства] В **Настройки › Устройства** видно, с каких устройств выполнен вход, и можно завершить любой другой сеанс или все сразу. ## Если федерация переехала [#если-федерация-переехала] Федерацию определяют её ID и ключ, а не домен. Если владелец перенёс её на новый адрес, приложение при запуске само переключит аккаунт на новый адрес, когда убедится, что там та же федерация с тем же ключом. Старые версии приложения продолжают работать через старый адрес, пока владелец держит его как псевдоним. ## Удаление аккаунта [#удаление-аккаунта] Удалить аккаунт можно в **Настройки › Конфиденциальность**. Что происходит: - ваши сообщения в личных чатах, группах и комнатах удаляются у всех; - аватар удаляется, профиль помечается удалённым, @имя освобождается; - все устройства выходят из аккаунта, ваши боты удаляются; - вы выходите из групп, каналов и сообществ. Если вы были их владельцем, владение переходит к самому давнему участнику; - если войти снова тем же способом, будет создан новый пустой профиль. Владелец федерации не может удалить свой аккаунт, пока не передаст владение федерацией другому человеку. # Словарь (/docs/guide/glossary) ## Люди и сервер [#люди-и-сервер] **Федерация.** Сервер Comon вместе с пользователями, чатами и правилами. Федерации между собой не связаны. См. [Федерации и аккаунты](./federations.mdx). **Владелец федерации.** Человек, который запустил федерацию и управляет ей из приложения: **Настройки › Управление федерацией**. Он один и может передать владение другому. **Роль федерации.** Набор прав внутри федерации: модерировать, смотреть жалобы, создавать сообщества и ботов, сколько новых личных чатов в день можно начать. У каждого есть встроенная роль `@everyone`. **Профиль.** Ваш аккаунт в одной федерации: имя, @имя, аватар. В каждой федерации профиль свой. **@имя (username).** Уникальное имя в федерации, от 3 до 32 символов: буква, затем буквы, цифры, `_` или `-`. У людей, ботов и публичных чатов общее пространство имён. **Облачный пароль.** Второй шаг входа с нового устройства, поверх входа организации. **Служебный чат.** Чат с профилем федерации: через него приходят ответы модераторов и уведомления от сервера. ## Чаты [#чаты] **Личный чат.** Переписка двух человек или человека с ботом. **Группа.** Общий чат до 256 участников. Добавлять людей может любой участник, а переименовывает группу, удаляет участников и передаёт владение только владелец. **Канал.** Лента публикаций: пишут владелец и публикаторы, остальные читают и реагируют. **Сообщество.** Пространство с комнатами, категориями и своими ролями, как сервер в Discord. **Комната.** Чат внутри сообщества: текстовая, для объявлений или голосовая. **Голосовая комната.** Комната с постоянным звонком: в неё заходят и выходят без звонка участникам, а внутри есть свой текстовый чат. **Публичный чат.** Группа, канал или сообщество с @именем: их находят в поиске и открывают по ссылке `/u/<имя>`. **Приглашение.** Ссылка `/join/<код>`, по которой вступают в чат или сообщество. Может иметь срок и лимит вступлений. ## Сообщения [#сообщения] **Отложенное сообщение.** Сообщение, которое сервер отправит в заданное время, в том числе повторяющееся. **Эфемерное сообщение.** Ответ бота, который видит только один человек. Он не попадает в историю чата и живёт до 24 часов. **Кружок.** Короткое квадратное видео до 60 секунд, которое показывается в чате кругом. ## Звонки [#звонки] **Звонок по ссылке.** Конференция, в которую входят по ссылке `/call/<код>`, в том числе гости без аккаунта. **Гость.** Человек без аккаунта в федерации, вошедший в звонок по ссылке. Видит только этот звонок и его чат. **Зал ожидания.** Место, где гости ждут, пока организатор звонка их впустит. **SFU.** Сервер, который пересылает видео и звук в групповых звонках, чтобы каждому участнику не приходилось отправлять поток всем остальным. **TURN.** Сервер-посредник для звонков, когда устройства не могут соединиться напрямую. ## Боты [#боты] **Бот.** Профиль без устройств, за который действует программа через HTTP Bot API. **Личный бот.** Бот, которого человек подключил к своим личным чатам: он читает выбранные чаты и может отвечать от имени человека. **Вебхук.** Адрес, на который сервер сам отправляет боту новые события. ## Обслуживание [#обслуживание] **Клиентский уровень.** Номер версии протокола в приложении. Федерация задаёт минимальный и рекомендуемый уровень, по нему приложение понимает, что пора обновиться. **Шлюз.** Дополнительный процесс сервера, который держит соединения клиентов и передаёт их основному серверу. Нужен для масштабирования. **Push relay.** Сервис, который доставляет push-уведомления через Apple, Google и браузеры, не видя текста сообщений. **Модуль.** Отдельная часть сервера со своей схемой в базе, которую можно включать и выключать. # Что такое Comon (/docs/guide) Comon — мессенджер с чатами, каналами, сообществами, звонками и ботами, у которого нет общего сервера. Каждая организация запускает свой сервер и решает, кто в нём состоит, какие действуют правила и где лежат данные. ## Из чего он состоит [#из-чего-он-состоит] Одно приложение для iPhone, Android, macOS, Windows, Linux и браузера. Открытые чаты хранятся на устройстве и открываются без сети; написанное без сети уходит, когда связь вернётся. Так в Comon называется сервер вместе с его пользователями, чатами и правилами. Её запускает и обслуживает владелец: компания, сообщество или один человек. Пароли учётных записей хранит не Comon, а сервис входа вашей организации (OIDC), например корпоративный вход. Comon добавляет к нему свой облачный пароль и ключ устройства. Подробнее на странице [Федерации и аккаунты](./federations.mdx). ## Что умеет [#что-умеет] - **Переписка.** Личные чаты, группы до 256 человек, каналы, сообщества с текстовыми и голосовыми комнатами. Форматирование, ответы и цитаты, пересылка, правка в течение 48 часов, отложенные сообщения, реакции, стикеры и эмодзи-наборы. - **Медиа.** Фото, видео, файлы до 1 ГБ, голосовые сообщения и кружки, расшифровка голосовых, превью ссылок. - **Звонки.** Личные и групповые звонки до 32 участников, голосовые комнаты в сообществах, конференции по ссылке с гостями и залом ожидания, демонстрация экрана. - **Боты.** HTTP Bot API в духе Telegram: команды с параметрами, кнопки, вебхуки, эфемерные сообщения, личные боты. - **Модерация.** Роли федерации, жалобы, фильтры слов и доменов, журнал действий модераторов. Полный список с правилами и лимитами — в разделе [Возможности](../features/index.mdx). ## Кому подходит [#кому-подходит] - Командам и компаниям, которым нужен свой мессенджер с данными на своём сервере. - Сообществам, которые хотят сами решать, кого пускать и как модерировать. - Тем, кого пригласили в федерацию: достаточно установить приложение и ввести её адрес. ## С чего начать [#с-чего-начать] Как войти в федерацию, несколько федераций в одном приложении, облачный пароль и устройства. От чистой Linux-машины до первого входа в приложение. # Документация Comon (/docs/) Comon — мессенджер, сервер которого организация запускает у себя. Документация о приложении, своём сервере со всеми настройками и API для ботов. } title="Знакомство" href="/guide"> Что такое Comon, федерации и аккаунты, приложения и платформы, словарь терминов. } title="Возможности" href="/features"> Сообщения, медиа, чаты, звонки, люди, безопасность. Кто что может, какие лимиты и что видит собеседник. } title="Свой сервер" href="/selfhost"> Требования, быстрый старт, справочник всех настроек, звонки, push, резервные копии, обновления и диагностика. } title="Боты" href="/bots"> Как создать бота, HTTP Bot API, команды, кнопки, вебхуки, личные боты и боты в сообществах. } title="Разработчикам" href="/develop"> Сборка из исходников, устройство репозитория, протокол и как прислать изменение. } title="Изменения" href="/develop/changelog"> Что нового в каждом релизе и что сделать владельцу сервера при обновлении. ## Часто открывают [#часто-открывают] - [Быстрый старт сервера](./selfhost/quick-start.mdx) - [Справочник настроек сервера](./selfhost/reference.mdx) - [Звонки, SFU и TURN](./selfhost/calls.mdx) - [Резервные копии и восстановление](./selfhost/backups.mdx) - [Обновление до новой версии](./selfhost/upgrading.mdx) - [Готовый бот на Python и Node.js](./bots/examples.mdx) ## Для языковых моделей [#для-языковых-моделей] Каждая страница доступна как Markdown: кнопка «Скопировать Markdown» под заголовком. Весь сайт одним списком лежит в [`/docs/llms.txt`](/llms.txt), целиком в [`/docs/llms-full.txt`](/llms-full.txt). # Версии приложений (/docs/selfhost/app-updates) ## Уровень приложения [#уровень-приложения] У каждой сборки приложения есть **уровень** — целое число, которое растёт, когда приложение начинает понимать что-то новое в протоколе. При входе и каждом подключении приложение называет свой уровень, платформу и версию, а сервер отвечает своей политикой: | Параметр | По умолчанию | Что значит | |---|---|---| | `--minimum-client-level` | `29` | Самый старый уровень, который сервер обслуживает. Ниже 29 задать нельзя. | | `--recommended-client-level` | равен минимальному | До какого уровня приложение предлагает обновиться. | | `--client-update-url` | нет | Куда отправлять за новой версией, по разу на платформу. | ``` --client-update-url=android=https://example.org/comon.apk --client-update-url=ios=https://apps.apple.com/app/... --client-update-url=windows=https://example.org/ComonSetup.exe ``` Платформы: `android`, `ios`, `macos`, `windows`, `linux`, `web`. Адреса только HTTPS. Те же ссылки страницы ссылок предлагают как кнопку «скачать» ([веб-версия и ссылки](./web.mdx#страницы-ссылок)). ## Что видит человек [#что-видит-человек] - **Уровень ниже минимального.** Вместо списка чатов этой федерации приложение показывает «Нужно обновить приложение» с кнопкой «Обновить», которая открывает ссылку для его платформы. Если ссылки нет, приложение советует установить новую версию оттуда, где его взяли. Уже сохранённые на устройстве чаты можно читать («Показать сохранённые чаты»). Другие федерации работают как обычно. - **Уровень ниже рекомендованного.** Над списком чатов появляется «Вышла новая версия приложения» с кнопками «Обновить» и «Позже». Всё продолжает работать. - **Сообщение, которое эта версия не умеет показать.** На его месте — «Обновите приложение, чтобы прочитать сообщение». Минимальный уровень поднимают, когда старые сборки опасны или новая версия сервера с ними не работает. Такие версии сервера отмечены в [истории изменений](../develop/changelog.mdx), и новый сервер сам поднимает значение по умолчанию. ## Обновление на компьютерах [#обновление-на-компьютерах] Приложения для Windows, Linux и macOS, установленные установщиком, обновляются сами из ленты выпусков проекта (`https://comon.chat/updates/`), независимо от федерации: - проверяют ленту при запуске и раз в час и скачивают новую версию в фоне; - показывают «Версия X готова к установке» с кнопкой «Обновить», которая перезапускает приложение уже новым; - во время звонка ждут его конца: «Приложение перезапустится и обновится после звонка»; - никогда не ставят обновление без согласия человека. Если ваша федерация требует или рекомендует новую версию, а приложение уже скачало её, кнопка «Обновить» перезапускает его в новую версию вместо перехода по вашей ссылке. Для официальных сборок на компьютерах `--client-update-url` поэтому нужен только как запасной путь. Телефоны обновляются через магазины приложений, веб-версия всегда последняя: её обновляете вы, пересобирая [веб-клиент](./web.mdx#веб-клиент). # Резервные копии (/docs/selfhost/backups) ## Что нужно сохранить [#что-нужно-сохранить] Федерация — это **база и тома вместе**. По отдельности они бесполезны: | Что | Почему без этого нельзя | |---|---| | База PostgreSQL | Всё, кроме байтов медиа: профили, чаты, сообщения, настройки. | | Том `federation` | Ключ Noise (без него устройства не подключатся) и файлы медиа, на которые ссылается база. | | Том `caddy` | Сертификаты и, при `tls internal`, свой центр сертификации. | | Каталог состояния | `stack.env` с паролями, ID федерации, ключи push, секреты TURN и SFU, файлы Compose. | | Ключ APNs `.p8` | В копию не входит: храните его отдельно. | База, запущенная на чужом или пустом томе медиа, не стартует с ошибкой `MediaVolumeMismatch`. ## Сделать копию [#сделать-копию] ```sh python3 tools/mvp-stack.py backup --backup /абсолютный/путь/backup-2026-10-26 ``` Команда на время **останавливает весь стек**, чтобы снимок PostgreSQL был согласованным, архивирует все тома и конфигурацию с суммами SHA-256 и запускает стек снова, даже если архивирование упало. Каталог копии должен быть новым. Архив **не зашифрован** и не подписан: в нём закрытые ключи и пароли. Храните его как пароли, шифруйте перед отправкой за пределы машины и восстанавливайте только свои копии. Расписания в стеке нет: запускайте команду по cron или таймеру systemd в тихие часы. Простой длится, пока архивируются тома, и растёт с объёмом медиа. ## Восстановление [#восстановление] На машине без томов `comon-mvp`, из той же версии репозитория: ```sh python3 tools/mvp-stack.py restore --state .local/restored --backup /абсолютный/путь/backup-2026-10-26 python3 tools/mvp-stack.py up --state .local/restored python3 tools/mvp-stack.py check --state .local/restored ``` `restore` проверяет суммы, требует новый каталог состояния и **отказывается, если тома уже есть**: он никогда не перезаписывает живые данные. Не удаляйте тома работающего стека, чтобы попробовать восстановление. Оставьте тот же домен и те же версии образов. Чтобы отрепетировать восстановление на той же машине, добавляйте `--project comon-mvp-restored` ко всем командам восстановленного стека и остановите исходный перед запуском копии: два расходящихся экземпляра одной федерации — не резервирование. ### Первый запуск из копии [#первый-запуск-из-копии] Восстановленная федерация старше того, что уже видели приложения, relay и внешний мир. Поэтому `restore` добавляет серверу `--restored-backup=<имя копии>`, и первый запуск до начала работы: - **проверяет медиа**: если файлов сообщений и аватаров не хватает, сервер не запустится и перечислит их в журнале (`restore_missing_media`). Восстановите том медиа, снятый вместе с базой, или запустите сервер с `--accept-missing-media`; - **обновляет ключи push**: ничего старого не уйдёт, устройства зарегистрируются заново; - **начинает историю с нового поколения**: приложения перечитывают чаты, а не пропускают то, что видели до сбоя, и сохраняют для людей отправки, сделанные после копии; - **придерживает исходящее**: отложенные сообщения не отправляются (авторы могут их изменить или удалить), вебхуки ботов не вызываются. В `/ready` видно `"outbound": "held"`. Следующие запуски с тем же именем ничего не меняют, так что параметр можно оставить. Когда убедились, что всё в порядке, разрешите исходящее (сервер остановлен): ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo restores dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo release-outbound dc start federation ``` `dc` — функция из [обслуживания](./operations.mdx#команды-compose-вручную). Если был включён push, после восстановления он **выключен**: старые отзывы и ключи предпросмотра нужно сверить, прежде чем снова допускать устройства ([push](./push.mdx#резервная-копия-relay)). ### Проверка после восстановления [#проверка-после-восстановления] 1. Уже вошедшее устройство подключается и видит прежние сообщения. 2. Вход со второго устройства проходит. 3. Новое сообщение доходит до обоих. # Боты и мосты (/docs/selfhost/bots-and-bridges) ## Боты [#боты] Ботов создают сами люди в приложении, а программы ботов работают где угодно и обращаются к серверу по [HTTP Bot API](../bots/index.mdx) (`https://<домен>/bot/v1/<метод>`). Отдельного сервиса для ботов поднимать не нужно. ### Кто может создавать ботов [#кто-может-создавать-ботов] Без настроек каждый может создать до 20 ботов. Иначе политику задаёт JSON-файл в `--bot-config`: ```json { "everyone": { "canCreate": false, "maximumBots": 0 }, "roles": { "developers": { "canCreate": true, "maximumBots": 50 } }, "profileRoles": { "": ["developers"] } } ``` | Поле | Что значит | |---|---| | `everyone` | Права всех: `canCreate` и `maximumBots`. | | `roles` | Именованные наборы тех же прав. | | `profileRoles` | Какие роли у каких профилей. | Человек получает самое щедрое из прав `everyone` и своих ролей. Эти роли существуют только в настройках ботов и не связаны с ролями федерации из модерации. ### Демо-бот [#демо-бот] Сервер сам запускает `@demo_bot`, который показывает все возможности ботов: кнопки, команды с подсказками, временные сообщения. Его владелец — служебный профиль федерации. Выключить: `--no-demo-bot`. Демо-бот не запустится и тогда, когда имя `demo_bot` уже кем-то занято. ### Вебхуки [#вебхуки] Бот получает обновления либо запросами к серверу, либо вебхуком: сервер сам отправляет их на адрес бота. По умолчанию вебхуки на частные адреса (локальная сеть, `localhost`) запрещены, чтобы через бота нельзя было обращаться к внутренним сервисам. Для разработки на своей машине их можно разрешить флагом `--bot-private-webhooks`. На публичном сервере не включайте его. ## Мосты: каналы Telegram [#мосты-каналы-telegram] Мост транслирует публичные каналы Telegram в федерацию: человек ищет канал Telegram по ссылке или имени, и в Comon появляется канал-трансляция с новыми постами и пометкой «Транслируется из Telegram». ```sh python3 tools/mvp-stack.py enable-bridge python3 tools/mvp-stack.py up ``` Команда пишет политику федерации `bridges.json`, настройки процесса моста `bridge.json` (с одним общим токеном) и добавляет сервис `bridge`. Мост и сервер общаются только внутри сети Docker. Политику меняют в `bridges.json`, после чего выполняют `up`. ### Чтение через служебный аккаунт [#чтение-через-служебный-аккаунт] Без аккаунта мост читает веб-превью каналов: видны только последние ~20 постов, правки и удаления доходят с опозданием. Со служебным аккаунтом мост читает Telegram через TDLib и видит правки и удаления сразу. 1. На my.telegram.org войдите номером служебного аккаунта (не личным) и создайте приложение. 2. Впишите его ключи в `stack.env` и выполните `up`: ```sh TELEGRAM_API_ID= TELEGRAM_API_HASH= ``` 3. Один раз войдите в аккаунт: команда спросит номер, код из Telegram и облачный пароль, если он есть. ```sh python3 tools/mvp-stack.py bridge-login ``` Сессия хранится в томе `bridge-tdlib`. Один аккаунт вступает примерно в 500 каналов, дальше трансляции получают новые посты, но не правки. ### Политика (`bridges.json`) [#политика-bridgesjson] ```json { "networks": { "telegram": { "title": "Telegram", "usernamePrefix": "telegram_", "linkHosts": ["t.me", "telegram.me"], "url": "http://bridge:8090", "token": "<от 16 символов>", "mediaBudgetBytes": 10737418240, "maximumPortals": 1000, "allow": [], "deny": [], "keepPolledMinutes": 60 } }, "everyone": { "canMirror": true, "mirrorsPerDay": 10 }, "roles": { "moderator": { "canTakeDown": true } }, "profileRoles": { "": ["moderator"] } } ``` | Поле | Что значит | |---|---| | `mediaBudgetBytes` | Сколько медиа хранят все трансляции сети. Сверх бюджета медиа остаются ссылками. По умолчанию 10 ГиБ. | | `maximumPortals` | Сколько каналов-трансляций может быть, включая остановленные. По умолчанию 1000. | | `allow`, `deny` | Имена каналов строчными буквами, без `@`. Пустой `allow` разрешает все. | | `everyone`, `roles`, `profileRoles` | `canMirror` и `mirrorsPerDay` — кто и сколько новых каналов в день может транслировать; `canTakeDown` — кто может останавливать трансляции. | ### Остановка трансляции [#остановка-трансляции] Человек с правом `canTakeDown` открывает страницу канала-трансляции и выбирает «Остановить трансляцию». Посты и медиа удаляются у всех, и этот канал больше нельзя транслировать. Чтобы канал не транслировался с самого начала, добавьте его в `deny`. ## Импорт стикеров из Telegram [#импорт-стикеров-из-telegram] Люди могут импортировать наборы стикеров Telegram по ссылке. Для этого федерации нужен свой бот Telegram: создайте его у @BotFather и передайте серверу файл с токеном `--telegram-bot-token-file=<файл>`. Без него импорт выключен. Лимит — 10 импортов в день на человека ([стикеры](../features/stickers.mdx)). # Звонки, SFU и TURN (/docs/selfhost/calls) Звонки идут по WebRTC. Сервер федерации только соединяет участников и раздаёт им настройки, а звук и видео идут мимо него: - **личный звонок** — напрямую между устройствами, а если они не видят друг друга, через **TURN** (coturn); - **групповой звонок, голосовая комната и звонок по ссылке** — через **SFU**, медиасервер федерации (`backend/comon_sfu`). SFU пересылает потоки, не декодируя их. Готовый стек поднимает оба сервиса и пишет их настройки сам. Без TURN устройства за строгим NAT не соединятся, без SFU групповой звонок не начнётся. ## Порты [#порты] | Порт | Протокол | Сервис | |---|---|---| | 3478 | TCP и UDP | TURN | | 49160–49200 | UDP | TURN: ретрансляция трафика | | 7882 | UDP | SFU: все медиа групповых звонков через один порт | | 5349 | TCP | TURN поверх TLS, если включён | Откройте их в брандмауэре машины. Если сервер за роутером, пробросьте **те же внешние порты** на адрес сервера в локальной сети, не меняя номера. HTTPS-прокси этот трафик не проводит. Управляющий API SFU (порт 7880) доступен только внутри сети Docker. Не публикуйте его. ## Настройки сервера федерации [#настройки-сервера-федерации] Параметр `--call-config` указывает на JSON: ```json { "stun_urls": ["stun:chat.example.org:3478"], "turn_urls": [ "turn:chat.example.org:3478?transport=udp", "turn:chat.example.org:3478?transport=tcp" ], "turn_secret_file": "/run/secrets/turn-secret", "sfu_url": "http://sfu:7880", "sfu_secret_file": "/run/secrets/sfu-secret" } ``` | Поле | Что значит | |---|---| | `stun_urls`, `turn_urls` | Серверы, которые получают устройства. До 8 адресов. | | `turn_secret_file` | Общий секрет coturn (`static-auth-secret`). Из него сервер выдаёт устройствам временные учётные данные TURN на 4 часа. | | `sfu_url` | Адрес управляющего API SFU внутри сети. | | `sfu_secret_file` | Общий секрет сервера и SFU. | Без `--call-config` устройства не получают ни STUN, ни TURN; без `sfu_url` групповые звонки отвечают «не поддерживается». ## TURN (coturn) [#turn-coturn] Готовый стек пишет `turnserver.conf` с общим секретом, портами 49160–49200 и `external-ip` — публичным адресом, который coturn сообщает устройствам. По умолчанию это адрес, в который разрешается домен. TURN работает в одном сетевом пространстве с SFU (`network_mode: service:sfu`): так устройства, пришедшие через TURN, достают до медиа SFU. Пересоздаёте SFU — пересоздайте и TURN. ## SFU [#sfu] | Параметр | Переменная | По умолчанию | Что значит | |---|---|---|---| | `-listen` | `COMON_SFU_LISTEN` | `:7880` | Адрес управляющего API, только внутренняя сеть | | `-secret-file` | `COMON_SFU_SECRET_FILE` | обязателен | Файл с общим секретом | | `-udp-port` | `COMON_SFU_UDP_PORT` | `7882` | Единственный UDP-порт для всех медиа | | `-public-ips` | `COMON_SFU_PUBLIC_IPS` | нет | Адреса через запятую, которые SFU сообщает устройствам | | `-log-level` | `COMON_SFU_LOG_LEVEL` | `info` | `debug`, `info`, `warn` или `error` | В готовом стеке переменные лежат в `sfu.env`. SFU не использует STUN и TURN: у него свой публичный адрес. Состояние комнат хранится в памяти: после перезапуска SFU идущие групповые звонки переподключаются сами, с разбросом до трёх секунд. Если UDP 7882 занят, задайте другой порт в `COMON_SFU_UDP_PORT` в `sfu.env` и пробросьте его же в `compose.yaml` у сервиса `sfu`. ## Сервер за NAT [#сервер-за-nat] - `external-ip` в `turnserver.conf` и `COMON_SFU_PUBLIC_IPS` в `sfu.env` должны называть **публичный IPv4**, доступный из интернета. Если домен внутри вашей сети разрешается в частный адрес, впишите публичный вручную. - Если публичный адрес сменился, поменяйте оба значения и пересоздайте `sfu` и `turn`. - **Устройства в той же сети, что и сервер**, попадают на публичный адрес, только если роутер умеет возвращать такой трафик внутрь (hairpin NAT). Многие домашние роутеры не умеют, и тогда групповые звонки из домашней сети идут только через TURN или не идут совсем. Допишите локальный адрес сервера в `COMON_SFU_PUBLIC_IPS` через запятую (`<публичный>,<локальный>`): SFU предложит оба, и устройство дома возьмёт тот, до которого достаёт. ## TURN поверх TLS [#turn-поверх-tls] Некоторые браузеры и сети выпускают наружу только TLS. Для них нужен `turns:`. Выпустите сертификат на домен федерации (PEM: цепочка и ключ) и выполните: ```sh python3 tools/mvp-stack.py enable-turn-tls \ --turn-tls-cert /path/fullchain.pem --turn-tls-key /path/privkey.pem python3 tools/mvp-stack.py up ``` Команда копирует файлы в `turn-tls/` состояния, включает TLS в coturn на порту 5349 (другой — `--turn-tls-port`) и добавляет `turns:<домен>:<порт>?transport=tcp` в `calls.json`. Обычные порты 3478 остаются. coturn читает сертификат только при запуске: после продления запустите `enable-turn-tls` с новыми файлами и перезапустите `turn`. Сертификат Caddy лежит в его хранилище; можно выгрузить его или выпустить отдельный. Порт 443 проходит через самые строгие сети, но его уже занимает прокси. Тогда нужен отдельный IP для coturn или отдельное имя TURN, которое прокси пропускает по SNI без расшифровки. Готовый стек такую схему не настраивает. ## Проверка [#проверка] Проверяйте снаружи вашей сети, с телефона в мобильной сети: запуск контейнеров и открытый TCP-порт не доказывают, что доходит UDP. 1. Личный звонок между телефоном в мобильной сети и компьютером в другой сети. 2. Групповой звонок с тремя участниками, в том числе с телефона в домашнем Wi-Fi сервера. 3. Если включён `turns:`, звонок из браузера в сети, где закрыт UDP. Сервер пишет каждое событие звонка в свой журнал строкой `calls`: начало и конец звонка с причиной (`cause=`), вход и выход участников (`reason=`), команды SFU и их ошибки. ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Участников группового звонка | 32 | | Ожидание ответа | 45 секунд | | Возвращение после обрыва | 20 секунд | | Звонков одновременно у одного человека | 8 | | Учётные данные TURN | 4 часа | | Ссылок на звонки у человека | 50 | | Гостей звонков по ссылке во всей федерации | 1024 | Звонки по ссылке и гости описаны в разделе [Возможности](../features/call-links.mdx); разрешить или запретить гостей можно в [настройках федерации](./federation-settings.mdx). # Внешние аккаунты (/docs/selfhost/external-accounts) Люди могут подключить свой аккаунт Google или Яндекса либо любой почтовый или календарный сервер по паролю приложения в разделе «Настройки → Аккаунты». Подключение хранит сервер федерации и сам работает с аккаунтом, поэтому календарь обновляется, даже когда все устройства человека выключены. Токены провайдера на устройства не попадают, а пароль приложения устройство отправляет один раз, при подключении. На сервере токены и пароли хранятся зашифрованными вашим ключом. Без этой настройки подключить аккаунт нельзя. ## Создайте OAuth-клиент Google [#создайте-oauth-клиент-google] 1. В [Google Cloud Console](https://console.cloud.google.com/) создайте проект и включите Google Calendar API. 2. Настройте экран согласия OAuth: внешний, название приложения, адрес поддержки и ваш домен в разрешённых доменах. 3. Добавьте области `openid`, `email` и `https://www.googleapis.com/auth/calendar.readonly`, а для почты ещё `https://mail.google.com/`. Доступ к календарю считается чувствительным, а к почте ограниченным: пока Google не проверит приложение, подключиться могут только тестовые пользователи, которых вы перечислили на экране согласия (до 100). 4. Создайте OAuth-клиент типа «Веб-приложение» с адресом перенаправления `https://<ваш сервер>/accounts/oauth/callback`. 5. Сохраните секрет клиента в файл, который может читать только сервер. ## Создайте OAuth-приложение Яндекса [#создайте-oauth-приложение-яндекса] 1. На [oauth.yandex.ru](https://oauth.yandex.ru) создайте приложение типа «Веб-сервисы» с адресом перенаправления `https://<ваш сервер>/accounts/oauth/callback`. 2. Дайте ему доступы `login:info` и `login:email`, а для почты ещё `mail:imap_full` и `mail:smtp`. 3. Сохраните секрет клиента в файл, который может читать только сервер. ## Подключение по паролю [#подключение-по-паролю] От вас ничего не нужно: когда файл настройки задан, люди могут подключить любой сервер IMAP/SMTP или CalDAV по паролю приложения. Сервер проверяет пароль, прежде чем его сохранить, и подключается только к адресам в интернете. Если почтовый сервер ваших людей стоит в вашей собственной сети, добавьте `"server_accounts": {"private_networks": true}`; `"server_accounts": {"enabled": false}` выключает подключение по паролю. ## Создайте ключ шифрования [#создайте-ключ-шифрования] ```sh head -c 32 /dev/urandom | base64 > external-accounts-current.key chmod 600 external-accounts-current.key ``` Храните ключ вместе с резервными копиями базы: без него подключённые аккаунты не прочитать, и людям придётся подключать их заново. ## Включите [#включите] Напишите файл настройки рядом с ключами: ```json { "secret_keys": ["external-accounts-current.key"], "google": { "client_id": "1234567890-abc.apps.googleusercontent.com", "client_secret_file": "google-client.secret" }, "yandex": { "client_id": "0123456789abcdef0123456789abcdef", "client_secret_file": "yandex-client.secret" } } ``` и запустите сервер с `--external-accounts=<файл>` ([все настройки](./reference.mdx)). Если процессов сервера несколько, каждому нужны тот же файл и те же ключи. ## Смените ключ [#смените-ключ] Поставьте новый ключ первым в `secret_keys`, а старый оставьте после него. Токены переходят на новый ключ по мере обновления. Уберите старый ключ, когда все аккаунты с тех пор синхронизировались: аккаунт, зашифрованный убранным ключом, попросит владельца подключить его заново. ## Неполадки [#неполадки] | Что видно | Что делать | |---|---| | Google пишет «Доступ заблокирован» или «приложение не проверено» | Добавьте человека в тестовые пользователи на экране согласия или пройдите проверку приложения. | | Google пишет, что адрес перенаправления не совпадает | У OAuth-клиента адрес должен быть ровно `https://<ваш сервер>/accounts/oauth/callback`. | | У аккаунта «Войти снова» | Google отказал в сохранённом доступе: сменили пароль, отозвали доступ в аккаунте Google или убрали тестового пользователя. Человек входит снова в «Настройки → Аккаунты». | | В логе сервера `external_account_sync_failed` | Google не ответил или ответил ошибкой; сервер повторит сам, не реже раза в час. | # Настройки федерации (/docs/selfhost/federation-settings) Большая часть настроек федерации меняется не в файлах, а в самом приложении: **Настройки › Управление федерацией**. Раздел видят люди с правом «Открывать панель федерации»; менять настройки может право «Управлять федерацией» (оно есть у владельца и администраторов). Настройки хранятся в базе и попадают в [резервную копию](./backups.mdx). В разделе пять страниц: «Жалобы», «Люди», «Роли», «Журнал действий» и «Правила и политики». Роли, жалобы и действия модераторов описаны в [Модерации](../features/moderation.mdx); здесь — «Правила и политики». ## Федерация [#федерация] | Настройка | Что меняет | |---|---| | Название | Как федерация называется в приложениях, в документе федерации и на публичных страницах. До 64 символов. | | Контакт поддержки | E-mail, ссылка или @username. Показывается на публичных страницах и в разделе о федерации. | ## Правила [#правила] «Правила на русском» и «Правила на английском» — текст, который люди принимают при первом входе. После изменения правил у них новая версия, и все принимают их снова. Правила видны в приложении и на странице `/rules`. ## Фильтр [#фильтр] «Слова и фразы» и «Домены», по одному в строке, до 500 каждого. Сообщения с ними не отправляются. Подробнее — в [Модерации](../features/moderation.mdx#фильтры). ## Политики [#политики] | Настройка | По умолчанию | Что значит | |---|---|---| | Причины жалоб | встроенный список | Дерево причин, которые человек выбирает в жалобе. До 50 причин и трёх уровней. | | Гости в звонках | разрешены | Можно ли входить в [звонки по ссылке](../features/call-links.mdx) без аккаунта. | | Новых личных чатов в день | 50 | Сколько личных чатов в день человек может начать с теми, у кого его нет в контактах. Пусто — без лимита. Роль может дать больше. | | Расшифровка | выключена | Распознаватель речи ([расшифровка](./transcription.mdx)). | | Распознавание речи, минут в день | 60 | Для всех; роль может разрешить больше. | ## Контакты и номера телефонов [#контакты-и-номера-телефонов] | Настройка | Варианты | |---|---| | Контакты | «Все участники» (по умолчанию): во вкладке «Контакты» все видят всех. «Записная книжка»: у каждого свои контакты, других находят по имени или @нику. «Скрытый»: других находят только по точному @нику, ссылке или карточке, номера телефонов никого не находят. | | Номера телефонов | «Выключены», «Необязательные», «Обязательные» ([номера телефонов](./sign-in.mdx#номера-телефонов)). | | Добавлений в группы в день | Сколько людей, у которых добавляющего нет в контактах, можно добавить в группы и каналы за день. Пусто — 50. Роль может разрешить больше. | Пока режим контактов в приложении не выбран, сервер берёт его из `--contacts-mode`. Как это выглядит для людей — в [Людях и контактах](../features/people.mdx). ## Роли федерации [#роли-федерации] Встроенные роли: владелец, администратор, модератор, поддержка и роль «Есть у всех» (@everyone), которая задаёт права и лимиты по умолчанию. Можно создавать свои роли, до 50 вместе со встроенными. Права и лимиты ролей подробно — в [Модерации](../features/moderation.mdx#роли-федерации). ## Владелец [#владелец] Владельцем становится первый человек, закончивший регистрацию в новой федерации. Если владельца нет, при запуске сервер назначает им профиль с самым ранним завершённым входом. Владелец может всё и только он может передать владение: **Управление федерацией › Люди**, карточка человека, «Передать владение». У прежнего владельца остаётся роль администратора. Владелец не может удалить аккаунт, пока не передаст владение. Если владелец потерял доступ, владение передаётся офлайн-командой при остановленном сервере ([обслуживание](./operations.mdx#офлайн-команды)): ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ --federation-id= list dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ --federation-id= grant-owner --profile= dc start federation ``` ID федерации — `COMON_FEDERATION_ID` в `stack.env`. `list` показывает роли и ID профилей, `set-roles --profile= --roles=admin,moderator` заменяет роли профиля (встроенные: `admin`, `moderator`, `support`). В отличие от приложения, офлайн-команда может поднять кого угодно до любой роли. ## Публичные страницы [#публичные-страницы] Сервер без входа отвечает на трёх адресах: | Адрес | Что там | |---|---| | `/rules` | Правила федерации | | `/child-safety` | Стандарты защиты детей и контакт | | `/delete-account` | Как удалить аккаунт и что при этом сохраняется | Язык выбирается параметром `?lang=ru` или `?lang=en`, иначе по заголовку браузера. Страницы берут название и контакт поддержки из настроек, поэтому заполните оба до публикации своей сборки приложения в магазинах: магазины требуют такие страницы. Журнал действий модераторов и материалы закрытых жалоб хранятся год и удаляются при запуске сервера. # Как устроен сервер (/docs/selfhost/how-it-works) ## Путь запроса [#путь-запроса] ``` приложение ──HTTPS / WSS──▶ прокси (Caddy) ──┬─ /identity/* ──▶ Keycloak ├─ /app/* ──▶ веб-клиент ├─ /push/* ──▶ push relay └─ всё остальное ──▶ сервер федерации ──▶ PostgreSQL │ └────▶ каталог данных ├── SFU (управление по HTTP внутри Docker) устройства ──UDP──▶ TURN, SFU (порты звонков, мимо прокси) ``` Прокси снимает TLS и передаёт запросы серверу по обычному HTTP внутри Docker (параметр `--behind-tls-proxy`). Звонки идут мимо прокси: устройства подключаются к TURN и SFU напрямую по UDP ([звонки](./calls.mdx)). ## Соединение приложения [#соединение-приложения] Приложение открывает WebSocket `wss://<домен>/comon` и поверх TLS заводит сессию по протоколу Noise с ключом сервера. По этому соединению идут все запросы приложения и живые обновления. Перед первым подключением приложение читает документ федерации: ``` GET https://<домен>/.well-known/comon-federation ``` ```json { "version": 1, "federation_id": "comon-1a2b3c4d5e6f", "endpoint": "wss://chat.example.org/comon", "server_public_key": "<ключ Noise, base64url>", "identity_issuer": "https://chat.example.org/identity/realms/comon", "display_name": "Наша федерация" } ``` Приложение запоминает ключ сервера и больше не подключается, если он изменится. ## Пути HTTP сервера [#пути-http-сервера] | Путь | Что там | |---|---| | `/comon` | WebSocket приложений | | `/.well-known/comon-federation` | Документ федерации, отвечает любому сайту (CORS), чтобы веб-клиенты находили другие федерации | | `/auth/oidc/start`, `/auth/oidc/callback` | Вход через OIDC | | `/u/<имя>`, `/join/<код>`, `/call/<код>` | Страницы ссылок для браузера ([веб-версия и ссылки](./web.mdx#страницы-ссылок)) | | `/rules`, `/child-safety`, `/delete-account` | Публичные страницы федерации ([настройки федерации](./federation-settings.mdx#публичные-страницы)) | | `/.well-known/apple-app-site-association`, `/.well-known/assetlinks.json` | Открытие ссылок в приложениях, если заданы `--apple-app-id`, `--android-app` | | `/bot/v1/<метод>` | [HTTP Bot API](../bots/index.mdx) | | `/health` | Процесс жив; базу не трогает | | `/ready` | Готов обслуживать: есть связь с базой и схема совпадает ([обслуживание](./operations.mdx#проверка-состояния)) | ## Где лежат данные [#где-лежат-данные] | Где | Что | |---|---| | PostgreSQL 17, база `comon` | Всё, кроме байтов медиа: схемы `federation`, `access`, `bots`, `messaging` и по схеме `module_<имя>` на каждый модуль | | Каталог данных (`--data`, том `federation`) | Ключ Noise `noise-server-key` и медиа в `media/` (или в `--media-dir`) | | Том `postgres` | Файлы PostgreSQL. В готовом стеке там же база Keycloak | | Том `caddy` | Сертификаты Caddy | | Каталог состояния `.local/mvp` | Конфигурация, пароли, ключи, файлы Compose | База и медиа неразделимы: строки медиа в базе ссылаются на файлы тома, а файл `comon-media-volume.json` в каталоге медиа называет, к какому тому привязана база. Сервер, запущенный с базой на чужом или пустом томе, откажется стартовать с ошибкой `MediaVolumeMismatch`. Сервер сам не меняет схему базы. Схему применяет отдельная команда `migrate_database`, которую готовый стек запускает перед сервером ([обновление](./upgrading.mdx)). ## Один писатель [#один-писатель] Сервер берёт в базе блокировку писателя: второй сервер на той же базе не запустится, пока работает первый. Офлайн-команды (`federation_admin`, `reset_profile_password`, `install_system_stickers`) берут ту же блокировку, поэтому перед ними сервер нужно остановить ([обслуживание](./operations.mdx#офлайн-команды)). Чтобы распределить соединения по нескольким машинам, перед сервером ставят шлюзы, но писать в базу всё равно может только один процесс ([масштабирование](./scaling.mdx)). ## Личность федерации [#личность-федерации] Федерацию определяют её **ID** (`--federation-id`, в готовом стеке случайный `comon-…`) и **ключ Noise** из каталога данных, а не домен. Приложения запоминают ключ при первом подключении. - Потеряли ключ — устройства больше не подключатся. Сервер откажется стартовать без ключа, если в базе есть авторизованные устройства, чтобы не выпустить новый ключ молча. - Сохраните ID и ключ в резервной копии ([резервные копии](./backups.mdx)). - Домен можно сменить, сохранив ID и ключ ([переезд](./upgrading.mdx#переезд-на-другой-домен)). ## Модули [#модули] Части сервера с собственным хранилищем подключаются как модули: у каждого своя схема в базе и свои фоновые задачи. Параметр `--modules` ограничивает, какие модули обслуживает процесс. В текущей сборке модулей с собственным хранилищем нет; распознавание речи встроено в ядро. # Свой сервер (/docs/selfhost) Федерация — это сервер Comon вашей организации со своими людьми, чатами и правилами. Приложения Comon подключаются к любой федерации по её адресу, так что свой сервер не требует своей сборки приложения: люди скачивают обычный Comon и добавляют вашу федерацию. } title="Быстрый старт" href="/selfhost/quick-start"> От чистой Linux-машины с доменом до первого входа в приложение. } title="Справочник параметров" href="/selfhost/reference"> Каждый параметр сервера и шлюза: значение по умолчанию и что он меняет. } title="Звонки" href="/selfhost/calls"> TURN, медиасервер для групповых звонков, порты и NAT. } title="Push-уведомления" href="/selfhost/push"> Как уведомления доходят до телефонов и браузеров и что для этого нужно. } title="Настройки федерации" href="/selfhost/federation-settings"> Роли, правила, фильтры, жалобы, гости и лимиты прямо в приложении. } title="Резервные копии" href="/selfhost/backups"> Как сделать копию и восстановить федерацию на другой машине. ## Из чего состоит [#из-чего-состоит] | Сервис | Что делает | Обязателен | |---|---|---| | Сервер федерации | Аккаунты, чаты, сообщения, медиа, звонки (сигналинг), боты, страницы ссылок | да | | PostgreSQL 17 | Все данные федерации, кроме файлов медиа | да | | Сервис входа (OIDC) | Проверяет, кто входит. В готовом стеке — Keycloak, можно подключить свой | да | | HTTPS-прокси | TLS и маршрутизация. В готовом стеке — Caddy с сертификатом Let's Encrypt | да | | TURN (coturn) | Помогает личным звонкам пройти через NAT | для звонков | | SFU | Медиасервер групповых звонков и голосовых комнат | для групповых звонков | | Push relay | Передаёт зашифрованные уведомления в Apple, Google и браузеры | для уведомлений в фоне | | Веб-клиент | Comon в браузере по адресу `/app/` | нет | | Распознаватель речи | Расшифровка голосовых | нет | | Мост | Трансляции публичных каналов Telegram | нет | Подробнее о том, как они связаны, — на странице [Как устроен сервер](./how-it-works.mdx). ## Требования [#требования] - **Машина** с Linux, Docker Engine и Docker Compose v2, Python 3.11 или новее и git. Docker нужно хотя бы 4 ГБ памяти. Образы сервера собираются из исходников на этой же машине. - **Домен**, у которого A-запись указывает на машину. Адрес федерации и её сервиса входа — это её личность: менять домен после того, как люди вошли, — отдельная процедура ([переезд на другой домен](./upgrading.mdx#переезд-на-другой-домен)). - **Публичный IPv4** и открытые порты: | Порт | Протокол | Для чего | |---|---|---| | 443 | TCP | HTTPS и WebSocket приложений, выпуск сертификата (TLS-ALPN) | | 3478 | TCP и UDP | TURN | | 49160–49200 | UDP | Трафик звонков через TURN | | 7882 | UDP | Медиа групповых звонков (SFU) | | 5349 | TCP | TURN поверх TLS, если включить | - **Память, процессор и диск** по числу людей: посчитайте в [калькуляторе](./sizing.mdx). Каждому человеку по умолчанию доступно 50 ГиБ медиа, всему серверу — 1 ТиБ; оба значения меняются параметрами ([лимиты](./limits.mdx)). - Для распознавания речи на процессоре — ещё около 1,3 ГБ под модели и до четырёх потоков. Стек из репозитория рассчитан на частную установку организации. Открытую регистрацию для всех желающих он не настраивает: публичный запуск требует отдельной подготовки мониторинга, нагрузки и защиты от злоупотреблений. ## Два способа установки [#два-способа-установки] 1. **Скрипт `tools/mvp-stack.py`** собирает и запускает весь стек в Docker Compose: сервер, PostgreSQL, Keycloak, Caddy, TURN и SFU, а по командам `enable-*` — push, мост и распознавание речи. С него начинается [быстрый старт](./quick-start.mdx). 2. **Своя схема.** Если у вас уже есть обратный прокси, свой сервис входа или своя база, запускайте те же образы со своими параметрами. Все параметры собраны в [справочнике](./reference.mdx), пример такой схемы — `deploy/hosted/compose.yaml` в репозитории (Traefik и внешний OIDC). ## Карта раздела [#карта-раздела] **Настройка** - [Вход и учётные записи](./sign-in.mdx): Keycloak, свой OIDC, облачный пароль, номера телефонов. - [Звонки](./calls.mdx): TURN, SFU, порты, NAT, TURN поверх TLS. - [Push-уведомления](./push.mdx): relay, APNs, FCM, Web Push. - [Веб-версия и ссылки](./web.mdx): веб-клиент, страницы ссылок, открытие ссылок в приложениях. - [Распознавание речи](./transcription.mdx). - [Боты, мосты и стикеры](./bots-and-bridges.mdx). - [Версии приложений](./app-updates.mdx): обязательные и рекомендуемые обновления. - [Настройки федерации](./federation-settings.mdx): владелец, роли, правила, фильтры, лимиты. **Справочник** - [Сколько нужно ресурсов](./sizing.mdx): калькулятор по замерам. - [Параметры сервера](./reference.mdx). - [Лимиты](./limits.mdx). **Эксплуатация** - [Обслуживание](./operations.mdx): проверка состояния, журналы, офлайн-команды, отчёты об ошибках. - [Резервные копии и восстановление](./backups.mdx). - [Обновление сервера](./upgrading.mdx). - [Масштабирование](./scaling.mdx): шлюзы, NATS, общий том медиа, модули. - [Решение проблем](./troubleshooting.mdx). # Лимиты (/docs/selfhost/limits) Лимиты бывают трёх видов: - **Ёмкость сервера** — сколько держит одна федерация. Часть настраивается параметрами. - **Лимиты продукта** — что видит человек: длина сообщения, размер группы. Одинаковы во всех федерациях, проверяются и приложением, и сервером. - **Ограничения частоты** — сколько действий в секунду. Живут в памяти сервера, перезапуск их обнуляет. ## Сервер [#сервер] | Что | Сколько | Что будет на пределе | |---|---:|---| | Профилей, с ботами, без гостей звонков | 10 000 | Вход, который создал бы новый профиль, не пройдёт. | | Гостей звонков по ссылке одновременно | 1024 | Новый гость не войдёт. | | Сообщений, которые хранит один профиль (`--maximum-messages-per-profile`) | 50 000 | Отправка этого человека не пройдёт, остальные пишут дальше. Удаление сообщений «у всех» освобождает место. | | Контактов у профиля | 1000 | Новый контакт не добавится, совпадение из телефонной книги тоже. | | Подписчиков одного канала | 10 000 | Новых участников не добавить. | | Медиа одного профиля (`--media-quota-bytes`) | 50 ГиБ | Новые загрузки этого человека не пройдут. | | Медиа всего сервера (`--media-storage-bytes`) | 1 ТиБ | Не пройдут только новые загрузки. | | Один файл (`--media-file-bytes`, можно только уменьшить) | 1 ГиБ | Файл не отправится. | Общего предела на число чатов или сообщений федерации нет: сообщения занимают диск, а не память. Квота каждого профиля вместе с ограничением частоты определяет, как быстро и насколько один человек может заполнить диск. Сколько это в гигабайтах — в [калькуляторе](./sizing.mdx). ## Сообщения и чаты [#сообщения-и-чаты] | Что | Сколько | |---|---:| | Текст сообщения или подписи | 32 768 символов | | Медиа в одном сообщении (альбом) | 10 | | Редактирование своего сообщения | 48 часов | | Удаление или пересылка за раз | 100 сообщений | | Отложенных сообщений в чате | 100 на автора, в канале 100 на всех публикующих | | Участников группы, с владельцем | 256 | | Подписчиков канала | ёмкость сервера, 10 000 | | Каналов у одного человека | 500 | | Сообществ у одного человека | 100 | | Комнат в сообществе | 500 | | Ролей в сообществе | 100 | | Участников голосовой комнаты | до 99 по настройке комнаты | | Ботов у одного человека | 20 ([политика ботов](./bots-and-bridges.mdx)) | ## Медиа [#медиа] | Что | Сколько | |---|---:| | Фото | 64 МиБ, до 10 000 px по стороне | | Видео | 128 МиБ, до 10 минут | | Файл | 1 ГиБ | | Голосовое | 2 часа | | Кружок | 60 секунд, 16 МиБ | | Аватар | 8 МиБ, до 1024 px | | Одновременных загрузок у человека | 32 | ## Звонки [#звонки] | Что | Сколько | |---|---:| | Участников группового звонка | 32 | | Незавершённых звонков у человека | 8 | | Ссылок на звонки у человека | 50 | | Сообщений и файлов гостя в чате звонка | 500 сообщений, 100 МБ (файл до 25 МБ) | ## Модерация и настройки федерации [#модерация-и-настройки-федерации] | Что | Сколько | |---|---:| | Ролей федерации, со встроенными | 50 | | Слов и фраз в фильтре; доменов | 500; 500 | | Причин жалоб | 50, до трёх уровней | | Языков правил | 8 | | Новых личных чатов с не-контактами в день | 50 по умолчанию, роль может дать до 10 000 | | Добавлений в группы и каналы людей без вас в контактах, в день | 50 по умолчанию, роль может дать до 10 000 | | Журнал аудита и закрытые жалобы хранятся | 365 дней | | Распознавание речи на человека в день | 1 час по умолчанию, до 24 часов | Последние три настраиваются в приложении ([настройки федерации](./federation-settings.mdx)). ## Частота действий [#частота-действий] | Действие | Запас, затем | |---|---| | Отправка, правка, удаление, закрепление сообщений | 30, затем 5 в секунду | | Изменения профиля | 10, затем 1 в 6 секунд | | Реакции | 20, затем 2 в секунду | | Жалобы | 10, затем 1 в 20 секунд | | Загрузка превью ссылок | 20, затем 1 в 2 секунды | | Входы гостей звонков и страницы ссылок с одного адреса | 10 и 60 в минуту | Сверх лимита команда отклоняется до записи, и сервер сообщает, через сколько её можно повторить. Полная таблица всех лимитов, включая технические размеры кадров и хранилища приложения, есть в [исходниках](https://github.com/serezhia/chat_playground/blob/master/docs/contracts/limits.md). # Почтовый сервер (/docs/selfhost/mail) Федерация может выдавать людям адреса `имя@<почтовый домен>`. Для этого рядом с ней запускается встроенный почтовый сервер Stalwart, а федерация сама создаёт на нём ящики. Пароль от ящика человеку не нужен: Comon подключается к нему сам, а для других почтовых программ человек делает пароли приложений. Если почта вашего домена уже работает на своём сервере, ничего из этой страницы не нужно: укажите его IMAP и SMTP в **Администрирование → Модули → Почта → Свой почтовый сервер**. Подробная инструкция для оператора — в [runbook почтового сервера](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/mail-server.md). ## Порты [#порты] | Порт | Наружу | Что | |---|---|---| | 25 | да | SMTP: почта от других серверов | | 465 | да | отправка писем по TLS | | 993 | да | IMAP по TLS | | 8080 | нет | веб-администрирование и API управления | API управления никогда не публикуется: он доступен только федерации во внутренней сети стека. ## Запуск [#запуск] 1. Скопируйте `compose.mail.yaml` из `deploy/hosted` (или `deploy/mvp`) в каталог состояния и добавьте в `stack.env` строку `COMON_MAIL_HOST=mail.example.org`. 2. Запустите стек (`prepare-hosted-stack.py up` или `mvp-stack.py up`). Stalwart стартует в режиме первоначальной настройки и печатает временного администратора в лог. 3. Откройте `/admin` через SSH-туннель к порту 8080 (не через публичный адрес), завершите настройку и сохраните постоянного администратора в `secrets/`. 4. Создайте API-ключ для федерации с правами администратора и сохраните его в `secrets/mail/api-key` (права 0600). 5. Добавьте в `stack.env` `COMON_MAIL_SERVER` и `COMON_MAIL_SERVER_KEY_FILE` и снова выполните `up`. 6. В настройках почты федерации выберите встроенный сервер и почтовый домен. После этого люди, чья роль даёт право «Почтовый адрес федерации», могут занять адрес `<имя пользователя>@<домен>`. ## DNS и TLS [#dns-и-tls] - `MX` домена указывает на `COMON_MAIL_HOST`, у него есть `A`/`AAAA`. - SPF (`v=spf1 mx -all`), DKIM с селектором, который сгенерировал Stalwart, и `_dmarc` (начните с `p=none`). - Обратная запись (PTR) адреса сервера — `COMON_MAIL_HOST`. Без неё почту часто отклоняют. - Многие хостеры по умолчанию закрывают исходящий порт 25: попросите открыть его заранее. Порты 80 и 443 занимает обратный прокси стека, поэтому сертификат для `COMON_MAIL_HOST` получайте через ACME с DNS-01 в самом Stalwart или подкладывайте файлы сертификата. Федерация проверяет сертификат почтового сервера, так что он нужен до того, как люди займут адреса. ## Письма от федерации [#письма-от-федерации] Свои письма (например, приглашения гостям по почте) федерация отправляет с адреса `noreply@`. Со встроенным сервером это `noreply@<домен>`; можно указать и другой сервер флагами `--mail-noreply-*` ([справочник](./reference.mdx)). Включаются письма в настройках почты федерации, там же можно отправить тестовое письмо. ## Бэкапы и обновления [#бэкапы-и-обновления] Весь почтовый сервер — это том `mail`. `prepare-hosted-stack.py backup` архивирует его вместе с остальными данными ([бэкапы](./backups.mdx)). Письма, пришедшие, пока сервер был выключен, ждут на серверах отправителей и приходят позже. Версию Stalwart меняйте в обоих файлах `compose.mail.yaml` сразу, прочитав его заметки об обновлении и сделав бэкап. # Обслуживание (/docs/selfhost/operations) ## Команды Compose вручную [#команды-compose-вручную] `mvp-stack.py` вызывает Docker Compose с файлами из каталога состояния. Для ручных команд — функция оболочки (здесь включён PostgreSQL; добавьте `-f compose.push.yaml`, `compose.bridge.yaml` или `compose.transcriber.yaml`, если включали эти части): ```sh cd .local/mvp dc() { docker compose --project-name comon-mvp --project-directory . --env-file stack.env \ -f compose.yaml -f compose.sql.yaml "$@"; } dc ps # что запущено dc logs -f federation # журнал сервера dc restart federation # перезапуск одного сервиса ``` Сервисы: `gateway` (Caddy), `federation`, `migrate`, `postgres`, `identity` (Keycloak), `sfu`, `turn`, `web`, `push-relay`, `bridge`, `transcriber`. ## Проверка состояния [#проверка-состояния] ```sh python3 tools/mvp-stack.py check ``` Команда проверяет `/health`, `/ready`, документ федерации, Keycloak и, если включён push, `/push/healthz`. То же можно спросить у сервера напрямую: | Путь | Ответ | |---|---| | `/health` | 200, если процесс жив. Базу не трогает. | | `/ready` | 200 и `"status": "ready"`, если есть связь с базой и схема совпадает; иначе 503 и `"status": "unavailable"`. Причина — только в журнале сервера. | Ответ `/ready` годится для мониторинга: ```json { "status": "ready", "latency_ms": 1, "sql": { "connections": { "open": 3, "budget": 3 } }, "sync_projections": { "pending": 0, "oldest_age_ms": 0, "poisoned": 0 }, "jobs": { "<задача>": { "running": true, "failures": 0, "last_success_age_ms": 1200 } }, "outbound": "held" } ``` - `sql` — счётчики и длительности запросов этого процесса, без текстов и строк. - `sync_projections` — изменения, которые ещё не доставлены в ленты людей: сколько ждут, возраст самого старого и сколько остановилось (`poisoned`). Отставание не делает сервер неготовым: принятые сообщения уже записаны. - `jobs` — фоновые задачи. Упавшая задача повторяется и видна здесь, сервер продолжает работать. - `outbound: held` — сервер восстановлен из копии и ещё не отправляет отложенное ([восстановление](./backups.mdx#восстановление)). Стоит следить за кодом `/ready`, ростом `poisoned` и `failures` и за `oldest_age_ms`, который долго растёт. ## Журналы [#журналы] Сервер пишет в стандартный вывод: `dc logs federation`. Строки с `calls` описывают звонки ([звонки](./calls.mdx#проверка)), строки `restore_missing_media` — недостающие файлы после восстановления. Тексты сообщений и токены в журнал не попадают. ## Офлайн-команды [#офлайн-команды] `federation_admin`, `reset_profile_password` и `install_system_stickers` берут ту же блокировку писателя, что и сервер, поэтому сначала остановите его: ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo list dc start federation ``` `federation_admin` есть в образе сервера. `reset_profile_password` и `install_system_stickers` запускаются из исходников через `dart run` с доступом к базе ([сброс облачного пароля](./sign-in.mdx#сброс-забытого-пароля)). Все команды — в [параметрах сервера](./reference.mdx#federation_admin). ## Сбои [#сбои] | Что случилось | Что видно | Что делать | |---|---|---| | PostgreSQL перезапустился или упал | `/ready` отвечает 503 и не восстанавливается сам | Перезапустите сервер: `mvp-stack.py stop`, затем `up`. Записанные сообщения целы; отправка, шедшая в момент сбоя, повторится из приложения. | | Сервер перезапустился | Приложения на секунды теряют соединение | Ничего: они переподключаются сами. Перезапускайте сервер, когда звонков мало. | | SFU перезапустился | Групповые звонки на секунды замолкают | Ничего: участники переподключаются с разбросом до трёх секунд. | | Второй сервер на той же базе | Он не запускается | Так и задумано: писатель может быть только один. | | Сервер не стартует с `MediaVolumeMismatch` | База и том медиа от разных установок | Подключите том, сделанный вместе с базой ([как устроен сервер](./how-it-works.mdx#где-лежат-данные)). | Запросы к базе ограничены 30 секундами, ожидание блокировки — 10 секундами. Все части сервера делят до 3 соединений с PostgreSQL, одно из них держит право записи; `migrate_database` открывает своё. ## Остановившиеся обработки [#остановившиеся-обработки] Каждое изменение доходит до ленты участника через обработку, которая повторяется с паузами. После последней попытки она останавливается, и лента этого участника ждёт за ней, чтобы не нарушить порядок. В `/ready` растёт `sync_projections.poisoned`. 1. Найдите ошибку в журнале сервера и устраните причину (например, обновитесь на сборку с исправлением). 2. Остановите сервер. 3. Посмотрите и перезапустите обработку: ```sh dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo incidents dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ redrive --target=<профиль> --scope= --seq= ``` 4. Запустите сервер: лента продолжится по порядку, ничего не пропустив. ## Анимированные эмодзи [#анимированные-эмодзи] Сообщение из одного эмодзи анимируется, если на сервере есть системный набор `AnimatedEmoji`. Установить его можно из открытого набора Google Noto Animated Emoji (CC BY 4.0), при остановленном сервере, из `backend/comon_federation_server`: ```sh dart run bin/install_system_stickers.dart --data=<каталог данных> \ --postgres-conninfo-file=<файл> --source=<каталог> --fetch-noto ``` Повторный запуск добавляет только новые эмодзи. Той же командой ставятся и свои системные наборы стикеров (`--short-name`, `--title`, `--kind=stickers|emoji`). ## Отчёты об ошибках [#отчёты-об-ошибках] Сервер может отправлять отчёты об ошибках в свой Sentry: `--sentry-dsn`, `--sentry-environment` и `--sentry-traces-sample-rate` ([параметры](./reference.mdx#восстановление-и-отчёты)). Без DSN ничего не отправляется. # Push-уведомления (/docs/selfhost/push) Пока приложение открыто, сообщения приходят по его собственному соединению с федерацией, без настройки. Push нужен, чтобы уведомления приходили, когда приложение закрыто или свёрнуто. На Windows push не используется: там уведомления показывает само приложение, пока оно запущено или в трее. ## Как это устроено [#как-это-устроено] ``` сервер федерации ──подписанный запрос──▶ push relay ──▶ APNs (Apple) / FCM (Google) / Web Push │ │ └── текст зашифрован ключом устройства ─────────────────┴──▶ устройство расшифровывает ``` - **Push relay** (`backend/comon_push_relay`) — отдельный сервис, который хранит токены Apple и Google и подписки браузеров и передаёт им уведомления. - Федерация хранит только непрозрачные идентификаторы relay, а не токены устройств. - Текст уведомления шифруется ключом конкретного устройства (JWE, A256GCM). Relay, Apple и Google видят зашифрованный блок, время и размер. Снаружи уведомление выглядит как «New message». - Федерация может доверять нескольким relay сразу: каждая привязка устройства помнит, через какой relay она сделана. ## Какой relay нужен [#какой-relay-нужен] Адрес relay **вшит в сборку приложения**, а ключи Apple и Google принадлежат тому, кто выпускает приложение. Отсюда два случая. **Официальные приложения Comon** шлют push через relay проекта. Чтобы они получали уведомления от вашей федерации, оператор этого relay должен доверять ключу отправителя вашей федерации (`federation_sender_keys` и `admission_senders` в его настройках), а ваша федерация — знать этот relay в `federation-push.json`. Без этого приложения работают, но уведомления приходят только пока они открыты. **Свой relay** имеет смысл: - со своей сборкой приложения: свой bundle ID и ключ APNs, свой проект Firebase ([разработчикам](../develop/index.mdx)); - для своей веб-версии: Web Push не требует ключей Apple и Google, только свою пару ключей VAPID ([веб-версия](./web.mdx)). ## Включить в готовом стеке [#включить-в-готовом-стеке] Команда настраивает одного провайдера: APNs для iPhone и Mac или FCM для Android. Нужен `openssl` на машине. ```sh # APNs python3 tools/mvp-stack.py enable-push \ --apns-key /path/AuthKey_KEYID.p8 --apns-key-id KEYID --apple-team-id TEAMID \ --push-topic --push-environment production # или FCM python3 tools/mvp-stack.py enable-push \ --fcm-credentials /path/firebase-service-account.json --fcm-project \ --push-topic python3 tools/mvp-stack.py up ``` Второго провайдера и Web Push добавляют в `relay.json` вручную (поля ниже), сохраняя уже созданные ключи. Команда создаёт ключи relay и федерации, пишет `relay.json` и `federation-push.json`, добавляет маршрут `/push/*` в Caddy и сервис `push-relay`. Повторный `enable-push` откажется, чтобы не заменить ключи. Relay живёт в одном сетевом пространстве с сервером: сервер обращается к нему по `http://127.0.0.1:8090`, приложения — по `https://<домен>/push`. Ключ `.p8` монтируется только для чтения и в контексты сборки не копируется. `--push-environment sandbox` — для сборок из Xcode, `production` — для TestFlight и App Store. ### Допуск установок [#допуск-установок] Relay принимает только известные установки приложения. Есть два пути: - **Через федерацию** (обычный): приложение входит в федерацию, получает от неё подписанный билет и с ним регистрируется в relay. Для этого ID федерации должен быть в `admission_senders`. - **Вручную**: приложение кладёт публичные данные установки в `comon-push/admission.json`, оператор проверяет, что файл пришёл с нужного устройства, и допускает его: ```sh python3 tools/mvp-stack.py admit-installation --admission-file /path/admission.json python3 tools/mvp-stack.py up ``` При регистрации relay ещё и проверяет, что устройство владеет токеном: присылает одноразовый код через сам APNs, FCM или Web Push. ## Настройки relay (`relay.json`) [#настройки-relay-relayjson] Файл должен быть доступен только владельцу (0600), иначе relay не запустится. | Поле | Что значит | |---|---| | `host`, `port` | Где слушать. По умолчанию `127.0.0.1:8090`. Любой адрес, кроме локального, требует `behind_tls_proxy: true` и TLS-прокси перед relay. | | `database_path` | Абсолютный путь к базе SQLite relay. | | `audience` | Имя relay в подписях, билетах и квитанциях. По умолчанию `comon-push-relay`. | | `storage_key` | 32 случайных байта (base64url): шифрование токенов в базе. Потеря ключа — всем регистрироваться заново. | | `receipt_seed` | 32 случайных байта (base64url): ключ Ed25519, которым relay подписывает квитанции. | | `allowed_topics` | Темы APNs: `@sandbox` или `@production`. Для звонков на iPhone добавьте `.voip@…`. | | `apns` | `key_path` (абсолютный путь к `.p8`), `key_id`, `team_id`. | | `fcm` | `credentials_path` (сервисный аккаунт Firebase), `project_id`, `allowed_topics` вида `@production`. | | `webpush` | `origins`: для каждого адреса веб-клиента `vapid_private_key_file` и `subject` (`mailto:` или `https:`); `allowed_push_hosts`: закрытый список сервисов push браузеров. | | `federation_sender_keys` | ID федерации → её публичный ключ отправителя. | | `admission_senders` | Федерации, которым разрешено допускать новые установки. | | `installation_keys` | Вручную допущенные установки. | | `max_queue` | Очередь задач, по умолчанию 10 000; одной федерации доступна четверть. | Relay требует Node и `curl` с поддержкой HTTP/2 для APNs; образ из готового стека их содержит. Список `allowed_push_hosts` для Web Push обычно такой: ```json ["fcm.googleapis.com", "updates.push.services.mozilla.com", "web.push.apple.com", "*.notify.windows.com"] ``` Пару ключей VAPID создаёт `backend/comon_push_relay/bin/vapid_keygen.dart`. **Не меняйте ключ VAPID**: браузеры привязывают к нему каждую подписку, и с новым ключом все подписки перестанут работать, пока люди не подпишутся заново. ## Настройки федерации (`federation-push.json`) [#настройки-федерации-federation-pushjson] Сервер получает файл через `--push-config`: ```json { "sender_seed": "<32 байта, base64url>", "storage_key": "<32 байта, base64url>", "relays": [ { "origin": "http://127.0.0.1:8090", "audience": "comon-push-relay", "public_key": "<ключ квитанций relay, base64url>", "allow_loopback_http": true } ] } ``` - `sender_seed` — ключ, которым федерация подписывает запросы к relay. Публичную часть нужно вписать в `federation_sender_keys` каждого relay. - `relays` — relay, которым федерация доверяет. Добавляя новый, оставьте прежний первым: ему принадлежат привязки, сделанные до того, как привязки стали помнить свой relay. - Убрали relay из списка — его привязки перестают работать, приложения привяжутся заново. - Прежние поля верхнего уровня `relay_origin`, `relay_audience`, `relay_public_key` и `allow_loopback_http` сервер не принимает и не запускается: перенесите их в одну запись `relays`. ## Доставка [#доставка] - Уведомление живёт до пяти минут и повторяется до восьми раз. При ошибках Apple или Google повтор откладывается на 15 минут, так что старые уведомления не приходят пачкой. - Прочитанное на другом устройстве уведомление relay пытается убрать, но Apple и Google этого не гарантируют. - `GET /push/healthz` показывает, что процесс жив, но не что уведомления доходят. ## Резервная копия relay [#резервная-копия-relay] База relay входит в [резервную копию](./backups.mdx) стека; ключ `.p8` — нет, храните его отдельно. После восстановления push выключается сам: старые отзывы и ключи предпросмотра нужно сверить, и устройства регистрируются заново. Не включайте старую копию relay вслепую. # Быстрый старт (/docs/selfhost/quick-start) Готовый стек запускается одной командой: сервер федерации, PostgreSQL, Keycloak для входа, Caddy с сертификатом Let's Encrypt, TURN и медиасервер звонков. Всё работает в Docker Compose на одной машине. Перед началом проверьте [требования](./index.mdx#требования): домен, указывающий на машину, и открытые порты. ### Скачайте исходники [#скачайте-исходники] ```sh git clone https://github.com/serezhia/chat_playground.git comon cd comon git checkout v0.2.4 # последний релиз, см. «Изменения» ``` Образы сервера собираются из этих исходников при запуске. Отдельно ставить Dart или Flutter не нужно: сборка идёт внутри Docker. ### Подготовьте состояние [#подготовьте-состояние] ```sh python3 tools/mvp-stack.py prepare \ --host chat.example.org --port 443 --listen 0.0.0.0 --public-tls ``` - `--host` — домен федерации. Он становится адресом федерации и её сервиса входа, поэтому выберите его сразу: поменять потом — это [переезд](./upgrading.mdx#переезд-на-другой-домен). - `--public-tls` — получить сертификат Let's Encrypt. Нужны порт 443 и DNS-запись, указывающая на машину. Без этого флага Caddy выпускает сертификат своего центра, которому приложения из магазинов не доверяют. - `--listen 0.0.0.0` — слушать на всех интерфейсах (по умолчанию только локально). Команда создаёт каталог состояния `.local/mvp/`: конфигурацию, случайные пароли и ключи, файлы Compose. Каталог доступен только владельцу. **Не публикуйте его и не кладите в Git**, и не запускайте `prepare` повторно поверх существующего: команда откажется. ### Запустите [#запустите] ```sh python3 tools/mvp-stack.py up ``` `up` собирает образы, создаёт базу, применяет миграции, запускает все сервисы и проверяет, что федерация отвечает. Первая сборка занимает несколько минут. Потом проверить состояние можно так: ```sh python3 tools/mvp-stack.py check ``` `check` спрашивает `/health`, `/ready`, документ федерации `/.well-known/comon-federation` и сервис входа. ### Заведите людей в Keycloak [#заведите-людей-в-keycloak] Откройте `https://chat.example.org/identity/admin/` и войдите как `operator`. Пароль лежит в `.local/mvp/stack.env` в строке `KEYCLOAK_ADMIN_PASSWORD`; не пересылайте его и не вставляйте в журналы. 1. Выберите realm `comon`. 2. Создайте пользователей и задайте им начальные пароли (**Users › Add user**, затем **Credentials**). 3. Заведите постоянного администратора Keycloak и удалите временного `operator`, как советует документация Keycloak. Самостоятельная регистрация и сброс пароля в Keycloak выключены, пока вы их не настроите. ### Войдите из приложения [#войдите-из-приложения] Установите Comon ([приложения](../guide/apps.mdx)), выберите «Добавить федерацию» и введите `chat.example.org`. Приложение проверит адрес и откроет страницу входа Keycloak в системном браузере. - При первом входе приложение попросит придумать **облачный пароль** федерации: он нужен для входа с новых устройств ([подробнее](./sign-in.mdx#облачный-пароль)). - **Первый человек, закончивший регистрацию, становится владельцем федерации.** Владелец видит в настройках раздел «Управление федерацией». ## Что дальше [#что-дальше] - Задайте название федерации, контакт поддержки и правила: [Настройки федерации](./federation-settings.mdx). - Проверьте звонки снаружи вашей сети: [Звонки](./calls.mdx#проверка). - Включите отправку видео: [ниже](#отправка-видео). - Подключите уведомления в фоне: [Push-уведомления](./push.mdx). - Соберите веб-версию: [Веб-версия и ссылки](./web.mdx). - Включите расшифровку голосовых: [Распознавание речи](./transcription.mdx). - Настройте резервные копии: [Резервные копии](./backups.mdx). ## Отправка видео [#отправка-видео] Готовый стек собирает сервер без `ffmpeg`, поэтому видео можно смотреть, но не отправлять. Чтобы включить отправку, в `.local/mvp/compose.yaml` у сервиса `federation` замените сборку и добавьте параметр: ```yaml federation: build: context: ./server-context dockerfile: Dockerfile.video command: # … остальные параметры без изменений - --video-validator-config=/config/video-validator.json ``` Образ `Dockerfile.video` содержит `ffmpeg` в изолированной песочнице и готовый `/config/video-validator.json`. Если включены push-уведомления, ту же строку добавьте и в `compose.push.yaml`: он повторяет команду сервера целиком. Затем снова `up`. ## Как менять параметры [#как-менять-параметры] Параметры сервера лежат в `command` сервиса `federation` в `.local/mvp/compose.yaml` (и в `compose.push.yaml`, если он есть). Добавьте нужный параметр из [справочника](./reference.mdx) и выполните `up`. При обновлении `up` дописывает в эти файлы только то, что нужно новой версии; после обновления проверьте, что ваши параметры на месте. ## Команды скрипта [#команды-скрипта] | Команда | Что делает | |---|---| | `prepare` | Создаёт новое состояние. Отказывается, если каталог не пуст. | | `up` | Собирает и запускает стек, применяет миграции, обновляет файлы под текущую версию, проверяет. | | `check` | Проверяет `/health`, `/ready`, документ федерации и вход. | | `stop` | Останавливает стек, данные остаются. | | `config` | Проверяет файлы Compose. | | `preflight` | Проверяет базу перед обновлением ([обновление](./upgrading.mdx#проверка-данных-до-обновления)). | | `backup`, `restore` | [Резервная копия и восстановление](./backups.mdx). | | `export-client` | Пишет `client.json` с публичными настройками для своей сборки приложения. | | `enable-push`, `admit-installation` | [Push-уведомления](./push.mdx). | | `enable-turn-tls` | [TURN поверх TLS](./calls.mdx#turn-поверх-tls). | | `enable-transcriber` | [Распознавание речи](./transcription.mdx). | | `enable-bridge`, `bridge-login` | [Мосты](./bots-and-bridges.mdx#мосты-каналы-telegram). | Общие параметры: `--state <каталог>` (по умолчанию `.local/mvp`) и `--project <имя>` (проект Docker, по умолчанию `comon-mvp`). На одной машине работает один проект `comon-mvp`: не запускайте два состояния сразу. # Параметры сервера (/docs/selfhost/reference) Параметры пишутся как `--имя=значение`, флаги — `--имя`. Неизвестный параметр, флаг со значением или параметр без значения не дают серверу запуститься: опечатка никогда не запустит федерацию на значении по умолчанию. В готовом стеке команда сервера лежит в `compose.yaml` состояния (и повторяется в `compose.push.yaml`, если включён push). Меняйте её там и выполняйте `mvp-stack.py up` ([как менять параметры](./quick-start.mdx#как-менять-параметры)). ## Сервер [#сервер] `comon_federation_server` ### Сеть и адреса [#сеть-и-адреса] | Параметр | По умолчанию | Что значит | |---|---|---| | `--host` | `127.0.0.1` | Адрес, на котором слушать. | | `--port` | `8443` | Порт. | | `--public-origin` | `https://localhost:` | Адрес HTTPS, по которому сервер видят приложения. Под ним живут страницы ссылок и картинки уведомлений. | | `--certificate`, `--private-key` | тестовые сертификаты из исходников | Сертификат и ключ TLS. | | `--behind-tls-proxy` | выключен | Обычный HTTP за TLS-прокси. Сертификат не читается, адрес клиента берётся из `X-Forwarded-For`. | | `--development-lan` | выключен | Тестовый вход слушает не только loopback, а адреса сервера и входа могут быть `localhost`, частным IPv4-адресом или именем `.local`: так войти можно с телефона в той же сети. Тестовый вход пускает кого угодно, поэтому флаг только для локального стенда. С `--oidc-config` и `--behind-tls-proxy` не работает. | ### Личность и хранилище [#личность-и-хранилище] | Параметр | По умолчанию | Что значит | |---|---|---| | `--federation-id` | `local` | ID федерации ([личность федерации](./how-it-works.mdx#личность-федерации)). | | `--data` | `.local/comon-federation` | Каталог данных: ключ Noise и медиа. | | `--postgres-conninfo-file` | обязателен | Файл с одной строкой подключения libpq. Все хранилища федерации — схемы этой базы. | | `--media-dir` | `/media` | Где хранить байты медиа. С `s3` — только незаконченные загрузки этого процесса. | | `--media-volume` | `local` | `local`, `shared` или `s3`. Первый запуск привязывает базу к тому или бакету, запуск на другом не пройдёт ([масштабирование](./scaling.mdx)). | | `--media-bucket-endpoint` | обязателен с `s3` | S3-совместимое хранилище (например, MinIO), `http(s)://host[:port]`. | | `--media-bucket` | обязателен с `s3` | Бакет. Им пользуется только эта федерация. | | `--media-bucket-region` | `us-east-1` | Регион бакета. | | `--media-bucket-credentials-file` | обязателен с `s3` | JSON-файл `{"access_key_id": "...", "secret_access_key": "..."}`. | | `--modules` | все модули сборки | `<имя>,...`: модули с собственным хранилищем, которые обслуживает процесс. Остальные отвечают «не поддерживается». | ### Живые обновления и шлюзы [#живые-обновления-и-шлюзы] | Параметр | По умолчанию | Что значит | |---|---|---| | `--live` | `in-process` | `nats` рассылает живые обновления шлюзам федерации; нужен `--media-volume=shared` или `s3`. | | `--live-nats` | `127.0.0.1:4222` | Сервер NATS, `:`. Должен пропускать сообщения от 2,1 МБ. | | `--live-nats-token-file` | обязателен с `nats` | Файл с токеном NATS. | | `--writers` | `one` | `many` — процесс обслуживает федерацию вместе с другими, запущенными так же, на одной базе. Нужны `--live=nats` и копия ключа `noise-server-key` федерации в `--data`; первый запуск из бэкапа идёт с `one` ([масштабирование](./scaling.mdx)). | | `--live-reconcile-interval` | `30` | Секунды между сверками заголовков ленты активных профилей. | ### Вход [#вход] | Параметр | По умолчанию | Что значит | |---|---|---| | `--oidc-config` | тестовый вход | Провайдер OIDC ([вход](./sign-in.mdx#свой-oidc-провайдер)). | | `--external-accounts` | без провайдеров | Ключи шифрования подключённых аккаунтов, OAuth-клиенты Google и Яндекса и подключение почтовых и календарных серверов по паролю ([внешние аккаунты](./external-accounts.mdx)). | | `--identity-origin` | публичный адрес | Адрес тестового входа, только без `--oidc-config`. | | `--web-client` | нет | Адрес веб-клиента, которому можно вернуть результат входа. Можно повторять. HTTPS или HTTP на loopback. | | `--profile-password-policy` | `required` | `required` или `optional` ([облачный пароль](./sign-in.mdx#облачный-пароль)). | ### Звонки, push, медиа [#звонки-push-медиа] | Параметр | По умолчанию | Что значит | |---|---|---| | `--call-config` | звонки без TURN и SFU | STUN, TURN и SFU ([звонки](./calls.mdx)). | | `--push-config` | push выключен | Relay и ключи ([push](./push.mdx#настройки-федерации-federation-pushjson)). | | `--video-validator-config` | видео только принимается | Пути к `ffmpeg`, `ffprobe` и песочнице. Включает отправку видео и конвертацию видеостикеров ([отправка видео](./quick-start.mdx#отправка-видео)). | | `--mail-server`, `--mail-server-key-file`, `--mail-server-hostname` | нет | API управления встроенного почтового сервера, файл его ключа и его публичное имя (на которое выписан сертификат); все три или ни одного. Одно имя без остальных не учитывается. | | `--mail-noreply-address`, `--mail-noreply-smtp`, `--mail-noreply-password-file`, `--mail-noreply-username` | нет | Свой отправитель noreply@ для писем федерации: адрес, SMTP-сервер в виде `smtps://host:465` (TLS) или `smtp://host:587` (STARTTLS), файл пароля и имя для входа (по умолчанию адрес). Первые три задаются вместе. Без них встроенный почтовый сервер отправляет от `noreply@<домен>`. | | `--transcriber-url`, `--transcriber-model`, `--transcriber-key-file` | нет | Распознавание речи по умолчанию ([расшифровка](./transcription.mdx)). | ### Боты, мосты, стикеры [#боты-мосты-стикеры] | Параметр | По умолчанию | Что значит | |---|---|---| | `--bot-config` | все, до 20 ботов | Кто может создавать ботов и сколько ([боты и мосты](./bots-and-bridges.mdx)). | | `--bot-private-webhooks` | выключен | Разрешить вебхуки ботов на частные адреса. Только для разработки. | | `--no-demo-bot` | `@demo_bot` включён | Выключает встроенного демо-бота. | | `--bridge-config` | мосты выключены | Сети для зеркалирования, процесс моста, бюджет медиа и кто может зеркалировать. | | `--telegram-bot-token-file` | импорт выключен | Токен своего бота Telegram, через которого федерация импортирует наборы стикеров. | ### Люди и лимиты [#люди-и-лимиты] | Параметр | По умолчанию | Что значит | |---|---|---| | `--contacts-mode` | `directory` | `address-book`, `directory` или `hidden`, пока в настройках федерации режим не выбран ([настройки федерации](./federation-settings.mdx)). | | `--maximum-messages-per-profile` | `50000` | Сколько сообщений хранит каждый профиль. | | `--media-quota-bytes` | 50 ГиБ | Медиа одного профиля. | | `--media-storage-bytes` | 1 ТиБ | Медиа всего сервера. | | `--media-file-bytes` | 1 ГиБ | Один файл, не больше лимита протокола. | Остальные лимиты не настраиваются ([лимиты](./limits.mdx)). ### Приложения и ссылки [#приложения-и-ссылки] | Параметр | По умолчанию | Что значит | |---|---|---| | `--minimum-client-level` | `29` | Самый старый уровень приложения, который сервер обслуживает. Не ниже 29 ([версии приложений](./app-updates.mdx)). | | `--recommended-client-level` | минимальный | До какого уровня приложение предлагает обновиться. Не ниже минимального. | | `--client-update-url` | нет | `<платформа>=`, по разу на `android`, `ios`, `macos`, `windows`, `linux`, `web`. | | `--link-scheme` | `comon` | Схема, которой страницы ссылок открывают приложение ([страницы ссылок](./web.mdx#страницы-ссылок)). | | `--apple-app-id` | нет | `.`, можно повторять или перечислить через запятую: приложение iOS или macOS, которое открывает ссылки федерации само. | | `--android-app` | нет | `:`, можно повторять или перечислить через запятую: то же для Android. | ### Восстановление и отчёты [#восстановление-и-отчёты] | Параметр | По умолчанию | Что значит | |---|---|---| | `--restored-backup` | нет | `<имя>`: хранилища восстановлены из этой копии ([восстановление](./backups.mdx#восстановление)). | | `--accept-missing-media` | выключен | Запуститься после восстановления, даже если не хватает файлов медиа. | | `--sentry-dsn` | нет | Куда сервер отправляет отчёты об ошибках. Без него ничего не отправляется ([обслуживание](./operations.mdx#отчёты-об-ошибках)). | | `--sentry-environment` | `prod` | Окружение в отчётах. | | `--sentry-traces-sample-rate` | `0.1` | Доля трассируемых запросов, от 0 до 1. | ## Шлюз [#шлюз] `comon_federation_gateway` принимает соединения приложений и передаёт их основному серверу ([масштабирование](./scaling.mdx)). | Параметр | По умолчанию | Что значит | |---|---|---| | `--federation-id` | обязателен | ID федерации основного сервера. | | `--noise-key-file` | обязателен | Копия `noise-server-key` основного сервера. | | `--host`, `--port` | `127.0.0.1`, `8443` | Адрес и порт. | | `--certificate`, `--private-key` | обязательны без `--behind-tls-proxy` | Сертификат и ключ TLS. | | `--behind-tls-proxy` | выключен | Обычный HTTP за TLS-прокси. | | `--live` | `nats` | Другого варианта нет. | | `--live-nats`, `--live-nats-token-file`, `--live-reconcile-interval` | как у сервера | Шина до основного сервера. | | `--media-volume` | нет | `shared` или `s3`: шлюз сам читает скачиваемые медиа основного сервера, получив от сервера разрешение на каждый кусок. Без опции все скачивания читает основной сервер. | | `--media-dir` | обязателен с `shared` | Общий том медиа основного сервера, подключённый только для чтения. | | `--media-bucket-endpoint`, `--media-bucket`, `--media-bucket-region`, `--media-bucket-credentials-file` | как у сервера, обязательны с `s3` | Бакет основного сервера. | ## migrate_database [#migrate_database] Создаёт и обновляет схему базы. Сервер сам схему не меняет и не запустится на базе старее или новее себя. Готовый стек запускает команду перед сервером при каждом `up`. ```sh migrate_database --postgres-conninfo-file=<файл> # применить недостающие миграции migrate_database --postgres-conninfo-file=<файл> --check # только проверить, код 1 при расхождении migrate_database --postgres-conninfo-file=<файл> --preflight # проверить данные перед обновлением ``` Миграции применяются одной транзакцией под блокировкой, так что два одновременных запуска не применят шаг дважды. ## federation_admin [#federation_admin] Офлайн-администрирование. Сервер должен быть остановлен ([офлайн-команды](./operations.mdx#офлайн-команды)). | Команда | Что делает | |---|---| | `list` | Кто какую роль занимает. | | `grant-owner --profile=` | Сделать профиль владельцем. | | `set-roles --profile= --roles=,...` | Назначить роли. | | `incidents` | Остановившиеся фоновые обработки. | | `redrive --target=<профиль> --scope= --seq=` | Перезапустить одну из них. | | `restores` | Список восстановлений из копий. | | `release-outbound` | После восстановления снова отправлять отложенные сообщения и вебхуки ботов. | | `check-stickers` | Прогнать сохранённые стикеры Lottie через нынешние проверки и вывести те, что они не пропускают. Ничего не меняет. | Общие параметры: `--data=<каталог данных>`, `--postgres-conninfo-file=<файл>`, `--federation-id=`. # Масштабирование (/docs/selfhost/scaling) По умолчанию федерация пишет в базу одним процессом, и масштабирование — это разгрузка этого писателя. Основные серверы с `--writers=many` пишут в одну базу вместе, каждый ведёт присутствие своих подключений; каждый звонок ведёт сервер, на котором его начали, а участвовать в нём можно с любого. Каждую фоновую задачу обслуживает один из них за раз. Шлюз держит каждое подключение на одном основном сервере. Режим пока экспериментальный, на проде его не включайте, пока он не прошёл нагрузку на нескольких серверах; звонок завершается, если его сервер остановился. Сколько нужно ресурсов на ваше число людей, считает [калькулятор](./sizing.mdx). ## Профили [#профили] | Профиль | Что запущено | Для кого | |---|---|---| | **S** | Сервер, PostgreSQL и медиа на одной машине (готовый стек) | Большинство установок | | **M** | Основной сервер, шлюзы, NATS, общий том медиа | Много одновременных соединений. Пока лабораторный профиль: репетиция в `tools/mlab-stack.py`, готового стека нет | Профиль S не переживает потерю своей единственной машины дальше последней [резервной копии](./backups.mdx). Профиль M тоже не обещает высокой доступности: писатель один. ## Что вынести в первую очередь [#что-вынести-в-первую-очередь] - **Медиа** — на отдельный диск: `--media-dir`. Это самый быстрорастущий объём. - **PostgreSQL** — на отдельную машину или управляемый сервис PostgreSQL 17: сервер получает строку подключения из `--postgres-conninfo-file`. Держите задержку до базы минимальной: каждое сообщение — транзакция. - **SFU и TURN** — на машину с хорошим каналом. Через них идёт весь трафик звонков, а серверу федерации от них нужен только адрес управляющего API (`sfu_url`) и секреты. TURN должен оставаться в одном сетевом пространстве с SFU ([звонки](./calls.mdx#turn-coturn)). - **Распознавание речи** — на машину с GPU ([расшифровка](./transcription.mdx)). ## Шлюзы [#шлюзы] Шлюз (`comon_federation_gateway`) принимает WebSocket приложений, держит шифрование Noise и очереди отправки и передаёт запросы основному серверу через NATS. Живые обновления шлюз получает из той же шины. Базы шлюз не открывает, блокировок не держит; звонки, присутствие и фоновые задачи остаются на основном сервере. ``` приложения ──WSS /comon──▶ прокси ──┬──▶ шлюз 1 ──┐ └──▶ шлюз 2 ──┼── NATS ──▶ основной сервер ──▶ PostgreSQL всё остальное (вход, ссылки, Bot API) ────────────┼──────────▶ основной сервер └── общий том медиа ``` Что нужно: 1. Основной сервер с `--live=nats --live-nats=: --live-nats-token-file=<файл> --media-volume=shared` или `--media-volume=s3`. С локальным каталогом медиа `nats` не запустится. 2. NATS, пропускающий сообщения от 2,1 МБ (`max_payload`), с токеном. 3. Шлюзы с `--federation-id`, `--noise-key-file` (копия `noise-server-key` основного сервера, только для чтения), теми же параметрами NATS и `--behind-tls-proxy`. 4. Прокси отправляет на шлюзы **только** `/comon`, всё остальное — на основной сервер. Все параметры шлюза — в [справочнике](./reference.mdx#шлюз). ### Что происходит при сбоях [#что-происходит-при-сбоях] | Событие | Что будет | |---|---| | Упал один шлюз | Его приложения переподключаются через другой. | | Остановился NATS | Шлюзы становятся неготовыми; после возвращения шины сверяют сессии с основным сервером и догоняют пропущенное. | | Остановился основной сервер | Шлюзы отклоняют запросы, пока он не вернётся. Записывать больше некому. | | Остановился один из нескольких основных серверов (`--writers=many`) | Шлюзы закрывают его подключения, приложения переподключаются к другому. Его звонки завершаются. | | Запустили второй основной сервер на той же базе | Если не у обоих `--writers=many`, он не стартует, первый продолжает работать. | ## Медиа в S3 (MinIO) [#медиа-в-s3-minio] С `--media-volume=s3` готовые медиа лежат в S3-совместимом бакете (MinIO на своих машинах или облачный S3), а не на общем диске. Каждый основной сервер принимает загрузки в свой `--media-dir`, проверяет их там и кладёт готовые файлы в бакет; скачивание всегда читает из бакета. Бакет принадлежит одной федерации: первый запуск пишет в него метку (`comon-media-volume.json`), запуск на другом бакете не пройдёт. ``` --media-volume=s3 --media-bucket-endpoint=http://minio:9000 --media-bucket=comon-media \ --media-bucket-credentials-file=/run/secrets/s3.json ``` Файл ключей — `{"access_key_id": "...", "secret_access_key": "..."}`. Ключу нужно читать, писать, удалять и перечислять объекты этого бакета. Существующая федерация переносит медиа с диска в бакет остановленной: 1. Остановите все процессы сервера федерации. 2. Запустите `federation_admin --data=... --postgres-conninfo-file=... --media-dir=<диск медиа> --media-volume=s3 --media-bucket...=... media-to-s3`. Он копирует то, чего в бакете нет, так что прерванный запуск просто повторяют. 3. Запустите серверы с параметрами S3. Старый диск держите, пока не убедитесь, что картинки, файлы и голосовые открываются. Резервную копию бакета делайте вместе с базой ([резервные копии](./backups.mdx)). ## Где предел [#где-предел] Ограничения одной федерации — в [лимитах](./limits.mdx#сервер): до 10 000 профилей, до 1 ТиБ медиа. Если нужно больше людей, поднимают несколько независимых федераций. Общаться между собой федерации не могут, а человек может состоять в нескольких сразу ([федерации](../guide/federations.mdx)). # Вход и учётные записи (/docs/selfhost/sign-in) Comon не хранит пароли людей. Кто входит, проверяет сервис входа организации по протоколу OpenID Connect (OIDC), а федерация доверяет его подписанному ответу. Пароль от сервиса входа Comon не видит: приложение открывает страницу входа в системном браузере. Человек в федерации определяется парой «издатель (`issuer`) и `sub`» из ответа провайдера. Почта и имя пользователя ключом не служат, их можно менять в провайдере без последствий. ## Keycloak из готового стека [#keycloak-из-готового-стека] `mvp-stack.py prepare` создаёт в Keycloak realm `comon` с клиентом `comon-federation`: - вход по коду авторизации с PKCE S256, неявный поток и вход по паролю через API выключены; - адрес возврата один: `https://<домен>/auth/oidc/callback`; - самостоятельная регистрация и сброс пароля **выключены**; - защита от подбора пароля включена. Консоль администратора: `https://<домен>/identity/admin/`, первый вход — `operator` с паролем из `stack.env` (`KEYCLOAK_ADMIN_PASSWORD`). Людей заводите в realm `comon`. Чтобы люди регистрировались сами, включите регистрацию в настройках входа realm и настройте отправку почты в Keycloak. ## Свой OIDC-провайдер [#свой-oidc-провайдер] Подойдёт любой провайдер с кодом авторизации и PKCE: Keycloak, Authentik, Zitadel, корпоративный сервис входа. Зарегистрируйте в нём клиента с адресом возврата `https://<домен>/auth/oidc/callback` и опишите его в JSON-файле, который сервер получает через `--oidc-config`: ```json { "issuer": "https://id.example.org", "client_id": "comon", "authorization_endpoint": "https://id.example.org/oauth2/authorize", "token_endpoint": "https://id.example.org/oauth2/token", "jwks_uri": "https://id.example.org/oauth2/jwks", "token_endpoint_auth_method": "client_secret_basic", "client_secret_file": "secrets/oidc-client-secret", "scopes": ["openid", "profile"] } ``` | Поле | Обязательно | Что значит | |---|---|---| | `issuer` | да | Издатель, точно как в токене. Только HTTPS. | | `client_id` | да | ID клиента у провайдера. | | `authorization_endpoint` | да | Страница входа. Только HTTPS. | | `token_endpoint` | да | Обмен кода на токены. | | `jwks_uri` | да | Ключи подписи провайдера. Подпись токена проверяется (RS256). | | `userinfo_endpoint` | нет | Откуда дочитать подтверждённый номер телефона и имя, если их нет в токене. | | `token_endpoint_auth_method` | нет | `none` (по умолчанию, публичный клиент), `client_secret_basic` или `client_secret_post`. | | `client_secret_file` | для `client_secret_*` | Файл с секретом клиента, путь относительно файла настроек. Перевод строки в конце допустим. Секрет не пишите ни в сам JSON, ни в параметры запуска. | | `scopes` | нет | По умолчанию `["openid", "profile"]`. Должен быть `openid`. Добавьте `phone`, чтобы получать подтверждённые номера. | | `nonce_mode` | нет | `required` (по умолчанию): провайдер должен вернуть `nonce`. `pkce_only` — для провайдеров без `nonce`, только с конфиденциальным клиентом. | | `allow_private_http` | нет | Разрешить `http://` для `token_endpoint`, `jwks_uri` и `userinfo_endpoint`, когда провайдер в той же внутренней сети. | Сервер проверяет подпись, издателя, получателя, сроки токена и `nonce`. Если что-то не сходится, вход отклоняется; режим `pkce_only` никогда не включается сам после неудачной проверки. Из токена сервер берёт `sub`, имя из `given_name` (как подсказку при регистрации) и, если запрошен `phone`, подтверждённый номер (`phone_number` при `phone_number_verified: true`). Издатель — часть личности каждого человека. Смена `issuer` у работающей федерации — это миграция: остановите сервер, сделайте [резервную копию](./backups.mdx) и перенесите соответствия в одной транзакции, иначе люди получат новые пустые профили. ## Без OIDC [#без-oidc] Без `--oidc-config` сервер запускает встроенный тестовый вход для разработки, где можно войти кем угодно. Он работает только локально; за TLS-прокси (`--behind-tls-proxy`) сервер требует настоящий OIDC. ## Веб-клиенты [#веб-клиенты] Чтобы вход работал в веб-версии, сервер должен знать её адрес: `--web-client=https://<домен>/app` (параметр можно повторять). Результат входа вернётся на `<адрес>/auth/callback/`; адрес возврата у провайдера остаётся прежним, `/auth/oidc/callback`. ## Облачный пароль [#облачный-пароль] Облачный пароль — второй шаг входа с нового устройства. Политику задаёт `--profile-password-policy`: | Значение | Что происходит | |---|---| | `required` (по умолчанию) | При первом входе человек придумывает пароль. Новые устройства без него не войдут. Убрать пароль нельзя. | | `optional` | Новые профили входят без пароля. Кто задал пароль сам, будет вводить его на новых устройствах, пока не выключит его в **Настройки › Конфиденциальность › Облачный пароль**. | Смена политики не удаляет уже заданные пароли. Как пароль хранится и сколько попыток даётся, описано в разделе [Безопасность](../features/security.mdx#облачный-пароль). ### Сброс забытого пароля [#сброс-забытого-пароля] Остановите сервер и выполните из `backend/comon_federation_server` (нужен Dart SDK; в образ сервера эта команда не входит, и ей нужен доступ к PostgreSQL федерации): ```sh dart run bin/reset_profile_password.dart --data=<каталог данных> --profile= \ --postgres-conninfo-file=<файл> ``` Команда спросит новый пароль дважды (или прочтёт его из стандартного ввода с `--password-stdin`) и **отключит все устройства** этого профиля. Пароль в аргументах не передаётся. ## Номера телефонов [#номера-телефонов] По умолчанию номеров нет. Владелец включает их в приложении: **Управление федерацией › Правила и политики › Контакты и номера телефонов › Номера телефонов**. | Режим | Что значит | |---|---| | Выключены | Номеров и поиска по телефонной книге нет. | | Необязательные | Номер приходит от провайдера входа, если тот передаёт подтверждённый, или его вписывает администратор в карточке человека. | | Обязательные | Без подтверждённого номера от провайдера войти нельзя. Уже вошедшие устройства остаются. Режим доступен, только если в `scopes` есть `phone`. | ## Владелец федерации [#владелец-федерации] Владельцем становится первый человек, закончивший регистрацию. Если владельца нет (например, у старой федерации), при запуске им становится профиль с самым ранним завершённым входом. Сменить владельца можно в приложении или офлайн-командой ([настройки федерации](./federation-settings.mdx#владелец)). ## Лимиты [#лимиты] | Что | Сколько | |---|---| | Профилей на сервере, с ботами, без гостей звонков | 10 000 | | Облачный пароль | от 10 до 128 символов | # Сколько нужно ресурсов (/docs/selfhost/sizing) Калькулятор считает по замерам, приведённым ниже. Подставьте своё число людей и то, как активно они пишут. Цифры приблизительные: реальная нагрузка зависит от того, как люди пользуются Comon, поэтому после запуска смотрите на [показатели сервера](./operations.mdx). ## Как считается [#как-считается] - **Сервер федерации**: 120 МБ плюс 0,92 МБ на каждого человека онлайн; 0,0052 ядра на человека онлайн, который делает действие раз в 20 секунд. Поле «Действий в минуту» пересчитывает это под вашу активность: в тесте было 3 действия в минуту, живые люди обычно делают меньше. - **PostgreSQL**: около 430 МБ с настройками по умолчанию (`shared_buffers` 128 МБ). Если дать базе больше памяти, она будет быстрее, но обязательной её делает только этот минимум. - **База данных**: около 3 КБ на сообщение вместе с поисковым индексом, плюс до 0,6 МБ на человека: лента синхронизации каждого человека хранит его последние 1000 событий, по 0,6 КБ. Пустая база занимает 14 МБ. В коротком тесте лента ещё не дошла до предела, поэтому размер базы в таблице ниже, делённый на число сообщений, гораздо больше 3 КБ. - **Медиа**: ровно столько, сколько люди загрузят. Каждому человеку по умолчанию можно хранить до 50 ГиБ ([лимиты](./limits.mdx)). - **Звонки**: верхняя граница по настройкам кодеков, а не замер. Камера отправляет на SFU три слоя (150 + 500 + 1500 кбит/с), получатель большой плитки берёт верхний (1500 кбит/с), маленькой — нижние, голос — 40 кбит/с. Звонки один на один идут напрямую или через TURN и SFU не нагружают. - **Машина**: вдвое больше памяти и процессора, чем нужно серверу, базе и SFU, плюс 1 ГБ памяти и 10 ГБ диска на систему; не меньше 2 ядер, 2 ГБ памяти и 20 ГБ диска. Keycloak, Caddy, веб-клиент и мосты не входят: добавьте их память отдельно (Keycloak — по [его документации](https://www.keycloak.org/high-availability/concepts-memory-and-cpu-sizing)). ## Замеры [#замеры] Нагрузочный тест `comon_load`: настоящие клиенты CDLib с той же машины входят, вступают в группы, каналы и сообщество, пишут текст, отправляют фото, файлы, голосовые, кружки и стикеры, звонят, читают и уходят офлайн. Каждый онлайн-человек делает действие раз в 20 секунд, сессия длится 3 минуты, перерыв 2 минуты. Устойчивая фаза — 5 минут. Машина: 4 vCPU Intel Xeon 2,1 ГГц, 16 ГБ памяти, PostgreSQL 16 с настройками по умолчанию, сервер 0.2.4 и SFU собраны в нативный код. | | 100 человек | 200 человек | 400 человек | |---|---:|---:|---:| | Онлайн в среднем / максимум | 65 / 78 | 126 / 138 | 219 / 267 | | Память сервера, в среднем / максимум | 143 / 181 МБ | 196 / 237 МБ | 344 / 461 МБ | | Процессор сервера, в среднем / пик за 5 с | 0,29 / 0,94 ядра | 0,65 / 1,32 ядра | 1,15 / 1,66 ядра | | Память SFU | 19 МБ | 19 МБ | 19 МБ | | Сообщений всего | 1 381 | 2 767 | 5 073 | | Размер базы | 49 МБ | 90 МБ | 254 МБ | | Медиа на диске | 74 МБ | 185 МБ | 265 МБ | | Доставка сообщения, медиана / 99 % | 0,4 / 1,4 с | 0,4 / 1,3 с | 1,8 / 31,5 с | Клиенты теста работали на той же машине и заняли почти все 4 ядра (средняя загрузка 10). Поэтому задержки выросли, а часть запросов не дождалась ответа. Процессор сервера при этом остался на линии 0,0052 ядра на человека онлайн, а память выросла сильнее из-за очередей. Калькулятор построен по замерам на 100 и 200 человек. Как повторить тест на своей машине, написано в [инструкции](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/load-test.md). # Расшифровка голосовых (/docs/selfhost/transcription) Люди могут превратить голосовое сообщение или кружок в текст кнопкой «Расшифровать» ([как это выглядит](../features/voice.mdx)). Распознаёт речь отдельный сервис-распознаватель, совместимый с API OpenAI `/audio/transcriptions`. Федерация читает запись и отправляет её распознавателю целиком. ## Какой распознаватель выбрать [#какой-распознаватель-выбрать] | Вариант | Модели | Что нужно | |---|---|---| | CPU (по умолчанию) | `auto`: GigaAM-v3 для русского, Whisper large-v3-turbo для остальных языков | Около 1,3 ГБ моделей на томе, до 4 потоков процессора | | GPU NVIDIA | Qwen3-ASR 1.7B на vLLM | Видеокарта, NVIDIA Container Toolkit и образ vLLM с этой моделью | | Внешний сервис | Любой с API OpenAI: облачный или свой vLLM | Адрес и ключ. Приложение покажет людям, что звук уходит за пределы федерации | Все модели готового стека открытые и работают без интернета после загрузки. Если в федерации говорят только по-русски, достаточно `gigaam-v3`: задайте `COMON_TRANSCRIBER_MODELS=gigaam-v3`, и загрузится меньше. ## Включить в готовом стеке [#включить-в-готовом-стеке] ```sh python3 tools/mvp-stack.py enable-transcriber # CPU python3 tools/mvp-stack.py enable-transcriber --transcriber-gpu # GPU python3 tools/mvp-stack.py up ``` Для GPU после `enable-transcriber` впишите образ vLLM в `COMON_VLLM_IMAGE` в `stack.env`. Команда добавляет сервис `transcriber` и передаёт серверу `--transcriber-url=http://transcriber:8000/v1` и `--transcriber-model`. Первая расшифровка скачивает модели в том `transcriber-models`, поэтому она медленная один раз. Повторный запуск команды откажется: дальше всё меняется в приложении. ## Настройки в приложении [#настройки-в-приложении] Администратор с правом управлять федерацией открывает **Управление федерацией › Правила и политики › Расшифровка**: 1. Включает «Распознавать речь» и вписывает «Адрес распознавателя» (и «API-ключ» для внешнего сервиса). Для встроенного: `http://transcriber:8000/v1`. 2. Нажимает «Проверить распознаватель»: приложение покажет модели сервиса, одну из них можно выбрать. 3. Задаёт «Максимальная длина записи, минут» (по умолчанию 30, не больше 120) и сохраняет. Параметры сервера `--transcriber-url`, `--transcriber-model` и `--transcriber-key-file` — только начальные значения. После первого сохранения в приложении действуют настройки приложения. ### Время на человека [#время-на-человека] Сколько минут в день человек может расшифровать, задают роли: строка «Распознавание речи, минут в день» у роли и такая же строка в настройках федерации для всех (по умолчанию 60). У человека, чьи роли дают 0, кнопок расшифровки нет. ## Внешний распознаватель [#внешний-распознаватель] Если адрес распознавателя — не имя сервиса Compose, не `localhost` и не частный адрес, под каждой расшифровкой приложение пишет «Распознано через `<сервис>`»: люди должны знать, что их голос уходит наружу. Для встроенного распознавателя используйте имя сервиса внутри сети. ## Неполадки [#неполадки] | Что видно | Причина | |---|---| | Кнопок расшифровки нет | Расшифровка выключена, или роли человека дают 0 минут. | | «Распознавание недоступно. Попробуйте позже.» | Сервер пишет в журнал `transcription_failed` с ошибкой распознавателя. Нажмите «Проверить распознаватель»; `dc logs transcriber` покажет загрузку моделей и ошибки декодирования. | | Первая расшифровка долгая | Модели ещё загружаются. | | «Распознано через …» под расшифровкой | Адрес распознавателя внешний (см. выше). | # Неполадки (/docs/selfhost/troubleshooting) Начинайте с `python3 tools/mvp-stack.py check` и журнала сервера (`dc logs federation`, функция `dc` — в [обслуживании](./operations.mdx#команды-compose-вручную)). ## Запуск [#запуск] | Что видно | Причина и что делать | |---|---| | Сервер не запускается, в журнале `MediaVolumeMismatch` | База запущена на чужом или пустом томе медиа. Подключите том, сделанный вместе с базой. | | Сервер не запускается без `noise-server-key` | В базе есть вошедшие устройства, а ключа Noise нет. Новый ключ отрезал бы их, поэтому сервер не создаёт его сам. Восстановите ключ из [резервной копии](./backups.mdx). | | Сервер отказывается стартовать из-за схемы | База старее или новее сервера. Обычно `up` применяет миграции сам; если запускаете сервер вручную, сначала выполните `migrate_database`. | | Сервер не стартует за прокси | С `--behind-tls-proxy` нужен настоящий OIDC (`--oidc-config`): тестовый вход за прокси запрещён. | | Неизвестный параметр, и сервер не стартует | Опечатка или параметр от другой версии. Сверьтесь со [справочником](./reference.mdx). | | Второй сервер на той же базе не стартует | Так и задумано: писатель один. | | Caddy не выпускает сертификат | Домен должен указывать на машину, а порты 80 и 443 — быть открыты снаружи. | ## Работа [#работа] | Что видно | Причина и что делать | |---|---| | `/ready` отвечает 503 после перезапуска PostgreSQL | Сервер не переподключается к базе сам. Перезапустите его: `mvp-stack.py stop`, затем `up`. | | Сообщения доходят с задержкой, в `/ready` растёт `sync_projections.poisoned` | Остановилась обработка ленты. См. [остановившиеся обработки](./operations.mdx#остановившиеся-обработки). | | Отложенные сообщения и вебхуки ботов не уходят после восстановления | Исходящее придержано до `release-outbound` ([восстановление](./backups.mdx#первый-запуск-из-копии)). | | Новые люди не могут войти, а в журнале предел профилей | В федерации 10 000 профилей ([лимиты](./limits.mdx#сервер)). | ## Вход [#вход] | Что видно | Причина и что делать | |---|---| | Провайдер входа ругается на адрес возврата | У клиента провайдера должен быть зарегистрирован `https://<домен>/auth/oidc/callback`. | | Вход отклоняется после страницы провайдера | Не сходятся `issuer`, `client_id`, подпись или `nonce`. Подробная причина — в журнале сервера. Провайдерам без `nonce` нужен `nonce_mode: pkce_only` и конфиденциальный клиент ([вход](./sign-in.mdx#свой-oidc-провайдер)). | | Вход в веб-версии не возвращается в приложение | Серверу не передан `--web-client` с адресом веб-клиента. | | Обязательные номера телефонов нельзя включить | Провайдер не передаёт подтверждённые номера: добавьте `phone` в `scopes`. | | Человек забыл облачный пароль | [Сброс пароля](./sign-in.mdx#сброс-забытого-пароля). | ## Звонки [#звонки] | Что видно | Причина и что делать | |---|---| | Личный звонок соединяется только в одной сети | Закрыты порты TURN (3478 TCP/UDP, 49160–49200 UDP), или `external-ip` в `turnserver.conf` — не публичный адрес. | | Групповой звонок не начинается | Нет SFU: в `calls.json` нет `sfu_url`, или сервис `sfu` не запущен. | | Групповой звонок идёт без звука и видео | Закрыт UDP 7882, или `COMON_SFU_PUBLIC_IPS` в `sfu.env` не публичный адрес. | | Из домашней сети сервера групповые звонки не работают, снаружи работают | Роутер не умеет hairpin NAT. Допишите локальный адрес в `COMON_SFU_PUBLIC_IPS` ([сервер за NAT](./calls.mdx#сервер-за-nat)). | | В браузере в корпоративной сети звонки не соединяются | Сеть пропускает только TLS: включите [TURN поверх TLS](./calls.mdx#turn-поверх-tls). | Проверяйте звонки с телефона в мобильной сети: открытый TCP-порт не доказывает, что доходит UDP. ## Уведомления и медиа [#уведомления-и-медиа] | Что видно | Причина и что делать | |---|---| | Уведомления приходят, только пока приложение открыто | Push не настроен, или relay, вшитый в приложение, не доверяет вашей федерации ([какой relay нужен](./push.mdx#какой-relay-нужен)). | | Push перестал работать после восстановления копии | Так и задумано: после восстановления push выключается ([резервная копия relay](./push.mdx#резервная-копия-relay)). | | Веб-версия перестала получать уведомления | Сменился ключ VAPID: все подписки браузеров нужно сделать заново. | | Видео не отправляется, а приходящие видео показываются | Образ сервера собран без `ffmpeg`. Включите [отправку видео](./quick-start.mdx#отправка-видео). | | Загрузки не проходят у всех | Закончилось место под медиа (`--media-storage-bytes`) или на диске. | | Сообщение из одного эмодзи не анимируется | Не установлен набор `AnimatedEmoji` ([анимированные эмодзи](./operations.mdx#анимированные-эмодзи)). | ## Приложения [#приложения] | Что видно | Причина и что делать | |---|---| | «Нужно обновить приложение» | Уровень приложения ниже `--minimum-client-level` ([версии приложений](./app-updates.mdx)). | | Приложение не подключается после переустановки сервера | Сменился ключ Noise: приложения запомнили прежний. Восстановите ключ из копии; иначе людям придётся удалить федерацию из приложения и добавить заново. | | Ссылки домена открываются в браузере, а не в приложении | Для своего домена нужна своя сборка приложения ([открытие ссылок](./web.mdx#открытие-ссылок-сразу-в-приложениях)). | # Обновление (/docs/selfhost/upgrading) ## Обновить сервер [#обновить-сервер] Каждая версия — тег в репозитории. Список изменений и особые шаги версии — в [истории изменений](../develop/changelog.mdx). ```sh python3 tools/mvp-stack.py backup --backup /абсолютный/путь/before-v0.2.5 git fetch --tags git checkout v0.2.5 python3 tools/mvp-stack.py up python3 tools/mvp-stack.py check ``` `up` пересобирает образы, применяет миграции базы (`migrate`) и только после их успеха запускает новый сервер. Если миграция не прошла, сервер не стартует, а база остаётся на прежней схеме. Пересоберите и [веб-клиент](./web.mdx#веб-клиент), если он у вас есть. Перескакивать через версии можно: миграции применяются по порядку. Исключение — федерации старше 0.2.0, хранившие данные в SQLite: их сначала переводит релиз 0.2.0 (`mvp-stack.py convert` из его checkout), и только потом можно обновляться дальше. ### Проверка данных до обновления [#проверка-данных-до-обновления] После `git checkout` новой версии, но до `up`: ```sh python3 tools/mvp-stack.py preflight ``` Команда собирает мигратор из новой версии и проверяет базу: пройдут ли данные миграции (например, нет ли конфликтов публичных имён и владельцев). Данные и схема не меняются. На время проверки сервер федерации останавливается, потому что проверка не идёт, пока он пишет в базу, и потом запускается снова в прежней версии. `up` делает ту же проверку перед миграцией и при конфликте не трогает базу. ### Порядок при нескольких процессах [#порядок-при-нескольких-процессах] - Шлюзы обновляйте **раньше** основного сервера. - SFU обновляйте **вместе** с сервером: их протокол меняется синхронно. ## Обязательные обновления приложений [#обязательные-обновления-приложений] Некоторые версии сервера не работают со старыми приложениями. Тогда сервер поднимает минимальный уровень приложения, и устаревшее приложение показывает экран обновления со ссылкой из `--client-update-url` ([версии приложений](./app-updates.mdx)). Список изменений помечает такие версии. Данные людей при этом сохраняются: после обновления приложение показывает прежние чаты. ## Откат [#откат] Схема базы обратно не мигрирует, а старый сервер не запустится на базе новее себя. Откат — это восстановление копии, сделанной перед обновлением, на старой версии. `restore` не трогает существующие тома, поэтому на той же машине копия поднимается отдельным проектом Docker, а новый стек сначала останавливается: ```sh python3 tools/mvp-stack.py stop --state .local/mvp git checkout v0.2.4 python3 tools/mvp-stack.py restore --state .local/rollback --project comon-rollback --backup /абсолютный/путь/before-v0.2.5 python3 tools/mvp-stack.py up --state .local/rollback --project comon-rollback ``` Дальше передавайте `--state .local/rollback --project comon-rollback` каждой команде этого стека. Тома остановленного стека остаются: удалите их, только когда убедитесь, что откат удался. Всё, что люди написали после копии, при откате теряется, а [первый запуск из копии](./backups.mdx#первый-запуск-из-копии) придержит исходящее до `release-outbound`. ## Переезд на другой домен [#переезд-на-другой-домен] Личность федерации — её ID и ключ Noise, а не домен: сохраните оба. 1. Направьте DNS нового домена на сервер и зарегистрируйте у провайдера входа новый адрес возврата `https://<новый домен>/auth/oidc/callback`. Издатель (`issuer`) не меняется. 2. Направьте **оба** домена на сервер, relay и веб-клиент в прокси. 3. Запустите сервер с `--public-origin` и `--web-client` нового домена: документ федерации, страницы ссылок и вход начнут называть его. 4. Поменяйте адреса медиа под новый домен: `calls.json`, `sfu.env`, сертификат TURN TLS. 5. Оставьте запись relay в `federation-push.json` без изменений: оба домена ведут к одному relay, а привязка устройства помнит свой relay. 6. Веб-клиенту на новом адресе нужны свой раздел `webpush` в `relay.json` и свой `web.env`. Браузер хранит данные по адресу, поэтому людям в веб-версии придётся войти один раз заново. Приложения, которые уже добавили вашу федерацию, помнят **старый** адрес и продолжают ходить через него, поэтому **оставьте старый домен псевдонимом** той же федерации. Новый вход и ссылки на звонки идут уже на новый домен. Сами переезжают только приложения, в сборку которых вшит новый адрес федерации по умолчанию. # Веб-версия и ссылки (/docs/selfhost/web) ## Веб-клиент [#веб-клиент] Веб-версия — то же приложение Comon, собранное для браузера. Готовый стек отдаёт её по адресу `https://<домен>/app/` из образа `comon_web` (Caddy, порт 8080 внутри сети, без TLS). Собирается она на машине с Flutter версии из `mise.toml` (внутри Docker Flutter не запускается): ```sh mise run build:web -- .local/mvp/web-context python3 tools/mvp-stack.py up ``` Скрипт выполняет `flutter build web --wasm --release` и кладёт сборку в `web-context/site`; `up` включает сервис `web`, как только там появился `index.html`. Пересобирайте веб-клиент при каждом обновлении. Сервер должен знать адрес веб-клиента, иначе вход в браузере не вернётся в приложение: `--web-client=https://<домен>/app` (готовый стек добавляет его сам). ### Настройки образа [#настройки-образа] Переменные лежат в `web.env` состояния. Значения могут содержать только символы URL и base64url. | Переменная | Что значит | |---|---| | `COMON_WEB_BASE_PATH` | Путь клиента, например `/app` (по умолчанию `/`). | | `COMON_WEB_MODE` | `multi` (по умолчанию: человек выбирает федерацию) или `single` (только своя). | | `COMON_WEB_HOME_FEDERATION` | Федерация по умолчанию; обязательна для `single`. | | `COMON_WEB_ENVIRONMENT` | `dev`, `stage` или `prod` (по умолчанию). | | `COMON_WEB_PUSH_RELAY_ORIGIN`, `COMON_WEB_PUSH_RELAY_AUDIENCE`, `COMON_WEB_PUSH_RELAY_PUBLIC_KEY`, `COMON_WEB_VAPID_PUBLIC_KEY` | Relay для Web Push: адрес, `audience`, ключ квитанций и публичный ключ VAPID. Все четыре или ни одной. | | `COMON_WEB_SENTRY_DSN` | Сервер отчётов об ошибках; без него ничего не отправляется. | Из этих переменных образ при запуске пишет `comon-web.json`. Свой файл, смонтированный в `/config/comon-web.json`, заменяет сгенерированный целиком. Чтобы веб-версия получала уведомления, у relay должен быть раздел `webpush` с её адресом и ключом VAPID ([push-уведомления](./push.mdx#настройки-relay-relayjson)). Для звонков из сетей, где закрыт UDP, нужен [TURN поверх TLS](./calls.mdx#turn-поверх-tls). Образ отдаёт строгие заголовки: изоляцию для wasm (`Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`), `Content-Security-Policy` только со своим источником, `Referrer-Policy: no-referrer`. Файлы с хешем в имени кешируются на год, точки входа — без кеша. Проверка: ```sh curl -sI https://<домен>/app/ | grep -i -E 'cache-control|cross-origin|content-security' curl -s https://<домен>/app/comon-web.json ``` ## Страницы ссылок [#страницы-ссылок] Сервер сам отвечает на ссылки `https://<домен>/u/<имя>`, `/join/<код>` и `/call/<код>` (и на старые `/@имя`, `/+код`): показывает страницу без скриптов на русском или английском, с превью и кнопками «открыть в приложении», «открыть веб-версию» и «скачать». Что открывается на разных устройствах, описано в [Ссылках Comon](../features/links.mdx). | Параметр | Что меняет | |---|---| | `--link-scheme` | Схема, через которую страница открывает приложение. По умолчанию `comon`. | | `--web-client` | Куда ведёт «открыть веб-версию». | | `--client-update-url` | Ссылки «скачать» по платформам ([версии приложений](./app-updates.mdx)). | Страницы приглашений и звонков закрыты от поисковиков. Один адрес может открыть не больше 60 страниц ссылок в минуту, дальше страницы отдаются без превью. ## Открытие ссылок сразу в приложениях [#открытие-ссылок-сразу-в-приложениях] На iPhone, Mac и Android система может открывать ссылки домена прямо в приложении, минуя браузер. Для этого нужны две стороны: 1. **Сервер** называет приложения, которым доверяет домен: ``` --apple-app-id=. # можно повторять --android-app=: # можно повторять ``` Тогда сервер отдаёт `/.well-known/apple-app-site-association` и `/.well-known/assetlinks.json`. Без параметров оба пути отвечают 404. 2. **Приложение** должно быть собрано с этим доменом (Associated Domains для Apple, фильтр App Links для Android). Официальные сборки знают только `comon.chat`, поэтому для своего домена это работает только со своей сборкой. Без этого ссылки всё равно работают: открывается страница федерации, и её кнопка передаёт ссылку в приложение через схему `comon://`. На Windows и Linux так всегда: схему регистрирует установщик. Ссылки внутри сообщений приложение открывает само на любом домене: оно проверяет документ федерации по адресу. ## Публичные страницы федерации [#публичные-страницы-федерации] `/rules`, `/child-safety` и `/delete-account` — правила, стандарты защиты детей и порядок удаления аккаунта, на языке из `?lang=ru|en` или заголовка браузера. Их текст берётся из [настроек федерации](./federation-settings.mdx); магазины приложений требуют такие страницы. # API basics (/docs/en/bots/api) ## Request [#request] ``` POST https:///bot/v1/ Authorization: Bearer Content-Type: application/json { ...parameters... } ``` - The body is a JSON object of at most 1 MiB. An empty body means "no parameters". - `GET` with parameters in the query string also works (`?offset=10&timeout=30`): integers are recognized. Pass complex parameters (buttons, commands) with `POST` only. - Method names are case-sensitive: `sendMessage`, not `sendmessage`. - The address is the same domain as the federation in the app. There is no separate API domain. ## Answer [#answer] Success is status 200: ```json { "ok": true, "result": } ``` An error has a status from the table below and: ```json { "ok": false, "error_code": 409, "description": "Refused: bot_stopped", "parameters": { "reason": "bot_stopped" } } ``` `parameters` is not always present: it holds `retry_after` (seconds, for 429) and `reason` (the machine-readable reason of a refusal). ## Errors [#errors] | Status | When | |---|---| | 400 | Wrong parameters: a required one missing, the wrong type, text too long, an unknown entity or button. `description` says what is wrong. | | 401 | No token, a wrong token or one already replaced, the bot is deleted or suspended together with its owner. | | 403 | The action is forbidden by rights or moderation (see `reason` below). | | 404 | Unknown method, the chat does not exist or the bot is not in it, an interaction older than 15 minutes. | | 405 | The HTTP method is neither `POST` nor `GET`. | | 409 | The state does not allow it: the person stopped the bot, the reply window closed, a webhook is set when calling `getUpdates`, data changed concurrently (retry). | | 413 | The body is larger than 1 MiB. | | 429 | Too often. Wait `parameters.retry_after` seconds. | | 500 | Server error. Details are in the server's log. | | 503 | The server is temporarily unavailable. Retry later. | ### Reasons (`parameters.reason`) [#reasons-parametersreason] | Reason | Status | Meaning | |---|---|---| | `bot_stopped` | 409 | The person stopped the bot. Wait for a `my_chat_member` update with status `member`. | | `reply_window_closed` | 409 | A personal bot answers more than 24 hours after the other person's last message. | | `storage_quota` | 409 | The sender ran out of stored-message quota. | | `chat_closed` | 403 | Moderators closed the chat. | | `content_filtered` | 403 | The text hits the federation's filter. | | `privacy_restricted` | 403 | The person's privacy settings do not allow it. | | `profile_restricted` | 403 | Moderators restricted the bot. | | `profile_suspended` | 403 | The profile is suspended. | A 403 is the federation's decision, not a temporary state: do not retry such a request in a loop. ## Retries and idempotency [#retries-and-idempotency] The network may fail after the server has already done the request. So that a retried `sendMessage` does not send twice, pass `idempotency_key` (1 to 128 characters): a retry with the same key returns the same message. ```json { "chat_id": "…", "text": "Build 42 is ready", "idempotency_key": "build-42" } ``` The key is scoped to one bot. The ID of the event the bot answers works well. ## Rates [#rates] Sending, editing and deleting messages spend the same budget as a person's: 30 actions at once, then 5 per second. Past it comes 429 with `retry_after`. Nothing is stored until a request is accepted. ## Server log [#server-log] The server writes a `[bots]` line to its log for every 4xx and 5xx answer (bot, method, status), every webhook failure (bot, host, status or error), every press or suggestion the bot left unanswered, and the first update of each kind dropped by `allowed_updates`. The token, the secret and the webhook URL's path never get into the log. If something does not work, ask the federation's administrator. # Buttons (/docs/en/bots/buttons) Buttons are part of a bot's message, not a separate keyboard: they sit under the text, and editing the message replaces them with it. Only bots can write buttons. ## Adding buttons [#adding-buttons] `buttons` is an array of rows, a row is an array of buttons. Each button has `text` and exactly one action: ```json { "chat_id": "…", "text": "Deploy build 42?", "buttons": [ [ { "text": "Yes", "callback_data": "deploy:42" }, { "text": "No", "callback_data": "cancel:42" } ], [ { "text": "Log", "url": "https://ci.example.org/42" }, { "text": "Copy hash", "copy_text": "9f2c1e7" } ] ] } ``` | Action | What a press does | |---|---| | `callback_data` | Up to 64 bytes. The bot gets a `callback_query` and answers. | | `url` | The app opens the address like an ordinary link, with confirmation. | | `copy_text` | Up to 256 characters. The app copies the text and says "Copied". | Up to 8 rows, up to 8 buttons per row, up to 32 buttons per message; a label is up to 64 characters. Buttons are not forwarded with the message. A personal bot answering on someone's behalf cannot write buttons. Older app versions see the line `🔘 Yes · No` instead of the buttons. ## A press [#a-press] A press of a button with `callback_data` arrives as an update: ```json { "update_id": 15, "callback_query": { "id": "…", "from": { "id": "…", "is_bot": false, "first_name": "Anna" }, "chat": { "id": "…", "type": "group", "title": "Releases" }, "message": { "message_id": "…", "text": "Deploy build 42?", ... }, "button_id": "…", "data": "deploy:42" } } ``` While the bot thinks, the button shows progress. ## Answering a press [#answering-a-press] Answer with `answerCallbackQuery` within **10 seconds**. The bot decides what the person sees: | Answer | What the person sees | |---|---| | `{"callback_query_id": "…", "text": "Done"}` | The app's toast: at the bottom above the composer on a phone, at the top right on a computer. A new one replaces the previous, so quick presses do not pile up. | | `{"callback_query_id": "…", "text": "Not allowed", "show_alert": true}` | A dialog the person closes. | | `{"callback_query_id": "…", "url": "https://…"}` | The address opens. | | `{"callback_query_id": "…"}` | Nothing. | If the bot does not answer within 10 seconds, the press ends with an empty answer and shows nothing. The answer's text is up to 200 characters. Often the bot changes the message itself along with the answer, for example removing the buttons after a choice: ```json { "chat_id": "…", "message_id": "…", "text": "Build 42 deployed ✅" } ``` (`editMessage` without `buttons` removes the buttons.) Instead of a toast, the bot can answer with an [ephemeral message](./ephemeral.mdx) only the presser sees. # Commands (/docs/en/bots/commands) Commands are `/name`s with descriptions that the app shows when someone types `/` in a chat with the bot. As in Discord, a command may have **options** with types, choices and suggestions from the bot. ## Setting commands [#setting-commands] ```sh curl -s -X POST "$API/setMyCommands" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' -d @- <<'JSON' { "commands": [ { "command": "start", "description": "Start" }, { "command": "weather", "description": "Weather in a city", "options": [ { "name": "city", "description": "Where", "required": true, "autocomplete": true }, { "name": "days", "type": "integer", "min_value": 1, "max_value": 7 } ] } ] } JSON ``` - Names are lowercase Latin letters, digits and `_`; descriptions are up to 256 characters. - Up to 100 commands in one scope, at most 64 KiB together. - `setMyCommands` replaces every command of the scope; an empty list deletes them. The app caches a chat's commands for five minutes, but sees changes at once when the bot makes them. ## Scopes [#scopes] | `scope` | Where it applies | |---|---| | `{"type": "default"}` (the default) | Everywhere. | | `{"type": "all_private_chats"}` | In every direct chat. | | `{"type": "all_group_chats"}` | In every group and room. | | `{"type": "chat", "chat_id": "…"}` | In one chat the bot belongs to. | The most specific scope wins. A bot may have commands in up to 64 scopes. ## How a command reaches the bot [#how-a-command-reaches-the-bot] **An ordinary command.** The app sends the command's text as the person's message, which everyone in the chat sees. The bot gets a `message` update and, when the command was picked from the list, the parsed options too: ```json "command": { "name": "weather", "options": { "city": "Almaty", "days": 3 } } ``` A command typed by hand reaches the bot as plain text, without `options`. In groups commands reach the bot in privacy mode too; `/command@bot_username` reaches only the bot with that name. **An ephemeral command** (`"ephemeral": true`). Nothing is written to the chat, nobody else sees the invocation, and the bot gets an `ephemeral_command` with an interaction ID and answers with an ephemeral message ([ephemeral messages](./ephemeral.mdx#ephemeral-commands)). ## Options [#options] | Field | Type | | |---|---|---| | `name` | string | The option's name. | | `description` | string | A hint. | | `required` | boolean | Required. Required options without a condition come first. | | `type` | string | `string` (default), `integer`, `number`, `boolean`, `user`, `date`. | | `choices` | array | Up to 25 choices `{"name", "value"}`; other values are refused. | | `autocomplete` | boolean | The bot suggests values as the person types (instead of `choices`). | | `min_value`, `max_value` | number | Bounds for `integer` and `number`. | | `min_length`, `max_length` | integer | Length for `string`, up to 1024. | | `shown_when` | object | A condition: the option exists only while another one has one of the values. | Values reach the bot by option name: | Type | JSON value | How the person chooses | |---|---|---| | `string` | string | Types text. | | `integer`, `number` | number | Types a number. | | `boolean` | `true` / `false` | "Yes" or "No". | | `user` | profile ID | Picks a member of the chat. | | `date` | string `YYYY-MM-DD` | Picks a date. | The server itself refuses an unknown option, a value of the wrong type, out of bounds or not one of the choices, a person outside the chat, and a missing required option: the bot gets only checked values. ### Conditions [#conditions] An option with `shown_when` appears only while an earlier option has one of the values: ```json { "command": "event", "description": "Event", "options": [ { "name": "kind", "required": true, "choices": [ { "name": "One-off", "value": "once" }, { "name": "Weekly", "value": "weekly" } ] }, { "name": "date", "type": "date", "required": true, "shown_when": { "option": "kind", "values": ["once"] } } ] } ``` Here the date is required only for a one-off event. The server refuses a value of a hidden option. ## Suggestions [#suggestions] For an option with `"autocomplete": true` the app asks the bot what to offer. The bot gets an `autocomplete_query`: ```json { "id": "…", "from": {...}, "chat": {...}, "command": "weather", "options": {"days": 3}, "focused": "city", "query": "Al" } ``` and answers with up to 25 choices within **3 seconds**, or the list stays empty: ```sh curl -s -X POST "$API/answerAutocompleteQuery" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"autocomplete_query_id": "…", "choices": [{"name": "Almaty", "value": "Almaty"}, {"name": "Altai", "value": "Altai"}]}' ``` `value` must fit the option's type and bounds. ## How it looks to people [#how-it-looks-to-people] Options are written right in the composer: `/weather city:Almaty days:3`. Above it the app shows the command with a pill per option and suggestions for the option under the caret: choices, the bot's answers, "Yes"/"No", members or a calendar. A wrong value turns red, and sending is refused until it is fixed. # Ephemeral messages (/docs/en/bots/ephemeral) An ephemeral message is seen by one person only. It sits in the chat's history among ordinary messages, marked "Only you can see this" with a "Dismiss" button, like ephemeral answers in Discord. It is not kept in the history, never reaches search, notifications or unread counts, and cannot be replied to, pinned or forwarded. It lives 24 hours from the first send, until the bot deletes it, the person dismisses it or the app closes. ## When a bot can answer this way [#when-a-bot-can-answer-this-way] Only in answer to a person's action, in the same chat and within **15 minutes**: - to an [ephemeral command](#ephemeral-commands): `id` of the `ephemeral_command`; - to a button press: `id` of the `callback_query`. ```json { "chat_id": "…", "text": "Your balance: 1,200 ₸", "ephemeral": { "interaction_id": "" } } ``` The answer: ```json { "ok": true, "result": { "ephemeral_message_id": "…", "chat": {...}, "receiver": {...}, "expires_at": 1793136400 } } ``` An ephemeral message passes the same checks as an ordinary one (a closed chat, blocks, the filter) and spends the same rate budget. One bot may keep up to 20 live ephemeral messages for one person: the twenty-first deletes the oldest. ## Ephemeral commands [#ephemeral-commands] A command with `"ephemeral": true` in `setMyCommands` writes nothing to the chat: nobody else sees the invocation, and the bot gets ```json { "update_id": 31, "ephemeral_command": { "id": "…", "from": {...}, "chat": {...}, "text": "/balance", "command": "balance", "args": "", "date": 1793050000 } } ``` The app tells the person beforehand: "Only you will see the answer". ## Editing in place [#editing-in-place] Buttons of an ephemeral message are pressed too: a `callback_query` update with `ephemeral_message_id`. The bot can answer by replacing the ephemeral message itself: ```json { "chat_id": "…", "text": "Counter: 2", "ephemeral": { "interaction_id": "", "replace": true } } ``` - A button of an **ephemeral** message was pressed: `replace` changes it in place (same ID, same expiry). - A button of an **ordinary** message was pressed: `replace` shows the ephemeral message in place of that message, for the presser only. Everyone else sees the original. - `replace_message_id` replaces a particular ephemeral message of this bot. Without presses, `editEphemeralMessage` changes an ephemeral message and `deleteEphemeralMessage` deletes it. The server keeps ephemeral messages in memory only, and the app never stores them on the device. # Examples (/docs/en/bots/examples) Both examples do the same: set commands, answer `/start` with a message with buttons, answer presses and echo any other text. They get updates by long polling and need nothing but the standard library. ```sh export COMON_API='https://comon.chat/bot/v1' # your federation's address export COMON_TOKEN='cbt_...' ``` Python 3.9 or newer. ```python title="echo_bot.py" import json import os import time import urllib.error import urllib.request API = os.environ["COMON_API"] TOKEN = os.environ["COMON_TOKEN"] def call(method, **params): request = urllib.request.Request( f"{API}/{method}", data=json.dumps(params).encode(), headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}, ) try: with urllib.request.urlopen(request, timeout=60) as response: return json.load(response)["result"] except urllib.error.HTTPError as error: body = json.load(error) retry = body.get("parameters", {}).get("retry_after") if retry: time.sleep(retry) return call(method, **params) raise RuntimeError(f"{method}: {body['error_code']} {body['description']}") def on_message(message): chat = message["chat"]["id"] text = message.get("text", "") if text.startswith("/start"): call("sendMessage", chat_id=chat, text="Hi! Press a button.", buttons=[[{"text": "Toss a coin", "callback_data": "coin"}], [{"text": "Comon website", "url": "https://comon.chat"}]]) elif text: call("sendMessage", chat_id=chat, text=text, reply_to_message_id=message["message_id"]) def on_callback(query): if query["data"] == "coin": side = "Heads" if time.time_ns() % 2 else "Tails" call("answerCallbackQuery", callback_query_id=query["id"], text=side) else: call("answerCallbackQuery", callback_query_id=query["id"]) def main(): call("setMyCommands", commands=[{"command": "start", "description": "Start"}]) offset = None while True: params = {"timeout": 50, "allowed_updates": ["message", "callback_query"]} if offset is not None: params["offset"] = offset for update in call("getUpdates", **params): offset = update["update_id"] + 1 if "message" in update: on_message(update["message"]) elif "callback_query" in update: on_callback(update["callback_query"]) if __name__ == "__main__": main() ``` Node.js 18 or newer. ```js title="echo_bot.mjs" const API = process.env.COMON_API; const TOKEN = process.env.COMON_TOKEN; async function call(method, params = {}) { const response = await fetch(`${API}/${method}`, { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify(params), }); const body = await response.json(); if (body.ok) return body.result; const retry = body.parameters?.retry_after; if (retry) { await new Promise((resolve) => setTimeout(resolve, retry * 1000)); return call(method, params); } throw new Error(`${method}: ${body.error_code} ${body.description}`); } async function onMessage(message) { const chat = message.chat.id; const text = message.text ?? ''; if (text.startsWith('/start')) { await call('sendMessage', { chat_id: chat, text: 'Hi! Press a button.', buttons: [ [{ text: 'Toss a coin', callback_data: 'coin' }], [{ text: 'Comon website', url: 'https://comon.chat' }], ], }); } else if (text) { await call('sendMessage', { chat_id: chat, text, reply_to_message_id: message.message_id }); } } async function onCallback(query) { const text = query.data === 'coin' ? (Math.random() < 0.5 ? 'Heads' : 'Tails') : undefined; await call('answerCallbackQuery', { callback_query_id: query.id, text }); } await call('setMyCommands', { commands: [{ command: 'start', description: 'Start' }] }); let offset; for (;;) { const updates = await call('getUpdates', { timeout: 50, offset, allowed_updates: ['message', 'callback_query'], }); for (const update of updates) { offset = update.update_id + 1; if (update.message) await onMessage(update.message); else if (update.callback_query) await onCallback(update.callback_query); } } ``` ## What next [#what-next] - Move to a webhook and verify the signature: [updates](./updates.mdx#webhook-setwebhook). - Commands with options and suggestions: [commands](./commands.mdx). - Answers only the presser sees: [ephemeral messages](./ephemeral.mdx). - Never send twice after a network failure: [`idempotency_key`](./api.mdx#retries-and-idempotency). # How bots work (/docs/en/bots/how-bots-work) ## A bot is a profile [#a-bot-is-a-profile] A bot is an ordinary federation profile marked as a bot. It has no devices and never signs in to the app: your program acts for it with the token. In chats the bot carries a "bot" badge, and its owner is shown only to the owner. - **The username** ends with `bot` (case does not matter) and shares the namespace of people and public chats. - **The token** is `cbt__<43 characters>`. The server keeps only its hash. A new token disables the old one at once: unfinished requests of the old token get 401, its webhook is removed, its long poll ends, and updates not yet received stay for the new token. - **Deleting the bot** revokes the token, removes the bot from every group and community and marks the profile deleted. Nobody can open a direct chat with a deleted bot. ## Where a bot can be [#where-a-bot-can-be] - **Direct chat.** Always started by a person, usually with "Start" (the bot gets `/start`). The person may stop the bot ("Stop bot", or by deleting the chat): then the bot cannot write to them until they restart it. The bot learns about stops and restarts through the [`my_chat_member`](./updates.mdx#my_chat_member) update. - **Groups and channels.** Only when the bot has "Can be added to groups" and it was added by someone who may add members. The bot learns the chat's ID from `my_chat_member` when added and from every message it receives. A bot never becomes the owner of a group, channel or community. - **Channels.** In a channel a bot starts as a subscriber. To let it post, make it a publisher in the subscriber list; then it posts with `sendMessage`, and new posts reach it as `channel_post`. - **Communities.** A member who may manage the community adds the bot ("Add to community"). The bot gets a role of its own with the chosen permissions: it cannot be deleted or given to anyone else, and it disappears when the bot leaves. Room permissions apply to the bot as to any member. ## What a bot hears [#what-a-bot-hears] In direct chats and channels a bot gets everything. In groups and community rooms **privacy mode** applies: the bot gets only - commands (`/command`, and `/command@bot_username` only when it is its name); - messages that mention it; - replies to its messages. It gets everything else when it has "Reads all messages in groups", or when its rights in the chat let it delete messages. A bot **never** gets its own messages or other bots' messages. Service messages ("X added Y") do not reach bots. Direct chats with a bot create no contacts. ## Restrictions [#restrictions] - A bot does not start direct chats and cannot write to people who stopped it (`bot_stopped`). - A bot passes the same checks as a person: a chat closed by moderators, the word filter, blocks, the recipient's privacy settings. Such refusals come as 403 ([errors](./api.mdx#errors)). - Sending spends the same rate budget as a person's: 30 messages at once, then 5 per second. - A deleted bot, and a bot whose owner moderators suspended or deleted, fails token checks and gets no updates. # Bots (/docs/en/bots) A bot is a federation profile run by your program. The program runs anywhere and talks to the federation server over HTTP: it receives updates (messages, button presses, commands) and calls methods (send a message, answer a press, set commands). Requests follow the Telegram Bot API: `POST /bot/v1/`, the token in a header, an answer of `{"ok": true, "result": …}`. } title="API basics" href="/en/bots/api"> Requests, the token, answers and errors. } title="Updates" href="/en/bots/updates"> Long polling, signed webhooks and every kind of update. } title="Methods" href="/en/bots/methods"> All 17 methods: parameters and results. } title="Commands" href="/en/bots/commands"> Commands with typed options and suggestions. } title="Buttons" href="/en/bots/buttons"> Buttons in messages and answers to presses. } title="Personal bots" href="/en/bots/personal"> A bot that answers someone's direct chats on their behalf. ## What bots can do [#what-bots-can-do] - **Talk in direct chats.** A person finds the bot by its @username and presses "Start". The bot answers with ordinary messages with formatting and buttons. - **Work in groups, channels and communities.** A bot is added as a member; in a channel it can publish posts, in a community it gets a role of its own. - **Commands** with a suggestion list, typed options (a number, a date, a member, a choice) and suggestions from the bot itself as the person types. - **Buttons** in messages: the bot answers with a toast, a dialog or a link; buttons can also open an address or copy text. - **Ephemeral messages** only one person sees, like ephemeral answers in Discord. - **Personal bots**: a person connects a bot to their direct chats, and it answers on their behalf. A bot cannot start a direct chat first, and never sees messages of other bots or its own. ## Quick start [#quick-start] ### Create a bot [#create-a-bot] In the app, open **Settings › Bots › My bots › Create a bot**. Choose a name and a username, which must end with `bot`, such as `weather_bot`. The app shows a **token** like `cbt__`. Copy it right away: it is shown only once. Whoever has the token controls the bot. If you lose it, issue a new one on the bot's card ("Issue a new token"); the old one stops working at once. ### Check the token [#check-the-token] ```sh export TOKEN='cbt_...' export API='https://comon.chat/bot/v1' # your federation's address curl -s -X POST "$API/getMe" -H "Authorization: Bearer $TOKEN" ``` ```json {"ok": true, "result": {"id": "…", "is_bot": true, "first_name": "Weather", "username": "weather_bot", "can_join_groups": false, "reads_all_messages": false, "supports_personal": false}} ``` ### Get the first message [#get-the-first-message] Find the bot in the app by its @username, press "Start" and write it something. Then: ```sh curl -s -X POST "$API/getUpdates" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' -d '{"timeout": 30}' ``` The answer holds a `message` update with `chat.id`. ### Answer [#answer] ```sh curl -s -X POST "$API/sendMessage" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"chat_id": "", "text": "Hi!", "buttons": [[{"text": "More", "callback_data": "more"}]]}' ``` Complete examples in Python and Node.js are in [examples](./examples.mdx). To see every capability live, talk to the built-in `@demo_bot`, unless your server turned it off. ## Bot settings [#bot-settings] On the bot's card in **My bots** the owner changes the name, description, "About" line, avatar and three switches: | Switch | Meaning | |---|---| | Can be added to groups | The bot can be added to a group, channel or community. Without it the bot lives only in direct chats. | | Reads all messages in groups | The bot gets every message of groups and rooms, not only commands, mentions and replies to it ([privacy](./how-bots-work.mdx#what-a-bot-hears)). | | Can be a personal bot | People can connect the bot as a [personal bot](./personal.mdx). | How many bots someone may create is the federation's decision: 20 per person by default ([bot policy](../selfhost/bots-and-bridges.mdx)). # Bot limits (/docs/en/bots/limits) ## Bots [#bots] | What | How much | |---|---:| | Bots per person | 20, the federation may change it ([policy](../selfhost/bots-and-bridges.mdx)) | | Username | 3–32 characters, ends in `bot` | | Description / "About" line | 512 / 120 characters | | Request body | 1 MiB | | Sending, editing and deleting rate | 30 at once, then 5 per second | ## Updates [#updates] | What | How much | |---|---:| | Keeping updates | 24 hours, at most 100,000 per bot | | `getUpdates`: `limit` / `timeout` | 1–100 / 0–50 seconds | | Webhook secret | 16–256 characters | | Waiting for a webhook answer | 10 seconds | | Pause between webhook retries | grows up to 1 minute | ## Messages [#messages] | What | How much | |---|---:| | Text | 32,768 characters | | Blocks in a document | 256 | | Whole document | 512 KiB | | Deleting at once | 100 messages | | `idempotency_key` | 1–128 characters | ## Commands [#commands] | What | How much | |---|---:| | Commands in one scope | 100, together up to 64 KiB | | Scopes with commands | 64 | | Command description | 256 characters | | Options per command | 10 | | Choices per option, suggestions per answer | 25 | | Choice name | 100 characters | | Text option, `max_length` | 1024 characters | | Answering a suggestion query | 3 seconds | | Command invocation text | 4096 characters | ## Buttons [#buttons] | What | How much | |---|---:| | Rows / buttons per row / buttons per message | 8 / 8 / 32 | | Button label | 64 characters | | `callback_data` | 64 bytes | | `copy_text` | 256 characters | | Answering a press | 10 seconds | | Press answer text | 200 characters | ## Ephemeral messages [#ephemeral-messages] | What | How much | |---|---:| | How long an interaction waits | 15 minutes | | Lifetime | 24 hours | | Live ones of one bot for one person | 20, a new one deletes the oldest | ## Personal bots [#personal-bots] | What | How much | |---|---:| | Answer window after the other person's last message | 24 hours | | People in an "only" or "except" list | 100 | # Messages (/docs/en/bots/messages) A bot writes a message in one of two ways: `text` with `entities` for plain text, or `document` for a rich message. Both can carry `buttons` and `reply_to_message_id`. ## Text [#text] ```json { "chat_id": "…", "text": "Hello, world" } ``` Up to 32,768 characters. Empty text or text of only spaces is refused. ### Formatting [#formatting] `entities` mark ranges of `text`. `offset` and `length` are in UTF-16 units ([Entity](./objects.mdx#entity)). ```json { "chat_id": "…", "text": "Build 42 is ready: open", "entities": [ { "type": "bold", "offset": 0, "length": 8 }, { "type": "text_link", "offset": 19, "length": 4, "url": "https://ci.example.org/42" } ] } ``` Markdown or HTML in the text is not parsed: asterisks stay asterisks. ## Documents [#documents] Comon messages are documents made of blocks: paragraphs, headings, lists, quotes, code, tables, columns, callouts, toggles ([formatting](../features/formatting.mdx)). A bot may send a whole document in the `document` field. Its shape is the JSON of the `InputDocument` message from `protocol/comon/federation/document.proto`, with camelCase fields. ```json { "chat_id": "…", "document": { "schemaVersion": 1, "blocks": [ { "id": "0000000000000000000000000000000a", "heading": { "level": 2, "content": { "id": "0000000000000000000000000000000b", "text": "Build 42" } } }, { "id": "0000000000000000000000000000000c", "code": { "content": { "id": "0000000000000000000000000000000d", "text": "flutter build web" }, "language": "sh" } }, { "id": "0000000000000000000000000000000e", "list": { "kind": "DOCUMENT_LIST_KIND_BULLET", "items": [ { "id": "0000000000000000000000000000000f", "blocks": [ { "id": "00000000000000000000000000000010", "paragraph": { "id": "00000000000000000000000000000011", "text": "tests passed" } } ] } ] } } ] }, "buttons": [[{ "text": "Open", "url": "https://ci.example.org/42" }]] } ``` - Block and text IDs are 32 lowercase hex characters, unique within the document. Their order does not matter: numbering them in sequence is fine. - Headings have levels 1–3. - Document limits: up to 256 blocks, lists and quotes nested up to 4 levels, up to 512 KiB ([limits](./limits.mdx)). - A wrong document gets 400 with a description of the error. ## Replying to a message [#replying-to-a-message] ```json { "chat_id": "…", "text": "Got it", "reply_to_message_id": "" } ``` The message must be from the same chat. ## Editing and deleting [#editing-and-deleting] `editMessage` replaces the whole content, buttons included: to remove the buttons, send the message without `buttons`. A bot edits its own messages: in direct chats and groups within 48 hours, in channels and community rooms without a time limit. `deleteMessage` deletes one (`message_id`) or up to 100 messages (`message_ids`) for everyone. ## Sending again [#sending-again] So that a retry after a network failure does not send twice, pass `idempotency_key` ([retries](./api.mdx#retries-and-idempotency)). ## Media [#media] Sending files, photos and voice messages through the Bot API is not supported yet. A bot receives incoming media in `document` as blocks with attachments and can point at outside addresses with buttons and links. # Methods (/docs/en/bots/methods) Every method is called as `POST /bot/v1/` with the token ([basics](./api.mdx)). Required parameters are in **bold**. The `User`, `Chat` and `Message` objects are in [objects](./objects.mdx). | Method | What it does | |---|---| | [`getMe`](#getme) | The bot's profile | | [`getUpdates`](#getupdates) | Receive updates | | [`setWebhook`](#setwebhook), [`deleteWebhook`](#deletewebhook), [`getWebhookInfo`](#getwebhookinfo) | The webhook | | [`sendMessage`](#sendmessage) | Send a message or an ephemeral message | | [`editMessage`](#editmessage) | Edit a message | | [`deleteMessage`](#deletemessage) | Delete messages | | [`answerCallbackQuery`](#answercallbackquery) | Answer a button press | | [`answerAutocompleteQuery`](#answerautocompletequery) | Suggest values for an option | | [`setMyCommands`](#setmycommands), [`getMyCommands`](#getmycommands), [`deleteMyCommands`](#deletemycommands) | Commands | | [`editEphemeralMessage`](#editephemeralmessage), [`deleteEphemeralMessage`](#deleteephemeralmessage) | Ephemeral messages | | [`getChat`](#getchat) | Chat details | | [`readPersonalMessages`](#readpersonalmessages) | Mark read on someone's behalf | ## getMe [#getme] No parameters. The result is the bot's [`User`](./objects.mdx#user) and its switches: ```json { "id": "…", "is_bot": true, "first_name": "Weather", "username": "weather_bot", "can_join_groups": true, "reads_all_messages": false, "supports_personal": false } ``` ## getUpdates [#getupdates] | Parameter | Type | | |---|---|---| | `offset` | integer | The first `update_id` you want; lower ones are deleted. | | `limit` | integer | 1–100, 100 by default. | | `timeout` | integer | Seconds to wait, 0–50, 0 by default. | | `allowed_updates` | strings | Kinds of updates. Remembered. | The result is an array of updates. 409 when a webhook is set. Details in [updates](./updates.mdx). ## setWebhook [#setwebhook] | Parameter | Type | | |---|---|---| | **`url`** | string | HTTPS on a public address. | | `secret` | string | 16–256 characters `A-Z a-z 0-9 _ -`; turns on the `X-Comon-Signature` signature. | | `allowed_updates` | strings | Kinds of updates. | | `drop_pending_updates` | boolean | Delete the waiting updates. | The result is `true`. Calling it again replaces the webhook and clears the last error. ## deleteWebhook [#deletewebhook] | Parameter | Type | | |---|---|---| | `drop_pending_updates` | boolean | Delete the waiting updates. | The result is `true`. ## getWebhookInfo [#getwebhookinfo] No parameters. The result: | Field | Type | | |---|---|---| | `url` | string | Empty when there is no webhook. | | `has_secret` | boolean | Whether a secret is set. | | `pending_update_count` | integer | How many updates wait. | | `last_error_date` | integer | Time of the last error, Unix seconds. | | `last_error_message` | string | The last error: `HTTP status 502`, `Timed out`, `Connection failed: …`. | ## sendMessage [#sendmessage] | Parameter | Type | | |---|---|---| | **`chat_id`** | string | Where. The bot must be in the chat, and in a direct chat the person must have started the bot. | | `text` | string | The text. `text` or `document` is required. | | `entities` | array | Formatting of `text` ([messages](./messages.mdx#formatting)). | | `document` | object | A document with headings, lists, code and other blocks ([messages](./messages.mdx#documents)). Instead of `text`. | | `buttons` | array of rows | Buttons ([buttons](./buttons.mdx)). | | `reply_to_message_id` | string | A reply to a message of this chat. | | `idempotency_key` | string | 1–128 characters; a retry with the same key returns the same message. | | `on_behalf_of` | string | A person's ID: a personal bot answers on their behalf ([personal bots](./personal.mdx)). | | `ephemeral` | object | Send an [ephemeral message](./ephemeral.mdx) instead of an ordinary one. | The result is the sent [`Message`](./objects.mdx#message). With `ephemeral` the result is different: ```json { "ephemeral_message_id": "…", "chat": {...}, "receiver": {...}, "expires_at": 1793136400 } ``` ## editMessage [#editmessage] | Parameter | Type | | |---|---|---| | **`chat_id`** | string | | | **`message_id`** | string | The bot's message (or the person's, for a personal bot with `on_behalf_of`). | | `text`, `entities`, `document`, `buttons`, `reply_to_message_id` | | The new content, as in `sendMessage`. Buttons are replaced entirely. | | `on_behalf_of` | string | A person's ID, for a personal bot. | The result is the edited `Message` or `true`. ## deleteMessage [#deletemessage] | Parameter | Type | | |---|---|---| | **`chat_id`** | string | | | `message_id` | string | One message. | | `message_ids` | strings | Or up to 100 messages at once. | | `on_behalf_of` | string | A person's ID, for a personal bot. | The result is `true`. A bot deletes its own messages, and others' when it has the right to delete in the chat. ## answerCallbackQuery [#answercallbackquery] | Parameter | Type | | |---|---|---| | **`callback_query_id`** | string | `id` of the `callback_query` update. | | `text` | string | Up to 200 characters: a toast. | | `show_alert` | boolean | Show `text` in a dialog the person closes. | | `url` | string | Open an address. | The result is `true`. Without `text` and `url` nothing is shown. Answer within 10 seconds; later gets 400. ## answerAutocompleteQuery [#answerautocompletequery] | Parameter | Type | | |---|---|---| | **`autocomplete_query_id`** | string | `id` of the `autocomplete_query` update. | | `choices` | array | Up to 25 choices `{"name": "Almaty", "value": "almaty"}`; `value` has the option's type. | The result is `true`. Answer within 3 seconds. ## setMyCommands [#setmycommands] | Parameter | Type | | |---|---|---| | **`commands`** | array | Up to 100 commands ([commands](./commands.mdx)). An empty array deletes the scope's commands. | | `scope` | object | `{"type": "default"}` (the default), `all_private_chats`, `all_group_chats` or `{"type": "chat", "chat_id": "…"}`. | The result is `true`. ## getMyCommands [#getmycommands] | Parameter | Type | | |---|---|---| | `scope` | object | As in `setMyCommands`. | The result is the scope's commands in the shape they were set. ## deleteMyCommands [#deletemycommands] | Parameter | Type | | |---|---|---| | `scope` | object | As in `setMyCommands`. | The result is `true`. ## editEphemeralMessage [#editephemeralmessage] | Parameter | Type | | |---|---|---| | **`ephemeral_message_id`** | string | An ephemeral message of this bot. | | `text`, `entities`, `document`, `buttons` | | The new content. | The result is `{"ephemeral_message_id": "…"}`. The lifetime is not extended. ## deleteEphemeralMessage [#deleteephemeralmessage] | Parameter | Type | | |---|---|---| | **`ephemeral_message_id`** | string | | The result is `true`. ## getChat [#getchat] | Parameter | Type | | |---|---|---| | **`chat_id`** | string | A chat the bot belongs to. | The result is a [`Chat`](./objects.mdx#chat), with `member_count` for direct chats and groups. 404 when the chat does not exist or the bot is not in it. ## readPersonalMessages [#readpersonalmessages] | Parameter | Type | | |---|---|---| | **`owner_id`** | string | The person who connected the bot. | | **`chat_id`** | string | Their direct chat. | | **`read_through_order`** | integer | `order` of the last message read. | The result is `true`. Needs the "Mark messages read" right ([personal bots](./personal.mdx)). # Objects (/docs/en/bots/objects) Every ID in Comon is an opaque string: do not parse it or turn it into a number. Times are Unix seconds. ## User [#user] A person's or a bot's profile. | Field | Type | | |---|---|---| | `id` | string | The profile ID. | | `is_bot` | boolean | Whether it is a bot. | | `first_name` | string | First name. | | `last_name` | string | Last name, if any. | | `username` | string | The @username without `@`, if any. | ```json { "id": "…", "is_bot": false, "first_name": "Anna", "last_name": "Kim", "username": "anna" } ``` ## Chat [#chat] | Field | Type | | |---|---|---| | `id` | string | The chat ID. | | `type` | string | `private` (direct), `group`, `channel`, `community`, `room` (a community room). | | `user` | `User` | For `private`: the bot's peer. | | `title` | string | For the others: the title. | | `username` | string | The public chat's @username, if any. | | `community_id` | string | For `room`: the community the room belongs to. | ```json { "id": "…", "type": "room", "title": "releases", "community_id": "…" } ``` ## Message [#message] | Field | Type | | |---|---|---| | `message_id` | string | The message's ID in the chat. | | `chat` | `Chat` | The chat. | | `from` | `User` | The author, if there is one. | | `date` | integer | When it was sent. | | `edited` | `true` | Present when the message was edited. | | `order` | integer | Its position in the chat; needed for `readPersonalMessages`. | | `text` | string | All the message's text: paragraphs, headings, code, captions and table cells, one line per block. | | `entities` | array | Formatting and mentions in `text`. | | `reply_to_message_id` | string | The message this one replies to. | | `document` | object | The message's full document with every block and attachment. | | `command` | object | Only in the `message` update: `{"name", "options"}` of an ordinary command run from the app ([commands](./commands.mdx)). | `text` is enough for simple bots. `document` matters when structure does: media, lists, tables, quotes. Its shape is in `protocol/comon/federation/document.proto`; in JSON the fields are camelCase. ## Entity [#entity] A range of `text` with formatting. `offset` and `length` count UTF-16 units, as in JavaScript and Telegram: an emoji outside the basic plane takes two units. | `type` | Extra | Meaning | |---|---|---| | `bold`, `italic`, `underline`, `strikethrough`, `code`, `spoiler` | | Formatting. | | `text_link` | `url` | A link under the text. | | `mention` | `user_id` | A mention of a person. Incoming messages only. | | `mention_all` | | A mention of every member. Incoming messages only. | ```json { "type": "text_link", "offset": 0, "length": 7, "url": "https://comon.chat" } ``` ## BotCommand [#botcommand] | Field | Type | | |---|---|---| | `command` | string | The name without `/`: lowercase Latin letters, digits and `_`. | | `description` | string | Up to 256 characters. | | `ephemeral` | boolean | An [ephemeral command](./ephemeral.mdx#ephemeral-commands). | | `options` | array | Options ([commands](./commands.mdx#options)). | # Personal bots (/docs/en/bots/personal) A person can connect one bot as their **personal bot**: it reads the chosen direct chats of that person and acts in them on their behalf, for example answering customers while the person is busy. To the other side, the bot's answer is an ordinary message of the person; the person sees "Sent by <bot>" under it. ## Connecting [#connecting] The bot must allow it: the "Can be a personal bot" switch in its settings. The person opens **Settings › Bots › Personal bot**, enters the bot's @username and chooses: - **Chats**: contacts, other people, only the listed people, or everyone but the listed ones. Chats with bots and with the federation's service profile are never covered. - **What the bot may do**: "Answer messages", "Mark messages read", "Delete its own answers", "Delete any message", "React to messages". In every covered chat the person sees a "<bot> manages this chat" banner with "Pause" and "Resume". ## Updates [#updates] | Kind | When | |---|---| | `personal_connection` | The person connected or disconnected the bot. | | `personal_message` | A new message in a covered chat, the person's own included. | | `edited_personal_message` | It was edited. | | `deleted_personal_messages` | Messages were deleted. | ```json { "personal_connection": { "owner": { "id": "…", "is_bot": false, "first_name": "Anna" }, "connected": true, "rights": { "reply": true, "mark_read": true, "delete_sent": true, "delete_all": false, "react": false }, "date": 1793050000 } } ``` ```json { "personal_message": { "message_id": "…", "chat": {...}, "from": {...}, "date": 1793050000, "order": 512, "text": "Hello, are you open on Saturday?", "owner_id": "…", "outgoing": false } } ``` - `owner_id` is the person who connected the bot; `chat` is shown from their side. - `outgoing: true` means the person wrote it (or the bot on their behalf, then also `sent_by_bot: true`). - Disconnecting (also by connecting another bot or deleting the account) withdraws this person's updates still in the queue; pausing a chat withdraws that chat's. ## Answering on someone's behalf [#answering-on-someones-behalf] ```json { "chat_id": "…", "text": "Yes, from 10 to 4.", "on_behalf_of": "" } ``` - Needs "Answer messages". - An answer is allowed only within **24 hours** of the other person's last message, otherwise 409 `reply_window_closed`. - Such messages cannot have buttons. - `deleteMessage` with `on_behalf_of` deletes only the bot's own answers ("Delete its own answers") or any message ("Delete any message"). - `readPersonalMessages` with `owner_id`, `chat_id` and `read_through_order` (the message's `order`) marks the chat read for the person. If the owner is suspended or deleted, the personal bot still reads but can do nothing. # Updates (/docs/en/bots/updates) Everything that happens to a bot arrives as **updates**. The server keeps them in the bot's queue, so they survive restarts of the server and of the bot. You can receive them in one of two ways, long polling or a webhook, but not both at once. Each update is an object with a number and exactly one kind field: ```json { "update_id": 42, "message": { ... } } ``` Numbers grow in order. The queue keeps updates for **24 hours** and at most **100,000** per bot; the oldest are dropped first. ## Long polling: `getUpdates` [#long-polling-getupdates] ```sh curl -s -X POST "$API/getUpdates" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"offset": 43, "timeout": 50, "allowed_updates": ["message", "callback_query"]}' ``` | Parameter | Type | Meaning | |---|---|---| | `offset` | integer | The first update you want. Every lower number counts as received and is deleted. Pass the last processed `update_id` + 1. | | `limit` | integer | How many to return, 1 to 100. 100 by default. | | `timeout` | integer | Seconds to wait when the queue is empty, 0 to 50. 0 by default (answer at once). | | `allowed_updates` | list of strings | Which kinds to receive. Remembered for later requests and for the webhook. Without it the previous list applies, or every kind if none was ever given. | The result is an array of updates (possibly empty). A new `getUpdates` of the same bot ends the previous waiting request with an empty answer, so keep one polling loop per bot. When a webhook is set, `getUpdates` answers 409: delete the webhook (`deleteWebhook`) to poll. ## Webhook: `setWebhook` [#webhook-setwebhook] The server sends each update to the bot's address in a `POST` request. ```sh curl -s -X POST "$API/setWebhook" -H "Authorization: Bearer $TOKEN" \ -H 'Content-Type: application/json' \ -d '{"url": "https://bot.example.org/comon", "secret": "a-long-random-secret-0123"}' ``` | Parameter | Type | Meaning | |---|---|---| | `url` | string | An HTTPS address on a public server. Required. | | `secret` | string | 16 to 256 characters: letters, digits, `_` and `-`. With it every request is signed. | | `allowed_updates` | list of strings | Which kinds to receive. | | `drop_pending_updates` | `true` | Delete the updates already waiting. | How the server delivers: - one update per request, in order: the next goes only when the previous one is accepted; - the body is the update's JSON, `Content-Type: application/json`; - a 2xx answer means delivered. Any other status, a 3xx redirect, a connection error or 10 seconds without an answer is a failure; the server retries with a growing pause of up to a minute until it succeeds or the update expires; - the address must lead to a public IP: private addresses, `localhost` and IPv6 forms carrying an IPv4 address (NAT64, 6to4, Teredo) are forbidden. The name is checked on `setWebhook` and before every post: if it now points at a private address, the update waits. The certificate is checked against the name in the address. `deleteWebhook` (with an optional `drop_pending_updates`) removes the webhook. `getWebhookInfo` shows the current state: ```json { "url": "https://bot.example.org/comon", "has_secret": true, "pending_update_count": 0, "last_error_date": 1793050000, "last_error_message": "HTTP status 502" } ``` ### Verifying the signature [#verifying-the-signature] With a `secret` every request carries the header: ``` X-Comon-Signature: t=1793050000,v1=5f2b… ``` `v1` is the hex HMAC-SHA256 of the string `.`, keyed by `secret`. Verify it over the raw body bytes, before parsing the JSON, and reject old `t` values so an intercepted request cannot be replayed. ```python import hashlib, hmac, time def verify(secret: str, header: str, body: bytes, tolerance: int = 300) -> bool: parts = dict(item.split("=", 1) for item in header.split(",")) t, v1 = parts.get("t", ""), parts.get("v1", "") if not t.isdigit() or abs(time.time() - int(t)) > tolerance: return False expected = hmac.new(secret.encode(), t.encode() + b"." + body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, v1) ``` ```js import { createHmac, timingSafeEqual } from 'node:crypto'; export function verify(secret, header, body, tolerance = 300) { const parts = Object.fromEntries(header.split(',').map((p) => p.split('=', 2))); const t = Number(parts.t); if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > tolerance) return false; const expected = createHmac('sha256', secret).update(`${t}.`).update(body).digest('hex'); const given = Buffer.from(parts.v1 ?? '', 'utf8'); return given.length === expected.length && timingSafeEqual(Buffer.from(expected), given); } ``` ## Kinds of updates [#kinds-of-updates] | Kind | When it arrives | |---|---| | `message` | A new message in a direct chat, group or room that the bot hears. | | `edited_message` | It was edited. | | `deleted_messages` | Messages were deleted. | | `channel_post` | A new post in a channel the bot belongs to. | | `callback_query` | Someone pressed a button with `callback_data`. | | `ephemeral_command` | Someone ran an ephemeral command. | | `autocomplete_query` | Someone is filling in an option with suggestions. | | `my_chat_member` | The bot was added to or removed from a chat, stopped or restarted. | | `personal_connection` | Someone connected or disconnected the bot as their personal bot. | | `personal_message` | A new message in a direct chat of the person who connected the bot. | | `edited_personal_message` | It was edited. | | `deleted_personal_messages` | Messages in such a chat were deleted. | The shapes of `User`, `Chat` and `Message` are in [objects](./objects.mdx). ### message, edited_message, channel_post [#message-edited_message-channel_post] A [`Message`](./objects.mdx#message). An edited channel post also arrives as `channel_post`, with `"edited": true`. When it is an ordinary command with options run from the app, it also has `command`: ```json { "update_id": 7, "message": { "message_id": "…", "chat": {"id": "…", "type": "group", "title": "Team"}, "from": {"id": "…", "is_bot": false, "first_name": "Anna"}, "date": 1793050000, "order": 118, "text": "/remind when:2026-11-01 what:release", "command": {"name": "remind", "options": {"when": "2026-11-01", "what": "release"}} } } ``` ### deleted_messages [#deleted_messages] ```json { "chat": {"id": "…", "type": "private", "user": {...}}, "message_ids": ["…", "…"] } ``` ### callback_query [#callback_query] ```json { "id": "…", "from": {...}, "chat": {...}, "message": {...}, "ephemeral_message_id": "…", "button_id": "…", "data": "more" } ``` `message` is the message with the button (when a button of an ordinary message was pressed), `ephemeral_message_id` is present when a button of an ephemeral message was pressed. Answer with `answerCallbackQuery` within **10 seconds** ([buttons](./buttons.mdx)). ### ephemeral_command [#ephemeral_command] ```json { "id": "…", "from": {...}, "chat": {...}, "text": "/secret hello", "command": "secret", "args": "hello", "options": {"to": ""}, "date": 1793050000 } ``` `id` is the interaction ID: answer with an ephemeral message within 15 minutes ([ephemeral messages](./ephemeral.mdx)). ### autocomplete_query [#autocomplete_query] ```json { "id": "…", "from": {...}, "chat": {...}, "command": "weather", "options": {"country": "KZ"}, "focused": "city", "query": "Al" } ``` Answer with `answerAutocompleteQuery` within **3 seconds** ([commands](./commands.mdx#suggestions)). ### my_chat_member [#my_chat_member] ```json { "chat": {...}, "from": {...}, "status": "member", "date": 1793050000 } ``` | `status` | When | |---|---| | `member` | The bot was added to a group, channel or community, or a person restarted the bot in a direct chat. | | `left` | The bot was removed from a group, channel or community. `chat` then holds only `id`. | | `stopped` | A person stopped the bot in a direct chat. | `from` is present only for a stop or restart in a direct chat: the person who did it. ### personal_connection, personal_message [#personal_connection-personal_message] See [personal bots](./personal.mdx#updates). # Building from source (/docs/en/develop/build) ## What you need [#what-you-need] - [mise](https://mise.jdx.dev) to install the tools pinned in `mise.toml` and `mise.lock`. - PostgreSQL: the federation server keeps everything there. - Xcode to build for iOS and macOS, the Android SDK for Android, Visual Studio with the C++ components for Windows. ## A test federation [#a-test-federation] ### Sources [#sources] ```sh git clone https://github.com/serezhia/chat_playground.git cd chat_playground mise trust mise install --locked mise run setup ``` ### Database [#database] Create an empty database and write its libpq connection string to a file, for example `host=localhost user=postgres password=postgres dbname=comon_local` in `.local/conninfo`. Then create the schemas: ```sh cd backend/comon_federation_server mise exec -- dart run bin/migrate_database.dart --postgres-conninfo-file=../../.local/conninfo ``` ### Server [#server] ```sh mise exec -- dart run bin/comon_federation_server.dart --postgres-conninfo-file=../../.local/conninfo ``` The server listens on `https://localhost:8443` with a test certificate, keeps files in `.local/comon-federation` of the current directory and lets anyone in under any name through a built-in sign-in page. It is not for real people: they need the [full stack](../selfhost/quick-start.mdx). The app has to be told to trust the test certificate. On Windows the `mise run run:local` script does that and also starts a couple of users to try messaging, see the [runbook](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/local-development.md). On macOS and Linux it is simpler to bring up the [full stack](../selfhost/quick-start.mdx) and build the app for it. ## The app for your federation [#the-app-for-your-federation] `tools/mvp-stack.py up` writes `.local/mvp/client.json` with the federation's address and, when Caddy's internal authority issued the certificate, that certificate. Pass it to the build: ```sh cd frontend/comon_client mise exec -- flutter run --dart-define-from-file=../../.local/mvp/client.json ``` Signed builds for stores and testers are in the runbooks for [Apple](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/apple-release.md), [Android](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/android-release.md) and [Windows](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/windows-flavors.md). ## Checks [#checks] Before sending changes, run the same checks as CI: ```sh mise run verify ``` How to run them only for changed packages is in [`AGENTS.md`](https://github.com/serezhia/chat_playground/blob/master/AGENTS.md). # Changelog (/docs/en/develop/changelog) The main changes in each release and what to do on the server when upgrading. The full list is kept in [`docs/releases/CHANGELOG.md`](https://github.com/serezhia/chat_playground/blob/master/docs/releases/CHANGELOG.md); releases and installers are on [GitHub](https://github.com/serezhia/chat_playground/releases). A "required update" means older apps stop connecting and show the update screen ([app versions](../selfhost/app-updates.mdx)). People keep their data. ## 0.3.1, November 22, 2026 [#031-november-22-2026] A regular update: the protocol is unchanged, and 0.3.0 apps keep working with a 0.3.1 server. - Chats scroll more smoothly during synchronization. - Chat history no longer hangs after a burst of events and needs no federation reconnect. - [Calendar](../features/calendar.mdx): after the daily event limit the refusal is kept and the other changes keep being sent. - On iOS the app opens faster after many notifications. - Mail: switching inbox tabs shows saved letters, and search keeps the position in every tab. **On the server.** Nothing to do: only the apps change. ## 0.3.0, November 16, 2026 [#030-november-16-2026] The main connection moved to a new protocol generation: 0.2.9 apps cannot connect to a 0.3.0 server and show the update screen. 0.3.0 apps show the update screen against a 0.2.9 server too, although the server is the outdated side. Upgrade the federation and publish the apps right after it. - A new interface on every screen: the shell, chat list, chat, mail, calendar, calls, communities, settings, groups, channels and links. Loading shows shimmer, and errors that clear on their own are retried without a "Retry" button. - [Groups](../features/chats.mdx): two-step creation, group descriptions, invite links with an expiry, a limit and approval, and join requests. - A reminder set on a computer rings as an alarm on the phone, even if the app on the phone was not opened. - [Calls](../features/calls.mdx): new one-to-one and conference screens; moving around the app collapses the call. - [Stickers](../features/stickers.mdx): reports about sets go to the federation's report queue; animated stickers are no longer rendered again on every loop. - Federation roles are reordered by dragging. - [Web](../selfhost/web.mdx): WebAssembly in current Chrome, Safari and Firefox, starting offline and an "Update" banner after a new release. **On the server.** Take a backup first. Run `migrate_database` before the federation starts: the server will not start without it, as it moves open sticker reports into the report queue. The calendar (50) and messaging (53) schemas migrate in place. Restart the push relay after the federation, then publish the apps. The server images build on `dart:3.14.0`; the web client needs the new `deploy/web/Caddyfile`. ## 0.2.9, November 10, 2026 [#029-november-10-2026] Not a required update: the minimum client level stays 29 and the recommended level is 30, so 0.2.8 apps offer the update. After a "before the start" reminder with travel time is chosen in a 0.2.9 app, 0.2.8 apps of that account cannot read the reminder settings until updated. 0.2.9 apps transfer media in chunks a 0.2.8 server refuses, so upgrade the federation first and publish the apps after it. - [Media](../features/media.mdx) uploads and downloads faster: 1 MiB and 512 KiB chunks, several requests at once, connections in a background thread. - [Calls](../features/calls.mdx): cameras use H.264 with the hardware encoder, 1080p on computers and 720p on phones, and a silent microphone sends almost nothing. Noise suppression can be changed during a call. - The app does less work in the background, writes to disk less often, catches up on chats faster after connecting and encrypts the connection with native code (except on the web). - A letter opened from a notification waits for the connection instead of showing an error, and returning to the app reconnects at once. - [Calendar](../features/calendar.mdx): months page without loading; with travel time a reminder can count from leaving or from the start of the event. - [Mail](../features/mail.mdx): with several mailboxes, notifications show which one a letter came to; the icon shows the sender's initials. Each mailbox can have a name and a choice of the sections and folders that notify, or be muted. **On the server.** Take a backup first. The server mail schema migrates in place to version 12. Upgrade the federation, restart the push relay after it, then publish the apps. ## 0.2.8, November 10, 2026 [#028-november-10-2026] The minimum client level is 29: apps sign push relay requests for the relay. New apps also work with a 0.2.7 server, so publish them first, then upgrade the federation and restart the push relay. - [Calendar](../features/calendar.mdx): create your own calendars and delete them with their events. Choose who sees your busy time and who sees the details of each calendar; calendars shared with you are turned on from the person's profile. Assistants can keep a calendar for its owner: create and change events and answer invitations on the owner's behalf. - On iOS 26, an alarm dismissed on another device also stops when the app is not running. - [Mail](../features/mail.mdx): new letters in the Inbox arrive within seconds, folders and letters open without loaders, recent letters can be read offline, and device-only mailboxes keep working offline. - Mail notifications disappear on every device once the letter is read, moved or deleted. Windows shows mail notifications. - Crashes reported in 0.2.7 are fixed, and Android sends videos from the gallery again. **On the server.** Back up first. Server and device data migrate in place. `federation-push.json` must list relays in `relays` ([push](../selfhost/push.mdx)); the old top-level `relay_origin` fields stop the server. Restart the push relay after the federation. ## 0.2.7, November 8, 2026 [#027-november-8-2026] The minimum client level is 28: travel time and a second reminder for meetings. Publish the new apps and check the update links, then upgrade the federation and the Telegram bridge. - Spaces: each has its own chats, calendar and mail tabs, sources and colour. A federation space lives on the federation; a device space can gather chats, calendars and mailboxes of several federations ([folders and spaces](../features/organization.mdx)). - Mail: a folder and mailbox sidebar, invitation cards with a day view, a separate composer, suggesting a time from free calendar slots, invitations from attached .ics files. - A federation mailbox is created without a password; mail apps use app passwords ([mail server](../selfhost/mail.mdx)). - On phones the calendar opens an event in a sheet with inline date and time pickers; events have travel time, a second reminder and alarm-style reminders where the device supports them. - Search opens as its own page with mailbox and folder filters. **On the server.** Back up first. The minimum client level is 28. Device data migrates in place. ## 0.2.6, November 7, 2026 [#026-november-7-2026] The minimum client level is 27. Update the server first, then the apps. - [Calendar](../features/calendar.mdx): personal events and meetings, shared schedules of groups and communities, calls in meetings, .ics import, Google, CalDAV and device calendars, public holidays, subscriptions by link, links for other apps, finding a time, rooms and a «Book time with me» page. - Connected Google, Yandex and app-password accounts for the calendar and mail ([external accounts](../selfhost/external-accounts.mdx)). - Chats whose history is already on the device open at once; a burst of new messages in an open chat no longer loses its middle; edits in a long chat show at once. - Stickers: Lottie vulnerabilities fixed; the server checks and rewrites uploaded animations. - Media can live in S3-compatible storage; several primaries on one database (experimental). **On the server.** Back up first. The databases move to new schemas in place, and the calendar and external accounts modules get their own schemas. Going back to 0.2.5 means restoring the backup. ## 0.2.5, October 28, 2026 [#025-october-28-2026] The minimum client level is 12: channel events are said by the channel, and 0.2.4 apps stop reading a channel at them. Update the server first, then the apps. - Chat actions in the header and the chat list: besides "typing…", recording and sending voice messages and round videos, sending photos, videos and files, choosing a sticker, each with its own animation. - [Service messages](../features/messages.mdx#service-messages): names open the profile, "You …" for your own actions, a pin quotes the message, one row per add, how someone joined, a call's length, the group photo in the row, channel and room events, a row menu. - Search in a chat by service messages and by one member. - The [community audit log](../features/communities.mdx#audit-log) shows what exactly changed and filters by kind and by person. - One toast for every notice of the app instead of the old bars, with Undo where it applies. - Deleting a chat and leaving a group or community confirm on a card over the screen. - Photos and video posters in unread chats download ahead; round videos start at once. - [Voice messages and round videos play in a row](../features/voice.mdx#playback), your own and played ones included. - A person's card opened outside the chat with them has a "Chat" button. - Windows: the tray icon opens the window and its menu again; messages read on another device no longer pop up after the computer wakes. - Android: the Comon icon instead of the default one; a call no longer aborts as it connects. **On the server.** The database moves to schema 38 in place. The minimum client level is 12. ## 0.2.4, October 26, 2026 [#024-october-26-2026] The minimum client level is 11. Update the server first, then the apps. - New call screens on phones and computers, voice rooms, link calls with guests and a call chat. - Deleting direct chats and leaving groups and communities. - Retrying unsent messages, instant round video sending. - An installer and in-app updates on Windows and Linux; `/u/`, `/join/` and `/call/` links that open in the app. - Android 8.0 or newer. **On the server.** The database moves to schema 36 in place. Gateways update with the primary server or before it, the server and the SFU together. New optional error-report settings ([operations](../selfhost/operations.mdx)). ## 0.2.3, October 24, 2026 [#023-october-24-2026] - Cached avatars, previews and stickers appear at once on start. - New profile, group and channel panels, a deletion animation, spoilers in notifications. - Zoom while recording round videos. **On the server.** No migrations. Back up and rebuild the server so spoilers are hidden in push notifications too. ## 0.2.2, October 22, 2026 [#022-october-22-2026] - Stickers survive a poor network; Telegram media show a preview at once. - Context menus in the new style. **On the server.** No migrations. Update the server and the Telegram bridge, then the apps. ## 0.2.1, October 21, 2026 [#021-october-21-2026] - The app opens without waiting for clean-up after the previous run. **On the server.** Database schemas update in place: check the migration on a copy first ([upgrading](../selfhost/upgrading.mdx)). A federation still on SQLite converts with 0.2.0 first. The server no longer accepts `--store`, `--messaging` and `--sync`. ## 0.2.0, October 19, 2026 [#020-october-19-2026] The minimum client level is 9. Before it starts, the server's 0.1.x data is converted by a separate converter. - Scheduled and silent messages, channel mentions, transcripts of voice and round video messages, address book import, an optional username. - A federation can change its domain: an app built with the new address moves a saved account to it by itself. **On the server.** PostgreSQL instead of SQLite files. An unknown flag stops the start. The server and the SFU update together, then the apps. # Where things are (/docs/en/develop) This site is for people who use Comon, run their own server and write bots ([Bot API](/en/bots)). Documentation for those who change Comon itself lives next to the code in the [repository](https://github.com/serezhia/chat_playground). ## Documentation in the repository [#documentation-in-the-repository] | What | Where | |---|---| | Where to start: processes, code map, general rules | [`docs/ARCHITECTURE.md`](https://github.com/serezhia/chat_playground/blob/master/docs/ARCHITECTURE.md) | | Glossary | [`docs/glossary.md`](https://github.com/serezhia/chat_playground/blob/master/docs/glossary.md) | | How subsystems work | [`docs/architecture/`](https://github.com/serezhia/chat_playground/blob/master/docs/architecture) | | Protocol and compatibility rules | [`docs/contracts/`](https://github.com/serezhia/chat_playground/blob/master/docs/contracts), sources in [`protocol/`](https://github.com/serezhia/chat_playground/blob/master/protocol) | | Architecture decisions | [`docs/decisions/`](https://github.com/serezhia/chat_playground/blob/master/docs/decisions) | | Security | [`docs/security/`](https://github.com/serezhia/chat_playground/blob/master/docs/security) | | Runbooks: building, releasing, device checks, operations | [`docs/runbooks/`](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks) | | Rules for working in the repository | [`AGENTS.md`](https://github.com/serezhia/chat_playground/blob/master/AGENTS.md) | | Review rules | [`REVIEW.md`](https://github.com/serezhia/chat_playground/blob/master/REVIEW.md) | Every package has its own README: purpose, layer, entry points and the test command. ## How the code is laid out [#how-the-code-is-laid-out] Everything is written in Dart and Flutter and lives in one repository: - `frontend/comon_client`: the app; - `frontend/packages/cdlib_*`: CDLib, the client library that stores data and syncs it with the server (like Telegram's TDLib); - `backend/comon_federation_server`: the federation server, with `comon_push_relay` and `comon_bridge` next to it; - `packages/comon_*`: code shared by client and server: protocol, encrypted transport, models; - `protocol/`: the protocol in Protobuf; - `deploy/`: the Docker Compose stacks the [self-hosting](/en/selfhost) section describes. ## How this site is built [#how-this-site-is-built] [Fumadocs](https://fumadocs.dev) builds the site from MDX files in [`site/`](https://github.com/serezhia/chat_playground/blob/master/site): Russian pages in `content/docs/ru`, English in `content/docs/en`. How to run it locally and where to add pages is in [`site/README.md`](https://github.com/serezhia/chat_playground/blob/master/site/README.md). # Calendar (/docs/en/features/calendar) The **Calendar** tab appears when the federation has turned the calendar module on and your role lets you use it. Every calendar is kept on the device, as chats are: a week, a month or the list open at once and offline, and changes go to the server in order when there is a connection. ## Events and meetings [#events-and-meetings] - Create an event in the calendar, or from a direct chat or small group: then it is a meeting and its people get an invitation. Reply to the whole series or to one meeting. - Repeating events are expanded on the device. **This and following** splits the rest of a series into a new one linked to the old: history, guests, replies and settings stay. - An event has **Travel time**, two reminders and alarm-style reminders where the device supports them. Reminders come from the device and from the server. - **Day**, **Week**, **Month** and list views; quick entry in Russian and English; on a computer the calendar works from the keyboard, and Ctrl+K or ⌘K searches events. ## A call in a meeting [#a-call-in-a-meeting] A meeting can have a call. Five minutes before it starts, **Join** appears, and the **Today** strip above the chats. Every meeting of a series has its own room; guests without an account join by link after the organizer lets them in. ## Shared schedules [#shared-schedules] Groups and communities keep a shared schedule. A group's owner chooses who creates events and who manages them; in a community those are separate role permissions. An event card in a chat does not invite the chat's members: **Follow** adds the event to your own calendar. ## Colleagues' time and rooms [#colleagues-time-and-rooms] - **Find a time** in the meeting form shows when you and your guests are busy that day, never what you do, and offers the next free times. Who sees your busy time (everybody, your contacts or nobody, with exceptions) is set in **Settings › Privacy › Calendar busy time**. - **Access** in a calendar's settings (or **Settings › Privacy › Calendar details**) lets others see what the events in it are: everybody, your contacts or nobody, with exceptions. Private events still show to them only as busy. Calendars opened to you appear under **Shared with me** in the calendar list and in a person's profile under **Calendar**; you only read them. - **Rooms** are listed by the federation's administrator; a meeting books a free one, and a booked room, or a move onto its booking, is refused. - **Book time with me** is a page of the days and hours you take meetings and a link where colleagues choose a free slot. A booking becomes a meeting in both calendars and your chat. ## Other calendars [#other-calendars] - Import an .ics file into a new or existing calendar. - Calendars of a connected Google or CalDAV account: the writable ones are edited in Comon and the changes reach the account ([connected accounts](../selfhost/external-accounts.mdx)). - The phone's or computer's calendars (Android, iOS, macOS) show next to Comon's on that device. **Copy to Comon** makes a copy for your other devices. Nothing leaves the device without that choice. - **Holidays** of a country with moved working days, **Subscribe by link** to a webcal or .ics address, and a **Link for other apps** for Google, Apple or Outlook, with all details or busy time only. The federation's administrator decides which of these are available. ## Spaces and mail [#spaces-and-mail] A space shows its own calendars ([folders and spaces](./organization.mdx)). Invitations from mail land in the calendar, and a letter can suggest a time from free slots ([mail](./mail.mdx)). # Call links (/docs/en/features/call-links) A call by link is a conference without a chat behind it: a permanent address like `https:///call/`. Federation members join with their own profile and, if allowed, guests without an account join with just a name. ## Create a link [#create-a-link] "Call by link" in the menu above the chat list, or **Settings › Calls › Call links**. A link has: | Setting | Options | |---|---| | Title | Optional, up to 64 characters. | | Guests without an account | Allowed by default. Turn it off and only federation members can join. | | Who waits for your approval | Nobody, guests (default) or everyone. | | The link works | Until revoked, 1 day or 1 week. | A link can be copied, sent, changed or revoked. A revoked link stops working and its call ends. Who can create links is decided by the federation owner through roles; by default everyone can. ## How to join [#how-to-join] Open the link. In an app signed in to this federation you can join with your profile. Without an account, enter a name and tap "Join as a guest": in the app, or in a browser if the federation has a web version. Before joining, a **preview** opens: camera, microphone and sound, to check them and turn them on or off in advance. The camera starts off; the microphone starts on if the call has no more than six people. The first person to join starts the call. The call ends when there are no participants and nobody waiting left, or when the link is revoked. ## Waiting room [#waiting-room] The host (the link's owner) sees those who need approval in the waiting room above the call and in "People": "Let in", "Decline" and "Let everyone in" buttons. Until someone is let in, they neither see nor hear the call. The host never waits. ## What the host can do [#what-the-host-can-do] - let in and decline those waiting; - mute participants and disconnect them; - invite people of the federation to the call: it rings them like a direct call, and they join without waiting; - copy the link and share it. ## The call chat [#the-call-chat] Every call by link has its own real chat, like a group: messages, files, reactions and mentions. The chat button with an unread counter is in the conference header, and on a phone in the control bar next to the microphone. - Everyone let in, guests included, is in the chat. People in the waiting room do not see it. - Whoever leaves the call stays in the chat until the call ends. Whoever the host disconnected loses it. - Notifications come only for mentions; the rest is shown by the counter on the call screen. - **When the call ends, the chat is deleted for everyone together with its files.** A new call on the same link gets a new chat. ## Guests [#guests] A guest is a temporary profile with the entered name. It sees only this call, its chat and the people of that chat. Search, contacts and the federation's public chats are unavailable to it. When a guest leaves the call or the call ends, their temporary profile is deleted together with its messages and files. | What | How much a guest has | |---|---| | Messages | 500, no more than one per second after the first ten | | Files | 100 MB in total, up to 25 MB each | The federation owner can forbid guests in the whole federation: **Manage Federation › Guests in calls**. ## Limits [#limits] | What | How much | |---|---| | Links per person | 50 | | People in the call's list (in the call, waiting, invited) | 64 | | Invited at once | 32 people | | Guests in the whole federation at once | 1024 | | Guest joins and link page views from one address | 10 and 60 per minute | # Calls (/docs/en/features/calls) Calls run over WebRTC. The federation server only connects the participants: a direct call goes straight between devices or through the federation's TURN server, a group call through its media server (SFU). No third-party services take part in a call. ## Direct calls [#direct-calls] A direct chat has audio and video call buttons. - The call rings on all of the other person's devices, and one answers. The others show that the call was answered on another device. - If the person does not answer within 45 seconds, the call counts as missed. If they are already in another call, you see "Busy". - An incoming call is shown by the system screen: CallKit on an iPhone, a full-screen notification on Android, a notification with "Accept" and "Decline" buttons on a Mac and Windows. - If the caller has their camera on, you can answer with video right away. - After it ends, the call shows its outcome and duration for three more seconds, with "Call back" and "Close" buttons. Who can call you is chosen in **Settings › Privacy › Calls**: everyone, contacts only or nobody. Bots and the federation's service chat cannot be called. ## Video [#video] - The other person's camera fills the screen and yours sits in a small window that you can drag to any corner. Tapping the small window swaps the cameras. - A phone can switch between the front and back camera. Your front camera is mirrored for you (turn this off in call settings); the other person sees it as is. - Turning on the camera on a phone switches sound to the speaker unless a headset is connected. - If the system stopped the camera (for example, the app was minimized on an older iPhone), the other person sees the avatar with "Camera paused" rather than a frozen frame. - The buttons over the video hide after 4 seconds; a tap brings them back. ## Screen sharing [#screen-sharing] You can share your screen in any call, together with the camera. | Where | How | |---|---| | macOS, Windows | Pick a screen or window in the app's own picker, with live previews. The source can change without stopping the share. | | Android | The system screen recording permission. Stop it from the notification. | | iPhone | The system screen broadcast sheet. Stop it in Control Center. | | Browser on a computer | The browser's picker: screen, window or tab. | | Browser on a phone | Not supported. | A shared screen can be zoomed with a pinch, the mouse wheel or a double tap, up to 5×. The computer's sound is not shared with the screen yet. ## Group calls [#group-calls] In a group the call button starts a group call or joins the one already running. It rings nobody: the chat gets a "started a group call" message that notifies members by their usual settings, and a bar to join appears under the group header. - **Grid**: all participants, 9 per page on a phone and 16 on a large screen. - **Speaker**: the speaker large, the rest in a strip. A shared screen takes the main place; if several people share, you can switch between them. - The speaker's frame glows; a muted microphone shows an icon. - A phone has a list mode: participants without video, only who is speaking and who has what on. A shared screen starts arriving there only when you tap "Watch". - Tapping a participant opens a menu: profile, write, and **this participant's volume, for you only**, from 0 to 200%. - The microphone button can be tapped to toggle it, or held to talk only while you hold it. If you are removed from the group or leave it, you also leave its call. The call ends when the last participant leaves. ## Voice rooms [#voice-rooms] A community voice room is a permanent group call. Tap a room to enter and another to switch. On a phone you always enter a voice room muted. Permissions and moderation are described in [Communities](./communities.mdx#voice-rooms). ## Calls in the background [#calls-in-the-background] A call is not interrupted when you leave the app: | Where | What you see | |---|---| | iPhone | The system picture-in-picture window. The camera keeps working on iOS 18 and pauses on iOS 16–17. | | Android | A picture-in-picture window with microphone and hang-up buttons, and an ongoing call notification. | | Computer | A small draggable window with the latest speaker on top of the app. | | Browser on a computer | A picture-in-picture window (Chrome, Edge). | Picture-in-picture is turned off in **Settings › Calls**. While a call runs the phone screen stays on, and when you talk with the phone at your ear without video, the proximity sensor turns the screen off. A minimized call is shown as a bar at the top of the app; tapping it returns to the call. ## Moving a call to another device [#moving-a-call-to-another-device] When a call is running on one of your devices, the other shows a bar with a "Move here" button. The call moves to that device without dropping. On a phone the card also comes as a notification. ## Call quality [#call-quality] Sound is protected against packet loss: each packet carries a copy of the previous one, and the codec adds redundancy by itself when the network loses data. If speech gets through badly, a note under the other person's name or in the conference header shows on which side the problem is. ## Call settings [#call-settings] In **Settings › Calls**: - this device's microphone, speaker and camera; - noise suppression: off, standard or enhanced (RNNoise, runs on the device, sound goes nowhere); - on Windows, whether to lower other apps during a call; - picture-in-picture and mirroring of your own camera; - your call links, see [Call links](./call-links.mdx). ## Where calls work [#where-calls-work] iPhone, Android, macOS, Windows and browsers. The Linux build has calls, but without the camera, and they have not been checked on devices yet. Group calls and voice rooms work only if the federation owner runs the media server, see [Calls, SFU and TURN](../selfhost/calls.mdx). ## Limits [#limits] | What | How much | |---|---| | Group call participants | 32 | | Waiting for an answer | 45 seconds | | Reconnecting after a dropped connection | 20 seconds in a direct call, 60 in a group call | | Simultaneous calls per person, incoming included | 8 | # Channels (/docs/en/features/channels) A channel is a feed of posts for a large audience. Posts go out in the channel's name; subscribers read them, react and forward them. There are no comments, discussions or "write to the channel". ## Creating [#creating] Tap "Create channel" in the menu above the chat list, give it a title and a description, and pick subscribers from your contacts. The people you add are subscribed at once. Until a channel has an @name it is private: people get in only by being added or through an invite link. ## Roles [#roles] | Action | Owner | Publisher | Subscriber | |---|:-:|:-:|:-:| | Read, forward from the channel, react | yes | yes | yes | | Own notifications, archive, folders | yes | yes | yes | | Post, forward into the channel | yes | yes | | | Edit and delete posts, pin | yes | yes | | | See the subscriber list | yes | yes | | | Change title and description, add and remove subscribers, appoint publishers | yes | | | | Transfer ownership, close the channel | yes | | | - Publishers edit each other's posts: to subscribers the author is always the channel, and they do not see who wrote a post. - Posts have no replies to messages and no "delete for me". - The owner can leave only by transferring ownership (they then become a publisher) or by closing the channel. ## For subscribers [#for-subscribers] Instead of the input line a subscriber has a "Mute" (or "Unmute") button. Under each post the view count and time are shown. - **Views** are an approximate number of times a post was shown. One person on several devices counts once per four days. It is not the number of readers. - **Reactions** are anonymous: only their counts are visible, and there are no notifications. - Subscribers do not see each other; only the owner and publishers see the list. - A new subscriber sees the whole past history but gets no notifications for old posts. ## For publishers [#for-publishers] - Posts can be scheduled: the channel's scheduled queue is shared by all publishers, see [Scheduled and silent messages](./scheduled.mdx). - **Silent posting** in the channel settings sends posts without sound by default. - A bot can post in a channel if you appoint it a publisher in the subscriber list. - You can forward a message into a channel only if you post there: only then does the channel appear in the forwarding list. ## Public channels [#public-channels] The owner can give a channel an @name. A public channel can be found in global search, read before subscribing and opened by the `/u/` link. A private channel has invite links and join requests that the owner approves. All of this is described in [Public chats and invites](./public-chats.mdx). ## Limits [#limits] | What | How much | |---|---| | Subscribers in a channel, with owner and publishers | no product limit; the server holds up to 10,000 | | Channels one person belongs to | 500 | | Description | 255 characters | | Subscribers added at once | 255 | # Direct chats and groups (/docs/en/features/chats) There are five kinds of chats: | Kind | What for | |---|---| | Direct chat | A conversation between two people, or a person and a bot. | | Group | A shared chat of up to 256 members. | | [Channel](./channels.mdx) | A feed of posts for a large audience. | | [Community](./communities.mdx) | A space with rooms, categories and roles. | | Call chat | The temporary chat of a link conference, see [Call links](./call-links.mdx). | The create menu above the chat list creates a group, channel or community, joins a community or creates a call link. ## Direct chats [#direct-chats] To write to someone, find them in search by name or @name, or open their profile and tap "Write". Who can start a direct chat with you is chosen in **Settings › Privacy › Messages**: everyone, contacts only or nobody. Chats that already exist keep working. More in [Privacy and blocking](./privacy.mdx). ### If a stranger writes [#if-a-stranger-writes] When someone outside your contacts writes to you for the first time, the chat shows "Block" and "Add to contacts" buttons under its header. Their photos and videos stay blurred until you open them. You can report them from the chat menu. ### New chats per day [#new-chats-per-day] To keep spam out, everyone has a daily limit of new direct chats with people who do not have you in their contacts. For the `@everyone` role it is 50 a day; the federation owner can change it through roles. Chats with people who have you in their contacts, with bots and with the federation's service chat do not count. ### The federation's service chat [#the-federations-service-chat] Everyone has a chat with the federation's profile. Moderators' answers to reports, warnings and server notices arrive there. A message you write in this chat goes to the federation's support. The service chat cannot be blocked, reported or called. ## Groups [#groups] A group is a closed chat for people of one federation. Joining is immediate, without an invitation: a member appears in the group at once. ### Creating [#creating] Tap "New group", give it a title and pick members from your contacts. You can create a group for yourself alone and add people later. ### Who can do what [#who-can-do-what] | Action | Owner | Member | |---|:-:|:-:| | Write, react | yes | yes | | Add members from their own contacts | yes | yes | | Rename, change the avatar | yes | | | Remove members | yes | | | Delete others' messages | yes | | | Pin messages | yes | | | Mention everyone (`@all`) | yes | | | Edit own messages without a time limit | yes | | | Transfer ownership | yes | | | Delete the group | yes | | You can add someone to a group only if their settings allow it: in **Settings › Privacy › Groups and Channels** everyone chooses who may add them (everyone or contacts only). Adding people who do not have you in their contacts is also capped by a daily limit: 50 a day for `@everyone`. ### History [#history] A new member sees the group's whole history. Their unread messages start from the moment they were added. ### Read state [#read-state] Two checks on your message in a group mean at least one member read it. The message menu shows the number of readers and who they are. ### Public groups [#public-groups] A group can get an @name: it can then be found in search and opened by link. You can also create invite links. See [Public chats and invites](./public-chats.mdx). ### Leaving or deleting [#leaving-or-deleting] A member can leave a group. The owner first transfers ownership to another member; if they are alone in the group, they can leave and the group closes. The owner can delete the whole group. See [Leaving and deleting chats](./leave-and-delete.mdx). ## Limits [#limits] | What | How much | |---|---| | Group members, owner included | 256 | | Added at once | 255 | | Group or channel title | up to 128 characters | | New direct chats with strangers per day | 50 for `@everyone`, up to 10,000 for a role | | Strangers added to groups and channels per day | 50 for `@everyone`, up to 10,000 for a role | # Communities (/docs/en/features/communities) A community is one row in the chat list that holds a banner and rooms by category. A room works like an ordinary chat: history, input line, reactions, pins and search. ## Rooms [#rooms] | Room | What it is | |---|---| | Text | An ordinary chat of the members. | | Announcements | A text room where by default only those allowed can write. | | Voice | A permanent call with its own text chat. People come and go freely, without ringing anyone. | Rooms are grouped into **categories** that everyone can collapse for themselves; collapsed categories are the same on all your devices. A room without a category sits above all categories. **A private room** is a room `@everyone` cannot see: only the roles allowed to see it do. **Slow mode** in a room limits how often a member can write (down to one message per 6 hours). It does not apply to those who can manage messages or rooms. In the chat list a community takes one row: the latest room with a new message, its author, the unread counter and a separate mention badge. The community menu: mark all read, notifications, invite, settings, leave. ## Roles and permissions [#roles-and-permissions] A community has one **owner**, who has every permission and cannot be removed. Every member gets the **@everyone** role, and there is a built-in **Admin** role with the "Administrator (everything)" permission. Custom roles are created above @everyone; the higher a role, the stronger it is. | Permission | What it grants | |---|---| | See rooms | See a room and read it. | | Send messages | Write in text rooms. | | Attach files | Send media and forward. | | Add reactions | React. | | Mention @everyone | Notify every member of the room. | | Delete messages of others | Delete and pin others' messages, no slow mode. | | Join voice rooms | Enter voice rooms. | | Speak | Turn on the microphone in a voice room. | | Camera and screen | Turn on the camera and share the screen. | | Mute others | Mute members of a voice room. | | Move and disconnect others | Move a member to another voice room or disconnect them. | | Manage rooms | Create, change and delete rooms and categories. | | Manage roles | Create roles below your own and grant permissions you have. | | Manage the community | Title, description, banner, visibility, @name, others' invites. | | Remove members | Remove those below you. | | Ban members | Ban those below you, deleting their messages from the last 7 days. | | Create invites | Create invite codes. | | View audit log | Read the community's audit log. | | Administrator (everything) | Every permission at once. | A new community gives `@everyone` the permissions to see, write, attach files, react, join voice rooms, speak, turn on the camera and create invites. **Room permissions.** A category and a room can override permissions: for @everyone, for a role or for a specific person. Community-wide permissions apply first, then the category's overrides, then the room's. Without "See rooms" the other permissions in a room do not apply. A room where you can read but not write opens read-only. Only the server computes permissions: the app shows an action if you have the right, but the server checks it anyway. ## Joining [#joining] - **A private community** can be joined only by invite. - **A public one** can be found in search and joined at once; it can get an @name. An invite is a link with an expiry and, optionally, a limit on joins. Anyone with "Create invites" creates one; the author or someone who manages the community revokes it. The link opens the app, and it can be pasted into search too. Before joining you see a card: title, kind, member count and description, with "Join". The public communities of your federations are in the "Communities" tab of the search above the chat list; with nothing typed it lists the largest. A banned member cannot come back by any route until unbanned. Who can create communities and how many one can belong to is decided by the federation owner through roles. By default everyone can create them. ## Notifications [#notifications] A community and each room have their own notification settings. A room inherits them from the community by default, and the community from its default setting. A new community notifies about **mentions only**: when you are mentioned, replied to, or @everyone is mentioned. A notification looks like "Community › room" with the author's name. ## Voice rooms [#voice-rooms] - Tap a voice room to enter. The list shows who is in it now under the room. - Without "Speak" you enter muted; without "Camera and screen" you cannot turn on the camera or share the screen. - A room can have a member limit (up to 99). Those who can move others are not held back by it. - A moderator can mute a member (it stays after they rejoin), move them to another voice room or disconnect them. - Tapping another voice room leaves the current call. More about calls in [Calls](./calls.mdx). ## Audit log [#audit-log] The server records what community managers do: changes to rooms, categories, roles and settings, role grants, removals, bans and unbans, invites, ownership transfer. The log is visible to the owner, admins and roles with "View audit log". Entries are kept for a year. An entry shows what exactly changed: "Title: lobby → hall", slow mode, a role's color, permissions given and taken, a room's permissions for a role or member, roles given and taken, how far back a ban deleted messages. The log filters by kind (community, rooms, roles, members, invite links) and by person: what they did or what was done to them. A name in an entry opens the profile, a room's name opens the room. ## Ownership and deletion [#ownership-and-deletion] If anyone else is in the community, the owner can leave only after transferring ownership. Only the owner can delete a community, together with all its rooms. Reports on a community and its rooms go to the federation's moderators. ## Limits [#limits] | What | How much | |---|---| | Rooms in a community | 500 | | Categories | 50, up to 50 rooms each | | Custom roles | 100 | | Communities per person | 100 (the federation owner can lower it) | | Active invites | 100 | | Community description, room topic | 1024 characters | | Slow mode | up to 6 hours | | Voice room members | up to 99 | # Formatting and blocks (/docs/en/features/formatting) A message in Comon is a document: plain text, or headings, lists, tables and columns. "Hi" is a document with one paragraph. ## Two input modes [#two-input-modes] - **The input line** at the bottom of the chat is for everyday conversation. It supports text formatting, mentions, attachments, the reply and quotes, and link cards. - **The full editor** opens with the "+" button and takes the whole chat. It offers every block: headings, lists, quotes, code, tables, columns and photo captions. Both modes work on the same draft: switching keeps the text, the cursor and the undo history. ## Text formatting [#text-formatting] Select text and a toolbar appears above it: block type, bold, italic, underline, strikethrough, monospace, spoiler, link, text and background color, and clear formatting. On a phone the toolbar opens through "Format" in the selection menu. Markdown is applied as you type: | Type | Result | |---|---| | `**text**` | **bold** | | `*text*` | *italic* | | `~~text~~` | ~~strikethrough~~ | | `` `text` `` | `monospace` | | `\|\|text\|\|` | spoiler | In the full editor, also at the start of a line: | Type | Result | |---|---| | `# `, `## `, `### ` | heading of three levels | | `- ` | bulleted list | | `1. ` | numbered list | | `[] ` | checklist | | `> ` | quote | | ```` ``` ```` | code block | | `---` | divider | Undo (Ctrl/Cmd+Z) brings back the typed characters if you did not want the conversion. **Colors.** Text and background can take one of nine colors: gray, brown, orange, yellow, green, blue, purple, pink and red. **A spoiler** hides words under a cloud of dots. Tapping the dots reveals the spoilers of that paragraph. The chat list and notifications show dots instead of the hidden text; the words never get there. ## Blocks [#blocks] In the full editor on a computer, "/" at the start of an empty line opens the block menu, and "/turn" turns the current block into another. Every block has a "+" and a drag handle on its left; clicking the handle opens the block menu: turn into, duplicate (Ctrl/Cmd+D), move, delete and the block's own settings. On a phone, blocks are added with the "+" button on the bar above the keyboard. | Block | What it is | |---|---| | Heading | Three levels. | | List | Bulleted, numbered or checklist. Up to four levels of nesting; Tab and Shift+Tab change the level. | | Checklist | Only the author ticks items, by editing the message. Readers see the ticks but cannot change them. | | Quote | Your own text with an optional author line at the bottom. It is a plain block, not a link to a message. | | Code | Monospace text highlighted for the chosen language. | | Divider | A horizontal line. | | Toggle | The first line is always visible; the rest opens with an arrow. Each reader opens it for themselves; it starts collapsed. | | Callout | A tinted box with an emoji and a color. | | Table | Up to 50 rows and 10 columns, a header row and column, cell colors. Tab moves between cells; Tab in the last cell adds a row. | | Columns | Two to four columns side by side. On a narrow screen they stack. | | Media | A photo, video or file, with or without a caption. | Enter on an empty line leaves the block: a list, quote, callout or table. So you can always go on with plain text after any block. ## Mentions [#mentions] Type `@` at the start of a word and a list of chat members appears, recent writers first. The mentioned person is notified even if the chat is muted for them. - `@all` notifies every member. It is available to the group owner, the channel owner and publishers, and community roles with the right to mention everyone. - In a community room, `#` at the start of a word inserts a link to another room. Such a link notifies nobody. - Mentions inside quotes, code, captions and forwarded messages do not notify. - If someone in a group or room mentioned you or replied to you and you have not read it yet, an "@" appears above the scroll-down button. Tapping it takes you to the earliest such message. ## Links and cards [#links-and-cards] Links in text are recognized automatically. An explicit link under a word is set from the formatting toolbar. If the link text differs from the address, or the address is not a web address, the app first asks "Open this link?" and shows the full address. Links to Comon chats and calls open right in the app. For the first link in the text the input line shows a **card**: site, title, description and image. You can remove the card, put it above or below the text, choose a small or large image and the link it is shown for. The federation server builds the card when you send, not the reader's device, so readers never contact the third-party site. | What | How much | |---|---| | Cards in one message | 5 | | Card image | JPEG up to 64 KB, up to 320 pixels on the long side | | New card requests | 20 at once, then 1 every 2 seconds | The server fetches only public http and https addresses and keeps a finished card for an hour. ## What's missing [#whats-missing] Formulas, polls, GIFs and stickers inside a document are not there yet. Stickers, voice messages and round videos are sent as separate messages. # Features (/docs/en/features) What you can do in Comon, who has the right to do it, what others see and which limits apply. The limits on these pages are defaults; the federation owner changes some of them through roles. } title="Messages" href="/en/features/messages"> Sending offline, replies and quotes, forwarding, editing, deleting, pins, read state. } title="Media" href="/en/features/media"> Photos, videos and files, voice messages and round videos with transcripts, stickers and custom emoji. } title="Chats" href="/en/features/chats"> Direct chats, groups, channels, communities with rooms and roles, public chats. } title="Calls" href="/en/features/calls"> Direct and group calls, screen sharing, voice rooms, call links with guests. } title="Privacy" href="/en/features/privacy"> Who can write and call, blocking, reports, moderation. } title="Security" href="/en/features/security"> What is encrypted, what the server sees, devices and the cloud password. ## All pages [#all-pages] **Messages** - [Messages](./messages.mdx): sending, drafts, unsent messages, replies, forwarding, editing, deleting, pinning, read state. - [Formatting and blocks](./formatting.mdx): text formatting, Markdown as you type, tables, columns, mentions, link cards. - [Scheduled and silent messages](./scheduled.mdx): at a time, on a schedule, when the other person is online, without sound. - [Reactions](./reactions.mdx). **Media** - [Photos, videos and files](./media.mdx). - [Voice messages and round videos](./voice.mdx): recording, playback, speech transcription. - [Stickers and emoji](./stickers.mdx): sets, creating them, importing from Telegram. **Chats** - [Direct chats and groups](./chats.mdx). - [Channels](./channels.mdx). - [Communities](./communities.mdx): rooms, roles, permissions, voice rooms. - [Public chats and invites](./public-chats.mdx). - [Leaving and deleting chats](./leave-and-delete.mdx). **Calls** - [Calls](./calls.mdx): direct, group, video, screen, calls in the background. - [Call links](./call-links.mdx): guests, the waiting room, the call chat. **People and safety** - [Profile, contacts and status](./people.mdx). - [Privacy and blocking](./privacy.mdx). - [Moderation](./moderation.mdx): federation roles, reports, moderator actions. - [Security and data](./security.mdx). **App** - [Notifications](./notifications.mdx). - [Search](./search.mdx). - [Folders, spaces and archive](./organization.mdx). - [Settings](./settings.mdx). - [Comon links](./links.mdx). # Leaving and deleting chats (/docs/en/features/leave-and-delete) A long press (or right click) on a chat in the list opens a menu. At its end, after a divider, is the action that removes the chat: | Chat | Action | |---|---| | Direct, with a bot, service | Delete chat | | Group | Leave group; for the owner also "Delete group" | | Channel | Unsubscribe | | Community | Leave community | The action is confirmed on a card over the blurred screen: the chat's avatar, a question with its name and red buttons above "Cancel". Unsubscribing from a channel asks nothing, unless you are its only member and owner. After you confirm, the chat hides for five seconds and a notice with an "Undo" button appears at the bottom. If you do not undo, the action is carried out. If the server refuses, the chat comes back to the list with an explanation. The same actions are in the other person's profile and in the group info. They confirm on the same card, without the five-second undo. ## Delete a direct chat [#delete-a-direct-chat] The app asks for whom to delete it: - **Only for you.** The other person keeps the chat and history. - **For both.** The history disappears for both of you and cannot be restored. On a phone these are two buttons. In a wide window (a computer, a tablet) the card has one "Delete" button and an "Also delete for…" checkbox: unticked, the chat is deleted only for you; ticked, for both. The chat leaves the list and comes back empty with the next message. The draft stays. The federation's service chat can be deleted only for yourself. Deleting a chat with a bot also stops the bot. To talk to it again, tap "Start" in its profile. ## Leave a group [#leave-a-group] A member leaves at any time. The owner of a group with anyone else in it first transfers ownership to another member. If the owner is alone, they leave and the group closes. ## Delete a group [#delete-a-group] Owner only. The group and its history disappear for all members, invites stop working and a running group call ends. This cannot be undone. ## Unsubscribe from a channel [#unsubscribe-from-a-channel] The channel leaves your list. You can come back through an invite link, or through search if the channel is public. The owner of a channel with subscribers first transfers ownership or closes the channel. ## Leave a community [#leave-a-community] The community's rooms leave your list. The owner leaves only after transferring ownership in the community settings. ## What else is deleted [#what-else-is-deleted] When you leave a group, channel or community, its history, pins, drafts and scheduled messages are deleted from the device. Messages you already sent stay with the other members. # Comon links (/docs/en/features/links) ## Kinds of links [#kinds-of-links] | Link | What it opens | |---|---| | `https:///u/` | A person, bot or public chat by @name | | `https:///join/` | An invite to a group, channel or community | | `https:///call/` | A call by link | Old `/@name` and `/+code` links still work: the server redirects them to the new ones. "Share" and "Copy link" in the app give links of exactly this form. ## How a link opens [#how-a-link-opens] **In the app.** Tapping a link in a message opens the chat or call right in the app. If the link leads to a federation you do not have yet, the app checks that a Comon federation really runs at the address and offers to connect; after you sign in, what the link pointed to opens. A link, an `@name` or a `+code` can also be pasted into search. **In a browser.** The federation shows a page without scripts, in Russian or English: what the link opens (the person's name, the chat's title and size, the call and its host) and buttons: - open in the app; - open the web version, if the federation has one; - download the app for your platform. Invite and call pages are kept out of search engines. **Straight into the app from anywhere.** On an iPhone, Mac and Android, `comon.chat` links open the app directly, bypassing the browser. For a federation on its own domain this is possible only if the app is built with that domain; otherwise the link opens the federation's page, which then hands the link to the app. On Windows and Linux links always go through the page: the installer registers the `comon://` scheme that the page uses to open the app. # Mail (/docs/en/features/mail) ## Connecting a mailbox [#connecting-a-mailbox] Comon shows the mail of mailboxes you already have. Open **Settings → Connected accounts** and connect a Google or Yandex account, or any mail server with an app password. Once your federation allows mail, the **Mail** tab appears in the navigation. Your federation's server synchronizes the mail, so new letters arrive while your devices are off, and a new letter in the Inbox brings a notification. When a mailbox asks you to sign in again, a **Sign in** button shows above its letters. Each mailbox's sender name, signature, screening of new senders, codes and notifications are in **Settings → Mail**. **Mail settings** in the Mail tab leads there too. ## Letters [#letters] - The menu above the list chooses the mailbox and folder: Inbox, Sent, Archive and the server's own folders. - A letter opens beside the list, or over it on a phone, and is marked read. - Pictures from the internet stay hidden until you press **Show**, so the sender does not learn you read the letter. Pictures inside the letter itself show at once. - Long-press or right-click a letter: read or unread, flag, snooze, move, select, archive, delete. - Several letters: **Select** in a letter's menu, then taps choose others. On a computer, Ctrl or ⌘ with a click, Shift for a range, Ctrl+A or ⌘A for all. Chosen letters are moved, snoozed, archived, deleted, marked read or flagged together, and with a mouse dragged onto a folder. - **New folder** in the folder menu or when moving creates a folder on the mail server. - **Snooze** hides a letter until the time you choose: later today, tomorrow morning, Monday morning or a date of your own. Snoozed letters are under Snoozed in the folder menu; on time the letter comes back to the top of its folder with a notification. - Search looks at senders, recipients, subjects and the start of the letters on the device. Changes show at once and reach the mail server in order; without a connection they wait for one. If the mail server refuses, Comon tells you. ## Replying and writing [#replying-and-writing] **Reply**, **Reply all** and **Forward** open the editor with the letter quoted; **New letter** opens an empty one. Attachments of one letter can be 1.5 MB together; a forward takes the original letter's attachments along by itself. A letter written offline waits on the device and goes once the connection is back. For 5 seconds after sending, **Undo** in the notice at the bottom takes the letter back. **Send later** (the clock button in the editor) sends it at the time you choose, even with your devices off; until then **Edit** above the letters opens it again. Snoozing and sending later work in Comon: other mail apps of the same mailbox do not see them. If the connection broke after the server took the letter, Comon never sends it again by itself and asks you to check Sent. Your federation's admin can allow mail read-only: letters show, but changes and sending do not. # Photos, videos and files (/docs/en/features/media) ## How to send [#how-to-send] - The attachment button in the input line opens the photo and video picker, up to ten at a time. - "Files" in the "+" menu sends anything as a file, uncompressed. - Files can be dragged into the chat or pasted from the clipboard. - On a phone you can share into Comon from another app through the system "Share" menu. You can send the message right away, without waiting for preparation and upload: photos and videos are prepared and uploaded in the background, and the chat already shows their thumbnail with progress. The upload goes on after you leave the chat and resumes after the app restarts. Several photos and videos picked together go out as one album message. Several files go out as one message with a list of files. An album has one shared caption. ## Photos [#photos] Before sending, the app prepares each photo: - rotates it according to the camera data and converts it to sRGB colors; - **removes EXIF and location**; - keeps three sizes: up to 320, 1280 and 2560 pixels on the long side. A small photo is never upscaled. While a photo loads, a blurred preview stands in its place. ## Videos [#videos] A video is rebuilt as MP4 (H.264, up to 1280 pixels on the long side, up to 30 frames per second), and its metadata is erased. If the video already fits, it is sent without re-encoding. In the chat a video plays muted by itself if auto-download allows it and at least 60% of it is on screen. Tapping opens the viewer: seeking, ±10 seconds, sound. The photos and videos of one chat are browsed in one viewer. ## Files [#files] A file is sent as is, with its name, size and checksum. The recipient downloads it with a tap, and the app checks the checksum before opening it. A GIF is always sent as a file to keep its animation. A right click (or long press) on the file row offers "Save as…". ## Auto-download and storage [#auto-download-and-storage] In **Settings › Data and Storage** you can: - turn auto-download on or off for mobile data and Wi-Fi, choose a level (low, medium, high) or set photos, videos and files separately for direct chats, groups, channels and communities, with a size limit; - see how much space media and files take by category and chat, and clear them; - set how long to keep media and the maximum cache size; - on a phone, save received photos and videos to the gallery; - see data usage. Clearing deletes the copies on the device; nothing is deleted on the server, and whatever you open again downloads again. **Download ahead.** While the app is connected, photos and the posters of videos and round videos in unread incoming messages download before the chat is opened, under the same auto-download rules: in the first 20 chats with unread messages outside the archive, up to 30 per chat. An open chat goes first. ## Limits [#limits] | What | How much | |---|---| | Photo | 64 MB, up to 10,000 pixels per side and 50 megapixels | | Video | 128 MB after preparation, up to 10 minutes | | File | 1 GB (the federation owner can lower it) | | File name | 255 characters | | Photos and videos in one message | 10 | | Server space for your media | 50 GB (the owner can change it) | Server space counts only your uploads that are still used in messages or avatars. Whatever is deleted for everyone frees space. # Messages (/docs/en/features/messages) ## Sending [#sending] On a computer, Enter sends the message and Shift+Enter starts a new line. If you prefer to send with Ctrl+Enter (Cmd+Enter on a Mac), change it in **Settings › Chats**. A message appears in the chat at once, before the server answers. Without a connection it waits in the device's send queue and goes out by itself when the connection returns, including after the app restarts. The order of messages in the chat is kept. A long press (or right click) on the send button offers three more options: "Send without sound", "Schedule message" and, in a direct chat, "Send when online". They are described in [Scheduled and silent messages](./scheduled.mdx). ### Drafts [#drafts] A message you started is kept as the chat's draft, together with attachments, the reply and the quotes. The draft survives an app restart and comes back when you open the chat again. ### If a message was not sent [#if-a-message-was-not-sent] A message the server refused, or whose fate is unknown, is marked "Not sent". Tapping it opens a short menu: | Action | What it does | |---|---| | Retry | Sends the message again and moves it to the end of the chat. | | Retry all | Retries every unsent message in this chat. | | Resend as new | For a message that may or may not have arrived: sends it as a new one. | | Copy | Copies the text. | | Delete | Removes the message from the queue. The server never had it, so there is no "delete for whom" question. | A photo or video that failed to upload has its own retry button on the tile. While an attachment uploads, the cross on it removes only that attachment. If the file was deleted from the device before the upload, the app says so and offers no retry. ## Replies and quotes [#replies-and-quotes] - **Reply.** Swipe the message to the left, double-click next to the text with a mouse, or choose "Reply" in the menu. Your message shows what it answers above it. Tapping that bar jumps to the original message. - **Quote part of a message.** Select words in a message and choose "Quote". A quote block with that fragment and its author is inserted into your message. A quote is not a reply and does not notify the author. One message can hold one reply and up to eight quotes. If the original message is deleted later, the reply bar keeps the last known text, but you can no longer jump to it. ## Forwarding [#forwarding] Select one or more messages (up to 100 at a time), tap "Forward" and pick one or more chats. The forwarding options let you: - **Hide sender name.** The message arrives as yours, without the "Forwarded message" bar. - **Remove photo captions.** When you forward a message that was already forwarded, the bar keeps the original author. Forwarding does not carry over a reply to another message, and mentions notify nobody. You can forward only within one federation. ## Editing [#editing] You can change your own message: "Edit" in the menu, or the up arrow in an empty input field on a computer (which edits your last text message). Editing happens in the same input field, and a draft you started is not lost. An edited message shows "edited" next to its time. | Where | Who edits | Time limit | |---|---|---| | Direct chat, group | author | 48 hours | | Group | group owner | none | | Channel | owner and publishers | none | | Community room | author | none | A message forwarded with its author shown and a contact card cannot be edited. An edit does not notify the mentioned people again. ## Deleting [#deleting] Select messages (up to 100 at a time) and tap "Delete". The options depend on the chat: - **Direct chat:** "Delete for me" or "Delete for me and" the other person. When both people have deleted a message for themselves, the server erases it completely. - **Group:** only "Delete for everyone". The author deletes their own message; the group owner deletes anyone's. - **Channel:** the owner and publishers delete, for all subscribers at once. - **Community room:** the author deletes their own message; anyone's is deleted by those whose role lets them manage messages. A deleted message leaves the screen at once. By default it drains into a black hole; in **Settings › Chats** you can pick a plain fade, which is the default in the browser. If the server refuses the deletion, the message comes back. ## Pinning [#pinning] A pinned message is shown in the bar above the chat; tapping the bar takes you to the message. With several pinned messages, the bar shows the number of the current one. - In a **direct chat** you pin a message for yourself or for both. - In a **group** only the owner pins for everyone. - In a **channel** the owner and publishers pin. - In a **community room**, whoever the role allows. Pinning adds a [service row](#service-messages) to the chat. ## Service messages [#service-messages] Rows in the middle of a chat report events: who added whom, who joined or left, what changed in the title, description or photo, what was pinned, when a call ran. - Names in a row are shown as they are now and open the profile. Your own actions read "You …", actions on you "… you". - One add is one row with everyone added: "Anna added Boris, Vera and Gleb". - A join says how the person got in: by an invite link or by a request, and who approved it. - A group call's row offers "Join" while the call runs and then shows how long it lasted. - A new group photo is shown in the row itself and opens on a tap. It stays in the row after the photo changes again. - A pin row quotes the start of the message and leads to it. If the message was deleted, the row says "a deleted message". A pin only for yourself is seen only by you. - In a **channel**, the rows of creation, a new title, description and photo are said by the channel. - In a **community room**, the rows of a new title, topic and slow mode name who changed them. A hold, a right click, Shift+F10 or the menu key opens the row's menu: the exact time, "Go to message" (on a pin), "Select" and "Delete". Deleting removes the row but does not undo the event. Service rows cannot be edited, forwarded, pinned, reacted to or reported. ## Read state [#read-state] - In a **direct chat** two checks on your message mean the other person read it. - In a **group** two checks appear once at least one member has read the message. The message menu shows how many people read it and who. There is no read time. - In **channels** subscribers do not see who read a post. A message counts as read when it actually reached the screen. The unread counter on the chat in the list and the "Unread" divider in the chat show where to continue. ## Selecting and copying [#selecting-and-copying] - **Phone.** A long press lifts the message above the chat and opens the menu. You can select words right in the lifted message; "Copy" in the menu copies the whole message. - **Computer.** Plain text is selected with the mouse, across several messages too. A right click opens the message menu with reactions; if something is selected, "Quote" and "Copy selected text" come first. - **Escape** clears the message selection, ends editing and removes the reply, in that order. ## Limits [#limits] | What | How much | |---|---| | Text of one message | 32,768 characters | | Photos and videos in one message | 10 | | Reply and quotes | 1 reply and up to 8 quotes | | Delete or forward at once | 100 messages | | Window to edit your own message | 48 hours | | Sending in a row | 30 messages at once, then 5 per second | Characters are counted in UTF-16 units, as in Telegram: most emoji take two. All server limits are collected in the [Limits](../selfhost/limits.mdx) reference. # Moderation (/docs/en/features/moderation) Federation moderation is done by people with roles. Everything happens in the app: **Settings › Manage Federation**. This section is visible to the owner and to those with the right to open the panel; it shows a counter of open reports. ## Federation roles [#federation-roles] Everyone has the built-in `@everyone` role. Creating a federation adds four more: | Role | What it can do | |---|---| | Support | Sees reports, replies as the federation, dismisses them and escalates to moderators, deletes reported messages | | Moderator | The same, plus restricts and suspends people, closes chats, sees the audit log | | Administrator | Everything, including roles and federation settings | | Owner | Everything. There is one owner; ownership is transferred by giving the owner role to another person. | Administrators create custom roles. A role can grant permissions, limits (reactions, sticker sets, communities, new direct chats per day, additions to groups per day, speech recognition minutes) and a badge: role badges are shown in the profile, so members can tell real moderators apart. | Permission | What it grants | |---|---| | Open the federation panel | See "Manage Federation", roles and profiles | | Review reports | Read cases, dismiss and escalate them | | Moderate content | Delete reported messages, hide or block sticker sets, write past the word filter | | Restrict profiles | Warn, restrict, suspend and restore profiles | | Close chats | Close and reopen groups, channels and communities | | View the audit log | Read the federation's audit log | | Manage roles | Create, change and assign roles below your own | | Manage the federation | Change federation settings and phone numbers | | Create communities, call links and sticker sets; publish and import sticker sets | `@everyone` has them by default | | Reply as the federation | Write to people from the service chat | | Administrator | Every permission except owner-only actions | **Hierarchy.** Only someone whose highest role is above a person's can act against that person or change their roles. Nobody can touch the owner. ## Reports [#reports] Reports about the same thing (messages of one author in one chat, a profile, a chat, a community or a sticker set) are gathered into one **case**. The queue sorts cases by severity, then oldest first. Reports about harm to children are marked urgent; violence and self-harm get high severity. Everyone who reviews reports gets a message about a new case in the service chat, an urgent one with a mark. A case shows who reported and why, copies of the messages at the time of the report, the profile's current state and the available actions. ## Moderator actions [#moderator-actions] | Action | What happens | |---|---| | Dismiss | The case is closed; reporters are told no violation was found. | | Escalate to moderators | The case is flagged and gets at least high severity. | | Reply | A message to the person from the service chat. | | Delete messages | Deleted for everyone. Outside public chats, only the reported messages. | | Warn | The person gets a warning with the reason; it is counted in their profile. | | Restrict | Until a date or until lifted, the person writes only in chats they are already in: they cannot create, join or add, and new direct chats only with mutual contacts. Others do not see this. | | Suspend | All devices are signed out, sign-in is refused, the profile shows "Account suspended". | | Restore | Lifts a restriction or suspension. | | Close chat, Reopen chat | A group, channel or community becomes read-only, cannot be joined or called and disappears from search. "Reopen chat" puts it back. | | Hide sticker set, Block sticker set, Keep sticker set | Hide a set from search, block it, or put it back. | An action can carry a reason and a note for other moderators, and can resolve the case at once. ## The service chat [#the-service-chat] The federation has its own profile with its name. Its chat receives report outcomes, warnings, restrictions and moderators' replies, in the recipient's language. A message a person writes in the service chat opens a support case: moderators answer in the same chat. ## Filters [#filters] The federation owner can set stop words (up to 500) and banned domains (up to 500, subdomains included). A message with them in its text or links is not sent. The filter does not apply to moderators and the service profile. ## Anti-spam limits [#anti-spam-limits] - New direct chats with people who do not have you in their contacts: 50 a day for `@everyone`. - Adding people who do not have you in their contacts to groups and channels: 50 a day. - Sending, reactions, reports and profile changes are rate limited. The limits change through roles, up to 10,000 a day. ## Audit log and retention [#audit-log-and-retention] Every moderator action, role change, ownership transfer and settings change is written to the federation's audit log. It can be filtered by who acted and against whom. The log and closed cases with their evidence are kept for a year, open cases until they are closed. ## Federation settings [#federation-settings] In **Manage Federation › Rules and policies**: federation name, support contact, rules in Russian and English, filters, the tree of report reasons, guests in calls, new direct chats per day, speech recognition, contacts mode, phone numbers and additions to groups per day. They are all described in detail in the [Self-hosting](../selfhost/federation-settings.mdx) section. # Notifications (/docs/en/features/notifications) ## Where they arrive [#where-they-arrive] | Platform | How | After the app is closed | |---|---|---| | iPhone, iPad, Mac | Push through Apple, text decrypted on the device | Yes | | Android | Push through Google, text decrypted on the device | Yes, unless force-stopped in system settings | | Windows | System notifications from the running app | While the app runs or sits in the tray | | Browser | Web Push through the browser's service | While the browser runs; on an iPhone, if the web version is added to the Home Screen | | Linux | None | — | The app asks for notification permission once, after the first sign-in. If you decline, there are no notifications until you turn them on in **Settings › Notifications and Sounds**. Notification text is encrypted with the device's key: neither the delivery service nor Apple nor Google sees it. If decryption fails, a plain "New message" arrives. ## What arrives [#what-arrives] - New messages in direct chats, groups, channels and community rooms. - Mentions of you and replies to you, even from muted chats. - Reactions to your messages (in direct chats and groups; who can send them is configurable). - Incoming calls: on a phone, as the system call screen. - A scheduled message that failed. If you read a message on one device, its notification disappears on the others too. If a message is deleted, its notification is removed as well. An edited message does not notify again. **Devices in turn.** The device you used last gets the notification first, the others 10–30 seconds later if you still have not read it. If the app is open and in use, an in-app banner replaces the system notification. An open chat gives no notifications about itself. ## Mute a chat [#mute-a-chat] In the chat menu or its info: "Mute for an hour" or "Mute indefinitely". Messages from a muted chat arrive and count as unread, but without a notification, except mentions. In a community, notifications are set for the whole community and separately for each room. By default a community notifies only about mentions and replies to you. ## Schedule [#schedule] In **Settings › Notifications and Sounds › Schedule** you set the hours when notifications are allowed, for example working hours on weekdays. Outside those hours messages arrive without notifications and stay unread. The schedule uses the chosen time zone and does not change if you travel. A space can have its own schedule too (see [Folders and spaces](./organization.mdx)). A notification arrives only if the federation and every space holding the chat allow it, and the chat itself is not muted. Mentions get past a muted chat, but not past the schedule. ## Archive [#archive] If an archived chat gets a new message and its notification is allowed, the chat leaves the archive by itself. If the chat is muted or it is quiet hours, it stays in the archive. ## Sounds [#sounds] In **Settings › Notifications and Sounds**: - **Sounds in the app**: messages, calls, voice rooms, microphone and sound; - **Ringtone** on a phone: the system one or Comon's; - **Reaction notifications**: from everyone, from contacts or from nobody. A message sent "without sound" arrives with a notification, but quietly. See [Scheduled and silent messages](./scheduled.mdx#silent-messages). # Folders, spaces and archive (/docs/en/features/organization) Folders, spaces, the archive and pinned chats are personal: only you see them, they are the same on all your devices and they change nothing in the chats themselves. Folders are separate in each federation. ## All chats [#all-chats] If you have several federations, at the top you can choose "All chats" (the chats of all federations together) or one federation. Chats are ordered by their last message; an edit, a read, a rename or a draft does not lift a chat. A folder's unread counter counts chats, not messages. A white counter means an unread chat with notifications is among them; a grey one means all unread chats are muted. ## Folders [#folders] A folder is a saved selection of chats, with its tab above the list. Folders are created in **Settings › Chats › Chat Folders**; if there are none yet, ready-made "Direct" and "Unread" folders are suggested there. A folder can set: - **chat kinds**: direct chats with contacts, other direct chats, groups, channels; - **unread only**; - **archive**: inbox only, archive only or everything; - **always include** chosen chats, even if they do not match the rules; - **exclude** chosen chats. Exclusion beats inclusion. Folders can be reordered, changed and deleted; deleting a folder does not touch the chats. ## Spaces [#spaces] A space is a separate workplace, such as "Work" or "Family": its own tabs on the bar (chats, calendar, mail) and its own sources in each. Spaces are created and changed in **Settings › Chats › Spaces** and switched with the space button on the bar. - **Chats**: for each federation, all its chats, the space's own folders or chosen chats. - **Calendars** and **mail**: chosen calendars and mailboxes. When everything comes from one federation, the space is kept there and is on all your devices, with its own [notification schedule](./notifications.mdx#schedule). With sources from several federations, the space is kept only on this device; the app warns before such a move. What you turn off in a space is not lost: it stays in other spaces and in All. A space creates no new chats and does not change who you write as. There are no nested spaces. While there are spaces, Settings open from the space switcher; the «Settings as a separate tab» switch there brings the tab back. ## Archive [#archive] The archive takes a chat out of the main list. Archiving is not muting, reading, deleting or leaving: the history, draft, unread counter and notifications stay. A chat leaves the archive by itself when it gets a new message you would be notified about. If the chat is muted or it is quiet hours, it stays in the archive. ## Pinned chats [#pinned-chats] A chat can be pinned to the top of the list: "Pin chat" in its menu. Pins are kept separately for each space and each folder. Pinning does not take a chat out of the archive. ## Limits [#limits] | What | How much | |---|---| | Spaces | 32 | | Folders | 64 | | Folder or space name | up to 64 characters | | Chats included or excluded by a folder | 1000 each | | Items in a space | 256 | | Pinned chats in one group | 100 | | Windows in the notification schedule | 64 | # Profile, contacts and status (/docs/en/features/people) ## Profile [#profile] In each federation you have your own profile: first name, last name (optional), @name and avatar. Changing the profile in one federation does not touch the others. - **@name**: from 3 to 32 characters, a Latin letter, then letters, digits, `_` or `-`. An @name can also be added later. Without an @name strangers cannot find you and you have no `/u/` link; contacts find you by name. - **Avatar**: a square photo cropped to a round mask; you can move, zoom and rotate it. You can replace it, view it in full or delete it. - **Phone** is shown only if the federation uses numbers. The number comes from the organization's sign-in service or is set by the federation owner; the person cannot change it. The profile is edited in **Settings** by tapping your profile at the top. Changes need a connection to the server: the profile does not change offline. ## Someone else's profile [#someone-elses-profile] A profile opens from contacts, search, the chat header, the member list, or a message author's avatar or name. Its buttons depend on where it was opened: | From | Buttons | |---|---| | The chat with this person | Call, Video, Sound, Search, More | | Elsewhere, with a conversation | Chat, Call, Sound, Search, More | | Elsewhere, without one | Chat, Call, Video, Sound, More | "Chat" opens the conversation or starts it, "Sound" sets notifications from this chat, "More" adds to contacts, sets your own name for the contact, blocks or reports. Viewing a profile does not create a chat: one appears only when you write or call. ## Finding people [#finding-people] What search finds depends on the contacts mode the federation owner chose: | Mode | Contact list | Finding strangers | |---|---|---| | Address book | Only the people you added | By part of the name or @name | | All members (default) | All federation members | Everyone, by part of the name | | Hidden | Only the people you added | Only by exact @name | In "All members" mode everyone is everyone's contact, and there is no need to add contacts. If you have several federations, search on the "All" tab goes through each of them and finds strangers only by exact @name. ## Contacts [#contacts] - A contact is one-way: if you add someone, nothing changes for them. The profile shows whether the contact is mutual and whether they added you. - Conversation does not add anyone to contacts by itself. - You can give a contact your own name for them: only you see it, and the profile shows the name the person set under it. - Blocking does not remove someone from contacts. - On the "Contacts" tab the list is sorted by last seen time or by name. - A contact can be sent to a chat as a card: "Contact" in the attachment menu. The recipient sees the avatar, name and @name and can write or add the contact right away. ### Phone book [#phone-book] On an iPhone and Android, if the federation uses phone numbers and you have a number, the "Contacts" tab offers to find people you know through your phone book. Those found become your contacts at once, with the name from your book. After that the app repeats the search no more than once a day. When someone from your book signs up, the chat with them gets a message about it. The uploaded phone book can be deleted from the server: **Settings › Privacy › Delete imported contacts**. The contacts themselves stay. Who sees your number and who can find you by it is chosen in the privacy settings. ## Online status [#online-status] | Where | What is shown | |---|---| | Direct chat header | "online", "last seen recently", "last seen 5 minutes ago", "last seen yesterday at 12:12", or what the other person is doing | | Chat list | An "online" dot on the avatar; the action in place of the last message | | Group and room header | The action with the member's name: "Vera is choosing a sticker…" | | Profile | The same as the header, with the exact time | Actions: typing, recording or sending a voice message, recording or sending a video message, sending a photo, video or file, choosing a sticker. Each has its own animation before the text. While the app connects, the header says "connecting" rather than the other person's status. The "online" status is lit while the app is open and visible on screen. On a computer it goes off after five minutes of inactivity. ### Who sees your status [#who-sees-your-status] **Settings › Privacy › Last Seen**: Everybody, My contacts or Nobody, plus "Always share with" and "Never share with" exceptions for people and groups. The rule is mutual: if you hid your exact time from someone, you do not see their exact time either. An approximate one is shown instead: recently, within a week, within a month or a long time ago. When you write to someone or type, that person sees you online for another 30 seconds, even if your status is hidden. ## Limits [#limits] | What | How much | |---|---| | First and last name | 64 characters each | | Avatar | a square up to 1024 pixels and 8 MB | | Contacts | 1000 | | Phone book | up to 5000 numbers, up to 1000 new numbers a day | # Privacy and blocking (/docs/en/features/privacy) ## Privacy settings [#privacy-settings] **Settings › Privacy** (each federation has its own): | Setting | Options | Default | |---|---|---| | Last Seen | Everybody, My contacts, Nobody, plus exceptions | Everybody | | Messages: who can start a chat with you | Everybody, My contacts, Nobody | Everybody | | Calls: who can call you | Everybody, My contacts, Nobody | Everybody | | Groups and Channels: who can add you | Everybody, My contacts | Everybody | | Phone number: who sees it | Everybody, My contacts, Nobody | My contacts | | Who can find me by my number | Everybody, My contacts | Everybody | - "Messages" decides only who can **start** a chat. Chats that already exist keep working. - The phone rows exist only in federations that use numbers. - In a federation in "All members" mode every member counts as a contact, so "My contacts" is not offered there. - On an iPhone, Android and a Mac, chat suggestions in the system "Share" menu are turned off here too. If your settings refuse someone, they do not learn why: a refusal because of blocking and one because of settings look the same. ## Blocking [#blocking] You can block someone from their profile, from the direct chat menu, or with the "Block" button when a stranger writes. The list of blocked people is in **Settings › Privacy › Blocked**, where you can also unblock. Blocking works both ways: - neither can start a direct chat or write in an existing one; - neither can call; - neither can add the other to a group or channel; - you do not see each other's status, and the blocked person does not see your avatar. The blocked person gets no notice of it. In shared groups and communities blocking does not stop the conversation, but the blocked person's messages are collapsed into "Message from a blocked user"; a tap shows it. The federation's service chat cannot be blocked. ## Reports [#reports] You can report messages (one or several selected), a person, a group, a channel, a community and a sticker set: "Report" in the menu of the message, profile, chat or set. 1. Pick a reason. The federation owner sets the reasons, and they can be nested. 2. If the reason requires it, add a comment. 3. For a person or chat you can tick "Also block this user" right away. Moderators see only what you saw at the moment of the report: a copy of the selected messages and a few recent messages of the chat. The rest of the conversation is unavailable to them. The outcome arrives in the federation's service chat: whether action was taken or no violation was found. There is no list of your reports. More on what moderators do in [Moderation](./moderation.mdx). ## Federation rules [#federation-rules] If the federation has rules, you accept them on first sign-in and again whenever the owner changes them. The rules, the support contact and the federation's public pages are in **Settings › Help**, together with "Write to support". ## Deleting your account [#deleting-your-account] **Settings › Privacy › Delete account**. What happens is described in [Federations and accounts](../guide/federations.mdx#deleting-your-account). # Public chats and invites (/docs/en/features/public-chats) ## @names [#names] People, groups, channels and communities of one federation share one @name space: a name taken by one of them is taken for all. In different federations identical names do not get in each other's way. - From 3 to 32 characters: a Latin letter, then letters, digits, `_` or `-`. - Case does not matter in search, but the name is shown as its owner wrote it. - When a chat is closed or deleted, its @name and invite codes are freed. ## Public or private [#public-or-private] | What | When it is public | Who sets the @name | |---|---|---| | Group, channel | When it has an @name. Remove the name and it becomes private. | Owner | | Community | When "public" is chosen in the settings. The @name is optional. | Roles that manage the community | An outsider sees a card for a public chat: title, description, member count, avatar, cover and @name. ## Links [#links] | Link | What it opens | |---|---| | `https:///u/` | A person or a public chat | | `https:///join/` | An invite to a chat or community | "Share" and "Copy link" in the app give exactly these addresses. If you open a link in a browser, the federation shows a page with a preview and buttons: open in the app, open the web version or download the app for your platform. How links open on different devices is described in [Comon links](./links.mdx). In the app you can paste a link into search, as well as a plain `@name` or `+code`. If the link leads to a federation you do not have yet, the app offers to connect to it and opens the chat after you sign in. ## Reading before joining [#reading-before-joining] A public group or public channel can be read without joining: messages, photos, videos and files are visible, with a "Join group" or "Subscribe" button at the bottom. Nothing is marked as read, and the chat does not appear in your list until you join. A public community shows only its card before you join. ## Invite links [#invite-links] Every group and channel has a primary link: it never expires and has no use limit. The owner can reissue it, and the old one then stops working. Additional links are created in the chat info. They can have: - a name, so you know whom you gave it to; - an expiry; - a join limit; - approval: joining by such a link is possible only after the request is approved. The group or channel owner manages links. Communities have their own invites, see [Communities](./communities.mdx). ## Join requests [#join-requests] If the owner turned on request approval for the chat, or the person came through a link with approval, a "Request to join" button replaces joining. A request can be withdrawn. The owner sees requests in the chat info, oldest first, and accepts or declines each. A request does not expire and survives turning approval off. ## Global search [#global-search] Search in the chat list finds public groups, channels and communities by @name or part of the title. Results you are not a member of yet are shown under "Global search". A query starting with `@` searches names only. ## Limits [#limits] | What | How much | |---|---| | Working invite links per chat | 100 | | Link name | 32 characters | | Requests waiting for approval | 1000 | | Link preview pages from one address per minute | 60, then without a preview | # Reactions (/docs/en/features/reactions) ## How to react [#how-to-react] - **A double tap** on a message on a phone adds or removes the quick reaction. - **A long press** (or right click) shows a row of reactions above the menu. On a phone you can slide your finger onto a reaction without lifting it and release. - The expand button at the end of the row opens the emoji panel: recent emoji, the federation's full set and the emoji sets you installed. Reactions are shown under the message or inside it, next to the time. While a message has no more than three reactions, the avatars of the people who left them are shown instead of a counter. A long press on a reaction from an emoji set opens that set. A reaction can be an emoji from the federation's set or any emoji sticker of the federation. ## How many [#how-many] The federation owner sets the numbers through [roles](./moderation.mdx). By default: | What | Default | Maximum for a role | |---|---:|---:| | Reactions by one person on a message | 1 | 3 | | Different reactions on one message | 11 | 11 | If only one reaction is allowed, a new one replaces the old. If several are, the earliest is removed when the limit is reached. ## Your settings [#your-settings] In **Settings › Stickers and Emoji** you choose the "Quick reaction" for a double tap and the "Reaction panel": up to seven reactions that come first in the menu. The settings are shared by all your devices. ## Who finds out about a reaction [#who-finds-out-about-a-reaction] - In a **direct chat and a group** the author of the message is notified about a reaction. Whose reactions to notify about is chosen in **Settings › Notifications and Sounds › Reaction notifications**: everyone (default), only contacts or nobody. If the reaction is removed before the notification goes out, it does not arrive. - New reactions to your messages are marked with a heart next to the unread counter in the chat list. In the chat itself a heart button appears above the scroll-down button: it takes you to the earliest message with an unread reaction. - In a **channel** reactions are anonymous: nobody sees who left them, and there are no notifications. A reaction is not a new message: it does not lift the chat in the list and does not raise the unread counter. Service messages cannot get reactions. When a message is deleted for everyone, its reactions go too. # Scheduled and silent messages (/docs/en/features/scheduled) A long press or right click on the send button opens a menu: - **Send without sound**: recipients see the message, but their phone stays quiet. - **Schedule message**: pick a date, time and repeat. - **Send when online**: only in a direct chat. Stickers (from their preview) and recorded voice messages and round videos (from the recording's send button) are sent the same way. Anything sent from the input line can be scheduled: text, a document, photos, files, stickers, voice messages and round videos. Forwarding cannot be scheduled. ## Schedule message [#schedule-message] Pick a day and time. A time less than ten seconds away sends the message at once, and you cannot pick more than a year ahead. **Repeat:** never, every day, every week, every 2 weeks, every month, every 3 months, every 6 months or every year. After it is sent, a repeating message stays in the queue with its next date. The federation server sends the message, so your phone can be off. ## When online [#when-online] The message goes out as soon as the other person comes online. If they are online right now, it goes out at once. The option is unavailable if the person hides from you when they are online. ## The scheduled queue [#the-scheduled-queue] When a chat has scheduled messages, an icon appears in the input line. It opens the "Scheduled messages" page, where you can, for each message: - send it now; - move it to another time or change the repeat; - edit the text; - delete it. The queue is visible on all your devices. Recipients see neither the queue nor any mark that a message was scheduled. In a **channel** the queue is shared by all publishers: each of them sees and can change the others' planned posts. ### If sending failed [#if-sending-failed] A scheduled message is not sent if, by its time, you can no longer write in the chat, your storage for messages has run out, or the server was down for more than a day past the set time. The message then stays in the queue with the reason, and you get one notification. You can send it again, move it or delete it. If you leave the chat or are removed, your scheduled messages there disappear at once, even if you come back before their time. ## Silent messages [#silent-messages] A message sent "without sound" arrives as usual, with a notification, the unread counter and mentions, but without sound or vibration. The recipient does not see that it was silent. In a channel a publisher can turn on "Silent posting": all their posts then go out without sound by default, and the send button's menu offers "Send with sound" once. ## Limits [#limits] | What | How much | |---|---| | Scheduled messages in one chat | 100 per author; in a channel 100 shared by all publishers | | How far ahead | 365 days | | Delay after which a message is not sent | 24 hours | | "Send now" at once | 32 messages | # Search (/docs/en/features/search) ## Global search [#global-search] The search field above the chat list (Ctrl/Cmd+K) searches everywhere at once: | Tab | What it finds | |---|---| | All | Up to three chats and three people, then messages | | Chats | Your chats by title | | People | Federation members, see [Profile, contacts and status](./people.mdx#finding-people) | | Messages | Text in all your chats | | Media, Links, Files, Voice | Messages with such content; without a query, the latest ones | Public groups, channels and communities you are not in yet are shown under "Global search". If you have several federations, search covers all of them at once, and if one is unavailable you can retry it separately. Tapping a result opens the chat at that message. Back returns to search with the same query and position in the list. ## Search in a chat [#search-in-a-chat] Ctrl/Cmd+F or "Search" in the chat menu. The chat jumps to the newest match at once, and the bottom shows "3 of 27" with arrows. Enter and Shift+Enter step through matches, Escape closes search. Matches are highlighted in the text, but not inside unrevealed spoilers. Results can be shown as a list. The filters button in the search bar: - **Service messages** lists the chat's events; they are found, for example, by a new title or by a person. - **From a member** limits the search to one member's messages or your own. Channels do not have it: every post there is the channel's. ## How words are matched [#how-words-are-matched] - A message is found if **every** word of the query is the start of some word in the message. "hel wor" finds "Hello, world". There is no morphology: "cat" does not find "kitten". - Case does not matter, "ё" and "е" count as one letter, and Latin letters with diacritics match those without. - Text, headings, lists, quotes, code, media captions, file names and voice transcripts are searched. Text from reply bars quoting other messages is not. - A query counts up to 16 words and up to 256 characters. Search runs on the federation server and does not work offline. ## Shared media [#shared-media] At the bottom of a person's profile, or of group or channel info, there are tabs: Media (photos and videos), Files, Links, Voice (voice messages and round videos) and, for a person, Groups in common. Only tabs with something in them are shown. A long press or right click on an item offers "Go to message". ## What's missing [#whats-missing] Search history, offline search over the cache, and chat and date filters in global search. # Security and data (/docs/en/features/security) ## Trust model [#trust-model] Comon is a messenger for organizations that keep the server themselves. The federation server is a trusted party: - **the federation server can read stored messages**. Comon has no end-to-end encryption between people (like "secret chats"); - on the other hand, data goes nowhere but the federation server: federations are not connected to each other, and you cannot write to another one. If you need the server owner to be unable to read conversations, Comon does not fit that today. ## Connection to the server [#connection-to-the-server] - The app connects to the federation over TLS and opens a separate **Noise** protocol session with the server's key on top of it. - On the first connection the app checks that a federation really runs at the address and remembers its key. If the server is swapped later, the app does not connect. - Each device gets its own key. The private part is kept in the system's secure storage (Keychain, Android Keystore and their equivalents), not in the app's database. ## Sign-in [#sign-in] Sign-in goes through your organization's sign-in service (OIDC): the app opens its page in the system browser or in the system's own sign-in session, never in an embedded web view. Comon never sees your password for that service. ### Cloud password [#cloud-password] The cloud password is a second sign-in step on a new device, in case the account in the sign-in service is taken over. It does not encrypt messages. - From 10 to 128 characters, spaces allowed. - The server keeps only a strong hash of it (PBKDF2-SHA256, 600,000 iterations). - After every five wrong attempts in a row, sign-in is locked: for a minute, then twice as long each time, but no more than a day. - A forgotten password is reset by the federation owner on the server. ## Devices [#devices] **Settings › Devices** shows every device signed in: name, platform, app version and when it was last active. You can sign out any other device, or all of them at once. Signing out on one device does not touch the others. ## Data on the device [#data-on-the-device] - The app's database and media cache are **encrypted** (SQLite with the ChaCha20 cipher, keys in the system's secure storage). - If the key is unavailable, the app does not wipe the data; it waits until the storage becomes available. - Leaving a federation deletes its data and sign-in key from the device. ## What the federation server sees [#what-the-federation-server-sees] | Sees | Does not see | |---|---| | Messages, files, profiles, chat members | Your password for the organization's sign-in service | | Device sign-in times and names | Devices' private keys | | Who writes to whom | Your cloud password (only its hash) | Moderators do not see all of this: only what is attached to a report. See [Moderation](./moderation.mdx). ## Push notifications [#push-notifications] Notifications on a phone and in a browser go through the **push relay**, a separate service that hands them to Apple, Google or the browser. - The notification text is **encrypted** with the device's key. The relay, Apple and Google see only an encrypted blob, the time and the size. - The federation does not store Apple and Google tokens; it has only opaque relay identifiers. The relay, in turn, does not know the keys the text is encrypted with. - Without the relay the app still receives messages while it is open; only background notifications stop. Details for administrators are in [Push notifications](../selfhost/push.mdx). ## Speech recognition [#speech-recognition] Voice messages are transcribed by the recognizer the federation owner chose. If it runs outside the federation, the app says where the sound goes. More in [Voice messages and round videos](./voice.mdx#speech-transcription). ## Error reports [#error-reports] The app can send crash reports only if the build names its own report server (Sentry); the "Send Error Reports" switch is in **Settings › Help**. You can send the log by hand with "Report a problem" in the same place. # Settings (/docs/en/features/settings) At the top of settings is your profile: avatar, name and `@name · federation`. With several federations, that is also where you choose whose profile's settings to show, or add a federation. The sections are grouped under "Account", "Apps" and "General". "Federations", "Language", "Appearance", how chats look, the Calendar tab and the device switches (notifications, sounds, call devices, reminders) apply to the whole device. The rest belong to the profile chosen at the top and are the same on all your devices. | Section | What's inside | |---|---| | Devices | Your devices, signing out other sessions. See [Security](./security.mdx#devices). | | Chats | Chat folders and spaces, how messages look, large emoji, send key. See [Chats](#chats). | | Mail | Mailboxes: sender name, signature, screening new senders, codes; connecting a mailbox; which letters send notifications. See [Mail](./mail.mdx). | | Calendar | Calendar tab in the navigation, week start, second time zone, this federation's calendar, reminders on this device. See [Calendar](#calendar). | | Calls | Microphone, speaker, camera, noise suppression, picture-in-picture, camera mirroring, call links. See [Calls](./calls.mdx#call-settings). | | Bots | My bots and the personal bot. See [Bots](../bots/index.mdx). | | Notifications and Sounds | System notifications, schedule, reaction notifications, sounds, ringtone. See [Notifications](./notifications.mdx). | | Privacy | Blocked people, cloud password, last seen, who can write, call and add you to groups, phone, account deletion. See [Privacy](./privacy.mdx). | | Data and Storage | Storage and data usage, auto-download, saving to the gallery, message history on the device. | | Appearance | Theme and interface scale. | | Stickers and Emoji | Quick reaction, reaction panel, emoji and sticker sets. See [Stickers and emoji](./stickers.mdx). | | Language | Russian or English. | | Federations | All your federations, their connection, send queue, leaving. See [Federations and accounts](../guide/federations.mdx). | | Help | Report a problem, error reports, the federation's rules and support. | | Logs | Viewing the app log (test builds only). | | Manage Federation | For the owner and moderators. See [Moderation](./moderation.mdx). | ## Chats [#chats] - **Chat Folders**: a federation's folders and a space's own folders. See [Folders, spaces and archive](./organization.mdx). - **Spaces**: spaces, their tabs and sources, «Settings as a separate tab». See [Spaces](./organization.mdx#spaces). - **Message color**, **message text size** and **chat background** with patterns, with a live chat preview. - **Message deletion**: "Black hole" or "Fade". - **Large emoji**: emoji-only messages without a bubble. - **Send key** (when there is a keyboard): Enter or Ctrl/Cmd+Enter. ## Calendar [#calendar] - **Show the calendar in the navigation**: hiding the tab does not change invitations or reminders. - **View**: week start, a second time zone and, when the device has calendars of its own, showing both copies. - **Calendars**: this federation's calendar, where invitations arrive. - **Reminders**: whether reminders work on this device, and permission for exact timing. See [Calendar](./calendar.mdx). ## Appearance [#appearance] - **Theme**: system (default), light or dark. - **Interface scale**. ## Data and Storage [#data-and-storage] - **Storage Usage**: a chart by category, clearing, how long to keep media (with exceptions for particular chats), the maximum cache size, and "Chats", "Media", "Files" and "Music" tabs. - **Data Usage**: how much traffic went where, separately for mobile data and Wi-Fi. - **Auto-download media** for mobile data and Wi-Fi. - **Save to gallery** received photos and videos (only in the phone app). - **Message history on the device** for each federation: database size and clearing. Clearing is not signing out: the sign-in, drafts, send queue and chat list stay, and the history loads again when you open the chats. ## Help [#help] - **Report a problem**: a form with a description, a screenshot, the app log and device details. "Send" opens the system "Share" menu, and you choose where it goes yourself: a chat, email or a file. The report is never sent anywhere automatically. The form can also open when you shake the phone ("Shake to Report", turned on here). - **Send Error Reports**: present in builds that name a report server. - The federation's rules, support contact, public pages and "Write to support". # Stickers and emoji (/docs/en/features/stickers) ## The emoji and sticker panel [#the-emoji-and-sticker-panel] The smiley button to the left of "Send" opens a panel with two tabs: "Emoji" and "Stickers". The panel opens on the tab you used last. It has recent items, favorite stickers, installed sets and search. - **A sticker** is sent as a separate message, without a bubble. Tapping a sticker in the chat opens its set, which you can add for yourself. - **Custom emoji** go right into the text and are drawn in place of the regular emoji with the same meaning. People without the set, and notifications, show the regular emoji. The message menu has "Emoji from the … pack", from which you add the set. - **Animated emoji.** If the federation owner installed an animated emoji set, a message made of one such emoji plays as a small sticker. Tapping plays it again. - **Large emoji.** A message of emoji only is shown large and without a bubble. Turn this off in **Settings › Chats**. ## Sets [#sets] There are two kinds of sets: stickers and emoji. Sets are shared by the whole federation: each has an author and a link by its short name. Public sets can be found by search; unpublished ones open only by link. The federation owner can also install **system sets** that everyone has. In **Settings › Stickers and Emoji** you can: - reorder installed sets by dragging and remove them; - add a set by link or short name; - find the federation's public sets; - create your own set; - import a set from Telegram; - turn animation looping and sticker suggestions by emoji on or off. Installed sets, recent items and favorites are stored in your profile and are the same on all devices. ## Your own set [#your-own-set] Create a set, give it a title and a short name, then add stickers: each needs at least one emoji. You can rename the set, change its cover, reorder and replace stickers, make it public or delete it. | Format | What to upload | |---|---| | Image | PNG or WEBP up to 512 KB | | Lottie animation | TGS up to 64 KB, vector only, up to 60 frames per second, by Telegram's rules (no masks, effects, repeaters or stars) | | Video | WEBM (VP9 with transparency) up to 256 KB, up to 30 frames per second | A sticker fits into 512 pixels, an emoji into a 100 × 100 square. An animation lasts no longer than three seconds. The server checks the files and converts them to the right shape itself. It parses a Lottie animation, writes it again and draws every frame in an isolated process, so the apps only ever get the checked file, never the uploaded one. If a set is deleted, stickers already sent from it keep showing. ## Import from Telegram [#import-from-telegram] Paste a `t.me/addstickers/…` or `t.me/addemoji/…` link into "Add by link" or choose "Import from Telegram". The server downloads the set through the federation's bot and creates a copy in your name. Files that fail the checks are skipped, and the app shows how many. - Import works only if the federation owner connected a Telegram bot. - An imported set cannot be made public; it is available by link. - A Telegram set is imported into a federation once: importing it again opens the existing copy right away. ## Reports [#reports] You can report someone else's set. Federation moderators can hide a set from search or block it: its stickers then stop showing everywhere, and its files cannot be uploaded again. ## Limits [#limits] The federation owner can change them through roles. The `@everyone` role's defaults are in brackets. | What | Maximum | |---|---| | Own sticker / emoji sets | 100 (20 / 10) | | Installed sticker / emoji sets | 500 (200 / 100) | | Stickers / emoji in a set | 120 / 200 | | Favorite stickers | 50 (5) | | Telegram imports per day | 100 (10) | | Custom emoji in one message | 512 | # Voice messages and round videos (/docs/en/features/voice) ## Recording [#recording] When the input field is empty, a microphone stands in place of the send button. A short tap switches it to the camera for a round video and back. | Gesture | What happens | |---|---| | Hold | Recording runs. | | Release | The recording is sent. | | Slide left | Cancel. | | Slide up | The recording locks: hands free, with "Cancel", "Stop" and "Send" buttons. | | Space / Escape on a computer | Pause / cancel a locked recording. | After "Stop" you can listen to the recording, trim a voice message from both ends, delete it or send it. If a call, minimizing the app or a camera error interrupts the recording, what was recorded is kept for preview. Recording works offline too: a voice message uploads to the server while you record when there is a connection, and otherwise goes out from the send queue. A voice message shorter than half a second and a round video shorter than a second are not sent. ### Round videos [#round-videos] A round video is shot with the front or back camera, with a flash button. Zoom with a pinch or the mouse wheel. Pausing ends a segment, and resuming records the next one: they are joined when sent. At 60 seconds the round video is sent by itself. ## Playback [#playback] - **A voice message** shows a waveform: tap or drag along it to seek. - **A round video** in the chat loops muted while it is on screen. A tap turns on sound and plays from the start; another tap pauses. While paused, drag your finger around the circle to seek. - **Speed** switches with a tap: 1×, 1.5×, 2×. A long press opens a slider from 0.5× to 2.5×. The speed is shared by voice messages and round videos and remembered on the device. - Voice messages and round videos play in a row: after one ends, the next newer voice message or round video of the chat starts by itself, yours or someone else's, played or not. A pause does not break the chain. While one plays, the next is already downloading, within the auto-download settings. - If the next round video has no bubble on screen, it plays in a floating circle and settles into its bubble when you scroll to it. If the next one is visible, the chat centers it. - On a phone with a proximity sensor, sound switches to the earpiece when the phone is at your ear. The player is shared by the whole app: leaving the chat does not stop the recording. Its bar is shown above the chat list and in the chat header; tapping the title takes you to the message. If a round video with sound scrolls off screen, it keeps playing in a floating window that you can drag to a corner or swipe away. A dot on a recording means you have not listened to it yet. The author sees whether anyone has listened. Channels do not have this mark. ## Speech transcription [#speech-transcription] If the federation owner turned on speech recognition, voice messages and round videos have a "Transcribe" button. The text appears under the recording, is visible to everyone in the chat and can be collapsed. Search covers transcripts. - Recognition starts only on a tap; nothing is recognized by itself when sent or received. - While recording a voice message you can turn on "Aa": speech is recognized live, and plain text is sent instead of the voice message; you can fix it before sending. - If the recognizer runs outside the federation, the app says where the sound goes: "Recognized by …". - Everyone has a daily recognition time. By default it is an hour; the federation owner changes it through roles. The same recording is recognized once: a forwarded or resent voice message gets the finished transcript for free. ## Limits [#limits] | What | How much | |---|---| | Voice message | up to 2 hours and 64 MB, Opus 48 kHz mono | | Round video | up to 60 seconds and 16 MB, sent at 400 × 400 pixels | | Length of a recording that is recognized | up to 30 minutes (the owner can raise it to 2 hours) | | Recognition time per day | 1 hour (the owner can raise it to 24 hours) | # Apps and platforms (/docs/en/guide/apps) Comon is one Flutter app for every platform. Features are almost the same everywhere; the differences are listed below. ## What works where [#what-works-where] | Platform | Chats, photos, files | Voice, round videos, video | Calls | Notifications in the background | |---|---|---|---|---| | iPhone and iPad | yes | yes | yes, with the system call screen | yes | | Android | yes | yes | yes, with a full-screen call notification | yes | | macOS | yes | yes | yes | yes | | Windows | yes | yes | yes | while the app runs or sits in the tray | | Linux | yes | no | see below | no | | Browser | yes | yes | yes | yes, while the browser runs | ### Platform notes [#platform-notes] - **iPhone.** New messages are fetched in the background on a push notification, so a chat opens with them even when the app was closed. You can share into Comon from any app through the system share sheet. - **Android.** An incoming call shows full screen, even on a locked phone. Sharing and importing the phone book work. - **Windows.** Closing the window sends Comon to the tray. A click on the tray icon opens the window, a right click opens a menu with "Open Comon" and "Exit". After Exit, notifications stop. - **Linux.** Messaging, photos and files work. Playing and recording voice messages, round videos and video, the camera and system notifications are not there yet. The Linux build has calls, but without a camera, and they have not been checked on devices yet. - **Browser.** The web app opens at the federation's address with `/app` at the end, if the owner has turned it on. Comon can be open in one tab only. On iPhone, notifications work only after adding the web app to the Home Screen. Screen sharing works in desktop browsers. ## Languages [#languages] The interface is in Russian and English. Change it in **Settings › Language**. ## Getting the app [#getting-the-app] Links to the builds for every platform are on [comon.chat/download](https://comon.chat/en/download). - **iPhone, iPad and macOS**: through TestFlight, by invitation. - **Android**: an APK file. - **Windows**: an installer that needs no administrator rights. - **Linux**: an AppImage file. - **Browser**: at the federation's address with `/app` at the end. The app is not in the App Store or Google Play yet. You can also build it yourself, see [Building from source](../develop/build.mdx). ## Updates [#updates] ### When a federation asks for an update [#when-a-federation-asks-for-an-update] Each federation tells the app which versions it supports. - If the app is too old, the chat list is replaced by «Update the app» with a link to the new version. Chats already loaded can still be opened for reading. - If a recommended version is out, a banner above the chat list suggests updating. You can close it. ### Windows, Linux and macOS from the installer [#windows-linux-and-macos-from-the-installer] A version installed by the installer updates itself: 1. At start and then every hour, the app checks for a new version and downloads it in the background. 2. When the download is ready, «Version X is ready to install · Update» shows above the chat list. 3. «Update» restarts the app into the new version. During a call, the restart waits for the call to end. An update is never installed without your tap. A version downloaded but not installed is offered again at the next start. Chats and settings are kept apart from the program and survive both updates and uninstalling. ### Other platforms [#other-platforms] iPhone, iPad and macOS builds from TestFlight update through TestFlight. An Android APK is downloaded again from the banner's link. The web app is always current. # Federations and accounts (/docs/en/guide/federations) ## What a federation is [#what-a-federation-is] A federation is a Comon server together with its users, chats and rules. Its owner runs it: a company for its staff, a community for its members or one person for friends. The owner decides who may sign in, which rules apply and where the data physically lives. Despite the name, every federation is a separate, closed world. You cannot write to a person in another federation, and there are no chats spanning federations. This way one organization's data never reaches someone else's server. ## Signing in [#signing-in] ### Get the address [#get-the-address] The federation's owner gives you its address, for example `chat.example.org`. ### Add the federation [#add-the-federation] On the app's first screen or in **Settings › Federations**, tap «Add federation» and enter the address. The app first checks that a Comon server really answers there and remembers its key. The server cannot be swapped unnoticed afterwards. ### Sign in [#sign-in] The app opens your organization's sign-in page: a company login or an account the owner gave you. If the federation requires a cloud password, the app asks you to set one. ### Complete your profile [#complete-your-profile] On the first sign-in, enter your name. You can choose an @name right away or add it later. If the federation has rules, you accept them. When the owner changes the rules, everyone accepts them again. ## Several federations in one app [#several-federations-in-one-app] If you belong to several federations, you do not need a second app. Add each one in **Settings › Federations**; you have a separate profile in each. «All chats» gathers the chats of every federation, «All federation chats» those of one. If one federation is unavailable, the others work as usual. Each federation in **Settings › Federations** has these actions: | Action | What happens | |---|---| | Disconnect | The connection is paused. Loaded chats, drafts and the outgoing queue stay on the device. The pause survives a restart. | | Connect | The connection resumes and the outgoing queue is sent. | | Sign in again | Signs in to the same federation and profile when the session has ended. | | Log out | Removes this federation's data and sign-in key from the device. Your messages stay on the server, and you can come back by signing in again. Unsent messages are lost. | ## Cloud password [#cloud-password] Comon's cloud password is a second sign-in step, asked for when you sign in on a new device. Set, change or turn it off in **Settings › Privacy › Cloud password**. - The federation's owner decides whether it is required. If it is, you cannot turn it off. - It is 10 to 128 characters long. - A forgotten password cannot be recovered by yourself; the federation's owner resets it. ## Devices [#devices] **Settings › Devices** lists the devices you are signed in on. You can end any other session or all of them at once. ## When a federation moves [#when-a-federation-moves] A federation is identified by its ID and key, not its domain. If the owner moves it to a new address, the app switches your account at start once it has made sure the same federation with the same key answers there. Older app versions keep working through the old address while the owner keeps it as an alias. ## Deleting your account [#deleting-your-account] Delete your account in **Settings › Privacy**. What happens: - your messages in direct chats, groups and rooms are deleted for everyone; - your avatar is removed, the profile is marked deleted and your @username becomes free; - every device is signed out and your bots are deleted; - you leave your groups, channels and communities. Where you were the owner, ownership goes to the longest-standing member; - signing in again the same way creates a new, empty profile. The federation's owner cannot delete their account before handing the federation over to someone else. # Glossary (/docs/en/guide/glossary) ## People and the server [#people-and-the-server] **Federation.** A Comon server together with its users, chats and rules. Federations are not connected to each other. See [Federations and accounts](./federations.mdx). **Federation owner.** The person who runs the federation and manages it from the app: **Settings › Manage Federation**. There is one owner, who can hand the federation over. **Federation role.** A set of rights inside the federation: moderating, reviewing reports, creating communities and bots, how many new direct chats a day one may start. Everyone holds the built-in role `@everyone`. **Profile.** Your account in one federation: name, @username, avatar. Each federation has its own. **@username.** A unique name in the federation, 3 to 32 characters: a letter, then letters, digits, `_` or `-`. People, bots and public chats share one namespace. **Cloud password.** The second sign-in step on a new device, on top of the organization's sign-in. **Service chat.** The chat with the federation's own profile: moderators' answers and notices from the server come through it. ## Chats [#chats] **Direct chat.** A conversation between two people, or a person and a bot. **Group.** A shared chat of up to 256 members. Any member can add people; only the owner renames the group, removes members and transfers ownership. **Channel.** A feed of posts: the owner and publishers write, everyone else reads and reacts. **Community.** A space with rooms, categories and roles of its own, like a Discord server. **Room.** A chat inside a community: text, announcements or voice. **Voice room.** A room with a call that is always there: people come and go without ringing anyone, and it has a text chat of its own. **Public chat.** A group, channel or community with a @name: found by search and opened by the link `/u/`. **Invite.** A link `/join/` to join a chat or community. It can have a lifetime and a limit of uses. ## Messages [#messages] **Scheduled message.** A message the server sends at a set time, repeating ones included. **Ephemeral message.** A bot's answer that one person sees. It never enters the chat's history and lives for up to 24 hours. **Round video.** A short square video of up to 60 seconds, shown as a circle in the chat. ## Calls [#calls] **Link call.** A conference joined through the link `/call/`, guests without an account included. **Guest.** Someone without an account in the federation who joined a call by its link. A guest sees only that call and its chat. **Waiting room.** Where guests wait until the call's host lets them in. **SFU.** The server that forwards video and sound in group calls, so that no participant has to send their stream to everyone else. **TURN.** A relay server for calls when devices cannot connect directly. ## Bots [#bots] **Bot.** A profile without devices, for which a program acts through the HTTP Bot API. **Personal bot.** A bot a person connected to their direct chats: it reads the chats they chose and may answer on their behalf. **Webhook.** An address the server posts a bot's new events to by itself. ## Operations [#operations] **Client level.** The protocol version number of an app. The federation sets a minimum and a recommended level, from which the app knows it is time to update. **Gateway.** An additional server process that holds client connections and passes them to the primary server. Used for scaling. **Push relay.** The service that delivers push notifications through Apple, Google and browsers without seeing message text. **Module.** A separate part of the server with its own database schema that can be turned on and off. # What is Comon (/docs/en/guide) Comon is a messenger with chats, channels, communities, calls and bots and no shared server. Each organization runs its own server and decides who is in it, which rules apply and where the data lives. ## What it is made of [#what-it-is-made-of] One app for iPhone, Android, macOS, Windows, Linux and the browser. Opened chats are kept on the device and open without a network; what you write offline is sent when the connection returns. Comon's name for a server together with its users, chats and rules. Its owner runs it: a company, a community or one person. Account passwords are kept not by Comon but by your organization's sign-in service (OIDC), such as a company login. Comon adds its own cloud password and a device key. More on [Federations and accounts](./federations.mdx). ## What it can do [#what-it-can-do] - **Messaging.** Direct chats, groups of up to 256 people, channels, communities with text and voice rooms. Formatting, replies and quotes, forwarding, editing within 48 hours, scheduled messages, reactions, stickers and emoji sets. - **Media.** Photos, videos, files up to 1 GB, voice messages and round videos, transcription of voice messages, link previews. - **Calls.** Direct and group calls with up to 32 participants, voice rooms in communities, conferences by link with guests and a waiting room, screen sharing. - **Bots.** A Telegram-style HTTP Bot API: commands with options, buttons, webhooks, ephemeral messages, personal bots. - **Moderation.** Federation roles, reports, word and domain filters, a log of moderator actions. The full list with rules and limits is in [Features](../features/index.mdx). ## Who it is for [#who-it-is-for] - Teams and companies that want their own messenger with the data on their own server. - Communities that want to decide themselves whom to let in and how to moderate. - Anyone invited to a federation: install the app and enter its address. ## Where to begin [#where-to-begin] Signing in to a federation, several federations in one app, the cloud password and devices. From a clean Linux machine to the first sign-in in the app. # Comon documentation (/docs/en) Comon is a messenger whose server an organization runs itself. Documentation for the app, your own server with every setting, and the bot API. } title="Getting started" href="/en/guide"> What Comon is, federations and accounts, apps and platforms, a glossary. } title="Features" href="/en/features"> Messages, media, chats, calls, people, security. Who can do what, the limits, and what the other person sees. } title="Self-hosting" href="/en/selfhost"> Requirements, quick start, the reference of every server setting, calls, push, backups, upgrades and troubleshooting. } title="Bots" href="/en/bots"> Creating a bot, the HTTP Bot API, commands, buttons, webhooks, personal bots and bots in communities. } title="Developers" href="/en/develop"> Building from source, the repository layout, the protocol and how to contribute. } title="Changelog" href="/en/develop/changelog"> What is new in each release and what a server owner does when upgrading. ## Popular pages [#popular-pages] - [Server quick start](./selfhost/quick-start.mdx) - [Server settings reference](./selfhost/reference.mdx) - [Calls, SFU and TURN](./selfhost/calls.mdx) - [Backups and restore](./selfhost/backups.mdx) - [Upgrading to a new version](./selfhost/upgrading.mdx) - [A complete bot in Python and Node.js](./bots/examples.mdx) ## For language models [#for-language-models] Every page is available as Markdown: the «Copy Markdown» button under the title. The whole site as a list is at [`/docs/llms.txt`](/llms.txt), in full at [`/docs/llms-full.txt`](/llms-full.txt). # App versions (/docs/en/selfhost/app-updates) ## The app's level [#the-apps-level] Every app build has a **level**, an integer that grows when the app learns something new in the protocol. On sign-in and every connection the app reports its level, platform and version, and the server answers with its policy: | Option | Default | Meaning | |---|---|---| | `--minimum-client-level` | `29` | The oldest level the server serves. Cannot be set below 29. | | `--recommended-client-level` | the minimum | The level the app suggests updating to. | | `--client-update-url` | none | Where to send people for a new version, once per platform. | ``` --client-update-url=android=https://example.org/comon.apk --client-update-url=ios=https://apps.apple.com/app/... --client-update-url=windows=https://example.org/ComonSetup.exe ``` Platforms: `android`, `ios`, `macos`, `windows`, `linux`, `web`. HTTPS addresses only. Link pages offer the same links as the "download" button ([web client and links](./web.mdx#link-pages)). ## What people see [#what-people-see] - **Level below the minimum.** Instead of this federation's chat list, the app shows "Update the app" with an "Update" button that opens the link for its platform. Without a link, the app suggests installing a newer version from where it came from. Chats already saved on the device can be read ("Show saved chats"). Other federations work as usual. - **Level below the recommended one.** "A new version of the app is available" appears above the chat list, with "Update" and "Later". Everything keeps working. - **A message this version cannot show.** In its place: "Update the app to read this message". The minimum level goes up when old builds are harmful or a new server version cannot work with them. Such server versions are marked in the [changelog](../develop/changelog.mdx), and the new server raises its default itself. ## Updates on computers [#updates-on-computers] Windows, Linux and macOS apps installed by the installer update themselves from the project's release feed (`https://comon.chat/updates/`), independently of any federation: - they check the feed at start and every hour and download a new version in the background; - they show "Version X is ready to install" with an "Update" button that restarts the app into the new version; - during a call they wait for it to end: "The app will restart to update when the call ends"; - they never install an update without the person's consent. If your federation requires or recommends a new version and the app has already downloaded it, the "Update" button restarts into the new version instead of opening your link. For official desktop builds, `--client-update-url` is therefore only a fallback. Phones update through the app stores. The web client is always the latest: you update it by rebuilding the [web client](./web.mdx#web-client). # Backups (/docs/en/selfhost/backups) ## What to keep [#what-to-keep] A federation is **the database and the volumes together**. Apart they are useless: | What | Why you cannot do without it | |---|---| | The PostgreSQL database | Everything except media bytes: profiles, chats, messages, settings. | | The `federation` volume | The Noise key (without it devices cannot connect) and the media files the database refers to. | | The `caddy` volume | Certificates and, with `tls internal`, Caddy's own certificate authority. | | The state directory | `stack.env` with passwords, the federation ID, push keys, TURN and SFU secrets, Compose files. | | The APNs `.p8` key | Not in the backup: keep it separately. | A database started on another or empty media volume refuses to start with `MediaVolumeMismatch`. ## Taking a backup [#taking-a-backup] ```sh python3 tools/mvp-stack.py backup --backup /absolute/path/backup-2026-10-26 ``` The command **stops the whole stack** for a while so the PostgreSQL snapshot is consistent, archives every volume and the configuration with SHA-256 sums, and starts the stack again, even if archiving failed. The backup directory must be new. The archive is **not encrypted** and not signed: it holds private keys and passwords. Keep it like passwords, encrypt it before it leaves the machine, and restore only your own backups. The stack has no schedule: run the command from cron or a systemd timer at quiet hours. The downtime lasts while the volumes are archived and grows with the amount of media. ## Restoring [#restoring] On a machine without `comon-mvp` volumes, from the same repository version: ```sh python3 tools/mvp-stack.py restore --state .local/restored --backup /absolute/path/backup-2026-10-26 python3 tools/mvp-stack.py up --state .local/restored python3 tools/mvp-stack.py check --state .local/restored ``` `restore` checks the sums, needs a new state directory and **refuses when the volumes already exist**: it never overwrites live data. Do not delete a running stack's volumes to try a restore. Keep the same domain and the same image versions. To rehearse a restore on the same machine, add `--project comon-mvp-restored` to every command of the restored stack and stop the original before starting the copy: two diverging instances of one federation are not redundancy. ### First start from a backup [#first-start-from-a-backup] A restored federation is older than what the apps, relays and the outside world have already seen. So `restore` adds `--restored-backup=` to the server, and before serving, the first start: - **checks media**: if files of messages and avatars are missing, the server does not start and lists them in the log (`restore_missing_media`). Restore the media volume taken together with the database, or start the server with `--accept-missing-media`; - **renews push keys**: nothing old goes out, and devices register again; - **starts history from a new generation**: apps read their chats again instead of skipping what they saw before the loss, and keep for their people the sends made after the backup; - **holds outbound work**: scheduled messages are not sent (their authors can edit or delete them), bot webhooks are not called. `/ready` shows `"outbound": "held"`. Later starts with the same name change nothing, so the option may stay. Once you have checked that everything is fine, release outbound work (with the server stopped): ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo restores dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo release-outbound dc start federation ``` `dc` is the function from [operations](./operations.mdx#compose-commands-by-hand). If push was on, it is **off** after a restore: old revocations and preview keys need reconciling before devices are admitted again ([push](./push.mdx#relay-backup)). ### Checking after a restore [#checking-after-a-restore] 1. A device already signed in connects and sees the earlier messages. 2. Signing in from a second device works. 3. A new message reaches both. # Bots and bridges (/docs/en/selfhost/bots-and-bridges) ## Bots [#bots] People create bots themselves in the app, and the bots' programs run anywhere and talk to the server over the [HTTP Bot API](../bots/index.mdx) (`https:///bot/v1/`). No separate bot service is needed. ### Who may create bots [#who-may-create-bots] Without settings, everyone may create up to 20 bots. Otherwise a JSON file in `--bot-config` sets the policy: ```json { "everyone": { "canCreate": false, "maximumBots": 0 }, "roles": { "developers": { "canCreate": true, "maximumBots": 50 } }, "profileRoles": { "": ["developers"] } } ``` | Field | Meaning | |---|---| | `everyone` | Everyone's rights: `canCreate` and `maximumBots`. | | `roles` | Named sets of the same rights. | | `profileRoles` | Which roles which profiles have. | A person gets the most generous of the rights of `everyone` and their roles. These roles exist only in the bot settings and are unrelated to the federation roles of moderation. ### The demo bot [#the-demo-bot] The server runs `@demo_bot` itself, which shows every bot capability: buttons, commands with suggestions, ephemeral messages. Its owner is the federation's service profile. To turn it off: `--no-demo-bot`. The demo bot also does not start when someone already holds the name `demo_bot`. ### Webhooks [#webhooks] A bot gets updates either by requesting them from the server or by webhook, where the server sends them to the bot's address. By default webhooks to private addresses (the local network, `localhost`) are forbidden, so a bot cannot be used to reach internal services. For development on your own machine the `--bot-private-webhooks` flag allows them. Do not turn it on for a public server. ## Bridges: Telegram channels [#bridges-telegram-channels] The bridge mirrors public Telegram channels into the federation: a person searches for a Telegram channel by link or name, and a mirrored channel with new posts appears in Comon, marked "Mirrored from Telegram". ```sh python3 tools/mvp-stack.py enable-bridge python3 tools/mvp-stack.py up ``` The command writes the federation's policy `bridges.json`, the bridge process settings `bridge.json` (with one shared token) and adds the `bridge` service. The bridge and the server talk only inside the Docker network. Change the policy in `bridges.json`, then run `up`. ### Reading through a service account [#reading-through-a-service-account] Without an account the bridge reads the channels' web preview: only the latest ~20 posts are visible, and edits and deletions arrive late. With a service account the bridge reads Telegram through TDLib and sees edits and deletions at once. 1. On my.telegram.org, sign in with the service account's number (not a personal one) and create an application. 2. Put its keys into `stack.env` and run `up`: ```sh TELEGRAM_API_ID= TELEGRAM_API_HASH= ``` 3. Sign the account in once: the command asks for the number, the code from Telegram and the two-step password, if there is one. ```sh python3 tools/mvp-stack.py bridge-login ``` The session lives in the `bridge-tdlib` volume. One account joins about 500 channels; past that, mirrors get new posts but not edits. ### Policy (`bridges.json`) [#policy-bridgesjson] ```json { "networks": { "telegram": { "title": "Telegram", "usernamePrefix": "telegram_", "linkHosts": ["t.me", "telegram.me"], "url": "http://bridge:8090", "token": "<16+ characters>", "mediaBudgetBytes": 10737418240, "maximumPortals": 1000, "allow": [], "deny": [], "keepPolledMinutes": 60 } }, "everyone": { "canMirror": true, "mirrorsPerDay": 10 }, "roles": { "moderator": { "canTakeDown": true } }, "profileRoles": { "": ["moderator"] } } ``` | Field | Meaning | |---|---| | `mediaBudgetBytes` | How much media all mirrors of the network keep. Past the budget, media stays a link. 10 GiB by default. | | `maximumPortals` | How many mirrored channels there may be, stopped ones included. 1000 by default. | | `allow`, `deny` | Channel names in lowercase, without `@`. An empty `allow` allows all. | | `everyone`, `roles`, `profileRoles` | `canMirror` and `mirrorsPerDay`: who may mirror and how many new channels a day; `canTakeDown`: who may stop mirrors. | ### Stopping a mirror [#stopping-a-mirror] A person with `canTakeDown` opens the mirrored channel's page and chooses "Stop mirroring". Posts and media are deleted for everyone, and the channel can never be mirrored again. To keep a channel from being mirrored in the first place, add it to `deny`. ## Importing stickers from Telegram [#importing-stickers-from-telegram] People can import Telegram sticker sets by link. For that the federation needs a Telegram bot of its own: create one with @BotFather and give the server a file with its token, `--telegram-bot-token-file=`. Without it importing is off. The limit is 10 imports a day per person ([stickers](../features/stickers.mdx)). # Calls, SFU and TURN (/docs/en/selfhost/calls) Calls run over WebRTC. The federation server only connects participants and hands out settings; audio and video bypass it: - a **direct call** goes straight between devices, and through **TURN** (coturn) when they cannot see each other; - a **group call, voice room or link call** goes through the **SFU**, the federation's media server (`backend/comon_sfu`). The SFU forwards streams without decoding them. The ready-made stack runs both services and writes their settings itself. Without TURN, devices behind strict NAT do not connect; without the SFU, a group call does not start. ## Ports [#ports] | Port | Protocol | Service | |---|---|---| | 3478 | TCP and UDP | TURN | | 49160–49200 | UDP | TURN: relayed traffic | | 7882 | UDP | SFU: all group call media on one port | | 5349 | TCP | TURN over TLS, if enabled | Open them in the machine's firewall. If the server is behind a router, forward **the same external ports** to the server's LAN address without renumbering them. An HTTPS proxy does not carry this traffic. The SFU's control API (port 7880) is reachable only inside the Docker network. Do not publish it. ## Federation server settings [#federation-server-settings] The `--call-config` option points to a JSON file: ```json { "stun_urls": ["stun:chat.example.org:3478"], "turn_urls": [ "turn:chat.example.org:3478?transport=udp", "turn:chat.example.org:3478?transport=tcp" ], "turn_secret_file": "/run/secrets/turn-secret", "sfu_url": "http://sfu:7880", "sfu_secret_file": "/run/secrets/sfu-secret" } ``` | Field | Meaning | |---|---| | `stun_urls`, `turn_urls` | Servers the devices receive. Up to 8 addresses. | | `turn_secret_file` | coturn's shared secret (`static-auth-secret`). From it the server issues devices temporary TURN credentials valid for 4 hours. | | `sfu_url` | The address of the SFU's control API inside the network. | | `sfu_secret_file` | The secret shared by the server and the SFU. | Without `--call-config` devices get neither STUN nor TURN; without `sfu_url` group calls answer "not supported". ## TURN (coturn) [#turn-coturn] The ready-made stack writes `turnserver.conf` with the shared secret, ports 49160–49200 and `external-ip`, the public address coturn tells devices. By default it is the address the domain resolves to. TURN runs in the SFU's network namespace (`network_mode: service:sfu`), so devices that come through TURN can reach the SFU's media. If you recreate the SFU, recreate TURN too. ## SFU [#sfu] | Option | Variable | Default | Meaning | |---|---|---|---| | `-listen` | `COMON_SFU_LISTEN` | `:7880` | Control API address, internal network only | | `-secret-file` | `COMON_SFU_SECRET_FILE` | required | File with the shared secret | | `-udp-port` | `COMON_SFU_UDP_PORT` | `7882` | The single UDP port for all media | | `-public-ips` | `COMON_SFU_PUBLIC_IPS` | none | Comma-separated addresses the SFU tells devices | | `-log-level` | `COMON_SFU_LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` | In the ready-made stack the variables live in `sfu.env`. The SFU uses neither STUN nor TURN: it has its own public address. Room state is kept in memory: after an SFU restart, running group calls reconnect by themselves, spread over up to three seconds. If UDP 7882 is taken, set another port in `COMON_SFU_UDP_PORT` in `sfu.env` and publish the same one for the `sfu` service in `compose.yaml`. ## Server behind NAT [#server-behind-nat] - `external-ip` in `turnserver.conf` and `COMON_SFU_PUBLIC_IPS` in `sfu.env` must name the **public IPv4** reachable from the internet. If the domain resolves to a private address inside your network, enter the public one by hand. - When the public address changes, update both values and recreate `sfu` and `turn`. - **Devices on the same network as the server** reach the public address only if the router can send such traffic back inside (hairpin NAT). Many home routers cannot, and then group calls from the home network go only through TURN or not at all. Add the server's LAN address to `COMON_SFU_PUBLIC_IPS` after a comma (`,`): the SFU offers both, and a device at home takes the one it can reach. ## TURN over TLS [#turn-over-tls] Some browsers and networks let only TLS out. They need `turns:`. Get a certificate for the federation's domain (PEM: chain and key) and run: ```sh python3 tools/mvp-stack.py enable-turn-tls \ --turn-tls-cert /path/fullchain.pem --turn-tls-key /path/privkey.pem python3 tools/mvp-stack.py up ``` The command copies the files to `turn-tls/` in the state, turns on TLS in coturn on port 5349 (or `--turn-tls-port`) and adds `turns::?transport=tcp` to `calls.json`. The plain 3478 ports stay. coturn reads the certificate only at start: after renewing it, run `enable-turn-tls` with the new files and restart `turn`. Caddy's certificate lives in its storage; you can export it or issue a separate one. Port 443 gets through the strictest networks, but the proxy already holds it. That needs a separate IP for coturn or a separate TURN name that the proxy passes through by SNI without terminating. The ready-made stack does not set that up. ## Testing [#testing] Test from outside your network, from a phone on a mobile network: running containers and an open TCP port do not prove that UDP gets through. 1. A direct call between a phone on a mobile network and a computer on another network. 2. A group call with three participants, including a phone on the server's home Wi-Fi. 3. If `turns:` is on, a call from a browser on a network where UDP is blocked. The server writes every call event to its log on a `calls` line: call start and end with a reason (`cause=`), participants joining and leaving (`reason=`), SFU commands and their errors. ## Limits [#limits] | What | How many | |---|---| | Group call participants | 32 | | Ringing timeout | 45 seconds | | Return after a drop | 20 seconds | | Calls at once per person | 8 | | TURN credentials | 4 hours | | Call links per person | 50 | | Link call guests across the federation | 1024 | Link calls and guests are described in [Features](../features/call-links.mdx); guests can be allowed or forbidden in the [federation settings](./federation-settings.mdx). # External accounts (/docs/en/selfhost/external-accounts) People can connect their Google or Yandex account, or any mail or calendar server with an app password, in Settings → Accounts. The federation server keeps the connection and works with the account on its own, so the calendar stays up to date even when all of a person's devices are off. Provider tokens never reach the devices; an app password is sent once, when connecting. On the server, tokens and passwords are stored encrypted with your key. Without this setting nobody can connect an account. ## Create a Google OAuth client [#create-a-google-oauth-client] 1. In [Google Cloud Console](https://console.cloud.google.com/) create a project and enable the Google Calendar API. 2. Configure the OAuth consent screen: external, the app name, a support address and your domain as an authorized domain. 3. Add the scopes `openid`, `email` and `https://www.googleapis.com/auth/calendar.readonly`, and for mail also `https://mail.google.com/`. Calendar access is a sensitive scope and mail access a restricted one: until Google verifies your app, only the test users you list on the consent screen can connect (up to 100). 4. Create an OAuth client of type "Web application" with the redirect URI `https:///accounts/oauth/callback`. 5. Save the client secret to a file only the server can read. ## Create a Yandex OAuth app [#create-a-yandex-oauth-app] 1. At [oauth.yandex.ru](https://oauth.yandex.ru) create an app of type "Web services" with the redirect URI `https:///accounts/oauth/callback`. 2. Give it the access `login:info` and `login:email`, and for mail also `mail:imap_full` and `mail:smtp`. 3. Save the client secret to a file only the server can read. ## Connecting with a password [#connecting-with-a-password] This needs nothing from you: once the file is given, people can connect any IMAP/SMTP or CalDAV server with an app password. The server checks the password before it keeps it, and connects only to addresses on the public internet. If your people's mail server is on your own network, add `"server_accounts": {"private_networks": true}`; `"server_accounts": {"enabled": false}` turns password accounts off. ## Create an encryption key [#create-an-encryption-key] ```sh head -c 32 /dev/urandom | base64 > external-accounts-current.key chmod 600 external-accounts-current.key ``` Keep the key with your database backups: without it, connected accounts cannot be read and people will have to connect them again. ## Turn it on [#turn-it-on] Write a configuration file next to the keys: ```json { "secret_keys": ["external-accounts-current.key"], "google": { "client_id": "1234567890-abc.apps.googleusercontent.com", "client_secret_file": "google-client.secret" }, "yandex": { "client_id": "0123456789abcdef0123456789abcdef", "client_secret_file": "yandex-client.secret" } } ``` and start the server with `--external-accounts=` ([all options](./reference.mdx)). With several server processes, every one needs the same file and keys. ## Change the key [#change-the-key] Put the new key first in `secret_keys` and keep the old one after it. Tokens move to the new key as they are refreshed. Remove the old key once every account has synchronized since; an account still sealed with a removed key asks its owner to connect it again. ## Troubleshooting [#troubleshooting] | What you see | What to do | |---|---| | Google says "Access blocked" or "app not verified" | Add the person as a test user on the consent screen, or get the app verified. | | Google says the redirect URI does not match | The redirect URI of the OAuth client must be exactly `https:///accounts/oauth/callback`. | | An account shows "Authorize again" | Google refused the saved access: the password changed, access was removed in the Google account, or the test user was removed. The person authorizes it again in Settings → Accounts. | | Server log `external_account_sync_failed` | Google did not answer or answered an error; the server retries on its own, at least once an hour. | # Federation settings (/docs/en/selfhost/federation-settings) Most federation settings change not in files but in the app itself: **Settings › Manage Federation**. The section is visible to people with "Open the federation panel"; changing settings takes "Manage the federation" (the owner and administrators have it). Settings live in the database and are part of the [backup](./backups.mdx). The section has five pages: "Reports", "People", "Roles", "Audit log" and "Rules and policies". Roles, reports and moderator actions are described in [Moderation](../features/moderation.mdx); this page covers "Rules and policies". ## Federation [#federation] | Setting | What it changes | |---|---| | Name | What the federation is called in the apps, in the federation document and on the public pages. Up to 64 characters. | | Support contact | Email, link or @username. Shown on the public pages and in the federation's details. | ## Rules [#rules] "Rules in Russian" and "Rules in English" are the text people accept on their first sign-in. When the rules change they get a new version, and everyone accepts them again. The rules are visible in the app and on the `/rules` page. ## Filter [#filter] "Words and phrases" and "Domains", one per line, up to 500 of each. Messages containing them are not sent. More in [Moderation](../features/moderation.mdx#filters). ## Policies [#policies] | Setting | Default | Meaning | |---|---|---| | Report reasons | built-in list | The tree of reasons a person picks in a report. Up to 50 reasons and three levels. | | Guests in calls | allowed | Whether people without an account may join [link calls](../features/call-links.mdx). | | New direct chats per day | 50 | How many direct chats a day a person may start with people who do not have them as a contact. Empty means no limit. A role may give more. | | Speech recognition | off | The speech recognizer ([voice transcription](./transcription.mdx)). | | Speech recognition, minutes per day | 60 | For everyone; a role may allow more. | ## Contacts and phone numbers [#contacts-and-phone-numbers] | Setting | Options | |---|---| | Contacts | "All members" (default): everyone sees every member in the Contacts tab. "Address book": everyone has their own contacts and finds others by name or @username. "Hidden": others are found only by exact @username, link or card, and phone numbers find no one. | | Phone numbers | "Off", "Optional", "Required" ([phone numbers](./sign-in.mdx#phone-numbers)). | | People added to groups per day | How many people who do not have the adder as a contact may be added to groups and channels a day. Empty means 50. A role may allow more. | Until a contacts mode is chosen in the app, the server takes it from `--contacts-mode`. How it looks to people: [people and contacts](../features/people.mdx). ## Federation roles [#federation-roles] Built-in roles: owner, administrator, moderator, support, and the role everyone has (@everyone), which sets default rights and limits. You can create your own roles, up to 50 including the built-in ones. Rights and limits of roles in detail: [Moderation](../features/moderation.mdx#federation-roles). ## Owner [#owner] The first person to finish sign-up in a new federation becomes the owner. If there is no owner, the server makes the profile with the earliest completed sign-in the owner at start. The owner can do everything, and only the owner can transfer ownership: **Manage Federation › People**, the person's card, "Transfer ownership". The previous owner keeps the administrator role. The owner cannot delete their account before transferring ownership. If the owner has lost access, ownership is transferred with an offline command while the server is stopped ([operations](./operations.mdx#offline-commands)): ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ --federation-id= list dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ --federation-id= grant-owner --profile= dc start federation ``` The federation ID is `COMON_FEDERATION_ID` in `stack.env`. `list` shows the roles and profile IDs; `set-roles --profile= --roles=admin,moderator` replaces a profile's roles (built-in: `admin`, `moderator`, `support`). Unlike the app, the offline command can raise anyone to any role. ## Public pages [#public-pages] Without sign-in the server answers on three addresses: | Address | What is there | |---|---| | `/rules` | The federation's rules | | `/child-safety` | Child safety standards and the contact | | `/delete-account` | How to delete an account and what is kept | The language comes from `?lang=ru` or `?lang=en`, otherwise from the browser's header. The pages use the name and support contact from the settings, so fill in both before publishing your own app build in the stores: the stores require such pages. The moderators' audit log and the material of closed reports are kept for a year and deleted when the server starts. # How the server works (/docs/en/selfhost/how-it-works) ## Request path [#request-path] ``` app ──HTTPS / WSS──▶ proxy (Caddy) ──┬─ /identity/* ──▶ Keycloak ├─ /app/* ──▶ web client ├─ /push/* ──▶ push relay └─ everything else ──▶ federation server ──▶ PostgreSQL │ └──────▶ data directory ├── SFU (HTTP control inside Docker) devices ──UDP──▶ TURN, SFU (call ports, bypassing the proxy) ``` The proxy terminates TLS and passes requests to the server over plain HTTP inside Docker (the `--behind-tls-proxy` option). Calls bypass the proxy: devices reach TURN and the SFU directly over UDP ([calls](./calls.mdx)). ## The app's connection [#the-apps-connection] The app opens the WebSocket `wss:///comon` and, inside TLS, sets up a Noise session with the server's key. Every request of the app and every live update goes over this connection. Before the first connection the app reads the federation document: ``` GET https:///.well-known/comon-federation ``` ```json { "version": 1, "federation_id": "comon-1a2b3c4d5e6f", "endpoint": "wss://chat.example.org/comon", "server_public_key": "", "identity_issuer": "https://chat.example.org/identity/realms/comon", "display_name": "Our federation" } ``` The app remembers the server's key and stops connecting if it ever changes. ## The server's HTTP paths [#the-servers-http-paths] | Path | What is there | |---|---| | `/comon` | The apps' WebSocket | | `/.well-known/comon-federation` | The federation document; answers any site (CORS) so web clients can find other federations | | `/auth/oidc/start`, `/auth/oidc/callback` | OIDC sign-in | | `/u/`, `/join/`, `/call/` | Link pages for browsers ([web client and links](./web.mdx#link-pages)) | | `/rules`, `/child-safety`, `/delete-account` | The federation's public pages ([federation settings](./federation-settings.mdx#public-pages)) | | `/.well-known/apple-app-site-association`, `/.well-known/assetlinks.json` | Opening links in the apps, when `--apple-app-id` or `--android-app` is set | | `/bot/v1/` | [HTTP Bot API](../bots/index.mdx) | | `/health` | The process is alive; does not touch the database | | `/ready` | Ready to serve: the database answers and its schema matches ([operations](./operations.mdx#health-checks)) | ## Where data lives [#where-data-lives] | Where | What | |---|---| | PostgreSQL 17, database `comon` | Everything except media bytes: the `federation`, `access`, `bots` and `messaging` schemas, and a `module_` schema per module | | Data directory (`--data`, the `federation` volume) | The Noise key `noise-server-key` and media in `media/` (or `--media-dir`) | | The `postgres` volume | PostgreSQL's files. In the ready-made stack Keycloak's database lives there too | | The `caddy` volume | Caddy's certificates | | The state directory `.local/mvp` | Configuration, passwords, keys, Compose files | The database and the media belong together: media rows in the database refer to files on the volume, and the `comon-media-volume.json` file in the media directory names the volume the database is bound to. A server started with its database on another or empty volume refuses to start with `MediaVolumeMismatch`. The server never changes the database schema itself. A separate `migrate_database` command applies it, and the ready-made stack runs it before the server ([upgrading](./upgrading.mdx)). ## One writer [#one-writer] The server takes a writer lock in the database: a second server on the same database will not start while the first one runs. The offline commands (`federation_admin`, `reset_profile_password`, `install_system_stickers`) take the same lock, so stop the server before running them ([operations](./operations.mdx#offline-commands)). To spread connections over several machines you put gateways in front of the server, but still only one process may write to the database ([scaling](./scaling.mdx)). ## The federation's identity [#the-federations-identity] A federation is defined by its **ID** (`--federation-id`, a random `comon-…` in the ready-made stack) and the **Noise key** in its data directory, not by its domain. Apps remember the key on their first connection. - Lose the key and devices can no longer connect. The server refuses to start without a key when the database has authorized devices, so it never issues a new key silently. - Keep the ID and the key in your backups ([backups](./backups.mdx)). - The domain can change as long as the ID and the key stay ([moving](./upgrading.mdx#moving-to-another-domain)). ## Modules [#modules] Parts of the server with their own storage plug in as modules: each has its own database schema and background jobs. The `--modules` option limits which modules a process serves. The current build has no modules with storage of their own; speech recognition is part of the core. # Self-hosting (/docs/en/selfhost) A federation is your organization's Comon server, with its own people, chats and rules. Comon apps connect to any federation by its address, so running your own server needs no app build of your own: people install the regular Comon app and add your federation. } title="Quick start" href="/en/selfhost/quick-start"> From a clean Linux machine with a domain to the first sign-in from the app. } title="Server options" href="/en/selfhost/reference"> Every server and gateway option: its default and what it changes. } title="Calls" href="/en/selfhost/calls"> TURN, the media server for group calls, ports and NAT. } title="Push notifications" href="/en/selfhost/push"> How notifications reach phones and browsers, and what that takes. } title="Federation settings" href="/en/selfhost/federation-settings"> Roles, rules, filters, reports, guests and limits, right in the app. } title="Backups" href="/en/selfhost/backups"> How to take a backup and restore the federation on another machine. ## What it consists of [#what-it-consists-of] | Service | What it does | Required | |---|---|---| | Federation server | Accounts, chats, messages, media, call signaling, bots, link pages | yes | | PostgreSQL 17 | All federation data except media files | yes | | Sign-in service (OIDC) | Checks who signs in. Keycloak in the ready-made stack; you can plug in your own | yes | | HTTPS proxy | TLS and routing. Caddy with a Let's Encrypt certificate in the ready-made stack | yes | | TURN (coturn) | Helps direct calls get through NAT | for calls | | SFU | Media server for group calls and voice rooms | for group calls | | Push relay | Passes encrypted notifications to Apple, Google and browsers | for background notifications | | Web client | Comon in the browser at `/app/` | no | | Speech recognizer | Transcribes voice messages | no | | Bridge | Broadcasts public Telegram channels | no | How they fit together: [how the server works](./how-it-works.mdx). ## Requirements [#requirements] - **A machine** with Linux, Docker Engine and Docker Compose v2, Python 3.11 or newer, and git. Docker needs at least 4 GB of memory. Server images are built from source on the same machine. - **A domain** whose A record points at the machine. The address of the federation and of its sign-in service is part of its identity: changing the domain after people have signed in is a procedure of its own ([moving to another domain](./upgrading.mdx#moving-to-another-domain)). - **A public IPv4 address** and open ports: | Port | Protocol | For | |---|---|---| | 443 | TCP | HTTPS and the apps' WebSocket, certificate issuance (TLS-ALPN) | | 3478 | TCP and UDP | TURN | | 49160–49200 | UDP | Call traffic relayed by TURN | | 7882 | UDP | Group call media (SFU) | | 5349 | TCP | TURN over TLS, if enabled | - **Memory, CPU and disk** for your number of people: work them out with the [calculator](./sizing.mdx). By default each person may store 50 GiB of media and the whole server 1 TiB; options change both ([limits](./limits.mdx)). - For speech recognition on the CPU, another 1.3 GB or so for models and up to four threads. The stack in the repository is meant for an organization's private installation. It does not set up open registration for anyone: a public launch needs its own preparation of monitoring, capacity and abuse controls. ## Two ways to install [#two-ways-to-install] 1. **The `tools/mvp-stack.py` script** builds and runs the whole stack in Docker Compose: the server, PostgreSQL, Keycloak, Caddy, TURN and the SFU, and with its `enable-*` commands push, the bridge and speech recognition. The [quick start](./quick-start.mdx) uses it. 2. **Your own setup.** If you already have a reverse proxy, a sign-in service or a database, run the same images with your own options. Every option is in the [reference](./reference.mdx); `deploy/hosted/compose.yaml` in the repository is an example of such a setup (Traefik and an external OIDC provider). ## Section map [#section-map] **Configuration** - [Sign-in and accounts](./sign-in.mdx): Keycloak, your own OIDC, cloud password, phone numbers. - [Calls](./calls.mdx): TURN, SFU, ports, NAT, TURN over TLS. - [Push notifications](./push.mdx): relay, APNs, FCM, Web Push. - [Web client and links](./web.mdx): the web client, link pages, opening links in the apps. - [Voice transcription](./transcription.mdx). - [Bots and bridges](./bots-and-bridges.mdx). - [App versions](./app-updates.mdx): required and recommended updates. - [Federation settings](./federation-settings.mdx): owner, roles, rules, filters, limits. **Reference** - [Sizing](./sizing.mdx): a calculator based on measurements. - [Server options](./reference.mdx). - [Limits](./limits.mdx). **Operations** - [Operations](./operations.mdx): health checks, logs, offline commands, error reports. - [Backups and restore](./backups.mdx). - [Upgrading](./upgrading.mdx). - [Scaling](./scaling.mdx): gateways, NATS, a shared media volume. - [Troubleshooting](./troubleshooting.mdx). # Limits (/docs/en/selfhost/limits) There are three kinds of limits: - **Server capacity**: how much one federation holds. Some of it is configurable. - **Product limits**: what a person sees, such as message length or group size. The same in every federation, checked by both the app and the server. - **Rate limits**: how many actions per second. They live in the server's memory, and a restart resets them. ## Server [#server] | What | How many | At the limit | |---|---:|---| | Profiles, bots included, call guests not | 10,000 | A sign-in that would create a new profile fails. | | Link call guests at once | 1024 | A new guest cannot join. | | Messages one profile keeps (`--maximum-messages-per-profile`) | 50,000 | That person's sends fail; everyone else keeps writing. Deleting messages for everyone frees room. | | Contacts per profile | 1000 | A new contact is not added, nor is a phone book match. | | Members of one channel | 10,000 | No more members can be added. | | Media of one profile (`--media-quota-bytes`) | 50 GiB | That person's new uploads fail. | | Media of the whole server (`--media-storage-bytes`) | 1 TiB | Only new uploads fail. | | One file (`--media-file-bytes`, can only be lowered) | 1 GiB | The file is not sent. | There is no overall limit on the federation's chats or messages: messages take disk, not memory. Each profile's quota together with the rate limit bounds how fast and how far one person can fill the disk. How many gigabytes that is: the [calculator](./sizing.mdx). ## Messages and chats [#messages-and-chats] | What | How many | |---|---:| | Message or caption text | 32,768 characters | | Media in one message (album) | 10 | | Editing one's own message | 48 hours | | Deleting or forwarding at once | 100 messages | | Scheduled messages in a chat | 100 per author; in a channel 100 shared by all publishers | | Group members, owner included | 256 | | Channel members | server capacity, 10,000 | | Channels per person | 500 | | Communities per person | 100 | | Rooms in a community | 500 | | Roles in a community | 100 | | Voice room participants | up to 99, set per room | | Bots per person | 20 ([bot policy](./bots-and-bridges.mdx)) | ## Media [#media] | What | How many | |---|---:| | Photo | 64 MiB, up to 10,000 px per side | | Video | 128 MiB, up to 10 minutes | | File | 1 GiB | | Voice message | 2 hours | | Round video | 60 seconds, 16 MiB | | Avatar | 8 MiB, up to 1024 px | | Uploads at once per person | 32 | ## Calls [#calls] | What | How many | |---|---:| | Group call participants | 32 | | Unfinished calls per person | 8 | | Call links per person | 50 | | A guest's messages and files in a call chat | 500 messages, 100 MB (a file up to 25 MB) | ## Moderation and federation settings [#moderation-and-federation-settings] | What | How many | |---|---:| | Federation roles, built-in included | 50 | | Filter words and phrases; domains | 500; 500 | | Report reasons | 50, up to three levels | | Rule languages | 8 | | New direct chats with non-contacts per day | 50 by default, a role may give up to 10,000 | | People without the adder as a contact added to groups and channels per day | 50 by default, a role may give up to 10,000 | | Audit log and closed reports are kept | 365 days | | Speech recognition per person per day | 1 hour by default, up to 24 hours | The last three are set in the app ([federation settings](./federation-settings.mdx)). ## Rates [#rates] | Action | Burst, then | |---|---| | Sending, editing, deleting, pinning messages | 30, then 5 per second | | Profile changes | 10, then 1 per 6 seconds | | Reactions | 20, then 2 per second | | Reports | 10, then 1 per 20 seconds | | Link preview fetches | 20, then 1 per 2 seconds | | Call guest joins and link pages from one address | 10 and 60 per minute | Past a limit the command is refused before anything is stored, and the server says when it may be retried. The full table of every limit, including technical frame sizes and the app's local store, is in the [source](https://github.com/serezhia/chat_playground/blob/master/docs/contracts/limits.md). # Mail server (/docs/en/selfhost/mail) A federation can give people addresses `name@`. For that the bundled Stalwart mail server runs beside it, and the federation creates the mailboxes on it itself. People need no mailbox password: Comon connects to the mailbox on its own, and other mail apps use app passwords the person makes. If your domain's mail already runs on a server of yours, you need nothing on this page: name its IMAP and SMTP in **Administration → Modules → Mail → Own mail server**. The full operator procedure is in the [mail server runbook](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/mail-server.md). ## Ports [#ports] | Port | Published | What | |---|---|---| | 25 | yes | SMTP: mail from other servers | | 465 | yes | submission over TLS | | 993 | yes | IMAP over TLS | | 8080 | no | web administration and the management API | The management API is never published: only the federation reaches it, on the stack's internal network. ## Starting it [#starting-it] 1. Copy `compose.mail.yaml` from `deploy/hosted` (or `deploy/mvp`) into the state directory and add `COMON_MAIL_HOST=mail.example.org` to `stack.env`. 2. Start the stack (`prepare-hosted-stack.py up` or `mvp-stack.py up`). Stalwart starts in setup mode and prints a temporary administrator in its log. 3. Open `/admin` through an SSH tunnel to port 8080 (never a public address), finish the setup and keep the permanent administrator in `secrets/`. 4. Create an API key for the federation with the administrator's permissions and keep it as `secrets/mail/api-key` (mode 0600). 5. Add `COMON_MAIL_SERVER` and `COMON_MAIL_SERVER_KEY_FILE` to `stack.env` and run `up` again. 6. In the federation's mail settings, choose the bundled server and the mail domain. People whose role holds «Federation mail address» can then claim `@`. ## DNS and TLS [#dns-and-tls] - The domain's `MX` points to `COMON_MAIL_HOST`, which has `A`/`AAAA` records. - SPF (`v=spf1 mx -all`), DKIM at the selector Stalwart generated, and `_dmarc` (start with `p=none`). - The server address's reverse DNS (PTR) is `COMON_MAIL_HOST`. Without it, mail is often rejected. - Many hosting providers block outbound port 25 by default: ask them to open it in advance. The stack's reverse proxy holds ports 80 and 443, so get the certificate for `COMON_MAIL_HOST` with ACME DNS-01 in Stalwart itself, or mount certificate files. The federation verifies the mail server's certificate, so it must be in place before people claim addresses. ## Letters from the federation [#letters-from-the-federation] The federation sends its own letters (such as invitations to guests by e-mail) from a `noreply@` sender. With the bundled server it is `noreply@`; another server can be named with the `--mail-noreply-*` flags ([reference](./reference.mdx)). An administrator turns the letters on in the federation's mail settings and can send a test letter there. ## Backups and upgrades [#backups-and-upgrades] The `mail` volume is the whole mail server. `prepare-hosted-stack.py backup` archives it with the rest ([backups](./backups.mdx)). Letters that arrive while the server is down wait at the senders' servers and come later. Change the Stalwart version in both `compose.mail.yaml` files at once, after reading its upgrade notes and taking a backup. # Operations (/docs/en/selfhost/operations) ## Compose commands by hand [#compose-commands-by-hand] `mvp-stack.py` calls Docker Compose with the files in the state directory. For commands by hand, use this shell function (PostgreSQL is included here; add `-f compose.push.yaml`, `compose.bridge.yaml` or `compose.transcriber.yaml` if you turned those on): ```sh cd .local/mvp dc() { docker compose --project-name comon-mvp --project-directory . --env-file stack.env \ -f compose.yaml -f compose.sql.yaml "$@"; } dc ps # what is running dc logs -f federation # the server's log dc restart federation # restart one service ``` Services: `gateway` (Caddy), `federation`, `migrate`, `postgres`, `identity` (Keycloak), `sfu`, `turn`, `web`, `push-relay`, `bridge`, `transcriber`. ## Health checks [#health-checks] ```sh python3 tools/mvp-stack.py check ``` The command checks `/health`, `/ready`, the federation document, Keycloak and, when push is on, `/push/healthz`. You can also ask the server directly: | Path | Answer | |---|---| | `/health` | 200 while the process is alive. Does not touch the database. | | `/ready` | 200 and `"status": "ready"` when the database answers and the schema matches; otherwise 503 and `"status": "unavailable"`. The reason is only in the server's log. | The `/ready` answer works for monitoring: ```json { "status": "ready", "latency_ms": 1, "sql": { "connections": { "open": 3, "budget": 3 } }, "sync_projections": { "pending": 0, "oldest_age_ms": 0, "poisoned": 0 }, "jobs": { "": { "running": true, "failures": 0, "last_success_age_ms": 1200 } }, "outbound": "held" } ``` - `sql`: counts and durations of this process's queries, never statements or rows. - `sync_projections`: changes not yet delivered to people's feeds: how many wait, the age of the oldest and how many have stopped (`poisoned`). A lag does not make the server unready: accepted messages are already stored. - `jobs`: background jobs. A failing job keeps retrying and shows here; the server keeps working. - `outbound: held`: the server was restored from a backup and does not send held work yet ([restoring](./backups.mdx#restoring)). Watch the `/ready` status code, growing `poisoned` and `failures`, and an `oldest_age_ms` that keeps growing. ## Logs [#logs] The server writes to standard output: `dc logs federation`. Lines with `calls` describe calls ([calls](./calls.mdx#testing)), `restore_missing_media` lines list missing files after a restore. Message texts and tokens never get into the log. ## Offline commands [#offline-commands] `federation_admin`, `reset_profile_password` and `install_system_stickers` take the same writer lock as the server, so stop it first: ```sh dc stop federation dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo list dc start federation ``` `federation_admin` is in the server image. `reset_profile_password` and `install_system_stickers` run from the source with `dart run` and access to the database ([resetting the cloud password](./sign-in.mdx#resetting-a-forgotten-password)). All commands are in the [server options](./reference.mdx#federation_admin). ## Outages [#outages] | What happened | What you see | What to do | |---|---|---| | PostgreSQL restarted or crashed | `/ready` answers 503 and does not recover by itself | Restart the server: `mvp-stack.py stop`, then `up`. Stored messages are safe; a send in flight at the moment of the outage is retried by the app. | | The server restarted | Apps lose their connection for seconds | Nothing: they reconnect by themselves. Restart the server when there are few calls. | | The SFU restarted | Group calls go quiet for seconds | Nothing: participants reconnect, spread over up to three seconds. | | A second server on the same database | It does not start | As designed: there is only one writer. | | The server does not start with `MediaVolumeMismatch` | The database and the media volume come from different installations | Attach the volume taken together with the database ([how the server works](./how-it-works.mdx#where-data-lives)). | Database queries are limited to 30 seconds, lock waits to 10 seconds. All parts of the server share up to 3 connections to PostgreSQL, one of which holds the right to write; `migrate_database` opens its own. ## Stopped processing [#stopped-processing] Each change reaches a member's feed through processing that is retried with pauses. After its last attempt it stops, and that member's feed waits behind it so the order is never broken. In `/ready`, `sync_projections.poisoned` grows. 1. Find the error in the server's log and fix its cause (for example, upgrade to a build with the fix). 2. Stop the server. 3. List and restart the processing: ```sh dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo incidents dc run --rm --no-deps --entrypoint /app/bin/federation_admin federation \ --data=/data --postgres-conninfo-file=/run/secrets/postgres-conninfo \ redrive --target= --scope= --seq= ``` 4. Start the server: the feed continues in order, skipping nothing. ## Animated emoji [#animated-emoji] A message of a single emoji is animated when the server has the `AnimatedEmoji` system set. Install it from Google's open Noto Animated Emoji (CC BY 4.0), with the server stopped, from `backend/comon_federation_server`: ```sh dart run bin/install_system_stickers.dart --data= \ --postgres-conninfo-file= --source= --fetch-noto ``` Running it again adds only new emoji. The same command installs your own system sticker sets (`--short-name`, `--title`, `--kind=stickers|emoji`). ## Error reports [#error-reports] The server can send error reports to your own Sentry: `--sentry-dsn`, `--sentry-environment` and `--sentry-traces-sample-rate` ([options](./reference.mdx#restore-and-reports)). Without a DSN nothing is sent. # Push notifications (/docs/en/selfhost/push) While the app is open, messages arrive over its own connection to the federation without any setup. Push is for notifications that arrive while the app is closed or in the background. On Windows push is not used: the app shows notifications itself while it runs or sits in the tray. ## How it works [#how-it-works] ``` federation server ──signed request──▶ push relay ──▶ APNs (Apple) / FCM (Google) / Web Push │ │ └── text encrypted to the device's key ───────────────┴──▶ the device decrypts it ``` - The **push relay** (`backend/comon_push_relay`) is a separate service that holds Apple and Google tokens and browser subscriptions and passes notifications to them. - The federation stores only opaque relay identifiers, never device tokens. - The notification text is encrypted to the key of the particular device (JWE, A256GCM). The relay, Apple and Google see an encrypted blob, the time and the size. From outside the notification looks like "New message". - A federation can trust several relays at once: each device binding remembers the relay it was made through. ## Which relay you need [#which-relay-you-need] The relay's address is **built into the app**, and the Apple and Google keys belong to whoever publishes the app. That gives two cases. **The official Comon apps** send push through the project's relay. For them to get notifications from your federation, that relay's operator must trust your federation's sender key (`federation_sender_keys` and `admission_senders` in its settings), and your federation must know that relay in `federation-push.json`. Without that the apps work, but notifications arrive only while they are open. **Your own relay** makes sense: - with your own app build: your own bundle ID and APNs key, your own Firebase project ([developers](../develop/index.mdx)); - for your own web client: Web Push needs no Apple or Google keys, only your own VAPID key pair ([web client](./web.mdx)). ## Turning it on in the ready-made stack [#turning-it-on-in-the-ready-made-stack] The command sets up one provider: APNs for iPhone and Mac, or FCM for Android. It needs `openssl` on the machine. ```sh # APNs python3 tools/mvp-stack.py enable-push \ --apns-key /path/AuthKey_KEYID.p8 --apns-key-id KEYID --apple-team-id TEAMID \ --push-topic --push-environment production # or FCM python3 tools/mvp-stack.py enable-push \ --fcm-credentials /path/firebase-service-account.json --fcm-project \ --push-topic python3 tools/mvp-stack.py up ``` A second provider and Web Push are added to `relay.json` by hand (fields below), keeping the keys already created. The command creates the relay's and the federation's keys, writes `relay.json` and `federation-push.json`, adds the `/push/*` route to Caddy and the `push-relay` service. Running `enable-push` again refuses, so it never replaces keys. The relay shares the server's network namespace: the server reaches it at `http://127.0.0.1:8090`, the apps at `https:///push`. The `.p8` key is mounted read-only and never copied into build contexts. `--push-environment sandbox` is for builds from Xcode, `production` for TestFlight and the App Store. ### Admitting installations [#admitting-installations] The relay accepts only known installations of the app. There are two ways: - **Through the federation** (the usual one): the app signs in to the federation, gets a signed ticket from it and registers with the relay using it. The federation's ID must be in `admission_senders`. - **By hand**: the app writes the installation's public data to `comon-push/admission.json`; the operator checks that the file came from the right device and admits it: ```sh python3 tools/mvp-stack.py admit-installation --admission-file /path/admission.json python3 tools/mvp-stack.py up ``` On registration the relay also checks that the device owns the token: it sends a one-time code through APNs, FCM or Web Push itself. ## Relay settings (`relay.json`) [#relay-settings-relayjson] Only the owner may read the file (0600), or the relay will not start. | Field | Meaning | |---|---| | `host`, `port` | Where to listen. `127.0.0.1:8090` by default. Any non-local address requires `behind_tls_proxy: true` and a TLS proxy in front of the relay. | | `database_path` | Absolute path to the relay's SQLite database. | | `audience` | The relay's name in signatures, tickets and receipts. `comon-push-relay` by default. | | `storage_key` | 32 random bytes (base64url) that encrypt tokens in the database. Lose it and everyone registers again. | | `receipt_seed` | 32 random bytes (base64url): the Ed25519 key the relay signs receipts with. | | `allowed_topics` | APNs topics: `@sandbox` or `@production`. For calls on iPhone add `.voip@…`. | | `apns` | `key_path` (absolute path to the `.p8`), `key_id`, `team_id`. | | `fcm` | `credentials_path` (Firebase service account), `project_id`, `allowed_topics` such as `@production`. | | `webpush` | `origins`: for each web client address, `vapid_private_key_file` and `subject` (`mailto:` or `https:`); `allowed_push_hosts`: a closed list of browser push services. | | `federation_sender_keys` | Federation ID → its public sender key. | | `admission_senders` | Federations allowed to admit new installations. | | `installation_keys` | Installations admitted by hand. | | `max_queue` | The job queue, 10,000 by default; one federation may use a quarter. | The relay needs Node and `curl` with HTTP/2 for APNs; the ready-made stack's image has both. The `allowed_push_hosts` list for Web Push is usually: ```json ["fcm.googleapis.com", "updates.push.services.mozilla.com", "web.push.apple.com", "*.notify.windows.com"] ``` `backend/comon_push_relay/bin/vapid_keygen.dart` creates a VAPID key pair. **Never change the VAPID key**: browsers tie every subscription to it, and with a new key every subscription stops working until people subscribe again. ## Federation settings (`federation-push.json`) [#federation-settings-federation-pushjson] The server reads the file through `--push-config`: ```json { "sender_seed": "<32 bytes, base64url>", "storage_key": "<32 bytes, base64url>", "relays": [ { "origin": "http://127.0.0.1:8090", "audience": "comon-push-relay", "public_key": "", "allow_loopback_http": true } ] } ``` - `sender_seed` is the key the federation signs relay requests with. Its public half goes into `federation_sender_keys` of every relay. - `relays` are the relays the federation trusts. When adding a new one, keep the old one first: it owns the bindings made before bindings started remembering their relay. - Remove a relay from the list and its bindings stop working; the apps bind again. - The former top-level fields `relay_origin`, `relay_audience`, `relay_public_key` and `allow_loopback_http` are refused and the server does not start: move them into one entry of `relays`. ## Delivery [#delivery] - A notification lives up to five minutes and is retried up to eight times. On Apple or Google errors the retry is postponed by 15 minutes, so old notifications never arrive in a batch. - The relay tries to remove a notification read on another device, but Apple and Google do not guarantee it. - `GET /push/healthz` shows that the process is alive, not that notifications get through. ## Relay backup [#relay-backup] The relay's database is part of the stack's [backup](./backups.mdx); the `.p8` key is not, so keep it separately. After a restore push turns itself off: old revocations and preview keys need reconciling, and devices register again. Do not turn an old relay copy back on blindly. # Quick start (/docs/en/selfhost/quick-start) The ready-made stack starts with one command: the federation server, PostgreSQL, Keycloak for sign-in, Caddy with a Let's Encrypt certificate, TURN and the call media server. Everything runs in Docker Compose on one machine. Before you start, check the [requirements](./index.mdx#requirements): a domain pointing at the machine, and open ports. ### Get the source [#get-the-source] ```sh git clone https://github.com/serezhia/chat_playground.git comon cd comon git checkout v0.2.4 # the latest release, see the changelog ``` The server images are built from this source when you start the stack. Dart and Flutter are not needed on the host: the build runs inside Docker. ### Prepare the state [#prepare-the-state] ```sh python3 tools/mvp-stack.py prepare \ --host chat.example.org --port 443 --listen 0.0.0.0 --public-tls ``` - `--host` is the federation's domain. It becomes the address of the federation and of its sign-in service, so choose it now: changing it later is a [move](./upgrading.mdx#moving-to-another-domain). - `--public-tls` gets a Let's Encrypt certificate. It needs port 443 and a DNS record pointing at the machine. Without it, Caddy issues a certificate from its own authority, which apps from the stores do not trust. - `--listen 0.0.0.0` listens on every interface (the default is local only). The command creates the state directory `.local/mvp/`: configuration, random passwords and keys, Compose files. Only its owner can read it. **Do not publish it or put it in Git**, and do not run `prepare` again over an existing state: it refuses. ### Start it [#start-it] ```sh python3 tools/mvp-stack.py up ``` `up` builds the images, creates the database, applies migrations, starts every service and checks that the federation answers. The first build takes a few minutes. Afterwards, check the state with: ```sh python3 tools/mvp-stack.py check ``` `check` asks `/health`, `/ready`, the federation document `/.well-known/comon-federation` and the sign-in service. ### Create people in Keycloak [#create-people-in-keycloak] Open `https://chat.example.org/identity/admin/` and sign in as `operator`. The password is in `.local/mvp/stack.env` on the `KEYCLOAK_ADMIN_PASSWORD` line; do not forward it or paste it into logs. 1. Choose the `comon` realm. 2. Create users and give them initial passwords (**Users › Add user**, then **Credentials**). 3. Create a permanent Keycloak administrator and delete the temporary `operator`, as the Keycloak documentation advises. Self-registration and password reset in Keycloak stay off until you set them up. ### Sign in from the app [#sign-in-from-the-app] Install Comon ([apps](../guide/apps.mdx)), choose "Add federation" and enter `chat.example.org`. The app checks the address and opens Keycloak's sign-in page in the system browser. - On the first sign-in the app asks for a federation **cloud password**: it is needed to sign in on new devices ([more](./sign-in.mdx#cloud-password)). - **The first person to finish sign-up becomes the federation's owner.** The owner sees the "Manage Federation" section in settings. ## What next [#what-next] - Set the federation's name, support contact and rules: [federation settings](./federation-settings.mdx). - Test calls from outside your network: [calls](./calls.mdx#testing). - Turn on sending video: [below](#sending-video). - Set up background notifications: [push notifications](./push.mdx). - Build the web client: [web client and links](./web.mdx). - Turn on voice transcription: [voice transcription](./transcription.mdx). - Set up backups: [backups](./backups.mdx). ## Sending video [#sending-video] The ready-made stack builds the server without `ffmpeg`, so video can be watched but not sent. To turn sending on, in `.local/mvp/compose.yaml` change the build of the `federation` service and add an option: ```yaml federation: build: context: ./server-context dockerfile: Dockerfile.video command: # … the other options unchanged - --video-validator-config=/config/video-validator.json ``` The `Dockerfile.video` image has `ffmpeg` in an isolated sandbox and a ready `/config/video-validator.json`. If push notifications are on, add the same line to `compose.push.yaml` too: it repeats the whole server command. Then run `up` again. ## Changing options [#changing-options] The server's options are the `command` of the `federation` service in `.local/mvp/compose.yaml` (and in `compose.push.yaml`, if present). Add an option from the [reference](./reference.mdx) and run `up`. On upgrades `up` adds to these files only what the new version needs; after an upgrade, check that your options are still there. ## Script commands [#script-commands] | Command | What it does | |---|---| | `prepare` | Creates a new state. Refuses when the directory is not empty. | | `up` | Builds and starts the stack, applies migrations, updates the files for the current version, checks. | | `check` | Checks `/health`, `/ready`, the federation document and sign-in. | | `stop` | Stops the stack; data stays. | | `config` | Validates the Compose files. | | `preflight` | Checks the database before an upgrade ([upgrading](./upgrading.mdx#checking-the-data-before-an-upgrade)). | | `backup`, `restore` | [Backups and restore](./backups.mdx). | | `export-client` | Writes `client.json` with public settings for your own app build. | | `enable-push`, `admit-installation` | [Push notifications](./push.mdx). | | `enable-turn-tls` | [TURN over TLS](./calls.mdx#turn-over-tls). | | `enable-transcriber` | [Voice transcription](./transcription.mdx). | | `enable-bridge`, `bridge-login` | [Bridges](./bots-and-bridges.mdx#bridges-telegram-channels). | Common options: `--state ` (default `.local/mvp`) and `--project ` (the Docker project, default `comon-mvp`). One `comon-mvp` project runs per machine: do not run two states at once. # Server options (/docs/en/selfhost/reference) Options are written `--name=value`, flags `--name`. An unknown option, a flag given a value or an option given none stops the server from starting: a typo never runs a federation on a default. In the ready-made stack the server's command is in `compose.yaml` in the state (and repeated in `compose.push.yaml` when push is on). Change it there and run `mvp-stack.py up` ([changing options](./quick-start.mdx#changing-options)). ## Server [#server] `comon_federation_server` ### Network and addresses [#network-and-addresses] | Option | Default | Meaning | |---|---|---| | `--host` | `127.0.0.1` | The address to listen on. | | `--port` | `8443` | The port. | | `--public-origin` | `https://localhost:` | The HTTPS origin the apps reach. Link pages and notification pictures live under it. | | `--certificate`, `--private-key` | test certificates from the source | TLS certificate and key. | | `--behind-tls-proxy` | off | Plain HTTP behind a TLS proxy. No certificate is read; the client's address comes from `X-Forwarded-For`. | | `--development-lan` | off | The development sign-in listens beyond loopback, and the public and identity origins may be `localhost`, a private IPv4 address or a `.local` name, so a phone on the same network can sign in. It lets anyone in, so it is for a local stand only. Not allowed with `--oidc-config` or `--behind-tls-proxy`. | ### Identity and storage [#identity-and-storage] | Option | Default | Meaning | |---|---|---| | `--federation-id` | `local` | The federation's ID ([the federation's identity](./how-it-works.mdx#the-federations-identity)). | | `--data` | `.local/comon-federation` | The data directory: the Noise key and media. | | `--postgres-conninfo-file` | required | A file with one libpq connection string. Every store of the federation is a schema of that database. | | `--media-dir` | `/media` | Where media bytes are kept. With `s3`, only this process's unfinished uploads. | | `--media-volume` | `local` | `local`, `shared` or `s3`. The first start binds the database to the volume or bucket; a start on another one fails ([scaling](./scaling.mdx)). | | `--media-bucket-endpoint` | required with `s3` | The S3-compatible store (MinIO, for example), `http(s)://host[:port]`. | | `--media-bucket` | required with `s3` | The bucket. Only this federation uses it. | | `--media-bucket-region` | `us-east-1` | The bucket's region. | | `--media-bucket-credentials-file` | required with `s3` | A JSON file `{"access_key_id": "...", "secret_access_key": "..."}`. | | `--modules` | every module of the build | `,...`: the modules with their own storage this process serves. The others answer "not supported". | ### Live updates and gateways [#live-updates-and-gateways] | Option | Default | Meaning | |---|---|---| | `--live` | `in-process` | `nats` publishes live updates to the federation's gateways; needs `--media-volume=shared` or `s3`. | | `--live-nats` | `127.0.0.1:4222` | The NATS server, `:`. Must allow messages of 2.1 MB or more. | | `--live-nats-token-file` | required with `nats` | A file with the NATS token. | | `--writers` | `one` | `many`: the process serves the federation together with the others started so, on one database. Needs `--live=nats` and a copy of the federation's `noise-server-key` in `--data`; the first start from a backup uses `one` ([scaling](./scaling.mdx)). | | `--live-reconcile-interval` | `30` | Seconds between checks of active profiles' feed heads. | ### Sign-in [#sign-in] | Option | Default | Meaning | |---|---|---| | `--oidc-config` | development sign-in | The OIDC provider ([sign-in](./sign-in.mdx#your-own-oidc-provider)). | | `--external-accounts` | no provider | The keys that encrypt connected accounts, the Google and Yandex OAuth clients, and connecting mail and calendar servers with a password ([external accounts](./external-accounts.mdx)). | | `--identity-origin` | the public origin | The development sign-in's origin, only without `--oidc-config`. | | `--web-client` | none | A web client address that may receive sign-in results. Repeatable. HTTPS, or HTTP on loopback. | | `--profile-password-policy` | `required` | `required` or `optional` ([cloud password](./sign-in.mdx#cloud-password)). | ### Calls, push, media [#calls-push-media] | Option | Default | Meaning | |---|---|---| | `--call-config` | calls without TURN or SFU | STUN, TURN and the SFU ([calls](./calls.mdx)). | | `--push-config` | push off | The relay and keys ([push](./push.mdx#federation-settings-federation-pushjson)). | | `--video-validator-config` | video is receive-only | Paths to `ffmpeg`, `ffprobe` and the sandbox. Enables sending video and converting video stickers ([sending video](./quick-start.mdx#sending-video)). | | `--mail-server`, `--mail-server-key-file`, `--mail-server-hostname` | none | The bundled mail server's management API, its key file and its public name (the one its certificate is for); all three or none. A hostname alone is ignored. | | `--mail-noreply-address`, `--mail-noreply-smtp`, `--mail-noreply-password-file`, `--mail-noreply-username` | none | Your own noreply@ sender for the federation's letters: the address, the SMTP server as `smtps://host:465` (TLS) or `smtp://host:587` (STARTTLS), the password file and the sign-in name (the address by default). The first three go together. Without them the bundled mail server sends from `noreply@`. | | `--transcriber-url`, `--transcriber-model`, `--transcriber-key-file` | none | Default speech recognition ([voice transcription](./transcription.mdx)). | ### Bots, bridges, stickers [#bots-bridges-stickers] | Option | Default | Meaning | |---|---|---| | `--bot-config` | everyone, up to 20 bots | Who may create bots and how many ([bots and bridges](./bots-and-bridges.mdx)). | | `--bot-private-webhooks` | off | Allow bot webhooks to private addresses. Development only. | | `--no-demo-bot` | `@demo_bot` on | Turns off the built-in demo bot. | | `--bridge-config` | bridges off | Networks to mirror, the bridge process, media budget and who may mirror. | | `--telegram-bot-token-file` | importing off | The token of your own Telegram bot, through which the federation imports sticker sets. | ### People and limits [#people-and-limits] | Option | Default | Meaning | |---|---|---| | `--contacts-mode` | `directory` | `address-book`, `directory` or `hidden`, until a mode is chosen in the federation settings ([federation settings](./federation-settings.mdx)). | | `--maximum-messages-per-profile` | `50000` | How many messages each profile keeps. | | `--media-quota-bytes` | 50 GiB | Media of one profile. | | `--media-storage-bytes` | 1 TiB | Media of the whole server. | | `--media-file-bytes` | 1 GiB | One file, no more than the protocol limit. | The other limits are not configurable ([limits](./limits.mdx)). ### Apps and links [#apps-and-links] | Option | Default | Meaning | |---|---|---| | `--minimum-client-level` | `29` | The oldest app level the server serves. Not below 29 ([app versions](./app-updates.mdx)). | | `--recommended-client-level` | the minimum | The level the app suggests updating to. Not below the minimum. | | `--client-update-url` | none | `=`, once each for `android`, `ios`, `macos`, `windows`, `linux`, `web`. | | `--link-scheme` | `comon` | The scheme link pages open the app with ([link pages](./web.mdx#link-pages)). | | `--apple-app-id` | none | `.`, repeatable or comma-separated: an iOS or macOS app that opens the federation's links itself. | | `--android-app` | none | `:`, repeatable or comma-separated: the same for Android. | ### Restore and reports [#restore-and-reports] | Option | Default | Meaning | |---|---|---| | `--restored-backup` | none | ``: the stores were restored from this backup ([restoring](./backups.mdx#restoring)). | | `--accept-missing-media` | off | Start after a restore even if media files are missing. | | `--sentry-dsn` | none | Where the server sends error reports. Without it nothing is sent ([operations](./operations.mdx#error-reports)). | | `--sentry-environment` | `prod` | The environment in reports. | | `--sentry-traces-sample-rate` | `0.1` | The share of traced requests, from 0 to 1. | ## Gateway [#gateway] `comon_federation_gateway` accepts the apps' connections and passes them to the primary server ([scaling](./scaling.mdx)). | Option | Default | Meaning | |---|---|---| | `--federation-id` | required | The primary server's federation ID. | | `--noise-key-file` | required | A copy of the primary server's `noise-server-key`. | | `--host`, `--port` | `127.0.0.1`, `8443` | Address and port. | | `--certificate`, `--private-key` | required without `--behind-tls-proxy` | TLS certificate and key. | | `--behind-tls-proxy` | off | Plain HTTP behind a TLS proxy. | | `--live` | `nats` | There is no other choice. | | `--live-nats`, `--live-nats-token-file`, `--live-reconcile-interval` | as on the server | The bus to the primary server. | | `--media-volume` | none | `shared` or `s3`: the gateway reads downloads from the primary server's media itself, after the server allows each piece. Without it the primary server reads every download. | | `--media-dir` | required with `shared` | The primary server's shared media volume, mounted read-only. | | `--media-bucket-endpoint`, `--media-bucket`, `--media-bucket-region`, `--media-bucket-credentials-file` | as on the server, required with `s3` | The primary server's bucket. | ## migrate_database [#migrate_database] Creates and upgrades the database schema. The server never changes the schema itself and will not start on a database older or newer than itself. The ready-made stack runs the command before the server on every `up`. ```sh migrate_database --postgres-conninfo-file= # apply missing migrations migrate_database --postgres-conninfo-file= --check # only check; exit code 1 on a mismatch migrate_database --postgres-conninfo-file= --preflight # check the data before an upgrade ``` Migrations are applied in one transaction under a lock, so two concurrent runs never apply a step twice. ## federation_admin [#federation_admin] Offline administration. The server must be stopped ([offline commands](./operations.mdx#offline-commands)). | Command | What it does | |---|---| | `list` | Who holds which role. | | `grant-owner --profile=` | Make a profile the owner. | | `set-roles --profile= --roles=,...` | Assign roles. | | `incidents` | Background processing that has stopped. | | `redrive --target= --scope= --seq=` | Restart one of them. | | `restores` | Restores from backups. | | `release-outbound` | After a restore, send scheduled messages and bot webhooks again. | | `check-stickers` | Run stored Lottie stickers through today's checks and list the ones they refuse. Changes nothing. | Common options: `--data=`, `--postgres-conninfo-file=`, `--federation-id=`. # Scaling (/docs/en/selfhost/scaling) By default a federation writes to its database from one process, and scaling means taking load off that writer. Primaries started with `--writers=many` write the same database together, each serving the presence of its own connections; each call runs on the primary where it started, and devices on any primary take part in it. Each background job is served by one of them at a time. A gateway keeps each connection on one primary. The mode is experimental, so keep it off in production until it has run under load on several primaries; a call ends when its primary stops. How many resources your number of people needs: the [calculator](./sizing.mdx). ## Profiles [#profiles] | Profile | What runs | For | |---|---|---| | **S** | Server, PostgreSQL and media on one machine (the ready-made stack) | Most installations | | **M** | Primary server, gateways, NATS, a shared media volume | Many concurrent connections. Still a lab profile: rehearsed by `tools/mlab-stack.py`, no ready-made stack | Profile S does not survive the loss of its only machine beyond the last [backup](./backups.mdx). Profile M promises no high availability either: there is one writer. ## What to move out first [#what-to-move-out-first] - **Media** to a separate disk: `--media-dir`. It is the fastest-growing volume. - **PostgreSQL** to another machine or a managed PostgreSQL 17 service: the server gets its connection string from `--postgres-conninfo-file`. Keep the latency to the database minimal: every message is a transaction. - **SFU and TURN** to a machine with a good uplink. All call traffic goes through them, and the federation server needs only the address of their control API (`sfu_url`) and the secrets. TURN must stay in the SFU's network namespace ([calls](./calls.mdx#turn-coturn)). - **Speech recognition** to a machine with a GPU ([voice transcription](./transcription.mdx)). ## Gateways [#gateways] A gateway (`comon_federation_gateway`) accepts the apps' WebSockets, holds the Noise encryption and send queues, and passes requests to the primary server over NATS. It gets live updates from the same bus. A gateway opens no database and holds no locks; calls, presence and background jobs stay on the primary. ``` apps ──WSS /comon──▶ proxy ──┬──▶ gateway 1 ──┐ └──▶ gateway 2 ──┼── NATS ──▶ primary server ──▶ PostgreSQL everything else (sign-in, links, Bot API) ────┼──────────▶ primary server └── shared media volume ``` What it takes: 1. The primary with `--live=nats --live-nats=: --live-nats-token-file= --media-volume=shared` or `--media-volume=s3`. With a node-local media directory `nats` does not start. 2. NATS that allows messages of 2.1 MB or more (`max_payload`), with a token. 3. Gateways with `--federation-id`, `--noise-key-file` (a read-only copy of the primary's `noise-server-key`), the same NATS options and `--behind-tls-proxy`. 4. The proxy sends **only** `/comon` to the gateways, everything else to the primary. Every gateway option is in the [reference](./reference.mdx#gateway). ### What happens on failures [#what-happens-on-failures] | Event | What happens | |---|---| | One gateway fails | Its apps reconnect through another. | | NATS stops | Gateways become unready; when the bus returns they reconcile sessions with the primary and catch up. | | The primary stops | Gateways refuse requests until it returns. Nobody else can write. | | One of several primaries stops (`--writers=many`) | Gateways close the connections it served; the apps reconnect to another primary. Its calls end. | | A second primary starts on the same database | Without `--writers=many` on both it does not start; the first keeps serving. | ## Media in S3 (MinIO) [#media-in-s3-minio] With `--media-volume=s3` the ready media lives in an S3-compatible bucket (MinIO on your own machines, or a cloud S3) instead of a shared disk. Each primary receives uploads in its own `--media-dir`, checks them there and puts the finished files into the bucket; every download is read from the bucket. The bucket belongs to one federation: the first start writes its mark (`comon-media-volume.json`) into it, and a start on another bucket fails. ``` --media-volume=s3 --media-bucket-endpoint=http://minio:9000 --media-bucket=comon-media \ --media-bucket-credentials-file=/run/secrets/s3.json ``` The credentials file is `{"access_key_id": "...", "secret_access_key": "..."}`. The key needs to read, write, delete and list objects of that bucket. An existing federation moves its media from the disk into the bucket while stopped: 1. Stop every server process of the federation. 2. Run `federation_admin --data=... --postgres-conninfo-file=... --media-dir= --media-volume=s3 --media-bucket...=... media-to-s3`. It copies what the bucket lacks, so a run cut short is simply run again. 3. Start the servers with the S3 options. Keep the old disk until you have checked that pictures, files and voice messages open. Back up the bucket along with the database ([backups](./backups.mdx)). ## Where the ceiling is [#where-the-ceiling-is] One federation's limits are in [limits](./limits.mdx#server): up to 10,000 profiles, up to 1 TiB of media. For more people, run several independent federations. Federations cannot talk to each other, but a person can belong to several at once ([federations](../guide/federations.mdx)). # Sign-in and accounts (/docs/en/selfhost/sign-in) Comon stores no passwords of its people. The organization's sign-in service checks who signs in over OpenID Connect (OIDC), and the federation trusts its signed answer. Comon never sees the sign-in password: the app opens the sign-in page in the system browser. A person in the federation is identified by the pair of the provider's `issuer` and `sub`. Email and username are not keys, so they can change in the provider without consequences. ## Keycloak from the ready-made stack [#keycloak-from-the-ready-made-stack] `mvp-stack.py prepare` creates the `comon` realm in Keycloak with the `comon-federation` client: - authorization code with PKCE S256; the implicit flow and password grant are off; - one redirect URI: `https:///auth/oidc/callback`; - self-registration and password reset are **off**; - brute-force protection is on. The admin console is at `https:///identity/admin/`; the first sign-in is `operator` with the password from `stack.env` (`KEYCLOAK_ADMIN_PASSWORD`). Create people in the `comon` realm. To let people register themselves, enable registration in the realm's login settings and set up email in Keycloak. ## Your own OIDC provider [#your-own-oidc-provider] Any provider with authorization code and PKCE works: Keycloak, Authentik, Zitadel, a corporate sign-in service. Register a client there with the redirect URI `https:///auth/oidc/callback` and describe it in a JSON file that the server reads through `--oidc-config`: ```json { "issuer": "https://id.example.org", "client_id": "comon", "authorization_endpoint": "https://id.example.org/oauth2/authorize", "token_endpoint": "https://id.example.org/oauth2/token", "jwks_uri": "https://id.example.org/oauth2/jwks", "token_endpoint_auth_method": "client_secret_basic", "client_secret_file": "secrets/oidc-client-secret", "scopes": ["openid", "profile"] } ``` | Field | Required | Meaning | |---|---|---| | `issuer` | yes | The issuer, exactly as in the token. HTTPS only. | | `client_id` | yes | The client ID at the provider. | | `authorization_endpoint` | yes | The sign-in page. HTTPS only. | | `token_endpoint` | yes | Exchanges the code for tokens. | | `jwks_uri` | yes | The provider's signing keys. The token's signature is checked (RS256). | | `userinfo_endpoint` | no | Where to read a verified phone number and name when the token lacks them. | | `token_endpoint_auth_method` | no | `none` (default, public client), `client_secret_basic` or `client_secret_post`. | | `client_secret_file` | for `client_secret_*` | A file holding the client secret, relative to the settings file. A trailing newline is fine. Never put the secret in the JSON itself or on the command line. | | `scopes` | no | `["openid", "profile"]` by default. Must include `openid`. Add `phone` to receive verified numbers. | | `nonce_mode` | no | `required` (default): the provider must return a `nonce`. `pkce_only` is for providers without `nonce`, with a confidential client only. | | `allow_private_http` | no | Allow `http://` for `token_endpoint`, `jwks_uri` and `userinfo_endpoint` when the provider is on the same internal network. | The server checks the signature, issuer, audience, token times and `nonce`. If anything does not match, the sign-in is refused; `pkce_only` never switches on by itself after a failed check. From the token the server takes `sub`, a name from `given_name` (as a hint during sign-up) and, when `phone` is requested, a verified number (`phone_number` with `phone_number_verified: true`). The issuer is part of every person's identity. Changing the `issuer` of a running federation is a migration: stop the server, take a [backup](./backups.mdx) and move the mappings in one transaction, or people get new empty profiles. ## Without OIDC [#without-oidc] Without `--oidc-config` the server starts a built-in development sign-in where anyone can sign in as anyone. It only works locally; behind a TLS proxy (`--behind-tls-proxy`) the server requires a real OIDC provider. ## Web clients [#web-clients] For sign-in to work in the web client, the server must know its address: `--web-client=https:///app` (repeatable). The sign-in result comes back to `
/auth/callback/`; the redirect URI at the provider stays `/auth/oidc/callback`. ## Cloud password [#cloud-password] The cloud password is the second sign-in step on a new device. `--profile-password-policy` sets the policy: | Value | What happens | |---|---| | `required` (default) | On the first sign-in a person sets a password. New devices cannot sign in without it. It cannot be removed. | | `optional` | New profiles sign in without a password. Whoever sets one enters it on new devices until they turn it off in **Settings › Privacy › Cloud password**. | Changing the policy does not remove passwords already set. How the password is stored and how many attempts are allowed: [security](../features/security.mdx#cloud-password). ### Resetting a forgotten password [#resetting-a-forgotten-password] Stop the server and run from `backend/comon_federation_server` (needs the Dart SDK; this command is not in the server image, and it needs access to the federation's PostgreSQL): ```sh dart run bin/reset_profile_password.dart --data= --profile= \ --postgres-conninfo-file= ``` The command asks for the new password twice (or reads it from standard input with `--password-stdin`) and **signs out every device** of that profile. The password is never passed as an argument. ## Phone numbers [#phone-numbers] There are no phone numbers by default. The owner turns them on in the app: **Manage Federation › Rules and policies › Contacts and phone numbers › Phone numbers**. | Mode | Meaning | |---|---| | Off | No numbers and no phone book matching. | | Optional | The number comes from the sign-in provider when it supplies a verified one, or an administrator enters it on the person's card. | | Required | Signing in needs a verified number from the provider. Devices already signed in stay. Available only when `scopes` includes `phone`. | ## The federation owner [#the-federation-owner] The first person to finish sign-up becomes the owner. If there is no owner (for example in an old federation), the profile with the earliest completed sign-in becomes the owner at start. The owner changes in the app or with an offline command ([federation settings](./federation-settings.mdx#owner)). ## Limits [#limits] | What | How many | |---|---| | Profiles per server, bots included, call guests not | 10,000 | | Cloud password | 10 to 128 characters | # Sizing (/docs/en/selfhost/sizing) The calculator works from the measurements below. Enter your number of people and how actively they write. The numbers are approximate: real load depends on how people use Comon, so after launch watch the [server's metrics](./operations.mdx). ## How it is calculated [#how-it-is-calculated] - **Federation server**: 120 MB plus 0.92 MB per person online; 0.0052 cores per online person acting once every 20 seconds. The "Actions per minute" field scales this to your activity: the test made 3 actions a minute, real people usually make fewer. - **PostgreSQL**: about 430 MB with default settings (`shared_buffers` 128 MB). More memory makes the database faster, but only this minimum is required. - **Database**: about 3 KB per message with its search index, plus up to 0.6 MB per person: each person's sync feed keeps their last 1000 events at 0.6 KB each. An empty database takes 14 MB. In a short test the feeds have not reached that cap yet, so the database size in the table below divided by the number of messages is much more than 3 KB. - **Media**: exactly what people upload. By default each person may store up to 50 GiB ([limits](./limits.mdx)). - **Calls**: a ceiling from the codec settings, not a measurement. A camera sends three layers to the SFU (150 + 500 + 1500 kbit/s), a receiver of a large tile takes the top one (1500 kbit/s), of a small one the lower ones; voice is 40 kbit/s. One-to-one calls go directly or through TURN and do not load the SFU. - **Machine**: twice the memory and CPU the server, database and SFU need, plus 1 GB of memory and 10 GB of disk for the system; at least 2 cores, 2 GB of memory and 20 GB of disk. Keycloak, Caddy, the web client and bridges are not included: add their memory separately (Keycloak: see [its documentation](https://www.keycloak.org/high-availability/concepts-memory-and-cpu-sizing)). ## Measurements [#measurements] The `comon_load` load test: real CDLib clients on the same machine sign up, join groups, channels and a community, write text, send photos, files, voice and round video messages and stickers, call, read and go offline. Each online person acts once every 20 seconds, a session lasts 3 minutes, a break 2 minutes. The steady phase is 5 minutes. Machine: 4 vCPU Intel Xeon 2.1 GHz, 16 GB of memory, PostgreSQL 16 with default settings, the 0.2.4 server and the SFU compiled to native code. | | 100 people | 200 people | 400 people | |---|---:|---:|---:| | Online, average / maximum | 65 / 78 | 126 / 138 | 219 / 267 | | Server memory, average / maximum | 143 / 181 MB | 196 / 237 MB | 344 / 461 MB | | Server CPU, average / 5 s peak | 0.29 / 0.94 cores | 0.65 / 1.32 cores | 1.15 / 1.66 cores | | SFU memory | 19 MB | 19 MB | 19 MB | | Messages in total | 1,381 | 2,767 | 5,073 | | Database size | 49 MB | 90 MB | 254 MB | | Media on disk | 74 MB | 185 MB | 265 MB | | Message delivery, median / 99% | 0.4 / 1.4 s | 0.4 / 1.3 s | 1.8 / 31.5 s | The test's clients ran on the same machine and took almost all 4 cores (load average 10), so latency grew and some requests timed out. The server's CPU stayed on the line of 0.0052 cores per online person, while its memory grew more because of queues. The calculator is built from the 100 and 200 people runs. How to repeat the test on your machine is in the [runbook](https://github.com/serezhia/chat_playground/blob/master/docs/runbooks/load-test.md). # Voice transcription (/docs/en/selfhost/transcription) People can turn a voice message or a round video into text with the "Transcribe" button ([how it looks](../features/voice.mdx)). A separate recognizer service, compatible with the OpenAI `/audio/transcriptions` API, does the recognition. The federation reads the recording and sends it to the recognizer whole. ## Choosing a recognizer [#choosing-a-recognizer] | Setup | Models | Needs | |---|---|---| | CPU (default) | `auto`: GigaAM-v3 for Russian, Whisper large-v3-turbo for other languages | About 1.3 GB of models on a volume, up to 4 CPU threads | | NVIDIA GPU | Qwen3-ASR 1.7B on vLLM | A GPU, the NVIDIA Container Toolkit and a vLLM image that serves the model | | Outside service | Any with the OpenAI API: a cloud one or your own vLLM | Its URL and key. The app tells people their audio leaves the federation | All models of the ready-made stack are open and work offline once downloaded. If your federation speaks only Russian, `gigaam-v3` is enough: set `COMON_TRANSCRIBER_MODELS=gigaam-v3` and less is downloaded. ## Turning it on in the ready-made stack [#turning-it-on-in-the-ready-made-stack] ```sh python3 tools/mvp-stack.py enable-transcriber # CPU python3 tools/mvp-stack.py enable-transcriber --transcriber-gpu # GPU python3 tools/mvp-stack.py up ``` For the GPU, after `enable-transcriber` put the vLLM image into `COMON_VLLM_IMAGE` in `stack.env`. The command adds the `transcriber` service and passes the server `--transcriber-url=http://transcriber:8000/v1` and `--transcriber-model`. The first transcription downloads the models into the `transcriber-models` volume, so it is slow once. Running the command again refuses: from then on everything changes in the app. ## Settings in the app [#settings-in-the-app] An administrator who may manage the federation opens **Manage Federation › Rules and policies › Speech recognition**: 1. Turns on "Recognize speech" and enters the "Recognizer URL" (and an "API key" for an outside service). For the built-in one: `http://transcriber:8000/v1`. 2. Presses "Check the recognizer": the app lists the service's models, and one can be chosen. 3. Sets "Longest recording, minutes" (30 by default, at most 120) and saves. The server options `--transcriber-url`, `--transcriber-model` and `--transcriber-key-file` are only initial values. After the first save in the app, the app's settings apply. ### Time per person [#time-per-person] How many minutes a day a person may transcribe is set by roles: the "Speech recognition, minutes per day" row on a role, and the same row in the federation settings for everyone (60 by default). A person whose roles all give 0 sees no transcription buttons. ## An outside recognizer [#an-outside-recognizer] If the recognizer's address is not a Compose service name, not `localhost` and not a private address, the app writes "Recognized by ``" under every transcript: people must know their voice leaves the federation. For the built-in recognizer, use the service name inside the network. ## Troubleshooting [#troubleshooting] | What you see | Cause | |---|---| | No transcription buttons | Recognition is off, or the person's roles give 0 minutes. | | "Speech recognition is unavailable. Try again later." | The server logs `transcription_failed` with the recognizer's error. Press "Check the recognizer"; `dc logs transcriber` shows model downloads and decoding errors. | | The first transcription is slow | The models are still downloading. | | "Recognized by …" under a transcript | The recognizer's address is outside (see above). | # Troubleshooting (/docs/en/selfhost/troubleshooting) Start with `python3 tools/mvp-stack.py check` and the server's log (`dc logs federation`; the `dc` function is in [operations](./operations.mdx#compose-commands-by-hand)). ## Starting [#starting] | What you see | Cause and what to do | |---|---| | The server does not start; the log says `MediaVolumeMismatch` | The database runs on another or empty media volume. Attach the volume taken together with the database. | | The server does not start without `noise-server-key` | The database has signed-in devices but no Noise key exists. A new key would cut them off, so the server never creates one itself. Restore the key from a [backup](./backups.mdx). | | The server refuses to start because of the schema | The database is older or newer than the server. `up` normally applies migrations itself; if you start the server by hand, run `migrate_database` first. | | The server does not start behind the proxy | With `--behind-tls-proxy` a real OIDC provider (`--oidc-config`) is required: the development sign-in is not allowed behind a proxy. | | Unknown option, and the server does not start | A typo or an option from another version. Check the [reference](./reference.mdx). | | A second server on the same database does not start | As designed: one writer. | | Caddy does not get a certificate | The domain must point at the machine, and ports 80 and 443 must be open from outside. | ## Running [#running] | What you see | Cause and what to do | |---|---| | `/ready` answers 503 after a PostgreSQL restart | The server does not reconnect to the database by itself. Restart it: `mvp-stack.py stop`, then `up`. | | Messages arrive late, and `sync_projections.poisoned` grows in `/ready` | Feed processing has stopped. See [stopped processing](./operations.mdx#stopped-processing). | | Scheduled messages and bot webhooks do not go out after a restore | Outbound work is held until `release-outbound` ([restoring](./backups.mdx#first-start-from-a-backup)). | | New people cannot sign in, and the log mentions the profile limit | The federation has 10,000 profiles ([limits](./limits.mdx#server)). | ## Sign-in [#sign-in] | What you see | Cause and what to do | |---|---| | The sign-in provider complains about the redirect URI | The provider's client must have `https:///auth/oidc/callback` registered. | | Sign-in is refused after the provider's page | `issuer`, `client_id`, the signature or `nonce` do not match. The detailed reason is in the server's log. Providers without `nonce` need `nonce_mode: pkce_only` and a confidential client ([sign-in](./sign-in.mdx#your-own-oidc-provider)). | | Sign-in in the web client does not return to the app | The server was not given `--web-client` with the web client's address. | | Required phone numbers cannot be turned on | The provider does not supply verified numbers: add `phone` to `scopes`. | | Someone forgot their cloud password | [Resetting the password](./sign-in.mdx#resetting-a-forgotten-password). | ## Calls [#calls] | What you see | Cause and what to do | |---|---| | A direct call connects only within one network | TURN ports are closed (3478 TCP/UDP, 49160–49200 UDP), or `external-ip` in `turnserver.conf` is not the public address. | | A group call does not start | No SFU: `calls.json` has no `sfu_url`, or the `sfu` service is not running. | | A group call has no audio or video | UDP 7882 is closed, or `COMON_SFU_PUBLIC_IPS` in `sfu.env` is not the public address. | | Group calls fail from the server's home network but work from outside | The router cannot do hairpin NAT. Add the LAN address to `COMON_SFU_PUBLIC_IPS` ([server behind NAT](./calls.mdx#server-behind-nat)). | | Calls from a browser on a corporate network do not connect | The network lets only TLS through: turn on [TURN over TLS](./calls.mdx#turn-over-tls). | Test calls from a phone on a mobile network: an open TCP port does not prove that UDP gets through. ## Notifications and media [#notifications-and-media] | What you see | Cause and what to do | |---|---| | Notifications arrive only while the app is open | Push is not set up, or the relay built into the app does not trust your federation ([which relay you need](./push.mdx#which-relay-you-need)). | | Push stopped working after a restore | As designed: push turns off after a restore ([relay backup](./push.mdx#relay-backup)). | | The web client stopped getting notifications | The VAPID key changed: every browser subscription has to be made again. | | Video cannot be sent, but incoming videos play | The server image was built without `ffmpeg`. Turn on [sending video](./quick-start.mdx#sending-video). | | Uploads fail for everyone | Media storage (`--media-storage-bytes`) or the disk is full. | | A single-emoji message is not animated | The `AnimatedEmoji` set is not installed ([animated emoji](./operations.mdx#animated-emoji)). | ## Apps [#apps] | What you see | Cause and what to do | |---|---| | "Update the app" | The app's level is below `--minimum-client-level` ([app versions](./app-updates.mdx)). | | Apps do not connect after the server was reinstalled | The Noise key changed: the apps remember the old one. Restore the key from a backup; otherwise people have to remove the federation from the app and add it again. | | The domain's links open in the browser, not in the app | Your own domain needs your own app build ([opening links](./web.mdx#opening-links-straight-in-the-apps)). | # Upgrading (/docs/en/selfhost/upgrading) ## Upgrading the server [#upgrading-the-server] Every version is a tag in the repository. Changes and special steps of each version are in the [changelog](../develop/changelog.mdx). ```sh python3 tools/mvp-stack.py backup --backup /absolute/path/before-v0.2.5 git fetch --tags git checkout v0.2.5 python3 tools/mvp-stack.py up python3 tools/mvp-stack.py check ``` `up` rebuilds the images, applies database migrations (`migrate`) and starts the new server only after they succeed. If a migration fails, the server does not start and the database stays on its previous schema. Rebuild the [web client](./web.mdx#web-client) too, if you have one. Skipping versions is fine: migrations apply in order. The exception is federations older than 0.2.0 that kept their data in SQLite: release 0.2.0 converts them first (`mvp-stack.py convert` from its checkout), and only then can they upgrade further. ### Checking the data before an upgrade [#checking-the-data-before-an-upgrade] After the `git checkout` of the new version, but before `up`: ```sh python3 tools/mvp-stack.py preflight ``` The command builds the migrator of the new version and checks the database: whether the data will pass the migrations (for example, no conflicts of public names and owners). Neither data nor schema change. The federation server stops for the check, which refuses while it writes to the database, and then starts again on the old version. `up` runs the same check before migrating and leaves the database alone on a conflict. ### Order with several processes [#order-with-several-processes] - Upgrade gateways **before** the primary server. - Upgrade the SFU **together** with the server. ## Required app updates [#required-app-updates] Some server versions do not work with old apps. Then the server raises the minimum app level, and an outdated app shows the update screen with the link from `--client-update-url` ([app versions](./app-updates.mdx)). The changelog marks such versions. People's data stays: after updating, the app shows their earlier chats. ## Rolling back [#rolling-back] The database schema does not migrate backwards, and an old server will not start on a database newer than itself. A rollback is restoring the backup taken before the upgrade, on the old version. `restore` never touches existing volumes, so on the same machine the copy comes up as a separate Docker project, after the upgraded stack is stopped: ```sh python3 tools/mvp-stack.py stop --state .local/mvp git checkout v0.2.4 python3 tools/mvp-stack.py restore --state .local/rollback --project comon-rollback --backup /absolute/path/before-v0.2.5 python3 tools/mvp-stack.py up --state .local/rollback --project comon-rollback ``` From then on pass `--state .local/rollback --project comon-rollback` to every command of that stack. The stopped stack's volumes stay: delete them only once the rollback has proven itself. Everything people wrote after the backup is lost in a rollback, and the [first start from a backup](./backups.mdx#first-start-from-a-backup) holds outbound work until `release-outbound`. ## Moving to another domain [#moving-to-another-domain] A federation's identity is its ID and Noise key, not its domain: keep both. 1. Point the new domain's DNS at the server and register the new redirect URI `https:///auth/oidc/callback` with the sign-in provider. The `issuer` stays. 2. Route **both** domains to the server, the relay and the web client in the proxy. 3. Start the server with `--public-origin` and `--web-client` of the new domain: the federation document, link pages and sign-in start naming it. 4. Update the media addresses for the new domain: `calls.json`, `sfu.env`, the TURN TLS certificate. 5. Leave the relay's entry in `federation-push.json` unchanged: both domains lead to the same relay, and a device binding remembers its relay. 6. A web client on the new address needs its own `webpush` section in `relay.json` and its own `web.env`. Browsers keep data per address, so web users sign in once more. Apps that already added your federation remember the **old** address and keep going through it, so **keep the old domain as an alias** of the same federation. New sign-ins and call links go to the new domain. Only apps whose build has the new address as their default federation move by themselves. # Web client and links (/docs/en/selfhost/web) ## Web client [#web-client] The web client is the same Comon app built for the browser. The ready-made stack serves it at `https:///app/` from the `comon_web` image (Caddy, port 8080 inside the network, no TLS). It is built on a machine with the Flutter version from `mise.toml` (Flutter does not run inside Docker): ```sh mise run build:web -- .local/mvp/web-context python3 tools/mvp-stack.py up ``` The script runs `flutter build web --wasm --release` and puts the build into `web-context/site`; `up` turns on the `web` service as soon as an `index.html` is there. Rebuild the web client on every upgrade. The server must know the web client's address, or sign-in in the browser will not return to the app: `--web-client=https:///app` (the ready-made stack adds it). ### Image settings [#image-settings] The variables live in `web.env` in the state. Values may contain only URL and base64url characters. | Variable | Meaning | |---|---| | `COMON_WEB_BASE_PATH` | The client's path, such as `/app` (`/` by default). | | `COMON_WEB_MODE` | `multi` (default: people choose a federation) or `single` (only yours). | | `COMON_WEB_HOME_FEDERATION` | The default federation; required for `single`. | | `COMON_WEB_ENVIRONMENT` | `dev`, `stage` or `prod` (default). | | `COMON_WEB_PUSH_RELAY_ORIGIN`, `COMON_WEB_PUSH_RELAY_AUDIENCE`, `COMON_WEB_PUSH_RELAY_PUBLIC_KEY`, `COMON_WEB_VAPID_PUBLIC_KEY` | The relay for Web Push: address, `audience`, receipt key and VAPID public key. All four or none. | | `COMON_WEB_SENTRY_DSN` | Where error reports go; without it nothing is sent. | At start the image writes `comon-web.json` from these variables. Your own file mounted at `/config/comon-web.json` replaces the generated one entirely. For the web client to get notifications, the relay needs a `webpush` section with its address and VAPID key ([push notifications](./push.mdx#relay-settings-relayjson)). For calls from networks where UDP is blocked you need [TURN over TLS](./calls.mdx#turn-over-tls). The image sends strict headers: isolation for wasm (`Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`), a same-origin-only `Content-Security-Policy`, `Referrer-Policy: no-referrer`. Files with a hash in their names are cached for a year, entry points are not cached. Check: ```sh curl -sI https:///app/ | grep -i -E 'cache-control|cross-origin|content-security' curl -s https:///app/comon-web.json ``` ## Link pages [#link-pages] The server answers the links `https:///u/`, `/join/` and `/call/` itself (and the old `/@name`, `/+code`): it shows a script-free page in Russian or English, with a preview and "open in the app", "open the web version" and "download" buttons. What opens on which device is in [Comon links](../features/links.mdx). | Option | What it changes | |---|---| | `--link-scheme` | The scheme the page opens the app with. `comon` by default. | | `--web-client` | Where "open the web version" leads. | | `--client-update-url` | "Download" links per platform ([app versions](./app-updates.mdx)). | Invite and call pages are hidden from search engines. One address may open at most 60 link pages a minute; past that pages come without a preview. ## Opening links straight in the apps [#opening-links-straight-in-the-apps] On iPhone, Mac and Android the system can open a domain's links right in the app, without the browser. That takes two sides: 1. **The server** names the apps the domain trusts: ``` --apple-app-id=. # repeatable --android-app=: # repeatable ``` The server then serves `/.well-known/apple-app-site-association` and `/.well-known/assetlinks.json`. Without the options both paths answer 404. 2. **The app** must be built with this domain (Associated Domains on Apple, an App Links filter on Android). The official builds know only `comon.chat`, so for your own domain this works only with your own build. Without that, links still work: the federation's page opens, and its button passes the link to the app through the `comon://` scheme. On Windows and Linux it always works this way: the installer registers the scheme. Links inside messages the app opens itself on any domain: it checks the federation document at that address. ## The federation's public pages [#the-federations-public-pages] `/rules`, `/child-safety` and `/delete-account` show the rules, child safety standards and how to delete an account, in the language from `?lang=ru|en` or the browser's header. Their text comes from the [federation settings](./federation-settings.mdx); app stores require such pages.