mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-28 02:40:53 +08:00
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>
129 lines
4.7 KiB
Go
129 lines
4.7 KiB
Go
// 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.
|