Files
iishko-public/moderation/policy.go
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

411 lines
12 KiB
Go

package main
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)
const (
ActionBan = "ban"
ActionUnban = "unban"
ActionMute = "mute"
ActionUnmute = "unmute"
ActionKick = "kick"
ActionResolve = "resolve"
ActionSetup = "setup"
ActionChatMode = "chatmode"
)
const (
msgMissingTarget = "Укажите получателя или ответьте на сообщение."
msgTargetConflict = "Укажите либо получателя, либо ответ на сообщение, но не оба."
msgEmptyArgument = "Пустой аргумент."
msgTooManyArguments = "Слишком много аргументов."
msgPermissions = "Недостаточно прав для выполнения команды."
msgSupergroupOnly = "Команда доступна только в супергруппе."
msgProtectedTarget = "Этот участник защищён от ограничений."
msgUnknownAction = "Неизвестное действие."
msgInvalidReplyID = "Некорректный ID ответа."
msgInvalidCandidate = "Некорректный ID кандидата."
msgInvalidProtected = "Некорректный ID защищённого участника."
msgInvalidUserID = "Некорректный ID пользователя."
msgNonPositiveUserID = "ID пользователя должен быть больше нуля."
msgUserIDRange = "ID пользователя вне допустимого диапазона."
msgInvalidUsername = "Некорректное имя пользователя."
msgTooManyModeArgs = "Укажите режим чата: quiet, mentions или replies."
msgInvalidMode = "Режим должен быть quiet, mentions или replies."
msgSetupArguments = "Команда setup не принимает аргументов."
)
// Candidate is a username-to-ID mapping supplied by the Python bridge for the
// current chat. The policy service never performs Telegram lookups itself.
type Candidate struct {
UID int64 `json:"uid"`
Username string `json:"username"`
}
// Request is the policy request produced by the Python bridge. Permission
// flags are the result of live Telegram checks and are trusted as provided.
type Request struct {
Action string `json:"action"`
Args []string `json:"args"`
ReplyUID int64 `json:"reply_uid"`
Candidates []Candidate `json:"candidates"`
ActorAllowed bool `json:"actor_allowed"`
BotAllowed bool `json:"bot_allowed"`
ChatType string `json:"chat_type"`
ProtectedUIDs []int64 `json:"protected_uids"`
BotUsername string `json:"bot_username"`
}
// Response is the resolved policy decision. Every field is always emitted.
type Response struct {
Action string `json:"action"`
TargetUID int64 `json:"target_uid"`
DurationSeconds int64 `json:"duration_seconds"`
Mode string `json:"mode"`
Reason string `json:"reason"`
}
// PolicyError carries a Russian user-facing message and the HTTP status the
// bridge should map the rejection to.
type PolicyError struct {
Status int
Message string
}
func (e *PolicyError) Error() string {
return e.Message
}
func policyError(status int, message string) *PolicyError {
return &PolicyError{Status: status, Message: message}
}
func badRequest(format string, args ...any) *PolicyError {
return policyError(http.StatusBadRequest, fmt.Sprintf(format, args...))
}
func protectedError() *PolicyError {
return policyError(http.StatusForbidden, msgProtectedTarget)
}
func durationPolicyError(err error) *PolicyError {
return badRequest("%s", err.Error())
}
// Plan resolves a single moderation command. It is pure and stateless: the
// bridge supplies candidates, chat kind, protection list and live permission
// booleans; Plan never touches Telegram, a database or the filesystem.
func Plan(req Request) (Response, error) {
if err := validateRequest(req); err != nil {
return Response{}, err
}
action := canonicalAction(req.Action)
if action == "" {
return Response{}, badRequest("%s", msgUnknownAction)
}
req.Action = action
switch action {
case ActionResolve:
// The shared legacy resolver must stay usable while permissions are
// still being computed by the caller.
return planResolve(req)
case ActionSetup:
if err := requireRights(req); err != nil {
return Response{}, err
}
if len(req.Args) != 0 {
return Response{}, badRequest("%s", msgSetupArguments)
}
return Response{Action: ActionSetup}, nil
case ActionChatMode:
if err := requireRights(req); err != nil {
return Response{}, err
}
return planChatMode(req)
case ActionBan, ActionUnban, ActionKick:
if err := requireRights(req); err != nil {
return Response{}, err
}
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
if action != ActionUnban && isProtected(req.ProtectedUIDs, targetUID) {
return Response{}, protectedError()
}
return Response{Action: action, TargetUID: targetUID}, nil
case ActionMute, ActionUnmute:
if err := requireRights(req); err != nil {
return Response{}, err
}
if !strings.EqualFold(req.ChatType, "supergroup") {
return Response{}, badRequest("%s", msgSupergroupOnly)
}
if action == ActionMute {
return planMute(req)
}
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
return Response{Action: ActionUnmute, TargetUID: targetUID}, nil
default:
return Response{}, badRequest("%s", msgUnknownAction)
}
}
func validateRequest(req Request) error {
if req.ReplyUID < 0 {
return badRequest("%s", msgInvalidReplyID)
}
for _, candidate := range req.Candidates {
if candidate.UID <= 0 {
return badRequest("%s", msgInvalidCandidate)
}
}
for _, uid := range req.ProtectedUIDs {
if uid <= 0 {
return badRequest("%s", msgInvalidProtected)
}
}
return nil
}
func canonicalAction(raw string) string {
switch strings.ToLower(strings.TrimSpace(raw)) {
case ActionBan:
return ActionBan
case ActionUnban:
return ActionUnban
case ActionMute:
return ActionMute
case ActionUnmute:
return ActionUnmute
case ActionKick:
return ActionKick
case ActionResolve:
return ActionResolve
case ActionSetup:
return ActionSetup
case ActionChatMode:
return ActionChatMode
default:
return ""
}
}
func requireRights(req Request) error {
if !req.ActorAllowed || !req.BotAllowed {
return policyError(http.StatusForbidden, msgPermissions)
}
return nil
}
func planResolve(req Request) (Response, error) {
targetUID, err := resolveSingleTarget(req)
if err != nil {
return Response{}, err
}
return Response{Action: ActionResolve, TargetUID: targetUID}, nil
}
func planChatMode(req Request) (Response, error) {
if len(req.Args) == 0 {
return Response{}, badRequest("%s", msgTooManyModeArgs)
}
if len(req.Args) > 1 {
return Response{}, badRequest("%s", msgTooManyArguments)
}
mode := asciiLower(strings.TrimSpace(req.Args[0]))
switch mode {
case "quiet", "mentions", "replies":
return Response{Action: ActionChatMode, Mode: mode}, nil
default:
return Response{}, badRequest("%s", msgInvalidMode)
}
}
// resolveSingleTarget handles commands that take exactly one target: an
// explicit ID/username or, when no explicit target is present, the replied
// message author.
func resolveSingleTarget(req Request) (int64, error) {
if len(req.Args) > 1 {
return 0, badRequest("%s", msgTooManyArguments)
}
if len(req.Args) == 1 {
if req.ReplyUID > 0 {
return 0, badRequest("%s", msgTargetConflict)
}
return parseTargetToken(req.Args[0], req.Candidates)
}
if req.ReplyUID <= 0 {
return 0, badRequest("%s", msgMissingTarget)
}
return req.ReplyUID, nil
}
// planMute resolves the extra duration rules for /mute:
// - /mute with a reply uses the replied author and one hour;
// - /mute 2h with a reply keeps the replied author, two hours;
// - /mute @name 2h uses an explicit target and duration;
// - a bare number is minutes only when a target is already unambiguous,
// otherwise it is an explicit user ID.
func planMute(req Request) (Response, error) {
switch len(req.Args) {
case 0:
if req.ReplyUID <= 0 {
return Response{}, badRequest("%s", msgMissingTarget)
}
return muteResponse(req, req.ReplyUID, DefaultMuteDuration)
case 1:
token := req.Args[0]
if token == "" {
return Response{}, badRequest("%s", msgEmptyArgument)
}
if req.ReplyUID > 0 {
if isDurationLike(token) {
duration, err := ParseDuration(token)
if err != nil {
return Response{}, durationPolicyError(err)
}
return muteResponse(req, req.ReplyUID, duration)
}
if isSignedDigits(token) {
if _, err := parseUserID(token); err != nil {
return Response{}, err
}
}
return Response{}, badRequest("%s", msgTargetConflict)
}
if isSignedDigits(token) {
uid, err := parseUserID(token)
if err != nil {
return Response{}, err
}
return muteResponse(req, uid, DefaultMuteDuration)
}
if isDurationLike(token) {
return Response{}, badRequest("%s", msgMissingTarget)
}
uid, err := resolveUsername(strings.TrimPrefix(token, "@"), req.Candidates)
if err != nil {
return Response{}, err
}
return muteResponse(req, uid, DefaultMuteDuration)
case 2:
if req.ReplyUID > 0 {
return Response{}, badRequest("%s", msgTargetConflict)
}
first, second := req.Args[0], req.Args[1]
if first == "" || second == "" {
return Response{}, badRequest("%s", msgEmptyArgument)
}
uid, err := parseTargetToken(first, req.Candidates)
if err != nil {
return Response{}, err
}
duration, err := ParseDuration(second)
if err != nil {
return Response{}, durationPolicyError(err)
}
return muteResponse(req, uid, duration)
default:
return Response{}, badRequest("%s", msgTooManyArguments)
}
}
func muteResponse(req Request, uid, duration int64) (Response, error) {
if isProtected(req.ProtectedUIDs, uid) {
return Response{}, protectedError()
}
return Response{Action: ActionMute, TargetUID: uid, DurationSeconds: duration}, nil
}
func parseTargetToken(token string, candidates []Candidate) (int64, error) {
if token == "" {
return 0, badRequest("%s", msgEmptyArgument)
}
if isSignedDigits(token) {
return parseUserID(token)
}
name := strings.TrimPrefix(token, "@")
if name == "" {
return 0, badRequest("%s", msgInvalidUsername)
}
return resolveUsername(name, candidates)
}
func parseUserID(token string) (int64, error) {
uid, err := strconv.ParseInt(token, 10, 64)
if err != nil {
if errors.Is(err, strconv.ErrRange) {
return 0, badRequest("%s", msgUserIDRange)
}
return 0, badRequest("%s", msgInvalidUserID)
}
if uid <= 0 {
return 0, badRequest("%s", msgNonPositiveUserID)
}
return uid, nil
}
func resolveUsername(raw string, candidates []Candidate) (int64, error) {
if raw == "" {
return 0, badRequest("%s", msgInvalidUsername)
}
wanted := asciiLower(raw)
var found int64
matches := 0
for _, candidate := range candidates {
name := strings.TrimPrefix(candidate.Username, "@")
if name == "" {
continue
}
if asciiLower(name) != wanted {
continue
}
matches++
found = candidate.UID
if matches > 1 {
return 0, badRequest("Несколько пользователей с именем @%s. Укажите ID.", raw)
}
}
if matches == 0 {
return 0, badRequest("Пользователь @%s не найден.", raw)
}
return found, nil
}
func isProtected(protected []int64, uid int64) bool {
for _, candidate := range protected {
if candidate == uid {
return true
}
}
return false
}
// asciiLower lowercases ASCII letters only. Telegram usernames are ASCII, so
// Unicode case folding is deliberately not applied.
func asciiLower(value string) string {
buffer := []byte(value)
changed := false
for i, b := range buffer {
if b < 'A' || b > 'Z' {
continue
}
buffer[i] = b + ('a' - 'A')
changed = true
}
if !changed {
return value
}
return string(buffer)
}