Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ADR 0039 — Messenger links: Telegram and Slack, templates as nodes, chat users by pairing

Status: proposed · 2026-11-07, amended 2026-11-08 (two links on one core, owner remark), numbered 0039 at the merge on 2026-11-09 (written as 0037 on its branch; 0037 and 0038 were taken on main) (owner request: a link for Telegram and Slack; the bot must be configurable for the many message kinds and formats Telegram has, “through actions or by creating nodes” — analyse which; and a structured answer to who may use the bot, so that other people cannot reach it).

Context

Sites want notifications and a small amount of remote interaction in the chats people already carry: an alarm in a Telegram group, a shift report in a Slack channel, “what is the boiler temperature” from a phone. Telegram’s Bot API has dozens of send methods and options (text in HTML or MarkdownV2, photos, documents, locations, polls, media groups, inline keyboards, forum topics, silent and protected messages, link previews, edits, reactions); Slack has chat.postMessage with mrkdwn and Block Kit. Both are HTTPS APIs with a bearer-like token.

What exists: portable Apps (ADR 0023, 0030) run one source embedded, as a process and as WASM, with tls_connect under the link’s net, a sealed store and random_bytes; the uplink (ADR 0035) is the pattern for “a platform client set up by Add actions with a secret from Set Password”; ADR 0029 makes a stored definition keep its author’s rights. Flows, the alarm link and the scheduler can invoke actions at write.

How to customise what a bot sends: actions or nodes

Three shapes were weighed:

  1. Everything in the action’s arguments (send {chat, method, text, parse_mode, reply_markup, …}). Full coverage, nothing to set up, but every caller (a flow, the alarm link, an operator) has to know the platform’s API, the chat ids and the escaping rules; a caller with write could send to any chat the bot is in; nothing is reusable or reviewable.
  2. One node per message kind / option (photos/…, polls/…). Mirrors the API but multiplies node kinds with every Telegram release and still leaves “to whom” and “what text” to the caller.
  3. Nodes for what is configured, actions for what happens — the DSA way the rest of WYRM follows (connections, devices, points are nodes; Add/Edit/Remove are actions on them). The configuration that needs review — who receives and what a message looks like — becomes nodes made at config; sending is an action at write whose form is generated from the node.

Who may use a bot

A bot token is the bot: whoever holds it reads every update and writes anywhere the bot is. Telegram bots are public — anyone can find one by its name and write to it, and anyone can add it to a group. Slack bots are reachable by everyone in the workspace once invited to a channel. So the question has two sides: who on the WYRM side may make the bot do something, and who on the chat side the bot listens to.

Decision

  • One link per platform on a shared core (amended 2026-11-08, owner remark: the platforms differ in what they can do and will grow apart, and more will come). crates/wyrm-messenger holds what every chat platform shares — bots, recipients, templates and their escaping, the queue and its pacing, pairing, chat commands and the three bounds — as Messenger<C>, a portable App over a Platform description: the API’s paths, request bodies and reply classes, the token’s shape, chat and thread ids, the send_raw allowlist, and what it can do (inbound: updates, chat users, user:<name> recipients; command_buttons; blocks; per-chat pacing; bearer or path token). Each platform is a link crate that fills that in and nothing else: links/telegram (Messenger<Telegram>, packages telegram and telegram-process) and links/slack (Messenger<Slack>, packages slack and slack-process). What a platform cannot do is not declared in its tree (a Slack bot has no users, no Invite User, no commands). Another messenger (Teams, Discord, Mattermost, Viber, Signal…) is one more crate with one Platform; a feature only one platform has is a field of Platform or an action of that link, never a branch on the platform’s name in the core. The test kit (wyrm-messenger feature testkit) runs any of them against a fake API on loopback.
  • Not embedded in wyrmd: a link needs egress to the internet and a token from an operator, which is a site’s decision (net: "api.telegram.org:443" or "slack.com:443", a read grant on the roots templates and chat users name, write for /set and /do). Root action add_bot (config); a bot is <bot>/{status, error, username, sent, failed, dropped, queued, rejected, last_sent, enabled} with set_token, test_connection, edit, remove (config). The token goes in with Set Token into the sealed store, never in a param, never shown or logged; an Edit that moves the API endpoint (URL or CA) deletes it (as ADR 0035’s amendment). api_url defaults to the public API and may name a local Telegram Bot API server; plain http only to loopback.
  • Option 3: nodes for configuration, actions for sending.
    • recipients/<r> (config): the only chats a bot writes to — a Telegram chat id, @channel or user:<paired user>, a Slack channel id; forum topic / thread_ts; silent; commands (whether paired users may command the bot in that group). Recipients are addressed by name, so callers never handle chat ids.
    • templates/<t> (config): kind (text, photo, document, location), format (Telegram html / markdown = MarkdownV2 / plain; Slack mrkdwn / plain, or Block Kit blocks JSON), text with {{placeholders}}, media, lat/lon, buttons (rows of Label | https://… or, on Telegram, Label | /command), silent, protect, preview, default to, and values (alias = wy/<site>/…): live values the link subscribes to and the text may name ({{alias}}, {{alias:.1}}, {{alias.q}}, {{alias.t}}); built-ins {{site}}, {{bot}}, {{now}}. Every filled-in value is escaped for the template’s markup (HTML entities, MarkdownV2 backslashes, mrkdwn entities; in Block Kit blocks mrkdwn entities and then JSON string content, amended 2026-11-09, as JSON alone left <!channel> and <url|text> active in text objects), so a value — a device name, an alarm message — never changes the markup or injects a link. Each template node declares its own send and preview (write) whose parameters are the template’s variables: a flow or the alarm link calls templates/high_temp ▸ send {limit: 80} and needs no knowledge of the API. A template keeps its author’s rights (ADR 0029): values outside them are refused at Add/Edit and never rendered after.
    • <bot> ▸ send {to, text, kind, format, media, lat, lon, silent} and recipients/<r> ▸ send (write): ad hoc messages, built-ins only (a variable is refused: “use a template”).
    • <bot> ▸ send_raw {method, params} (config): the rest of the API (polls, media groups, edits, pins, reactions) without a node kind per method. It fails closed (amended 2026-11-09, security review): methods are an explicit list of exact names per platform (Platform::raw_methods, the guides list them), each with the params that must name a chat (chat_id, from_chat_id, channel); every param of the API that names a chat or an account (Platform::raw_chat_params: Telegram chat_id, from_chat_id, user_id, sender_chat_id; Slack channel, channel_id, user, users) must be a recipient’s or a paired user’s chat wherever it appears; a missing chat param of the method, or a param whose chat cannot be checked (inline_message_id, business_connection_id, Slack file, file_comment), refuses the request. getUpdates, webhooks, logOut, close are never offered (they would take the bot’s inbound channel from the link). A prefix allowlist (send*, chat.*) and a check of one chat field only were the first version and let other fields and new methods through.
  • Delivery. One queue per bot (queue_max, default 500; the oldest is dropped and counted), flushed every 200 ms, at most 4 requests per event, one message per chat per second on Telegram; 429 holds the whole bot for retry_after; network errors and 5xx back off (1 s ×2 to 60 s) and keep the message (5 attempts); a refused message (400, 403, channel_not_found) is dropped and counted failed; a message whose markup does not parse is sent once more as plain text; a refused token (401/404, invalid_auth, …) makes the bot failed until Set Token. Delivery is at least once per attempt and best effort overall: an alarm that must not be lost is kept by the alarm link, not by the chat.
  • Who may use a bot: five layers, deny by default.
    1. The token is a secret of the link (sealed store, never logged, removed when the endpoint moves). The Telegram token is in the request path, so no error message is built from the request.
    2. WYRM levels. Defining bots, recipients, templates, users and raw requests is config; sending is write; the host checks the action’s level. Definitions keep their author’s rights (ADR 0029); a token without auth cannot define anything that acts later.
    3. The bot only talks to known chats. Sends go to recipients by name; raw requests only to a recipient’s or a paired user’s chat. A Telegram group or channel the bot is added to that is no recipient is left (leaveChat, leave_unknown, default on) and counted rejected; nothing from it is acted on.
    4. Chat identity by pairing, never by name. An operator invites a named user (<bot> ▸ invite_user {name, level: read | write, select: keys}); the link draws a one-time code from the host’s random source (10 Crockford base32 characters, 50 bits), returns it once, and keeps only its SHA-256 with an expiry of 15 minutes. The person sends /start <code> to the bot in a private chat; the link binds that account’s numeric Telegram id (from.id, which Telegram authenticates; usernames change hands and are never used). A code is single use, compared in constant time, typed leniently (case, dashes, O/0, I/L/1); 5 wrong codes lock an account out for an hour; a code posted in a group is void at once (it was exposed); an account already paired cannot take a second user. new_code re-pairs (a lost phone) and needs the caller to hold the user’s rights; so do edit and enable (amended 2026-11-09: enable hands the rights back to the paired account, the rights kept with the user stay the inviter’s); disable/remove at config. Unknown accounts are ignored; in a private chat they hear “not authorized” at most once an hour (the bot is no amplifier) and every rejection is counted and logged.
    5. Every command within three bounds at once: the user’s own level and select (key prefixes), the rights of the operator who invited or last edited the user (kept with it, ADR 0029; an invite or edit beyond the caller’s own rights is refused), and the link’s grants (the host). Writes never target the messenger itself. Commands: /get <key> (read), /set <key> <value>, /do <key> <action> (write), /whoami, /help; keys full or below the site. Group commands only where the recipient has commands: true and only from paired users. Inline buttons carry a command; a press runs it for the presser, under the presser’s pairing — a button in a group message gives nobody more than they have. Per user rate_per_min (20); each command is logged with the user, command and key (never a value).
  • Slack: send only, for now. Slack has no polling API for messages; receiving needs Socket Mode (a WebSocket client over the host’s TLS) or the Events API (an inbound HTTPS endpoint with signing secret verification). Both are later work; until then Slack bots refuse commands, /command buttons and invite_user. The pairing model carries over unchanged (Slack user id + team id instead of the Telegram id).
  • Updates by polling, not webhooks. getUpdates with timeout=0 every poll_s (3 s) — no inbound port, no public URL, works behind NAT; the next offset is kept in the store so a restart never replays commands. A webhook set by someone else on the same token makes Telegram answer 409, shown as the bot’s error.

Consequences

  • Configuration a reviewer cares about — who receives, what is said, which values leave the site, who may command — is in the tree as nodes, with their rights kept; senders (flows, the alarm link, the scheduler, operators) see one Send form per template.
  • New Telegram features need no new node kind: send_raw reaches them at config, and a template kind can be added when a feature becomes common.
  • A chat user can do no more than the operator who invited them, the user’s own level and keys, and the link’s grants all allow — the narrowest wins. Taking over a bot needs the token (the store) or a fresh, unexposed pairing code within 15 minutes.
  • Polling every 3 s costs one HTTPS request per bot per poll; commands: false turns it off for send-only bots.
  • No delivery guarantee beyond the queue; no message history in the broker; no inbound media.
  • Bounds: 8 bots, 64 recipients, 64 templates, 100 users per bot; 16 values and 4 KiB text per template; 16 KiB blocks; 10×8 buttons.

Alternatives

  • One messenger link for every platform (the first version, 2026-11-07). Refused by the owner: one package and one release for platforms that differ in features, an add_<platform> per platform on one root, and every new messenger touching the shared link. The core crate keeps the shared code in one place without that.
  • Everything in the send’s arguments (option 1). Refused as the main interface: callers need the API, chat ids and escaping; write would mean “any chat”. Kept as send_raw at config.
  • A node kind per Telegram method (option 2). Refused: the API grows faster than the tree should, and it still leaves recipients and text to the caller.
  • Allow lists of usernames or chat ids typed by the operator. Refused: usernames are reassigned, an operator typing ids proves nothing about who holds the account, and nothing would bind the chat account to rights. Pairing proves possession of the account once and binds rights to it.
  • Webhooks. They need a public HTTPS endpoint on the broker; polling needs only egress. A later option for a site with a reverse proxy.
  • Embedding it in every wyrmd, as the uplink. Refused: a messenger reaches the internet with a third-party token; it is installed where a site decides so.