From 58bafdbf760bfd481134004460786493ea5f65a1 Mon Sep 17 00:00:00 2001 From: shiv Date: Sat, 21 Nov 2026 16:33:15 +0530 Subject: [PATCH 1/2] feat(chatbridge): inbound chat bridge core with a Telegram long-poll transport First part of #5: the transport-agnostic bridge core, the Telegram adapter, the mandatory chat allowlist, storage, API and settings page. Task commands, main-agent routing and remote approvals follow in separate PRs on top of this one. - chatbridge: Transport interface and Router. The router enforces the allowlist (an unknown chat gets one refusal naming its chat ID, then silence, bounded memory), drops updates older than two minutes so a backlog is never executed, ignores bot senders and commands addressed to another bot, and dispatches commands (/help, /whoami for now). - Telegram transport: getUpdates long polling (no inbound port), plain-text sendMessage truncated to the Bot API limit, getMe for the identity. It reuses notify's dial guard and redirect policy through small exported wrappers, and its errors never carry the token. - Storage: migration 0015 adds chat_bridges, one row per kind. config is sealed at rest (added to secretColumns) and masked in the API with the notification-channel convention. The update cursor is committed before a batch is acted on, only moves forward, and is written only for the config_version the poller read, so a poll of a replaced token can never move the new bot's cursor. A token change clears it. - Server: one loop per transport started by server.New; it re-reads its row each round and Reload interrupts a poll in flight, so saving the form applies without a restart. Exponential backoff on errors, honours Telegram's retry_after, logs under [tgbot] without message text. - API: GET /api/chat-bridges, PUT /api/chat-bridges/{kind}, POST /api/chat-bridges/{kind}/test. A bridge may run with an empty allowlist: it then serves no chat and only sends the one-time refusal naming the chat ID, which is how an operator finds the ID to add. - Web: System -> Chat bot page with live status, zh-CN and tr strings. - Docs: docs/chat-bridge.md; README lists the token among stored secrets. The migration test lists 0015; the pre-0012 test rolls it back with the others and it re-applies (the migration is idempotent). Co-authored-by: krad <222954346+dar1k0@users.noreply.github.com> --- README.md | 2 + chatbridge/bridge.go | 128 +++++++ chatbridge/config.go | 73 ++++ chatbridge/router.go | 197 ++++++++++ chatbridge/router_test.go | 152 ++++++++ chatbridge/telegram.go | 265 +++++++++++++ chatbridge/telegram_test.go | 222 +++++++++++ db/chat_bridges.go | 105 ++++++ db/chat_bridges_test.go | 79 ++++ db/migrate_test.go | 7 +- db/migrations/0015_chat_bridges.sql | 25 ++ db/secrets.go | 6 +- docs/chat-bridge.md | 63 ++++ notify/http.go | 25 ++ server/chatbridge.go | 351 ++++++++++++++++++ server/chatbridge_api.go | 215 +++++++++++ server/chatbridge_test.go | 291 +++++++++++++++ server/server.go | 10 + .../app/(main)/system/chat-bridge/page.tsx | 259 +++++++++++++ web/src/i18n/locales/tr.json | 21 +- web/src/i18n/locales/zh-CN.json | 21 +- web/src/lib/api.ts | 14 + web/src/lib/types.ts | 29 ++ web/src/navigation/sidebar/sidebar-items.ts | 2 + 24 files changed, 2555 insertions(+), 7 deletions(-) create mode 100644 chatbridge/bridge.go create mode 100644 chatbridge/config.go create mode 100644 chatbridge/router.go create mode 100644 chatbridge/router_test.go create mode 100644 chatbridge/telegram.go create mode 100644 chatbridge/telegram_test.go create mode 100644 db/chat_bridges.go create mode 100644 db/chat_bridges_test.go create mode 100644 db/migrations/0015_chat_bridges.sql create mode 100644 docs/chat-bridge.md create mode 100644 server/chatbridge.go create mode 100644 server/chatbridge_api.go create mode 100644 server/chatbridge_test.go create mode 100644 web/src/app/(main)/system/chat-bridge/page.tsx diff --git a/README.md b/README.md index a11b4f34..5f14f676 100644 --- a/README.md +++ b/README.md @@ -772,6 +772,7 @@ gunzip -c backups/artex-db-.sql.gz | docker compose exec -T postgres ``` Stored secrets (LLM API keys, proxies and gateway custom headers, MCP env, task credentials, notification channel config, +the chat bot token, Brave/Tavily search keys, web search and global proxies, the execution spec of custom tools, the capture-proxy rewrite rules) are encrypted in the database with the key in `keys/secret.key` (generated at first start, mode 0600, @@ -960,6 +961,7 @@ Please report vulnerabilities privately through GitHub Security Advisories; see Operational security properties: - **Secrets at rest**: LLM keys/proxies/gateway headers, MCP environment, task credentials, notification config, + the chat bot token, search keys, proxies, custom-tool execution specs, capture-proxy rewrite rules and traffic evidence snapshots are encrypted with AES-256-GCM using `keys/secret.key` (or `ARTEX_SECRET_KEY`). ARTEX refuses to start when diff --git a/chatbridge/bridge.go b/chatbridge/bridge.go new file mode 100644 index 00000000..4978ac6c --- /dev/null +++ b/chatbridge/bridge.go @@ -0,0 +1,128 @@ +// Package chatbridge is the inbound side of the chat-app integration: an +// operator talks to ARTEX from a chat app (Telegram first) instead of the web +// UI. The outbound side, pushing findings, stays in package notify. +// +// The package is transport-agnostic. A Transport only knows how to fetch new +// updates, send a text reply and identify the bot; the Router owns every rule +// that does not depend on the chat app: the chat allowlist, the one-line +// refusal for unknown chats, dropping stale updates and command parsing. +// +// Like notify, the package imports nothing from db or server and transports +// are stateless: the configuration arrives as map[string]any (the decrypted +// chat_bridges.config row) on every call, so a token rotation takes effect on +// the next call without a restart. +package chatbridge + +import ( + "context" + "fmt" + "sort" + "strings" + "time" +) + +// Update is one inbound event from a chat app, already normalized. +type Update struct { + // ID is the transport's cursor. The next Poll asks for updates after it. + ID int64 + // ChatID identifies the conversation (a private chat or a group). It is the + // unit the allowlist works on. + ChatID string + // ChatType is the transport's own label, for example "private" or "group". + ChatType string + // UserID and UserName identify the sender inside the chat. They are kept + // for attribution in logs; the allowlist does not look at them. + UserID string + UserName string + // FromBot is set when the sender is itself a bot. Bot messages are ignored + // so two bots in one group cannot drive each other. + FromBot bool + // Text is the message text. Empty for updates that carry no text (stickers, + // photos, joins); those are ignored. + Text string + // Date is when the chat app received the message. + Date time.Time +} + +// Identity describes the bot account behind a configuration. +type Identity struct { + ID string `json:"id"` + UserName string `json:"username"` + Name string `json:"name"` +} + +// Transport is one chat app. +type Transport interface { + // Kind is the stable identifier stored in chat_bridges.kind. + Kind() string + // Validate checks a configuration before it is saved or used. + Validate(cfg map[string]any) error + // SecretKeys names the configuration fields that are credentials. They + // are sealed at rest by the db layer and masked in API responses. + SecretKeys() []string + // DestinationKeys names the fields that decide where the credentials are + // sent. Changing one requires re-entering every secret. + DestinationKeys() []string + // ValidateChatID checks one allowlist entry. + ValidateChatID(id string) error + // Identity asks the chat app which bot the configuration belongs to. + Identity(ctx context.Context, cfg map[string]any) (Identity, error) + // Poll returns the updates after cursor offset. It may block up to the + // transport's long-poll window and returns early when ctx ends. + Poll(ctx context.Context, cfg map[string]any, offset int64) ([]Update, error) + // Send delivers a plain-text reply to a chat. Transports truncate text + // that exceeds the chat app's message limit. + Send(ctx context.Context, cfg map[string]any, chatID, text string) error +} + +var registry = map[string]Transport{ + KindTelegram: telegramTransport{}, +} + +// Get returns the transport of a kind. +func Get(kind string) (Transport, bool) { + t, ok := registry[kind] + return t, ok +} + +// Kinds lists the registered transport kinds in a stable order. +func Kinds() []string { + out := make([]string, 0, len(registry)) + for k := range registry { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// MaxAllowedChats caps the allowlist. The bridge is an operator console, not +// a broadcast channel; a long list is more likely a mistake than a need. +const MaxAllowedChats = 50 + +// NormalizeAllowedChats trims, validates and de-duplicates an allowlist, +// keeping the operator's order. +func NormalizeAllowedChats(t Transport, ids []string) ([]string, error) { + out := make([]string, 0, len(ids)) + seen := map[string]bool{} + for _, raw := range ids { + id := strings.TrimSpace(raw) + if id == "" || seen[id] { + continue + } + if err := t.ValidateChatID(id); err != nil { + return nil, fmt.Errorf("chat id %q: %w", id, err) + } + seen[id] = true + out = append(out, id) + } + if len(out) > MaxAllowedChats { + return nil, fmt.Errorf("at most %d chats can be allowed", MaxAllowedChats) + } + return out, nil +} + +// The allowlist is mandatory in the sense that matters: the Router serves only +// listed chats, and every other chat gets one refusal and then silence. An +// empty allowlist is therefore a valid, closed state rather than an error: the +// bridge runs, serves nobody, and answers each chat with the refusal that names +// its chat ID. That is how an operator learns the ID to add. diff --git a/chatbridge/config.go b/chatbridge/config.go new file mode 100644 index 00000000..ed481662 --- /dev/null +++ b/chatbridge/config.go @@ -0,0 +1,73 @@ +package chatbridge + +import ( + "errors" + "fmt" + + "github.com/Autumn-27/artex/notify" +) + +// The masking convention is the one the notification channels use, so the UI +// handles both forms the same way: a credential is echoed as +// notify.MaskedPrefix plus its last characters, sending the masked value back +// unchanged keeps the stored secret, and an empty string clears the field. + +// MaskConfig returns a copy of cfg with the transport's credential fields +// masked. An unknown kind yields an empty map rather than the raw config. +func MaskConfig(kind string, cfg map[string]any) map[string]any { + t, ok := Get(kind) + if !ok { + return map[string]any{} + } + secrets := map[string]bool{} + for _, k := range t.SecretKeys() { + secrets[k] = true + } + out := make(map[string]any, len(cfg)) + for k, v := range cfg { + if !secrets[k] { + out[k] = v + continue + } + if s, ok := v.(string); ok && s != "" { + out[k] = notify.MaskedValue(s) + } + } + return out +} + +// PrepareConfigUpdate merges an incoming configuration from the API into the +// stored one. +// +// A masked secret keeps the stored value. When a destination field changes +// (for example base_url, which decides where the bot token is sent) every +// secret must be supplied again in clear: a masked value would otherwise send +// the old token to the new address. +func PrepareConfigUpdate(kind string, stored, incoming map[string]any) (map[string]any, error) { + t, ok := Get(kind) + if !ok { + return nil, fmt.Errorf("chat bridge kind %q is not registered", kind) + } + if stored == nil { + stored = map[string]any{} + } + changed := false + for _, k := range t.DestinationKeys() { + in, present := incoming[k] + if !present { + continue + } + if fmt.Sprint(in) != fmt.Sprint(stored[k]) && !(in == "" && stored[k] == nil) { + changed = true + } + } + if changed { + for _, k := range t.SecretKeys() { + s, _ := incoming[k].(string) + if s == "" || notify.IsMasked(s) { + return nil, errors.New("the API address changed: enter the bot token again") + } + } + } + return notify.MergeConfig(stored, incoming), nil +} diff --git a/chatbridge/router.go b/chatbridge/router.go new file mode 100644 index 00000000..2e48077c --- /dev/null +++ b/chatbridge/router.go @@ -0,0 +1,197 @@ +package chatbridge + +import ( + "context" + "fmt" + "sort" + "strings" + "sync" + "time" +) + +// MaxUpdateAge is how old an update may be and still be acted on. +// +// Chat apps queue updates while the bridge is offline (Telegram keeps them for +// a day). Executing a backlog after a restart or an outage would run commands +// the operator typed long ago and has likely given up on, such as resuming a +// task they meant to keep paused. Anything older than this is dropped and +// logged instead. +const MaxUpdateAge = 2 * time.Minute + +// maxRefusedChats bounds the memory of chats that were already refused once. +const maxRefusedChats = 1024 + +// Request is one authorized message handed to a command. +type Request struct { + Kind string // transport kind + ChatID string + UserID string + UserName string + Command string // lower-case command name without the slash; "" for plain text + Args string // text after the command, or the whole text when Command is "" +} + +// CommandFunc handles one command and returns the reply text. An empty reply +// sends nothing. +type CommandFunc func(ctx context.Context, req Request) string + +// Command is one entry of the command table. +type Command struct { + Name string // without the slash, lower case + Usage string // argument hint shown by /help, for example "" + Summary string // one line shown by /help + Run CommandFunc +} + +// Decision is what the Router did with an update, for logging and tests. +type Decision int + +const ( + DecisionIgnored Decision = iota // no text, a bot sender, or a command for another bot + DecisionStale // older than MaxUpdateAge + DecisionRefused // unknown chat, refusal sent + DecisionMuted // unknown chat, already refused once + DecisionHandled // allowed chat, a command or text handler ran +) + +func (d Decision) String() string { + switch d { + case DecisionStale: + return "stale" + case DecisionRefused: + return "refused" + case DecisionMuted: + return "muted" + case DecisionHandled: + return "handled" + default: + return "ignored" + } +} + +// Router applies the transport-independent rules to an update and picks the +// handler. It is safe for concurrent use. +type Router struct { + // BotUserName, when set, lets the router tell "/help@this_bot" from + // "/help@another_bot" in a group. Commands addressed to another bot are + // ignored. + BotUserName string + // Commands is the command table. /help is built in. + Commands []Command + // Text handles a message that is not a command. Nil replies with a hint to + // use /help. + Text CommandFunc + // Now is the clock; nil uses time.Now. + Now func() time.Time + + mu sync.Mutex + refused map[string]bool +} + +// Route decides what to do with an update from an allowed or unknown chat and +// returns the reply to send (possibly empty). +func (r *Router) Route(ctx context.Context, kind string, allowed []string, u Update) (Decision, string) { + if u.FromBot || strings.TrimSpace(u.Text) == "" { + return DecisionIgnored, "" + } + now := time.Now + if r.Now != nil { + now = r.Now + } + if !u.Date.IsZero() && now().Sub(u.Date) > MaxUpdateAge { + return DecisionStale, "" + } + if !contains(allowed, u.ChatID) { + return r.refuse(u.ChatID) + } + + name, args, forOther := parseCommand(u.Text, r.BotUserName) + if forOther { + return DecisionIgnored, "" + } + req := Request{Kind: kind, ChatID: u.ChatID, UserID: u.UserID, UserName: u.UserName, Command: name, Args: args} + if name == "" { + if r.Text == nil { + return DecisionHandled, "Send /help to see what this bot can do." + } + return DecisionHandled, r.Text(ctx, req) + } + if name == "help" || name == "start" { + return DecisionHandled, r.help() + } + for _, c := range r.Commands { + if c.Name == name { + return DecisionHandled, c.Run(ctx, req) + } + } + return DecisionHandled, fmt.Sprintf("Unknown command /%s. Send /help to see the commands.", name) +} + +// refuse answers an unknown chat once per process and then stays silent, so a +// stranger who found the bot cannot use it to make it talk. The chat id is in +// the refusal so the operator can add it to the allowlist when the chat is +// their own; it is the chat's own identifier and reveals nothing else. +func (r *Router) refuse(chatID string) (Decision, string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.refused == nil { + r.refused = map[string]bool{} + } + if r.refused[chatID] { + return DecisionMuted, "" + } + if len(r.refused) >= maxRefusedChats { + // A flood of distinct chats: stop answering any new one rather than + // grow without bound or forget earlier refusals. + return DecisionMuted, "" + } + r.refused[chatID] = true + return DecisionRefused, "This chat is not allowed to use this ARTEX bot. If it is yours, add chat ID " + chatID + " to the allowlist in ARTEX (System → Chat bot)." +} + +func (r *Router) help() string { + var b strings.Builder + b.WriteString("ARTEX bot commands:\n/help - this list") + cmds := append([]Command(nil), r.Commands...) + sort.Slice(cmds, func(i, j int) bool { return cmds[i].Name < cmds[j].Name }) + for _, c := range cmds { + b.WriteString("\n/") + b.WriteString(c.Name) + if c.Usage != "" { + b.WriteString(" ") + b.WriteString(c.Usage) + } + if c.Summary != "" { + b.WriteString(" - ") + b.WriteString(c.Summary) + } + } + return b.String() +} + +// parseCommand splits "/name@bot args". It returns name "" for plain text, +// and forOther when the command is addressed to a different bot. +func parseCommand(text, botUserName string) (name, args string, forOther bool) { + text = strings.TrimSpace(text) + if !strings.HasPrefix(text, "/") { + return "", text, false + } + head, rest, _ := strings.Cut(text[1:], " ") + head, target, addressed := strings.Cut(head, "@") + if head == "" { + return "", text, false + } + if addressed && botUserName != "" && !strings.EqualFold(target, botUserName) { + return "", "", true + } + return strings.ToLower(head), strings.TrimSpace(rest), false +} + +func contains(list []string, v string) bool { + for _, s := range list { + if s == v { + return true + } + } + return false +} diff --git a/chatbridge/router_test.go b/chatbridge/router_test.go new file mode 100644 index 00000000..5d4ea434 --- /dev/null +++ b/chatbridge/router_test.go @@ -0,0 +1,152 @@ +package chatbridge + +import ( + "context" + "strings" + "testing" + "time" +) + +var testNow = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + +func testRouter() *Router { + return &Router{ + BotUserName: "artex_bot", + Now: func() time.Time { return testNow }, + Commands: []Command{{ + Name: "echo", Usage: "", Summary: "repeat the text", + Run: func(_ context.Context, req Request) string { return "echo:" + req.Args + ":" + req.UserName }, + }}, + } +} + +func msg(chat, text string) Update { + return Update{ID: 1, ChatID: chat, UserID: "7", UserName: "op", Text: text, Date: testNow.Add(-time.Second)} +} + +func TestRouteAllowedCommand(t *testing.T) { + r := testRouter() + d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/echo hello world ")) + if d != DecisionHandled || reply != "echo:hello world:op" { + t.Fatalf("got %v %q", d, reply) + } +} + +func TestRouteCommandAddressedToThisOrOtherBot(t *testing.T) { + r := testRouter() + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/ECHO@Artex_Bot x")); d != DecisionHandled || !strings.HasPrefix(reply, "echo:x") { + t.Fatalf("own bot: got %v %q", d, reply) + } + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/echo@other_bot x")); d != DecisionIgnored || reply != "" { + t.Fatalf("other bot: got %v %q", d, reply) + } +} + +func TestRouteUnknownChatRefusedOnceThenMuted(t *testing.T) { + r := testRouter() + d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("555", "/echo hi")) + if d != DecisionRefused || !strings.Contains(reply, "555") { + t.Fatalf("first contact: got %v %q", d, reply) + } + if strings.Contains(reply, "echo") { + t.Fatalf("refusal must not run the command: %q", reply) + } + for i := 0; i < 3; i++ { + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("555", "hello?")); d != DecisionMuted || reply != "" { + t.Fatalf("repeat %d: got %v %q", i, d, reply) + } + } +} + +func TestRouteEmptyAllowlistRefusesEveryone(t *testing.T) { + r := testRouter() + if d, _ := r.Route(context.Background(), KindTelegram, nil, msg("100", "/help")); d != DecisionRefused { + t.Fatalf("got %v, want refused", d) + } +} + +func TestRouteRefusalMemoryIsBounded(t *testing.T) { + r := testRouter() + for i := 0; i < maxRefusedChats; i++ { + r.Route(context.Background(), KindTelegram, nil, msg("c"+itoa(i), "hi")) + } + if d, reply := r.Route(context.Background(), KindTelegram, nil, msg("brand-new", "hi")); d != DecisionMuted || reply != "" { + t.Fatalf("over the cap: got %v %q", d, reply) + } + if len(r.refused) > maxRefusedChats { + t.Fatalf("refused set grew to %d", len(r.refused)) + } +} + +func TestRouteDropsStaleAndBotAndEmpty(t *testing.T) { + r := testRouter() + old := msg("100", "/echo late") + old.Date = testNow.Add(-MaxUpdateAge - time.Second) + if d, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, old); d != DecisionStale || reply != "" { + t.Fatalf("stale: got %v %q", d, reply) + } + // A stale message from an unknown chat is dropped before the refusal, so + // a backlog never produces a burst of refusals. + old.ChatID = "999" + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, old); d != DecisionStale { + t.Fatalf("stale unknown chat: got %v", d) + } + b := msg("100", "/echo x") + b.FromBot = true + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, b); d != DecisionIgnored { + t.Fatalf("bot sender: got %v", d) + } + if d, _ := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", " ")); d != DecisionIgnored { + t.Fatalf("empty text: got %v", d) + } +} + +func TestRouteHelpAndUnknownAndPlainText(t *testing.T) { + r := testRouter() + _, help := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/start")) + if !strings.Contains(help, "/echo - repeat the text") || !strings.Contains(help, "/help") { + t.Fatalf("help = %q", help) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/nope")); !strings.Contains(reply, "Unknown command /nope") { + t.Fatalf("unknown = %q", reply) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "status please")); !strings.Contains(reply, "/help") { + t.Fatalf("plain text without handler = %q", reply) + } + r.Text = func(_ context.Context, req Request) string { return "text:" + req.Args } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "status please")); reply != "text:status please" { + t.Fatalf("plain text handler = %q", reply) + } + if _, reply := r.Route(context.Background(), KindTelegram, []string{"100"}, msg("100", "/")); reply != "text:/" { + t.Fatalf("bare slash = %q", reply) + } +} + +func TestNormalizeAllowedChats(t *testing.T) { + tr, _ := Get(KindTelegram) + got, err := NormalizeAllowedChats(tr, []string{" 123 ", "", "-1001234567890", "123"}) + if err != nil || strings.Join(got, ",") != "123,-1001234567890" { + t.Fatalf("got %v %v", got, err) + } + if _, err := NormalizeAllowedChats(tr, []string{"@channel"}); err == nil { + t.Fatal("a username must be refused: updates carry numeric ids") + } + many := make([]string, MaxAllowedChats+1) + for i := range many { + many[i] = itoa(i + 1) + } + if _, err := NormalizeAllowedChats(tr, many); err == nil { + t.Fatal("over the cap must be refused") + } +} + +func itoa(i int) string { + if i == 0 { + return "0" + } + var b []byte + for ; i > 0; i /= 10 { + b = append([]byte{byte('0' + i%10)}, b...) + } + return string(b) +} diff --git a/chatbridge/telegram.go b/chatbridge/telegram.go new file mode 100644 index 00000000..dd602158 --- /dev/null +++ b/chatbridge/telegram.go @@ -0,0 +1,265 @@ +package chatbridge + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/Autumn-27/artex/notify" +) + +// KindTelegram is the Telegram Bot API transport. +const KindTelegram = "telegram" + +const ( + telegramDefaultBase = "https://api.telegram.org" + // telegramPollWindow is the long-poll timeout sent to getUpdates. The + // client timeout must stay above it, or every idle poll ends as an error. + telegramPollWindow = 25 * time.Second + telegramClientWindow = telegramPollWindow + 15*time.Second + // telegramPollLimit caps one getUpdates batch. + telegramPollLimit = 50 + // telegramTextLimit is the Bot API message limit (4096 characters). The + // reply is cut a little earlier to leave room for the ellipsis. + telegramTextLimit = 4000 + // telegramBodyLimit caps a response body; 50 text updates fit well inside. + telegramBodyLimit = 1 << 20 +) + +// telegramClient is shared by every Telegram call of the bridge. It carries +// notify's dial guard and refuses cross-host redirects: the bot token is in +// the URL path, so following a redirect to another host would hand it over. +var telegramClient = notify.NewGuardedClient(telegramClientWindow) + +// A bot token is ":". Rejecting anything else keeps a pasted +// value with a slash or whitespace from changing the request path. +var telegramTokenRe = regexp.MustCompile(`^[0-9]{1,20}:[A-Za-z0-9_-]{20,100}$`) + +// Chat ids are signed integers; groups and channels are negative. +var telegramChatIDRe = regexp.MustCompile(`^-?[0-9]{1,20}$`) + +type telegramTransport struct{} + +func (telegramTransport) Kind() string { return KindTelegram } + +// The bot token is the whole credential. base_url decides where it is sent, so +// changing base_url requires entering the token again. +func (telegramTransport) SecretKeys() []string { return []string{"bot_token"} } +func (telegramTransport) DestinationKeys() []string { return []string{"base_url"} } + +func (telegramTransport) Validate(cfg map[string]any) error { + token := cfgString(cfg, "bot_token") + if token == "" { + return errors.New("missing bot token") + } + if !telegramTokenRe.MatchString(token) { + return errors.New(`the bot token should look like "123456789:AA…" as BotFather shows it`) + } + if base := cfgString(cfg, "base_url"); base != "" { + if err := notify.ValidateEndpointURL(base); err != nil { + return fmt.Errorf("invalid API URL: %w", err) + } + } + return nil +} + +func (telegramTransport) ValidateChatID(id string) error { + if !telegramChatIDRe.MatchString(id) { + return errors.New("a Telegram chat id is a number, for example 123456789 or -1001234567890") + } + return nil +} + +type telegramUser struct { + ID int64 `json:"id"` + IsBot bool `json:"is_bot"` + UserName string `json:"username"` + FirstName string `json:"first_name"` +} + +type telegramUpdate struct { + UpdateID int64 `json:"update_id"` + Message *struct { + Date int64 `json:"date"` + Chat struct { + ID int64 `json:"id"` + Type string `json:"type"` + } `json:"chat"` + From *telegramUser `json:"from"` + Text string `json:"text"` + } `json:"message"` +} + +type telegramResponse[T any] struct { + OK bool `json:"ok"` + Result T `json:"result"` + ErrorCode int `json:"error_code"` + Description string `json:"description"` + Parameters *struct { + RetryAfter int `json:"retry_after"` + } `json:"parameters"` +} + +func (t telegramTransport) Identity(ctx context.Context, cfg map[string]any) (Identity, error) { + var me telegramUser + if err := t.call(ctx, cfg, "getMe", nil, &me); err != nil { + return Identity{}, err + } + return Identity{ID: strconv.FormatInt(me.ID, 10), UserName: me.UserName, Name: me.FirstName}, nil +} + +func (t telegramTransport) Poll(ctx context.Context, cfg map[string]any, offset int64) ([]Update, error) { + req := map[string]any{ + "timeout": int(telegramPollWindow / time.Second), + "limit": telegramPollLimit, + "allowed_updates": []string{"message"}, + } + if offset > 0 { + req["offset"] = offset + } + var raw []telegramUpdate + if err := t.call(ctx, cfg, "getUpdates", req, &raw); err != nil { + return nil, err + } + out := make([]Update, 0, len(raw)) + for _, r := range raw { + u := Update{ID: r.UpdateID} + if m := r.Message; m != nil { + u.ChatID = strconv.FormatInt(m.Chat.ID, 10) + u.ChatType = m.Chat.Type + u.Text = m.Text + u.Date = time.Unix(m.Date, 0) + if m.From != nil { + u.UserID = strconv.FormatInt(m.From.ID, 10) + u.UserName = m.From.UserName + u.FromBot = m.From.IsBot + } + } + // Updates without a message still advance the cursor; the Router + // ignores them because they carry no text. + out = append(out, u) + } + return out, nil +} + +func (t telegramTransport) Send(ctx context.Context, cfg map[string]any, chatID, text string) error { + if err := t.ValidateChatID(chatID); err != nil { + return err + } + body := map[string]any{ + "chat_id": chatID, + "text": truncateRunes(text, telegramTextLimit), + // Plain text on purpose: no parse_mode, so agent output can never be + // rejected for a stray markup character or render as a link. + "link_preview_options": map[string]any{"is_disabled": true}, + } + return t.call(ctx, cfg, "sendMessage", body, nil) +} + +// call performs one Bot API method. Every error it returns is safe to log and +// to show in the UI: it never contains the request URL, and so never the token. +func (t telegramTransport) call(ctx context.Context, cfg map[string]any, method string, payload, result any) error { + if err := t.Validate(cfg); err != nil { + return err + } + base := strings.TrimRight(cfgString(cfg, "base_url"), "/") + if base == "" { + base = telegramDefaultBase + } + endpoint := base + "/bot" + cfgString(cfg, "bot_token") + "/" + method + + var body io.Reader + if payload != nil { + raw, err := json.Marshal(payload) + if err != nil { + return fmt.Errorf("telegram %s: build request: %w", method, err) + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, body) + if err != nil { + return fmt.Errorf("telegram %s: invalid API address", method) + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := telegramClient.Do(req) + if err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return fmt.Errorf("telegram %s: %s", method, notify.RedactTransportError(err)) + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, telegramBodyLimit)) + if err != nil { + return fmt.Errorf("telegram %s: read response: %w", method, err) + } + + var env telegramResponse[json.RawMessage] + if err := json.Unmarshal(raw, &env); err != nil { + return fmt.Errorf("telegram %s: HTTP %d, response is not Bot API JSON: %s", method, resp.StatusCode, notify.OneLine(string(raw), 120)) + } + if !env.OK { + return telegramError(method, resp.StatusCode, env) + } + if result == nil { + return nil + } + if err := json.Unmarshal(env.Result, result); err != nil { + return fmt.Errorf("telegram %s: unexpected result: %w", method, err) + } + return nil +} + +// RetryAfterError asks the caller to wait before the next call. +type RetryAfterError struct { + After time.Duration + Msg string +} + +func (e *RetryAfterError) Error() string { return e.Msg } + +func telegramError(method string, status int, env telegramResponse[json.RawMessage]) error { + code := env.ErrorCode + if code == 0 { + code = status + } + desc := notify.OneLine(env.Description, 200) + switch code { + case http.StatusUnauthorized, http.StatusNotFound: + return fmt.Errorf("telegram %s: the bot token was rejected (%d %s)", method, code, desc) + case http.StatusConflict: + return fmt.Errorf("telegram %s: another poller or a webhook is using this bot token (%s); give ARTEX its own bot or remove the webhook", method, desc) + case http.StatusTooManyRequests: + after := 5 * time.Second + if env.Parameters != nil && env.Parameters.RetryAfter > 0 { + after = time.Duration(env.Parameters.RetryAfter) * time.Second + } + return &RetryAfterError{After: after, Msg: fmt.Sprintf("telegram %s: rate limited, retry after %s", method, after)} + } + return fmt.Errorf("telegram %s: %d %s", method, code, desc) +} + +func cfgString(cfg map[string]any, key string) string { + s, _ := cfg[key].(string) + return strings.TrimSpace(s) +} + +// truncateRunes cuts s to at most n runes, marking the cut. +func truncateRunes(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + r := []rune(s) + return string(r[:n-1]) + "…" +} diff --git a/chatbridge/telegram_test.go b/chatbridge/telegram_test.go new file mode 100644 index 00000000..8973c398 --- /dev/null +++ b/chatbridge/telegram_test.go @@ -0,0 +1,222 @@ +package chatbridge + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Autumn-27/artex/notify" +) + +const testToken = "123456789:AAtest_token-abcdefghijklmnop" + +// fakeTelegram records calls and answers from a per-method table. +type fakeTelegram struct { + mu sync.Mutex + calls []string + bodies map[string]map[string]any + answers map[string]func(w http.ResponseWriter) +} + +func newFakeTelegram(t *testing.T) (*fakeTelegram, map[string]any) { + t.Helper() + t.Setenv(notify.AllowLocalTargetsEnv, "1") // httptest listens on 127.0.0.1 + f := &fakeTelegram{bodies: map[string]map[string]any{}, answers: map[string]func(http.ResponseWriter){}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + prefix := "/bot" + testToken + "/" + if !strings.HasPrefix(r.URL.Path, prefix) { + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"ok":false,"error_code":404,"description":"Not Found"}`) + return + } + method := strings.TrimPrefix(r.URL.Path, prefix) + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + f.mu.Lock() + f.calls = append(f.calls, method) + f.bodies[method] = body + answer := f.answers[method] + f.mu.Unlock() + if answer == nil { + _, _ = io.WriteString(w, `{"ok":true,"result":true}`) + return + } + answer(w) + })) + t.Cleanup(srv.Close) + return f, map[string]any{"bot_token": testToken, "base_url": srv.URL} +} + +func (f *fakeTelegram) on(method, body string, status int) { + f.mu.Lock() + defer f.mu.Unlock() + f.answers[method] = func(w http.ResponseWriter) { + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + } +} + +func TestTelegramValidate(t *testing.T) { + tr := telegramTransport{} + cases := map[string]map[string]any{ + "missing token": {}, + "malformed token": {"bot_token": "not-a-token"}, + "path injection": {"bot_token": "123:abcdefghijklmnopqrstuvwxyz/../x"}, + "bad base url": {"bot_token": testToken, "base_url": "ftp://example.com"}, + } + for name, cfg := range cases { + if err := tr.Validate(cfg); err == nil { + t.Errorf("%s: want error", name) + } + } + if err := tr.Validate(map[string]any{"bot_token": testToken}); err != nil { + t.Fatalf("valid config refused: %v", err) + } +} + +func TestTelegramPollParsesAndSendsOffset(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getUpdates", `{"ok":true,"result":[ + {"update_id":41,"message":{"date":1763726400,"chat":{"id":-100123,"type":"group"},"from":{"id":7,"is_bot":false,"username":"op"},"text":"/help"}}, + {"update_id":42,"my_chat_member":{}} + ]}`, 200) + got, err := telegramTransport{}.Poll(context.Background(), cfg, 41) + if err != nil { + t.Fatal(err) + } + if len(got) != 2 { + t.Fatalf("want 2 updates (the second only advances the cursor), got %d", len(got)) + } + u := got[0] + if u.ID != 41 || u.ChatID != "-100123" || u.ChatType != "group" || u.UserID != "7" || u.UserName != "op" || u.Text != "/help" || u.FromBot { + t.Fatalf("update = %+v", u) + } + if !u.Date.Equal(time.Unix(1763726400, 0)) { + t.Fatalf("date = %v", u.Date) + } + if got[1].ID != 42 || got[1].Text != "" { + t.Fatalf("non-message update = %+v", got[1]) + } + body := f.bodies["getUpdates"] + if body["offset"] != float64(41) || body["timeout"] != float64(25) { + t.Fatalf("getUpdates body = %v", body) + } + if au, _ := body["allowed_updates"].([]any); len(au) != 1 || au[0] != "message" { + t.Fatalf("allowed_updates = %v", body["allowed_updates"]) + } +} + +func TestTelegramSendIsPlainTextAndTruncated(t *testing.T) { + f, cfg := newFakeTelegram(t) + long := strings.Repeat("é", telegramTextLimit+50) + if err := (telegramTransport{}).Send(context.Background(), cfg, "100", long); err != nil { + t.Fatal(err) + } + body := f.bodies["sendMessage"] + if _, ok := body["parse_mode"]; ok { + t.Fatal("replies must be sent as plain text") + } + text, _ := body["text"].(string) + if n := len([]rune(text)); n != telegramTextLimit || !strings.HasSuffix(text, "…") { + t.Fatalf("text has %d runes, suffix %q", n, text[len(text)-3:]) + } + if body["chat_id"] != "100" { + t.Fatalf("chat_id = %v", body["chat_id"]) + } + if err := (telegramTransport{}).Send(context.Background(), cfg, "@someone", "x"); err == nil { + t.Fatal("a non-numeric chat id must be refused") + } +} + +func TestTelegramIdentity(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getMe", `{"ok":true,"result":{"id":123456789,"is_bot":true,"username":"artex_bot","first_name":"ARTEX"}}`, 200) + id, err := telegramTransport{}.Identity(context.Background(), cfg) + if err != nil || id.UserName != "artex_bot" || id.ID != "123456789" || id.Name != "ARTEX" { + t.Fatalf("identity = %+v, %v", id, err) + } +} + +func TestTelegramErrorsNeverCarryTheToken(t *testing.T) { + f, cfg := newFakeTelegram(t) + f.on("getMe", `{"ok":false,"error_code":401,"description":"Unauthorized"}`, 401) + _, err := telegramTransport{}.Identity(context.Background(), cfg) + if err == nil || !strings.Contains(err.Error(), "token was rejected") { + t.Fatalf("401: %v", err) + } + f.on("getUpdates", `{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request"}`, 409) + _, err = telegramTransport{}.Poll(context.Background(), cfg, 0) + if err == nil || !strings.Contains(err.Error(), "another poller") { + t.Fatalf("409: %v", err) + } + f.on("sendMessage", `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":7}}`, 429) + err = telegramTransport{}.Send(context.Background(), cfg, "1", "x") + var ra *RetryAfterError + if !errors.As(err, &ra) || ra.After != 7*time.Second { + t.Fatalf("429: %v", err) + } + + // A transport failure: nothing listens on this address. The error must + // name the host but never the path that carries the token. + dead := map[string]any{"bot_token": testToken, "base_url": "http://127.0.0.1:1"} + _, err = telegramTransport{}.Identity(context.Background(), dead) + if err == nil { + t.Fatal("want a dial error") + } + for _, e := range []error{err} { + if strings.Contains(e.Error(), "AAtest_token") || strings.Contains(e.Error(), "/bot") { + t.Fatalf("error leaks the token: %v", e) + } + } +} + +func TestTelegramPollHonoursCancel(t *testing.T) { + f, cfg := newFakeTelegram(t) + release := make(chan struct{}) + f.mu.Lock() + f.answers["getUpdates"] = func(w http.ResponseWriter) { <-release } + f.mu.Unlock() + defer close(release) + ctx, cancel := context.WithCancel(context.Background()) + go func() { time.Sleep(50 * time.Millisecond); cancel() }() + start := time.Now() + _, err := telegramTransport{}.Poll(ctx, cfg, 0) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + if time.Since(start) > 5*time.Second { + t.Fatal("cancel did not interrupt the long poll") + } +} + +func TestConfigMaskAndPrepare(t *testing.T) { + stored := map[string]any{"bot_token": testToken} + masked := MaskConfig(KindTelegram, stored) + if s, _ := masked["bot_token"].(string); !notify.IsMasked(s) || strings.Contains(s, "AAtest") { + t.Fatalf("masked = %v", masked) + } + // Masked value sent back keeps the stored token. + got, err := PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": masked["bot_token"]}) + if err != nil || got["bot_token"] != testToken { + t.Fatalf("keep: %v %v", got, err) + } + // Changing base_url with a masked token is refused. + if _, err := PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": masked["bot_token"], "base_url": "https://tg.example.com"}); err == nil { + t.Fatal("destination change with a masked token must be refused") + } + // ...and accepted with the token in clear. + got, err = PrepareConfigUpdate(KindTelegram, stored, map[string]any{"bot_token": testToken, "base_url": "https://tg.example.com"}) + if err != nil || got["base_url"] != "https://tg.example.com" { + t.Fatalf("destination change: %v %v", got, err) + } + if m := MaskConfig("nope", stored); len(m) != 0 { + t.Fatalf("unknown kind must mask to empty, got %v", m) + } +} diff --git a/db/chat_bridges.go b/db/chat_bridges.go new file mode 100644 index 00000000..9461d6bf --- /dev/null +++ b/db/chat_bridges.go @@ -0,0 +1,105 @@ +package db + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "time" +) + +// ChatBridge is the stored configuration of one inbound chat bridge +// (migration 0015). Config is the decrypted JSON; parsing it is left to +// package chatbridge, like notification channel configs. +type ChatBridge struct { + ID int64 `json:"id"` + Kind string `json:"kind"` + Enabled bool `json:"enabled"` + Config json.RawMessage `json:"config"` + AllowedChats []string `json:"allowed_chats"` + PollOffset int64 `json:"poll_offset"` + // ConfigVersion grows on every save; SetChatBridgeOffset only writes for + // the version the poller read. + ConfigVersion int64 `json:"config_version"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// ErrChatBridgeNotFound is returned when no row exists for a kind. +var ErrChatBridgeNotFound = errors.New("chat bridge not configured") + +const chatBridgeCols = `id, kind, enabled, config, allowed_chats, poll_offset, config_version, created_at, updated_at` + +func scanChatBridge(sc interface{ Scan(...any) error }) (*ChatBridge, error) { + var b ChatBridge + var cfg, allowed string + if err := sc.Scan(&b.ID, &b.Kind, &b.Enabled, &cfg, &allowed, &b.PollOffset, &b.ConfigVersion, &b.CreatedAt, &b.UpdatedAt); err != nil { + return nil, err + } + plain, err := openSecret(colChatBridgeConfig, cfg) + if err != nil { + return nil, err + } + b.Config = json.RawMessage(plain) + if err := json.Unmarshal([]byte(allowed), &b.AllowedChats); err != nil { + return nil, err + } + if b.AllowedChats == nil { + b.AllowedChats = []string{} + } + return &b, nil +} + +// ChatBridgeByKind returns the bridge of a transport kind. +func (d *DB) ChatBridgeByKind(ctx context.Context, kind string) (*ChatBridge, error) { + row := d.QueryRowContext(ctx, `SELECT `+chatBridgeCols+` FROM chat_bridges WHERE kind=$1`, kind) + b, err := scanChatBridge(row) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrChatBridgeNotFound + } + return b, err +} + +// SaveChatBridge creates or replaces the configuration of b.Kind and bumps its +// config version. resetOffset clears the update cursor in the same statement; +// the caller sets it when the bot token changed, because update ids are per +// bot and the old cursor means nothing to the new one. +func (d *DB) SaveChatBridge(ctx context.Context, b *ChatBridge, resetOffset bool) (*ChatBridge, error) { + if b.Config == nil { + b.Config = json.RawMessage(`{}`) + } + if b.AllowedChats == nil { + b.AllowedChats = []string{} + } + cfg, err := sealSecret(colChatBridgeConfig, string(b.Config)) + if err != nil { + return nil, err + } + allowed, err := json.Marshal(b.AllowedChats) + if err != nil { + return nil, err + } + row := d.QueryRowContext(ctx, `INSERT INTO chat_bridges(kind, enabled, config, allowed_chats) +VALUES($1, $2, $3::jsonb, $4::jsonb) +ON CONFLICT (kind) DO UPDATE SET + enabled=EXCLUDED.enabled, config=EXCLUDED.config, allowed_chats=EXCLUDED.allowed_chats, + poll_offset=CASE WHEN $5 THEN 0 ELSE chat_bridges.poll_offset END, + config_version=chat_bridges.config_version+1, updated_at=NOW() +RETURNING `+chatBridgeCols, b.Kind, b.Enabled, cfg, string(allowed), resetOffset) + return scanChatBridge(row) +} + +// SetChatBridgeOffset records the transport cursor for the configuration +// version the poller read. It only moves forward, and it does nothing once +// the configuration was saved again, so neither a slow writer nor a poller +// of a replaced token can move the cursor of the current bot. It reports +// whether the cursor was written. +func (d *DB) SetChatBridgeOffset(ctx context.Context, kind string, version, offset int64) (bool, error) { + res, err := d.ExecContext(ctx, `UPDATE chat_bridges SET poll_offset=$3 +WHERE kind=$1 AND config_version=$2 AND poll_offset < $3`, kind, version, offset) + if err != nil { + return false, err + } + n, _ := res.RowsAffected() + return n > 0, nil +} diff --git a/db/chat_bridges_test.go b/db/chat_bridges_test.go new file mode 100644 index 00000000..ee1541e8 --- /dev/null +++ b/db/chat_bridges_test.go @@ -0,0 +1,79 @@ +package db + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestChatBridgeSaveSealedAndOffset(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + t.Cleanup(func() { _ = d.Close() }) + ctx := context.Background() + const kind = "t-bridge" + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) }) + + if _, err := d.ChatBridgeByKind(ctx, kind); !errors.Is(err, ErrChatBridgeNotFound) { + t.Fatalf("missing row: err = %v", err) + } + + const token = "123456789:AAsecret-bot-token-value" + b, err := d.SaveChatBridge(ctx, &ChatBridge{ + Kind: kind, + Enabled: true, + Config: json.RawMessage(`{"bot_token":"` + token + `"}`), + AllowedChats: []string{"100", "-1001"}, + }, false) + if err != nil { + t.Fatalf("SaveChatBridge: %v", err) + } + if !b.Enabled || b.PollOffset != 0 || b.ConfigVersion != 1 || strings.Join(b.AllowedChats, ",") != "100,-1001" || !strings.Contains(string(b.Config), token) { + t.Fatalf("saved = %+v (config %s)", b, b.Config) + } + + // The token never sits in clear in the table. + var raw string + if err := d.QueryRow(`SELECT config::text FROM chat_bridges WHERE kind=$1`, kind).Scan(&raw); err != nil { + t.Fatal(err) + } + if strings.Contains(raw, "AAsecret") || !strings.Contains(raw, sealedJSONKey) { + t.Fatalf("chat_bridges.config is not sealed at rest: %q", raw) + } + + // The cursor only moves forward. + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 42); err != nil || !ok { + t.Fatalf("set 42: %v %v", ok, err) + } + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 7); err != nil || ok { + t.Fatalf("rewind to 7 must be a no-op: %v %v", ok, err) + } + got, err := d.ChatBridgeByKind(ctx, kind) + if err != nil || got.PollOffset != 42 || !got.UpdatedAt.Equal(b.UpdatedAt) { + t.Fatalf("after cursor writes = %+v, %v; want offset 42 and updated_at unchanged", got, err) + } + + // Saving again updates in place, keeps the cursor and bumps the version. + b2, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: false, Config: json.RawMessage(`{"bot_token":"` + token + `"}`)}, false) + if err != nil { + t.Fatal(err) + } + if b2.ID != b.ID || b2.Enabled || b2.PollOffset != 42 || b2.ConfigVersion != 2 || len(b2.AllowedChats) != 0 { + t.Fatalf("update = %+v", b2) + } + + // A poller still holding version 1 cannot move the cursor any more. + if ok, err := d.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, 99); err != nil || ok { + t.Fatalf("stale version write must be a no-op: %v %v", ok, err) + } + + // A token change clears the cursor in the same save. + b3, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Config: json.RawMessage(`{"bot_token":"987654321:AAother-bot-token-value"}`)}, true) + if err != nil || b3.PollOffset != 0 || b3.ConfigVersion != 3 { + t.Fatalf("reset save = %+v, %v", b3, err) + } +} diff --git a/db/migrate_test.go b/db/migrate_test.go index bdbd6a42..d346638b 100644 --- a/db/migrate_test.go +++ b/db/migrate_test.go @@ -123,7 +123,7 @@ func readApplied(t *testing.T, d *DB) []appliedMigration { // embedded migration is recorded with the SHA-256 of its file. func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { t.Helper() - for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions"} { + for _, table := range []string{"llm_records", "llm_usage", "llm_context", "traffic_tamper_hooks", "traffic_tamper_hook_versions", "chat_bridges"} { var exists bool if err := d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, table).Scan(&exists); err != nil { t.Fatal(err) @@ -140,9 +140,10 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration { {5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}, {7, "0007_finding_report_state.sql"}, {8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"}, {11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}, - {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}} + {13, "0013_lesson_evidence_history.sql"}, {14, "0014_bedrock_gateway_profiles.sql"}, + {15, "0015_chat_bridges.sql"}} if len(applied) != len(want) { - t.Fatalf("schema_migrations = %+v, want versions 1 to 14", applied) + t.Fatalf("schema_migrations = %+v, want versions 1 to 15", applied) } for i, w := range want { content, err := fs.ReadFile(migrationsFS(), w.name) diff --git a/db/migrations/0015_chat_bridges.sql b/db/migrations/0015_chat_bridges.sql new file mode 100644 index 00000000..b7ca83da --- /dev/null +++ b/db/migrations/0015_chat_bridges.sql @@ -0,0 +1,25 @@ +-- Inbound chat bridges (issue #5): an operator drives ARTEX from a chat app. +-- One row per transport kind ('telegram' first). Global configuration: not +-- part of a task archive. +-- +-- config is sealed at rest by db/secrets.go (it holds the bot token) and +-- masked in API responses. allowed_chats is the mandatory allowlist of chat +-- ids, a JSON array of strings; the server refuses to enable a bridge while +-- it is empty. poll_offset is the transport's update cursor, committed before +-- an update is acted on so a restart never replays a command. +-- +-- config_version grows on every save. The poller writes its cursor only for +-- the version it read, so a cursor of the old bot can never land on a row +-- whose token was just replaced. updated_at is the time of the last save, +-- set by SaveChatBridge rather than a trigger, so cursor writes leave it alone. +CREATE TABLE IF NOT EXISTS chat_bridges ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL UNIQUE, + enabled BOOLEAN NOT NULL DEFAULT false, + config JSONB NOT NULL DEFAULT '{}'::jsonb, + allowed_chats JSONB NOT NULL DEFAULT '[]'::jsonb, + poll_offset BIGINT NOT NULL DEFAULT 0, + config_version BIGINT NOT NULL DEFAULT 1, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); diff --git a/db/secrets.go b/db/secrets.go index 2a47e58a..0c15fa8b 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -83,7 +83,9 @@ var ( colMCPEnv = secretColumn{"mcp_servers", "env", true, ""} colCredPass = secretColumn{"task_credentials", "password", false, ""} colNotifConfig = secretColumn{"notification_channels", "config", true, ""} - colToolExec = secretColumn{"tools", "exec", true, ""} // system=false rows: headers, proxy, body, code, command + // Inbound chat bridges: the config carries the bot token. + colChatBridgeConfig = secretColumn{"chat_bridges", "config", true, ""} + colToolExec = secretColumn{"tools", "exec", true, ""} // system=false rows: headers, proxy, body, code, command // Evidence head blocks carry the captured Cookie and Authorization headers. colEvReqHead = secretColumn{"traffic_evidence_snapshots", "req_head", false, ""} colEvRespHead = secretColumn{"traffic_evidence_snapshots", "resp_head", false, ""} @@ -96,7 +98,7 @@ var ( colHookSource = secretColumn{"traffic_tamper_hooks", "source", false, ""} colHookVerMatchers = secretColumn{"traffic_tamper_hook_versions", "matchers", true, ""} colHookVerSource = secretColumn{"traffic_tamper_hook_versions", "source", false, ""} - secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) + secretColumns = append([]secretColumn{colLLMKey, colLLMProxy, colLLMHeaders, colMCPEnv, colCredPass, colNotifConfig, colChatBridgeConfig, colToolExec, colEvReqHead, colEvRespHead, colRewriteMatchers, colRewriteActions, colHookMatchers, colHookSource, colHookVerMatchers, colHookVerSource}, secretSettingColumns()...) ) // secretSettingKeys are the settings stored encrypted, AAD "settings.". diff --git a/docs/chat-bridge.md b/docs/chat-bridge.md new file mode 100644 index 00000000..2f164e0e --- /dev/null +++ b/docs/chat-bridge.md @@ -0,0 +1,63 @@ +# Chat Bot (Inbound Chat Bridge) + +The chat bot lets an operator talk to ARTEX from a chat app instead of the web UI. Telegram is the +first transport. This page describes the bridge core: connecting a bot, the chat allowlist and how +updates are processed. Task commands, the main-agent conversation and remote approvals build on it +([issue #5](https://github.com/BaaRai/ARTEX/issues/5)). + +Outbound notifications (pushing findings to a chat) are a separate feature under +**System → Notifications** and keep working without the bot. + +--- + +## Setup + +1. Create a bot with [@BotFather](https://t.me/BotFather) and copy its token. Give ARTEX a bot of + its own: Telegram allows one consumer per token, so a token already used by another poller or by + a webhook fails with a conflict error. +2. Open **System → Chat bot**, paste the token, switch the bot on and save. **Test connection** asks + Telegram which bot the token belongs to; it sends no message. The status card shows **Online** + and the bot's username once it is polling. +3. With the allowlist still empty the bot serves no chat. From each chat you want to use (a private + chat or a group), send the bot any message: it answers once with a refusal that names the chat ID. +4. Add those chat IDs to **Allowed chat IDs** and save. The change applies at once. +5. Send `/help` to see the commands. `/whoami` shows the chat ID and your user ID. + +## Security model + +- **Only allowlisted chats are served.** A chat that is not listed gets one refusal line, naming its + chat ID, and is then ignored for the life of the process. An empty allowlist serves no chat at all; + that is the state a new bot starts in while you collect chat IDs. Allowing a group allows every + member of that group. +- **No inbound port.** The bot uses long polling (`getUpdates`) over outbound HTTPS. +- **The token is a secret.** It is encrypted at rest with `keys/secret.key` like other stored + secrets, shown masked in the UI and API, and never written to logs or error messages (errors keep + only the scheme and host of the API address). Changing the API address requires entering the + token again, so a stored token is never sent to a new host. +- **Same network guard as notifications.** Calls refuse loopback and link-local addresses (including + cloud metadata) unless `ARTEX_NOTIFY_ALLOW_LOCAL=1`, and never follow a cross-host redirect. +- **No replays.** The update cursor is committed before a batch is acted on, so a crash loses a + batch rather than running it twice. Messages older than two minutes when they reach ARTEX (for + example a backlog queued while ARTEX was down) are dropped and logged instead of executed. +- **Message text is not logged.** Logs (tag `[tgbot]`) record the chat, the sender and the decision. + +## Configuration changes + +Saving the form takes effect immediately, without a restart: a poll in progress is interrupted and +the new configuration is read. A new token clears the update cursor, because Telegram update IDs +are per bot. A batch fetched under a configuration that was replaced during the poll is dropped. + +## API + +All routes require the administrator JWT. + +| Method | Path | Purpose | +| --- | --- | --- | +| `GET` | `/api/chat-bridges` | Every transport with its masked configuration, allowlist and live status | +| `PUT` | `/api/chat-bridges/{kind}` | Save `enabled`, `config` and `allowed_chats`; omitted fields keep their stored value | +| `POST` | `/api/chat-bridges/{kind}/test` | Check the stored token and return the bot identity | + +`config` follows the notification channel convention: a masked value sent back unchanged keeps the +stored secret, and an empty string clears a field. Telegram's fields are `bot_token` and the +optional `base_url` (for a self-hosted Bot API server). The live `status.state` is `off`, +`connecting`, `online` or `error`, with `last_error` when it fails. diff --git a/notify/http.go b/notify/http.go index 8188af62..5056cbf1 100644 --- a/notify/http.go +++ b/notify/http.go @@ -299,3 +299,28 @@ func redactURLsInText(s string) string { } return b.String() } + +// The helpers below let the inbound chat bridge (package chatbridge) talk to the +// same chat platforms with the same protections as delivery: the dial guard, +// the redirect policy and the credential-safe error text. They are wrappers, +// not copies, so a fix to the guard reaches both directions at once. + +// NewGuardedClient returns a client with the delivery dial guard and redirect +// policy and its own timeout. Long polling needs a timeout longer than the +// 15 seconds a delivery gets. +func NewGuardedClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + Transport: notifyTransport, + CheckRedirect: httpClient.CheckRedirect, + } +} + +// RedactTransportError returns the text of a transport error with any URL +// reduced to scheme and host, so a credential carried in the URL never +// reaches a log line or an API response. +func RedactTransportError(err error) string { return redactTransportError(err) } + +// ValidateEndpointURL checks a configured platform address the way the +// channels do: http(s) only, a host, and no loopback or link-local literal. +func ValidateEndpointURL(raw string) error { return validateHTTPURL(raw) } diff --git a/server/chatbridge.go b/server/chatbridge.go new file mode 100644 index 00000000..6de9ee29 --- /dev/null +++ b/server/chatbridge.go @@ -0,0 +1,351 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "sync" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// The inbound chat bridge (issue #5): one long-poll loop per registered +// transport kind, started by server.New. The loop re-reads its row on every +// round, so saving the configuration (a new token, a new allowlist, enabling +// or disabling) takes effect without a restart; Reload interrupts a poll that +// is waiting so the change applies at once instead of after the poll window. +// +// Order of work for a batch: commit the cursor, then act. If ARTEX crashes in +// between, the updates of that batch are lost rather than executed twice. For +// an operator console that is the safe side: a lost "/pause" is retyped, a +// replayed one acts on a task the operator may have resumed since. + +const ( + // chatBridgeIdleWait is how long a disabled or unconfigured bridge sleeps + // before it looks at its row again. Saving the row wakes it earlier. + chatBridgeIdleWait = 30 * time.Second + chatBridgeMinRetry = 2 * time.Second + chatBridgeMaxRetry = time.Minute + chatBridgeSendWait = 15 * time.Second +) + +// chatBridgeStatus is the live state shown in the UI ("bot online"). +type chatBridgeStatus struct { + // State is off (disabled or not configured), connecting, online or error. + State string `json:"state"` + Bot *chatbridge.Identity `json:"bot,omitempty"` + LastError string `json:"last_error,omitempty"` + LastErrorAt *time.Time `json:"last_error_at,omitempty"` + LastPollAt *time.Time `json:"last_poll_at,omitempty"` + LastUpdateAt *time.Time `json:"last_update_at,omitempty"` +} + +type chatBridgeState struct { + wake chan struct{} + cancel context.CancelFunc // cancels the poll in flight; nil when none + status chatBridgeStatus + router *chatbridge.Router + sig string // hash of the config the router and identity were built for + retry time.Duration +} + +type chatBridgeRunner struct { + pg *db.DB + // transport resolves a kind; tests substitute a fake. + transport func(kind string) (chatbridge.Transport, bool) + // commands builds the command table of a bridge; the server's commands + // are added here as they land. + commands func(kind string) []chatbridge.Command + + mu sync.Mutex + state map[string]*chatBridgeState +} + +func newChatBridgeRunner(pg *db.DB) *chatBridgeRunner { + return &chatBridgeRunner{ + pg: pg, + transport: chatbridge.Get, + commands: defaultChatBridgeCommands, + state: map[string]*chatBridgeState{}, + } +} + +// defaultChatBridgeCommands is the command table. /help is built into the +// router. Task and approval commands follow in later changes. +func defaultChatBridgeCommands(string) []chatbridge.Command { + return []chatbridge.Command{{ + Name: "whoami", + Summary: "show this chat's ID and your user ID", + Run: func(_ context.Context, req chatbridge.Request) string { + return fmt.Sprintf("Chat ID: %s\nYour user ID: %s", req.ChatID, req.UserID) + }, + }} +} + +func (r *chatBridgeRunner) get(kind string) *chatBridgeState { + r.mu.Lock() + defer r.mu.Unlock() + st := r.state[kind] + if st == nil { + st = &chatBridgeState{wake: make(chan struct{}, 1), status: chatBridgeStatus{State: "off"}} + r.state[kind] = st + } + return st +} + +// Status returns a copy of a bridge's live state. +func (r *chatBridgeRunner) Status(kind string) chatBridgeStatus { + if r == nil { + return chatBridgeStatus{State: "off"} + } + st := r.get(kind) + r.mu.Lock() + defer r.mu.Unlock() + out := st.status + if out.Bot != nil { + b := *out.Bot + out.Bot = &b + } + return out +} + +// Reload makes the loop of kind re-read its configuration now, interrupting +// a poll in flight. +func (r *chatBridgeRunner) Reload(kind string) { + if r == nil { + return + } + st := r.get(kind) + r.mu.Lock() + if st.cancel != nil { + st.cancel() + } + st.sig = "" // rebuild identity and router from the saved row + st.retry = 0 + r.mu.Unlock() + select { + case st.wake <- struct{}{}: + default: + } +} + +// Run starts one loop per registered transport and returns when ctx ends. +func (r *chatBridgeRunner) Run(ctx context.Context) { + if r == nil || r.pg == nil { + return + } + var wg sync.WaitGroup + for _, kind := range chatbridge.Kinds() { + wg.Add(1) + go func(kind string) { + defer wg.Done() + r.loop(ctx, kind) + }(kind) + } + wg.Wait() +} + +func (r *chatBridgeRunner) loop(ctx context.Context, kind string) { + st := r.get(kind) + for ctx.Err() == nil { + wait := r.step(ctx, kind) + if wait <= 0 { + continue + } + t := time.NewTimer(wait) + select { + case <-ctx.Done(): + t.Stop() + return + case <-st.wake: + t.Stop() + case <-t.C: + } + } +} + +// step runs one round for kind: load the row, make sure the bot identity is +// known, poll once and act on the batch. It returns how long to wait before +// the next round (0 = poll again at once). +func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration { + tag := chatBridgeLogTag(kind) + tr, ok := r.transport(kind) + if !ok { + return chatBridgeIdleWait + } + b, err := r.pg.ChatBridgeByKind(ctx, kind) + if errors.Is(err, db.ErrChatBridgeNotFound) || (err == nil && !b.Enabled) { + r.setOff(kind) + return chatBridgeIdleWait + } + if err != nil { + return r.fail(kind, fmt.Errorf("load configuration: %w", err)) + } + var cfg map[string]any + if err := json.Unmarshal(b.Config, &cfg); err != nil { + return r.fail(kind, fmt.Errorf("configuration is not valid JSON: %w", err)) + } + if err := tr.Validate(cfg); err != nil { + return r.fail(kind, err) + } + + st := r.get(kind) + sig := configSig(b.Config) + r.mu.Lock() + known := st.sig == sig && st.router != nil + router := st.router + r.mu.Unlock() + if !known { + r.setState(kind, "connecting") + me, err := tr.Identity(ctx, cfg) + if err != nil { + return r.fail(kind, err) + } + router = &chatbridge.Router{BotUserName: me.UserName, Commands: r.commands(kind)} + r.mu.Lock() + st.sig, st.router = sig, router + st.status.Bot = &me + r.mu.Unlock() + log.Printf("%s online as @%s, %d allowed chat(s)", tag, me.UserName, len(b.AllowedChats)) + } + + pollCtx, cancel := context.WithCancel(ctx) + r.mu.Lock() + st.cancel = cancel + r.mu.Unlock() + updates, err := tr.Poll(pollCtx, cfg, b.PollOffset) + r.mu.Lock() + st.cancel = nil + r.mu.Unlock() + cancel() + if err != nil { + if ctx.Err() != nil { + return 0 + } + if errors.Is(err, context.Canceled) { + return 0 // Reload interrupted the poll: re-read the row at once + } + var ra *chatbridge.RetryAfterError + if errors.As(err, &ra) { + r.fail(kind, err) + return ra.After + } + return r.fail(kind, err) + } + now := time.Now() + r.mu.Lock() + st.status.State, st.status.LastPollAt, st.retry = "online", &now, 0 + r.mu.Unlock() + if len(updates) == 0 { + return 0 + } + + next := b.PollOffset + for _, u := range updates { + if u.ID >= next { + next = u.ID + 1 + } + } + wrote, err := r.pg.SetChatBridgeOffset(ctx, kind, b.ConfigVersion, next) + if err != nil { + // Acting without a committed cursor would repeat the batch on the + // next poll. Skip it and try again. + return r.fail(kind, fmt.Errorf("save update cursor: %w", err)) + } + if !wrote { + // The configuration was saved while this poll ran (a new token, a + // new allowlist, or the bridge was disabled). The batch belongs to + // the old configuration: drop it and start over from the saved row. + log.Printf("%s configuration changed during a poll, %d update(s) dropped", tag, len(updates)) + return 0 + } + r.mu.Lock() + st.status.LastUpdateAt = &now + r.mu.Unlock() + + for _, u := range updates { + decision, reply := router.Route(ctx, kind, b.AllowedChats, u) + switch decision { + case chatbridge.DecisionRefused: + log.Printf("%s refused chat %s (user %s @%s): not in the allowlist", tag, u.ChatID, u.UserID, u.UserName) + case chatbridge.DecisionStale: + log.Printf("%s dropped a message from chat %s sent %s ago (older than %s)", tag, u.ChatID, now.Sub(u.Date).Round(time.Second), chatbridge.MaxUpdateAge) + case chatbridge.DecisionHandled: + // The message text is not logged: it can carry anything the + // operator typed, including target details. + log.Printf("%s handled a message in chat %s from user %s", tag, u.ChatID, u.UserID) + } + if reply == "" { + continue + } + sendCtx, cancelSend := context.WithTimeout(ctx, chatBridgeSendWait) + if err := tr.Send(sendCtx, cfg, u.ChatID, reply); err != nil { + log.Printf("%s reply to chat %s failed: %v", tag, u.ChatID, err) + } + cancelSend() + } + return 0 +} + +func (r *chatBridgeRunner) setOff(kind string) { + st := r.get(kind) + r.mu.Lock() + defer r.mu.Unlock() + st.status = chatBridgeStatus{State: "off"} + st.sig, st.router, st.retry = "", nil, 0 +} + +func (r *chatBridgeRunner) setState(kind, state string) { + st := r.get(kind) + r.mu.Lock() + st.status.State = state + r.mu.Unlock() +} + +// fail records an error and returns the backoff before the next round: +// doubling from chatBridgeMinRetry up to chatBridgeMaxRetry, reset by the +// next successful poll or a Reload. +func (r *chatBridgeRunner) fail(kind string, err error) time.Duration { + st := r.get(kind) + now := time.Now() + r.mu.Lock() + first := st.status.LastError != err.Error() + st.status.State = "error" + st.status.LastError = err.Error() + st.status.LastErrorAt = &now + if st.retry == 0 { + st.retry = chatBridgeMinRetry + } else if st.retry < chatBridgeMaxRetry { + st.retry *= 2 + if st.retry > chatBridgeMaxRetry { + st.retry = chatBridgeMaxRetry + } + } + wait := st.retry + r.mu.Unlock() + if first { + // Log a changed error once rather than on every retry. + log.Printf("%s %v (retrying in %s)", chatBridgeLogTag(kind), err, wait) + } + return wait +} + +func configSig(cfg []byte) string { + sum := sha256.Sum256(cfg) + return hex.EncodeToString(sum[:8]) +} + +// chatBridgeLogTag is the log prefix of a bridge: [tgbot] for Telegram as +// issue #5 proposes, [chatbridge:] for later transports. +func chatBridgeLogTag(kind string) string { + if kind == chatbridge.KindTelegram { + return "[tgbot]" + } + return "[chatbridge:" + kind + "]" +} diff --git a/server/chatbridge_api.go b/server/chatbridge_api.go new file mode 100644 index 00000000..67eabab7 --- /dev/null +++ b/server/chatbridge_api.go @@ -0,0 +1,215 @@ +package server + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// HTTP API of the inbound chat bridges. Mounted behind requireAuth like the +// other admin APIs. A bridge is addressed by its transport kind; v1 has one +// bot per deployment, so there is one row per kind. + +// chatBridgeDTO is the external form of a bridge. Config is masked: the bot +// token comes back as a masked hint, and sending that hint back unchanged +// keeps the stored token (same convention as notification channels). +type chatBridgeDTO struct { + Kind string `json:"kind"` + Configured bool `json:"configured"` + Enabled bool `json:"enabled"` + Config map[string]any `json:"config"` + AllowedChats []string `json:"allowed_chats"` + SecretKeys []string `json:"secret_keys"` + Status chatBridgeStatus `json:"status"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +type chatBridgeRequest struct { + Enabled *bool `json:"enabled"` + Config map[string]any `json:"config"` + AllowedChats *[]string `json:"allowed_chats"` +} + +func (s *Server) chatBridgeDTO(kind string, b *db.ChatBridge) chatBridgeDTO { + tr, _ := chatbridge.Get(kind) + out := chatBridgeDTO{ + Kind: kind, + Config: map[string]any{}, + AllowedChats: []string{}, + SecretKeys: tr.SecretKeys(), + Status: s.chatBridges.Status(kind), + } + if b == nil { + return out + } + var cfg map[string]any + _ = json.Unmarshal(b.Config, &cfg) + out.Configured = true + out.Enabled = b.Enabled + out.Config = chatbridge.MaskConfig(kind, cfg) + out.AllowedChats = b.AllowedChats + updated := b.UpdatedAt + out.UpdatedAt = &updated + return out +} + +// chatBridgeKind reads and checks the {kind} path value. +func chatBridgeKind(w http.ResponseWriter, r *http.Request) (chatbridge.Transport, bool) { + kind := r.PathValue("kind") + tr, ok := chatbridge.Get(kind) + if !ok { + writeErr(w, 404, fmt.Sprintf("unknown chat bridge %q, available: %s", kind, strings.Join(chatbridge.Kinds(), ", "))) + return nil, false + } + return tr, true +} + +func (s *Server) chatBridgeList(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + out := []chatBridgeDTO{} + for _, kind := range chatbridge.Kinds() { + b, err := pg.ChatBridgeByKind(r.Context(), kind) + if err != nil && !errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 500, err.Error()) + return + } + out = append(out, s.chatBridgeDTO(kind, b)) + } + writeJSON(w, 200, out) +} + +func (s *Server) chatBridgeSave(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + tr, ok := chatBridgeKind(w, r) + if !ok { + return + } + kind := tr.Kind() + var req chatBridgeRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil { + writeErr(w, 400, "request body is not valid JSON: "+err.Error()) + return + } + + stored, err := pg.ChatBridgeByKind(r.Context(), kind) + if err != nil && !errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 500, err.Error()) + return + } + storedCfg := map[string]any{} + allowed := []string{} + enabled := false + if stored != nil { + _ = json.Unmarshal(stored.Config, &storedCfg) + allowed = stored.AllowedChats + enabled = stored.Enabled + } + + cfg := storedCfg + if req.Config != nil { + cfg, err = chatbridge.PrepareConfigUpdate(kind, storedCfg, req.Config) + if err != nil { + writeErr(w, 400, err.Error()) + return + } + } + if req.AllowedChats != nil { + allowed, err = chatbridge.NormalizeAllowedChats(tr, *req.AllowedChats) + if err != nil { + writeErr(w, 400, err.Error()) + return + } + } + if req.Enabled != nil { + enabled = *req.Enabled + } + // A disabled bridge may hold a partial configuration (the form is saved + // before the token is at hand); an enabled one must be complete. + if enabled || cfgHas(cfg, tr.SecretKeys()) { + if err := tr.Validate(cfg); err != nil { + writeErr(w, 400, err.Error()) + return + } + } + + raw, err := json.Marshal(cfg) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + // Update ids are per bot: a new token makes the old cursor meaningless, + // so it is cleared in the same statement that stores the token. + saved, err := pg.SaveChatBridge(r.Context(), &db.ChatBridge{Kind: kind, Enabled: enabled, Config: raw, AllowedChats: allowed}, secretsChanged(tr, storedCfg, cfg)) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + s.chatBridges.Reload(kind) + writeJSON(w, 200, s.chatBridgeDTO(kind, saved)) +} + +// chatBridgeTest asks the chat app which bot the stored configuration +// belongs to. It checks the token without sending any message. +func (s *Server) chatBridgeTest(w http.ResponseWriter, r *http.Request) { + pg := s.pg(w) + if pg == nil { + return + } + tr, ok := chatBridgeKind(w, r) + if !ok { + return + } + b, err := pg.ChatBridgeByKind(r.Context(), tr.Kind()) + if errors.Is(err, db.ErrChatBridgeNotFound) { + writeErr(w, 400, "save the bot token first") + return + } + if err != nil { + writeErr(w, 500, err.Error()) + return + } + var cfg map[string]any + _ = json.Unmarshal(b.Config, &cfg) + if err := tr.Validate(cfg); err != nil { + writeErr(w, 400, err.Error()) + return + } + start := time.Now() + me, err := tr.Identity(r.Context(), cfg) + if err != nil { + // Transport errors are already free of the token (see chatbridge.telegramTransport.call). + writeErr(w, 502, err.Error()) + return + } + writeJSON(w, 200, map[string]any{"ok": true, "bot": me, "latency_ms": time.Since(start).Milliseconds()}) +} + +func cfgHas(cfg map[string]any, keys []string) bool { + for _, k := range keys { + if s, _ := cfg[k].(string); strings.TrimSpace(s) != "" { + return true + } + } + return false +} + +func secretsChanged(tr chatbridge.Transport, before, after map[string]any) bool { + for _, k := range tr.SecretKeys() { + if fmt.Sprint(before[k]) != fmt.Sprint(after[k]) { + return true + } + } + return false +} diff --git a/server/chatbridge_test.go b/server/chatbridge_test.go new file mode 100644 index 00000000..3720aae8 --- /dev/null +++ b/server/chatbridge_test.go @@ -0,0 +1,291 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/Autumn-27/artex/chatbridge" + "github.com/Autumn-27/artex/db" +) + +// fakeBridgeTransport is an in-memory chat app. The runner tests use their +// own kind so they never read or write the real "telegram" row. +type fakeBridgeTransport struct { + mu sync.Mutex + updates []chatbridge.Update + offsets []int64 + sent map[string][]string + pollErr error + identity int +} + +const fakeBridgeKind = "t-fake-bridge" + +func (f *fakeBridgeTransport) Kind() string { return fakeBridgeKind } +func (f *fakeBridgeTransport) Validate(map[string]any) error { return nil } +func (f *fakeBridgeTransport) SecretKeys() []string { return []string{"bot_token"} } +func (f *fakeBridgeTransport) DestinationKeys() []string { return nil } +func (f *fakeBridgeTransport) ValidateChatID(string) error { return nil } +func (f *fakeBridgeTransport) Identity(context.Context, map[string]any) (chatbridge.Identity, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.identity++ + return chatbridge.Identity{ID: "1", UserName: "fake_bot"}, nil +} +func (f *fakeBridgeTransport) Poll(_ context.Context, _ map[string]any, offset int64) ([]chatbridge.Update, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.offsets = append(f.offsets, offset) + if f.pollErr != nil { + return nil, f.pollErr + } + out := f.updates + f.updates = nil + return out, nil +} +func (f *fakeBridgeTransport) Send(_ context.Context, _ map[string]any, chatID, text string) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.sent == nil { + f.sent = map[string][]string{} + } + f.sent[chatID] = append(f.sent[chatID], text) + return nil +} + +func bridgeTestDB(t *testing.T) *db.DB { + t.Helper() + skipWithoutDSN(t) + // NewManager opens the database and loads the secrets key, as at startup. + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _, _ = m.pg.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, fakeBridgeKind) + m.Close() + }) + return m.pg +} + +func TestChatBridgeRunnerStep(t *testing.T) { + pg := bridgeTestDB(t) + ctx := context.Background() + fake := &fakeBridgeTransport{} + r := newChatBridgeRunner(pg) + r.transport = func(kind string) (chatbridge.Transport, bool) { return fake, kind == fakeBridgeKind } + + // Not configured: the bridge is off and sleeps. + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeIdleWait || r.Status(fakeBridgeKind).State != "off" { + t.Fatalf("unconfigured: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } + + saved, err := pg.SaveChatBridge(ctx, &db.ChatBridge{ + Kind: fakeBridgeKind, Enabled: true, + Config: json.RawMessage(`{"bot_token":"x"}`), + AllowedChats: []string{"100"}, + }, false) + if err != nil { + t.Fatal(err) + } + + now := time.Now() + fake.updates = []chatbridge.Update{ + {ID: 10, ChatID: "100", UserID: "7", Text: "/whoami", Date: now}, + {ID: 11, ChatID: "666", UserID: "9", Text: "/whoami", Date: now}, + {ID: 12, ChatID: "666", UserID: "9", Text: "again", Date: now}, + {ID: 13, ChatID: "100", UserID: "7", Text: "/whoami", Date: now.Add(-time.Hour)}, + } + if wait := r.step(ctx, fakeBridgeKind); wait != 0 { + t.Fatalf("online step: wait %v, status %+v", wait, r.Status(fakeBridgeKind)) + } + st := r.Status(fakeBridgeKind) + if st.State != "online" || st.Bot == nil || st.Bot.UserName != "fake_bot" { + t.Fatalf("status = %+v", st) + } + if got := fake.sent["100"]; len(got) != 1 || !strings.Contains(got[0], "Chat ID: 100") { + t.Fatalf("allowed chat replies = %q (the stale /whoami must not be answered)", got) + } + if got := fake.sent["666"]; len(got) != 1 || !strings.Contains(got[0], "not allowed") || strings.Contains(got[0], "Your user ID") { + t.Fatalf("unknown chat replies = %q, want one refusal", got) + } + b, _ := pg.ChatBridgeByKind(ctx, fakeBridgeKind) + if b.PollOffset != 14 { + t.Fatalf("cursor = %d, want 14", b.PollOffset) + } + + // The next poll asks from the committed cursor, and the identity is reused. + r.step(ctx, fakeBridgeKind) + if last := fake.offsets[len(fake.offsets)-1]; last != 14 || fake.identity != 1 { + t.Fatalf("second poll offset %d, identity calls %d", last, fake.identity) + } + + // A save during a poll: the cursor write is refused for the old version + // and the batch is dropped, not acted on. + fake.updates = []chatbridge.Update{{ID: 20, ChatID: "100", UserID: "7", Text: "/whoami", Date: time.Now()}} + fake.pollErr = nil + r.transport = func(kind string) (chatbridge.Transport, bool) { + return &saveDuringPoll{fakeBridgeTransport: fake, pg: pg, saved: saved}, true + } + before := len(fake.sent["100"]) + r.step(ctx, fakeBridgeKind) + if len(fake.sent["100"]) != before { + t.Fatal("a batch polled under a replaced configuration was acted on") + } + + // An empty allowlist: the bridge runs but serves no chat. Every chat, + // including one that was allowed a moment ago, gets the refusal with its + // chat ID and no command runs. + r.transport = func(kind string) (chatbridge.Transport, bool) { return fake, true } + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: saved.Config}, false); err != nil { + t.Fatal(err) + } + fake.sent = nil + fake.updates = []chatbridge.Update{ + {ID: 30, ChatID: "100", UserID: "7", Text: "/whoami", Date: time.Now()}, + {ID: 31, ChatID: "777", UserID: "8", Text: "/whoami", Date: time.Now()}, + } + if wait := r.step(ctx, fakeBridgeKind); wait != 0 || r.Status(fakeBridgeKind).State != "online" { + t.Fatalf("empty allowlist: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } + for _, chat := range []string{"100", "777"} { + got := fake.sent[chat] + if len(got) != 1 || !strings.Contains(got[0], "chat ID "+chat) || strings.Contains(got[0], "Your user ID") { + t.Fatalf("empty allowlist, chat %s replies = %q, want one refusal naming the chat ID", chat, got) + } + } + + // Disabling turns the bridge off. + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: false, Config: json.RawMessage(`{}`)}, false); err != nil { + t.Fatal(err) + } + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeIdleWait || r.Status(fakeBridgeKind).State != "off" { + t.Fatalf("disabled: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } +} + +// saveDuringPoll saves the row while the poll is "in flight". +type saveDuringPoll struct { + *fakeBridgeTransport + pg *db.DB + saved *db.ChatBridge +} + +func (s *saveDuringPoll) Poll(ctx context.Context, cfg map[string]any, offset int64) ([]chatbridge.Update, error) { + out, err := s.fakeBridgeTransport.Poll(ctx, cfg, offset) + if _, serr := s.pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: s.saved.Config, AllowedChats: s.saved.AllowedChats}, false); serr != nil { + return nil, serr + } + return out, err +} + +func TestChatBridgeRunnerBackoff(t *testing.T) { + pg := bridgeTestDB(t) + ctx := context.Background() + fake := &fakeBridgeTransport{pollErr: &chatbridge.RetryAfterError{After: 9 * time.Second, Msg: "rate limited"}} + r := newChatBridgeRunner(pg) + r.transport = func(string) (chatbridge.Transport, bool) { return fake, true } + if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{}`), AllowedChats: []string{"1"}}, false); err != nil { + t.Fatal(err) + } + if wait := r.step(ctx, fakeBridgeKind); wait != 9*time.Second { + t.Fatalf("retry-after wait = %v", wait) + } + fake.pollErr = context.DeadlineExceeded + w1 := r.step(ctx, fakeBridgeKind) + w2 := r.step(ctx, fakeBridgeKind) + if !(w2 > w1) || w2 > chatBridgeMaxRetry { + t.Fatalf("backoff did not grow: %v then %v", w1, w2) + } + if st := r.Status(fakeBridgeKind); st.State != "error" || st.LastError == "" { + t.Fatalf("status = %+v", st) + } + r.Reload(fakeBridgeKind) + fake.pollErr = nil + if wait := r.step(ctx, fakeBridgeKind); wait != 0 || r.Status(fakeBridgeKind).State != "online" { + t.Fatalf("after reload: wait %v status %+v", wait, r.Status(fakeBridgeKind)) + } +} + +func TestChatBridgeAPI(t *testing.T) { + s, _, request := trafficEvidenceServer(t) + pg := s.m.pg + ctx := context.Background() + if _, err := pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram); err == nil { + t.Skip("a telegram bridge is already configured in this test database; not touching it") + } + t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, chatbridge.KindTelegram) }) + + const token = "123456789:AAapi-test-token-abcdefghij" + + w := request(http.MethodGet, "/api/chat-bridges", "") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"kind":"telegram"`) || !strings.Contains(w.Body.String(), `"configured":false`) { + t.Fatalf("list = %d %s", w.Code, w.Body) + } + + // Enabling with an empty allowlist is allowed: the bridge serves no chat + // and only answers with the refusal that names the chat ID, which is how + // the operator finds the ID to add. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":true,"config":{"bot_token":"`+token+`"}}`) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"allowed_chats":[]`) { + t.Fatalf("enable with an empty allowlist = %d %s", w.Code, w.Body) + } + // A malformed chat id is refused. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"allowed_chats":["@me"]}`) + if w.Code != 400 { + t.Fatalf("bad chat id = %d %s", w.Code, w.Body) + } + // Unknown kind. + if w = request(http.MethodPut, "/api/chat-bridges/carrier-pigeon", `{}`); w.Code != 404 { + t.Fatalf("unknown kind = %d", w.Code) + } + + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":false,"config":{"bot_token":"`+token+`"},"allowed_chats":["100"," 100 ","-1001"]}`) + if w.Code != 200 { + t.Fatalf("save = %d %s", w.Code, w.Body) + } + if strings.Contains(w.Body.String(), "AAapi-test") { + t.Fatalf("the token leaked into the response: %s", w.Body) + } + var dto chatBridgeDTO + if err := json.Unmarshal(w.Body.Bytes(), &dto); err != nil { + t.Fatal(err) + } + masked, _ := dto.Config["bot_token"].(string) + if !dto.Configured || strings.Join(dto.AllowedChats, ",") != "100,-1001" || !strings.HasPrefix(masked, "__masked__") { + t.Fatalf("dto = %+v", dto) + } + + // Sending the masked token back keeps the stored one and enables the bridge. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"enabled":true,"config":{"bot_token":"`+masked+`"}}`) + if w.Code != 200 { + t.Fatalf("enable = %d %s", w.Code, w.Body) + } + b, err := pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram) + if err != nil || !b.Enabled || !strings.Contains(string(b.Config), token) { + t.Fatalf("stored = %+v %v", b, err) + } + + // Changing the API address with the masked token is refused. + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"config":{"bot_token":"`+masked+`","base_url":"https://tg.example.com"}}`) + if w.Code != 400 || !strings.Contains(w.Body.String(), "bot token again") { + t.Fatalf("destination change = %d %s", w.Code, w.Body) + } + + // A new token clears the update cursor. + if _, err := pg.SetChatBridgeOffset(ctx, chatbridge.KindTelegram, b.ConfigVersion, 500); err != nil { + t.Fatal(err) + } + w = request(http.MethodPut, "/api/chat-bridges/telegram", `{"config":{"bot_token":"987654321:AAanother-token-abcdefghij"}}`) + if w.Code != 200 { + t.Fatalf("token change = %d %s", w.Code, w.Body) + } + if b, _ = pg.ChatBridgeByKind(ctx, chatbridge.KindTelegram); b.PollOffset != 0 { + t.Fatalf("cursor after token change = %d", b.PollOffset) + } +} diff --git a/server/server.go b/server/server.go index d2d85f57..74450e7b 100644 --- a/server/server.go +++ b/server/server.go @@ -59,6 +59,8 @@ type Server struct { execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own isolation IsolationStatus // result of the startup isolation self-test (isolation.go); zero when not run + chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL + setupMu sync.Mutex setupToken string // one-time token POST /api/auth/init requires; empty when none is active // pwdVersion is auth.password_version, a counter. Zero means no password @@ -290,6 +292,10 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi // Vulnerability IM push delivery engine. Sits beside the Scheduler but independent: push latency demands (3s) // differ from the triggers' business cadence, and neither's failures drag the other down — a stuck push must not affect agent triggers. go newNotifier(s).Run(s.ctx) + // Inbound chat bridges: an operator drives ARTEX from a chat app. Off until a bridge is enabled + // with a non-empty chat allowlist; long polling only, so no inbound port is opened. + s.chatBridges = newChatBridgeRunner(m.pg) + go s.chatBridges.Run(s.ctx) logSink.SetDB(ctx, m.pg) // restore last 100 log rows and enable async persistence } // precedence: persisted DB config > env. @@ -937,6 +943,10 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/notify/channels/{id}/test", s.notifyTestChannel) mux.HandleFunc("GET /api/notify/deliveries", s.notifyListDeliveries) mux.HandleFunc("POST /api/notify/deliveries/{id}/retry", s.notifyRetryDelivery) + // Inbound chat bridges, one per transport kind (telegram). + mux.HandleFunc("GET /api/chat-bridges", s.chatBridgeList) + mux.HandleFunc("PUT /api/chat-bridges/{kind}", s.chatBridgeSave) + mux.HandleFunc("POST /api/chat-bridges/{kind}/test", s.chatBridgeTest) mux.HandleFunc("POST /api/settings/web-search/test", s.testWebSearch) mux.HandleFunc("GET /api/report", s.getReport) mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions) diff --git a/web/src/app/(main)/system/chat-bridge/page.tsx b/web/src/app/(main)/system/chat-bridge/page.tsx new file mode 100644 index 00000000..6797bd56 --- /dev/null +++ b/web/src/app/(main)/system/chat-bridge/page.tsx @@ -0,0 +1,259 @@ +"use client"; + +import * as React from "react"; + +import { PlugZapIcon, SaveIcon } from "lucide-react"; +import { toast } from "sonner"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { Textarea } from "@/components/ui/textarea"; +import { t } from "@/i18n"; +import { api } from "@/lib/api"; +import type { ChatBridge, ChatBridgeStatus } from "@/lib/types"; + +// v1 ships one transport. The page is written against the kind so a second chat app only needs +// its own fields here; the backend is already transport-agnostic. +const KIND = "telegram"; +// How often the live status ("bot online") is refreshed while the page is open. +const STATUS_POLL_MS = 5000; + +interface Form { + enabled: boolean; + token: string; // empty = keep the stored token + baseURL: string; + chats: string; // one chat ID per line +} + +function formFrom(b: ChatBridge | undefined): Form { + return { + enabled: b?.enabled ?? false, + token: "", + baseURL: typeof b?.config.base_url === "string" ? b.config.base_url : "", + chats: (b?.allowed_chats ?? []).join("\n"), + }; +} + +function parseChats(raw: string): string[] { + return raw + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter(Boolean); +} + +function StatusBadge({ status }: { status: ChatBridgeStatus }) { + switch (status.state) { + case "online": + return {t("Online")}; + case "connecting": + return {t("Connecting")}; + case "error": + return {t("Error")}; + default: + return {t("Off")}; + } +} + +export default function ChatBridgePage() { + const [bridge, setBridge] = React.useState(); + const [form, setForm] = React.useState
(formFrom(undefined)); + const [loaded, setLoaded] = React.useState(false); + const [saving, setSaving] = React.useState(false); + const [testing, setTesting] = React.useState(false); + + const load = React.useCallback(async (resetForm: boolean) => { + const list = await api.chatBridges(); + const b = list.find((x) => x.kind === KIND); + setBridge(b); + if (resetForm) setForm(formFrom(b)); + setLoaded(true); + }, []); + + React.useEffect(() => { + load(true).catch((e) => + toast.error(t("Failed to load the chat bot settings: {error}", { error: (e as Error).message })), + ); + // Only the status is refreshed; the form keeps what the operator is typing. + const id = window.setInterval(() => { + load(false).catch(() => { + // A missed refresh is retried on the next tick; the status card keeps its last value. + }); + }, STATUS_POLL_MS); + return () => window.clearInterval(id); + }, [load]); + + const storedToken = typeof bridge?.config.bot_token === "string" ? bridge.config.bot_token : ""; + + async function save() { + const config: Record = { base_url: form.baseURL.trim() }; + // An empty token field keeps the stored token: the masked value tells the server "unchanged". + config.bot_token = form.token.trim() || storedToken; + setSaving(true); + try { + const saved = await api.chatBridgeSave(KIND, { + enabled: form.enabled, + config, + allowed_chats: parseChats(form.chats), + }); + setBridge(saved); + setForm(formFrom(saved)); + toast.success(t("Saved")); + } catch (e) { + toast.error(t("Save failed: {error}", { error: (e as Error).message })); + } finally { + setSaving(false); + } + } + + async function test() { + setTesting(true); + try { + const r = await api.chatBridgeTest(KIND); + toast.success(t("Connected to @{bot} in {ms} ms", { bot: r.bot.username, ms: String(r.latency_ms) })); + } catch (e) { + toast.error(t("Connection test failed: {error}", { error: (e as Error).message })); + } finally { + setTesting(false); + } + } + + const status: ChatBridgeStatus = bridge?.status ?? { state: "off" }; + const chatCount = parseChats(form.chats).length; + + return ( +
+
+

{t("Chat bot")}

+

+ {t( + "Talk to ARTEX from Telegram. Only the chats you allow below can use the bot; every other chat gets one refusal and is then ignored.", + )} +

+
+ + + + + {t("Status")} + + + + + {status.bot && ( +

+ {t("Bot")}: @{status.bot.username} +

+ )} + {status.state === "off" && ( +

{t("The bot is off. Enter a token and switch it on.")}

+ )} + {status.last_poll_at && ( +

+ {t("Last poll: {time}", { time: new Date(status.last_poll_at).toLocaleString() })} +

+ )} + {status.state === "error" && status.last_error && ( +

{status.last_error}

+ )} +
+
+ + + + Telegram + + +
+ setForm((f) => ({ ...f, enabled: v }))} + /> + +
+ +
+ + setForm((f) => ({ ...f, token: e.target.value }))} + /> +

+ {t( + "Create a bot with @BotFather and paste its token. Give ARTEX its own bot: a token used by another poller or a webhook cannot be shared.", + )} +

+
+ +
+ +