From 38b95adc6da5315fb2ca9345284fd3622557709d Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Sun, 12 Apr 2026 16:28:03 +0200 Subject: [PATCH 1/9] feat: command filtering --- src/lib/managed-commands/command.ts | 43 ++++++- src/lib/managed-commands/index.ts | 170 +++++++++++++++++++++------- src/utils/arrays.ts | 9 ++ src/utils/once.ts | 7 +- src/utils/types.ts | 10 +- 5 files changed, 189 insertions(+), 50 deletions(-) create mode 100644 src/utils/arrays.ts diff --git a/src/lib/managed-commands/command.ts b/src/lib/managed-commands/command.ts index a25c396..28b46fd 100644 --- a/src/lib/managed-commands/command.ts +++ b/src/lib/managed-commands/command.ts @@ -1,6 +1,6 @@ import type { Conversation } from "@grammyjs/conversations" import type { Context } from "grammy" -import type { Message } from "grammy/types" +import type { BotCommand, Message } from "grammy/types" import type { z } from "zod" import type { MaybeArray } from "@/utils/types" import type { ConversationContext } from "./context" @@ -168,6 +168,14 @@ export type AnyCommand +export type AnyGroupCommand = Command< + CommandArgs, + CommandReplyTo, + "group" | "both", + TRole, + C +> + /** * Type guard to check if a command is allowed in groups. * @param cmd The command to check @@ -221,3 +229,36 @@ export function isAllowedInPrivateOnly< >(cmd: Command): cmd is Command { return cmd.scope === "private" } + +export function isAllowedInPrivate< + A extends CommandArgs, + R extends CommandReplyTo, + TRole extends string = string, + C extends Context = Context, +>(cmd: Command): cmd is Command { + return cmd.scope !== "group" +} + +export function isAllowedEverywhere< + A extends CommandArgs, + R extends CommandReplyTo, + TRole extends string = string, + C extends Context = Context, +>(cmd: Command): cmd is Command { + return cmd.scope === "both" || cmd.scope === undefined +} + +export function toBotCommands(command: AnyCommand): BotCommand[] { + const triggers = Array.isArray(command.trigger) ? command.trigger : [command.trigger] + return triggers.map((trigger) => ({ + command: trigger, + description: command.description ?? "No description", + })) +} + +export function isForThisScope(cmd: AnyCommand, chatType: "private" | "group" | "supergroup" | "channel"): boolean { + if (chatType === "channel") return false + if (cmd.scope === "private") return chatType === "private" + if (cmd.scope === "group") return chatType === "group" || chatType === "supergroup" + return true +} diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 951c8c3..50d3f8e 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -9,16 +9,20 @@ import { hydrate } from "@grammyjs/hydrate" import { hydrateReply, parseMode } from "@grammyjs/parse-mode" import type { CommandContext, Context, Middleware, MiddlewareObj } from "grammy" import { Composer, MemorySessionStorage } from "grammy" -import type { Message } from "grammy/types" +import type { BotCommand, Message } from "grammy/types" import type { Result } from "neverthrow" import { err, ok } from "neverthrow" import z from "zod" +import { asyncFilter, asyncMap } from "@/utils/arrays" import { isFromGroupChat, isFromPrivateChat } from "@/utils/chat" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" +import { once } from "@/utils/once" +import type { ContextWith } from "@/utils/types" import type { CommandsCollection } from "./collection" import type { AnyCommand, + AnyGroupCommand, ArgumentMap, ArgumentOptions, Command, @@ -29,7 +33,7 @@ import type { CommandScopedContext, RepliedTo, } from "./command" -import { isAllowedInGroups, isTypedArgumentOptions } from "./command" +import { isAllowedInGroups, isAllowedInPrivate, isForThisScope, isTypedArgumentOptions, toBotCommands } from "./command" import type { ManagedCommandsFlavor } from "./context" export type Hook = ( @@ -71,7 +75,7 @@ export type ManagedCommandsHooks) => Promise + overrideGroupAdminCheck?: (userId: number, chatId: number, context: OC) => Promise /** * Called when a command is invoked, before any processing is done, can be used to implement custom logic that should * run before checking permissions or requirements, for example logging or analytics @@ -82,6 +86,11 @@ export type ManagedCommandsHooks + /** + * A function to externally cache wether a user has had the commands menu generated for them or not + * @returns true if the user has had the commands menu generated, false otherwise + */ + cachedUserSetCommands?: (userId: number, chatId: number) => Promise } export interface IManagedCommandsOptions { @@ -99,7 +108,7 @@ export interface IManagedCommandsOptions { + * getUserRoles: async (userId) => { * const roles = await db.getUserRoles(userId) // Array<"admin" | "user">[] * return roles * }, @@ -114,7 +123,7 @@ export interface IManagedCommandsOptions) => Promise + getUserRoles: (userId: number) => Promise /** * Additional plugins to apply to the conversation inner composer. @@ -162,7 +171,7 @@ export class ManagedCommands< { private composer = new Composer() private commands: Record[]> = {} - private getUserRoles: (userId: number, context: CommandContext) => Promise + private getUserRoles: (userId: number) => Promise private hooks: ManagedCommandsHooks private adapter: ConversationStorage private registeredTriggers = new Set() @@ -281,10 +290,13 @@ export class ManagedCommands< private static formatCommandShort(cmd: AnyCommand): string { const args = cmd.args ?? [] + const trigger: string = + typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | ") return fmt(({ i, n }) => [ - typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | "), + trigger, ...args.map(({ key, optional }) => (optional ? i` [${key}]` : i` <${key}>`)), n`\n\t${cmd.description ?? "No description"}`, + n`\n\tScope: ${cmd.scope === "private" ? "Private Chat" : cmd.scope === "group" ? "Groups" : "Groups and Private Chat"}`, ]) } @@ -364,13 +376,41 @@ export class ManagedCommands< }) ) - this.composer.command("help", async (ctx) => { - if (ctx.chat.type !== "private") - return void ephemeral( - ctx.reply(fmt(({ n, code }) => n`You can only send ${code`/help`} in private chat with the bot.`)), - 10_000 - ) + const setFreeCommands = once(async (ctx: OC) => { + const freeCommands = this.getCommands().filter((cmd) => this.isCommandAllowedForRoles(cmd, [])) + const privateCommands: BotCommand[] = freeCommands + .filter((cmd) => isAllowedInPrivate(cmd)) + .flatMap((cmd) => toBotCommands(cmd)) + .concat([{ command: "help", description: "Show available commands" }]) + await ctx.api.setMyCommands(privateCommands, { scope: { type: "all_private_chats" } }).catch(() => {}) + const groupCommands: BotCommand[] = freeCommands + .filter((cmd) => isAllowedInGroups(cmd) && this.isCommandAllowedInGroup(cmd, -100)) // only include commands that are allowed in all groups + .flatMap((cmd) => toBotCommands(cmd)) + .concat([{ command: "help", description: "Show available commands" }]) + await ctx.api.setMyCommands(groupCommands, { scope: { type: "all_group_chats" } }).catch(() => {}) + }) + this.composer.use(async (ctx, next) => { + await setFreeCommands(ctx) + return next() + }) + + this.composer.on("message").use(async (ctx, next) => { + if (!ctx.from) return next() + const shouldSkip = (await this.hooks.cachedUserSetCommands?.(ctx.from.id, ctx.chat.id)) ?? false + if (shouldSkip) return next() + const allowedCommands = await this.getAllowedCommandsFor(ctx) + await ctx.api + .setMyCommands(allowedCommands.flatMap(toBotCommands), { + scope: { type: "chat_member", chat_id: ctx.chat.id, user_id: ctx.from.id }, + }) + .catch(() => {}) + return next() + }) + + this.composer.command("help", async (ctx) => { + if (!ctx.from) return + const userId = ctx.from.id const text = ctx.message?.text ?? "" const [_, cmdArg] = text.replaceAll("/", "").split(" ") @@ -383,12 +423,24 @@ export class ManagedCommands< return ctx.reply(ManagedCommands.formatCommandUsage(cmd)) } + const getUserRoles = once(async () => await this.getUserRoles(userId)) + const isFromGroupAdmin = once(async () => await this.isFromGroupAdmin(ctx)) + + const rawCollections = await asyncMap(Object.entries(this.commands), async ([collection, cmds]) => ({ + collection, + commands: await asyncFilter( + cmds.filter((c) => isForThisScope(c, ctx.chat.type)), + async (cmd) => this.checkPermissionsCached(cmd, ctx, getUserRoles, isFromGroupAdmin) + ), + })) + const collections = rawCollections.filter((c) => c.commands.length > 0) + const reply = fmt( ({ u, b, skip, n, code }) => [ b`Available commands:`, - ...Object.entries(this.commands).flatMap(([collection, cmds]) => [ + ...collections.flatMap(({ collection, commands }) => [ collection === "default" ? "" : u`${b`\n${collection}:`}`, - ...cmds.flatMap((cmd) => [skip`${ManagedCommands.formatCommandShort(cmd)}`]), + ...commands.map((cmd) => skip`${ManagedCommands.formatCommandShort(cmd)}`), ]), n`\n\nType ${code`\/help `} for more details on a specific command.`, ], @@ -407,36 +459,78 @@ export class ManagedCommands< return cmds } - private async checkPermissions(command: AnyCommand, ctx: CommandContext): Promise { - if (!command.permissions) return true - if (!ctx.from) return false + private isCommandAllowedInGroup(command: AnyGroupCommand, chatId: number): boolean { + const { allowedGroupsId, excludedGroupsId } = command.permissions ?? {} + if (allowedGroupsId && !allowedGroupsId.includes(chatId)) return false + if (excludedGroupsId?.includes(chatId)) return false + return true + } - const { allowedRoles, excludedRoles } = command.permissions + private isCommandAllowedForRoles(command: AnyCommand, roles: TRole[]): boolean { + const { allowedRoles, excludedRoles } = command.permissions ?? {} + if (allowedRoles?.every((r) => !roles.includes(r))) return false + if (excludedRoles?.some((r) => roles.includes(r))) return false + return true + } + + private async isFromGroupAdmin(ctx: OC): Promise { + if (!ctx.from || !ctx.chatId) return false + if (this.hooks.overrideGroupAdminCheck) { + const isAdmin = await this.hooks.overrideGroupAdminCheck(ctx.from.id, ctx.chatId, ctx) + if (isAdmin) return true + } else { + const { status: groupRole } = await ctx.getChatMember(ctx.from.id) + if (groupRole === "administrator" || groupRole === "creator") return true + } + return false + } + + private async getAllowedCommandsFor(ctx: ContextWith): Promise[]> { + const getUserRoles = once(() => this.getUserRoles(ctx.from.id)) + const isFromGroupAdmin = once(() => this.isFromGroupAdmin(ctx)) + + return await Promise.all( + this.getCommands() + .filter(isFromPrivateChat(ctx) ? (cmd) => isAllowedInPrivate(cmd) : (cmd) => isAllowedInGroups(cmd)) + .map((cmd) => + this.checkPermissionsCached(cmd, ctx, getUserRoles, isFromGroupAdmin).then((allowed) => + allowed ? cmd : null + ) + ) + ).then((cmds) => cmds.filter((c) => c !== null)) + } + + private async checkPermissionsCached( + command: AnyCommand, + ctx: ContextWith, + getUserRoles: () => Promise, + isFromGroupAdmin: () => Promise + ): Promise { + if (!command.permissions) return true if (isAllowedInGroups(command) && (ctx.chat.type === "group" || ctx.chat.type === "supergroup")) { - const { allowGroupAdmins, allowedGroupsId, excludedGroupsId } = command.permissions - - if (allowedGroupsId && !allowedGroupsId.includes(ctx.chatId)) return false - if (excludedGroupsId?.includes(ctx.chatId)) return false - - if (allowGroupAdmins) { - if (this.hooks.overrideGroupAdminCheck) { - const isAdmin = await this.hooks.overrideGroupAdminCheck(ctx.from.id, ctx.chatId, ctx) - if (isAdmin) return true - } else { - const { status: groupRole } = await ctx.getChatMember(ctx.from.id) - if (groupRole === "administrator" || groupRole === "creator") return true - } + const allowed = this.isCommandAllowedInGroup(command, ctx.chat.id) + if (!allowed) return false + + if (command.permissions.allowGroupAdmins) { + const isAdmin = await isFromGroupAdmin() + if (isAdmin) return true } } - const roles = await this.getUserRoles(ctx.from.id, ctx) - - // blacklist is stronger than whitelist - if (allowedRoles?.every((r) => !roles.includes(r))) return false - if (excludedRoles?.some((r) => roles.includes(r))) return false + const roles = await getUserRoles() + return this.isCommandAllowedForRoles(command, roles) + } - return true + private async checkPermissions(command: AnyCommand, ctx: CommandContext): Promise { + if (!ctx.from) return false + const userId = ctx.from.id + return this.checkPermissionsCached( + command, + ctx, + () => this.getUserRoles(userId), + () => this.isFromGroupAdmin(ctx) + ) } /** diff --git a/src/utils/arrays.ts b/src/utils/arrays.ts new file mode 100644 index 0000000..4cb15c8 --- /dev/null +++ b/src/utils/arrays.ts @@ -0,0 +1,9 @@ +export function asyncFilter(arr: T[], predicate: (item: T) => Promise): Promise { + return Promise.all(arr.map(async (item) => ({ item, keep: await predicate(item) }))).then((results) => + results.filter((result) => result.keep).map((result) => result.item) + ) +} + +export function asyncMap(arr: T[], mapper: (item: T) => Promise): Promise { + return Promise.all(arr.map(mapper)) +} diff --git a/src/utils/once.ts b/src/utils/once.ts index a6ae914..65574a3 100644 --- a/src/utils/once.ts +++ b/src/utils/once.ts @@ -1,4 +1,5 @@ import type { MaybePromise } from "./types" +import { Awaiter } from "./wait" /** * Wraps a function so that it can only be invoked once. @@ -15,14 +16,14 @@ import type { MaybePromise } from "./types" * @returns A wrapped version of `fn` that only runs on the first call */ export function once(fn: (...args: A) => MaybePromise) { + const result: Awaiter = new Awaiter() let called = false - let result: R return async (...args: A) => { if (!called) { called = true - result = await fn(...args) + result.resolve(await fn(...args)) } - return result + return await result } } diff --git a/src/utils/types.ts b/src/utils/types.ts index b6ccd85..0c42622 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -5,14 +5,8 @@ import type { ApiInput, ApiOutput } from "@/backend" import type { ManagedCommandsFlavor } from "@/lib/managed-commands" import type { TelemetryContextFlavor } from "@/modules/telemetry" -export type OptionalPropertyOf = Exclude< - { - [K in keyof T]: T[K] extends undefined ? never : K - }[keyof T], - undefined -> -export type ContextWith

> = Exclude & { - [K in P]: NonNullable +export type ContextWith = C & { + [K in P]: NonNullable } export type MaybePromise = T | Promise From 940ec81c1f093e1991c23a02428a3a4931913434 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Mon, 13 Apr 2026 02:13:50 +0200 Subject: [PATCH 2/9] feat: caching, better formatting --- src/commands/index.ts | 48 +++++++++--- src/lib/managed-commands/command.ts | 9 +++ src/lib/managed-commands/index.ts | 39 ++++++---- src/redis/set.ts | 117 ++++++++++++++++++++++++++++ 4 files changed, 189 insertions(+), 24 deletions(-) create mode 100644 src/redis/set.ts diff --git a/src/commands/index.ts b/src/commands/index.ts index 21e757e..0aee1e0 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -7,6 +7,7 @@ import { logger } from "@/logger" import { modules } from "@/modules" import type { TelemetryContextFlavor } from "@/modules/telemetry" import { redis } from "@/redis" +import { RedisSet } from "@/redis/set" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" import type { Context, Role } from "@/utils/types" @@ -19,6 +20,19 @@ import { pin } from "./pin" import { report } from "./report" import { search } from "./search" +const userSet = new RedisSet({ + redis, + prefix: "managed-commands:cached-users", + ttl: 60 * 60 * 24, // 24h, we can afford some staleness here and it helps reduce the number of Redis calls significantly +}) + +const userRolesCache = new RedisFallbackAdapter({ + redis, + prefix: "managed-commands:user-roles", + ttl: 60 * 5, + logger, +}) + const adapter = new RedisFallbackAdapter>({ redis, prefix: "conv", @@ -34,6 +48,14 @@ export const commands = new ManagedCommands { + const key = `${userId}:${chatId}` + if (await userSet.has(key)) { + return true + } + await userSet.add(key) + return false + }, wrongScope: async ({ context, command }) => { await context.deleteMessage().catch(() => {}) logger.info( @@ -104,19 +126,15 @@ export const commands = new ManagedCommands { - // TODO: cache this to avoid hitting the db on every command - const { roles } = await api.tg.permissions.getRoles.query({ userId }) - return roles || [] + const cached = await userRolesCache.read(String(userId)) + if (cached) return cached + + const res = await api.tg.permissions.getRoles.query({ userId }) + const roles = res.roles ?? [] + await userRolesCache.write(String(userId), roles) + return roles }, }) - .createCommand({ - trigger: "ping", - scope: "private", - description: "Replies with pong", - handler: async ({ context }) => { - await context.reply("pong") - }, - }) .createCommand({ trigger: "start", scope: "private", @@ -138,4 +156,12 @@ export const commands = new ManagedCommands { + await context.reply("pong") + }, + }) .withCollection(linkAdminDashboard, report, search, management, moderation, pin, invite) diff --git a/src/lib/managed-commands/command.ts b/src/lib/managed-commands/command.ts index 28b46fd..52073db 100644 --- a/src/lib/managed-commands/command.ts +++ b/src/lib/managed-commands/command.ts @@ -262,3 +262,12 @@ export function isForThisScope(cmd: AnyCommand, chatType: "private" | "group" | if (cmd.scope === "group") return chatType === "group" || chatType === "supergroup" return true } + +export function switchOnScope( + cmd: Command, + handlers: { private: T; group: T; both: T } +) { + if (cmd.scope === "private") return handlers.private + if (cmd.scope === "group") return handlers.group + return handlers.both +} diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 50d3f8e..21f1f24 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -33,7 +33,7 @@ import type { CommandScopedContext, RepliedTo, } from "./command" -import { isAllowedInGroups, isAllowedInPrivate, isForThisScope, isTypedArgumentOptions, toBotCommands } from "./command" +import { isAllowedInGroups, isAllowedInPrivate, isTypedArgumentOptions, switchOnScope, toBotCommands } from "./command" import type { ManagedCommandsFlavor } from "./context" export type Hook = ( @@ -272,9 +272,11 @@ export class ManagedCommands< */ private static formatCommandUsage(cmd: AnyCommand): string { const args = cmd.args ?? [] - const scope = - cmd.scope === "private" ? "Private Chat" : cmd.scope === "group" ? "Groups" : "Groups and Private Chat" - + const scope = switchOnScope(cmd, { + private: "๐Ÿ‘ค Private chats only", + group: "๐Ÿ‘ฅ Groups only", + both: "๐ŸŒ Both private and group chats", + }) return fmt(({ n, b, i }) => [ typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | "), ...args.map(({ key, optional }) => (optional ? n`[${i`${key}`}]` : n`<${i`${key}`}>`)), @@ -292,11 +294,12 @@ export class ManagedCommands< const args = cmd.args ?? [] const trigger: string = typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | ") + const scope = switchOnScope(cmd, { private: "๐Ÿ‘ค", group: "๐Ÿ‘ฅ", both: "๐ŸŒ" }) + const admin = isAllowedInGroups(cmd) && cmd.permissions?.allowGroupAdmins ? "๐Ÿ›ก๏ธ" : "" return fmt(({ i, n }) => [ trigger, ...args.map(({ key, optional }) => (optional ? i` [${key}]` : i` <${key}>`)), - n`\n\t${cmd.description ?? "No description"}`, - n`\n\tScope: ${cmd.scope === "private" ? "Private Chat" : cmd.scope === "group" ? "Groups" : "Groups and Private Chat"}`, + n`\n\t${scope}${admin}${cmd.description ?? "No description"}`, ]) } @@ -424,25 +427,29 @@ export class ManagedCommands< } const getUserRoles = once(async () => await this.getUserRoles(userId)) - const isFromGroupAdmin = once(async () => await this.isFromGroupAdmin(ctx)) + const isFromGroupAdmin = once(async () => { + if (ctx.chat.type === "private") return true + return await this.isFromGroupAdmin(ctx) + }) const rawCollections = await asyncMap(Object.entries(this.commands), async ([collection, cmds]) => ({ collection, - commands: await asyncFilter( - cmds.filter((c) => isForThisScope(c, ctx.chat.type)), - async (cmd) => this.checkPermissionsCached(cmd, ctx, getUserRoles, isFromGroupAdmin) + commands: await asyncFilter(cmds, async (cmd) => + this.checkPermissionsCached(cmd, ctx, getUserRoles, isFromGroupAdmin) ), })) const collections = rawCollections.filter((c) => c.commands.length > 0) const reply = fmt( - ({ u, b, skip, n, code }) => [ + ({ u, b, skip, n, code, i }) => [ b`Available commands:`, ...collections.flatMap(({ collection, commands }) => [ collection === "default" ? "" : u`${b`\n${collection}:`}`, ...commands.map((cmd) => skip`${ManagedCommands.formatCommandShort(cmd)}`), ]), - n`\n\nType ${code`\/help `} for more details on a specific command.`, + i`\n๐Ÿ‘ค: Private only, ๐Ÿ‘ฅ: Group only, ๐ŸŒ: Everywhere`, + i`Commands marked with ๐Ÿ›ก๏ธ are restricted to administrators.`, + n`Type ${code`\/help `} for more details on a specific command.`, ], { sep: "\n" } ) @@ -459,6 +466,9 @@ export class ManagedCommands< return cmds } + /** + * Checks whether a command is allowed in a specific group based on its permissions + */ private isCommandAllowedInGroup(command: AnyGroupCommand, chatId: number): boolean { const { allowedGroupsId, excludedGroupsId } = command.permissions ?? {} if (allowedGroupsId && !allowedGroupsId.includes(chatId)) return false @@ -466,6 +476,9 @@ export class ManagedCommands< return true } + /** + * Checks whether a command is allowed for a specific set of roles based on its permissions + */ private isCommandAllowedForRoles(command: AnyCommand, roles: TRole[]): boolean { const { allowedRoles, excludedRoles } = command.permissions ?? {} if (allowedRoles?.every((r) => !roles.includes(r))) return false @@ -508,7 +521,7 @@ export class ManagedCommands< ): Promise { if (!command.permissions) return true - if (isAllowedInGroups(command) && (ctx.chat.type === "group" || ctx.chat.type === "supergroup")) { + if (isAllowedInGroups(command)) { const allowed = this.isCommandAllowedInGroup(command, ctx.chat.id) if (!allowed) return false diff --git a/src/redis/set.ts b/src/redis/set.ts new file mode 100644 index 0000000..ada3c75 --- /dev/null +++ b/src/redis/set.ts @@ -0,0 +1,117 @@ +import { EventEmitter } from "node:events" +import { + createClient, + type RedisClientOptions, + type RedisClientType, + type RedisFunctions, + type RedisModules, + type RedisScripts, +} from "redis" + +export interface RedisSetOptions { + /** Redis client instance, or options to create one */ + redis: RedisClientType | RedisClientOptions + /** Time to live for each entry in seconds, uses redis' EXPIRE command */ + ttl?: number + /** + * Prefix for each key stored in redis, to avoid collisions, if not provided a + * default one will be used to ensure uniqueness across multiple instances + */ + prefix?: string +} + +export class RedisSet< + M extends RedisModules = RedisModules, + F extends RedisFunctions = RedisFunctions, + S extends RedisScripts = RedisScripts, +> { + private static instanceCount = 0 + private prefix: string + // In-memory cache used when Redis is not available + private memoryCache: Set = new Set() + // temporary store for keys that need to be deleted once redis is back (used when delete does not find the key in memoryCache) + private deletions: Set = new Set() + private redisClient: RedisClientType + + constructor(private options: RedisSetOptions) { + const prefix = options.prefix ?? `redis-set-${RedisSet.instanceCount++}` + if (prefix.endsWith(":")) { + prefix.slice(0, -1) + } + this.prefix = prefix + if (options.redis instanceof EventEmitter) { + // RedisClient extends event emitter :) + this.redisClient = options.redis + } else { + this.redisClient = createClient(options.redis) + void this.redisClient.connect() + } + + this.redisClient.on("ready", () => { + void this.flushMemoryCache() + }) + } + + /** + * Flush the in-memory cache to Redis. Called automatically when the Redis + * connection is re-established. + */ + private async flushMemoryCache() { + // write all memoryCache entries to redis + await Promise.all(this.memoryCache.values().map((value) => this._add(value))) + this.memoryCache.clear() + // delete all keys that were marked for deletion while redis was down + await Promise.all(this.deletions.values().map((k) => this._delete(k))) + this.deletions.clear() + } + + private ready(): boolean { + return this.redisClient.isOpen && this.redisClient.isReady + } + + /** + * Writes a value to Redis. + * + * Sets an expiry if ttl is set in options. + * @param value The value to insert in the set. + */ + private async _add(value: string) { + await this.redisClient.sAdd(this.prefix, value) + if (this.options.ttl) { + await this.redisClient.expire(this.prefix, this.options.ttl) + } + } + + /** + * Deletes a key from Redis. + * @param key The key to delete. + */ + private async _delete(value: string) { + await this.redisClient.sRem(this.prefix, value) + } + + async add(value: string): Promise { + if (this.ready()) { + await this._add(value) + } else { + this.memoryCache.add(value) + } + } + + async delete(value: string): Promise { + if (this.ready()) { + await this._delete(value) + } else { + // Try to delete from memory cache, if not found add to deletions set + if (!this.memoryCache.delete(value)) this.deletions.add(value) + } + } + + async has(value: string): Promise { + if (this.ready()) { + return await this.redisClient.sIsMember(this.prefix, value) + } else { + return this.memoryCache.has(value) + } + } +} From 3f3d9b03f685de6dbe814b7846d742de4d45ec16 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Sun, 26 Apr 2026 16:00:15 +0200 Subject: [PATCH 3/9] test: dummy bot for telegram middleware testing; fix: `managed-commands` options defs and removed dependency on other files, `once` impl Co-authored-by: Copilot --- src/lib/managed-commands/index.ts | 13 +- src/utils/once.ts | 13 +- tests/common/dummy-bot.ts | 150 ++++++++++ tests/managed-commands/permissions.test.ts | 312 +++++++++++++++++++++ tests/once.test.ts | 66 +++++ 5 files changed, 540 insertions(+), 14 deletions(-) create mode 100644 tests/common/dummy-bot.ts create mode 100644 tests/managed-commands/permissions.test.ts create mode 100644 tests/once.test.ts diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 21f1f24..90bc61a 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -16,9 +16,9 @@ import z from "zod" import { asyncFilter, asyncMap } from "@/utils/arrays" import { isFromGroupChat, isFromPrivateChat } from "@/utils/chat" import { fmt } from "@/utils/format" -import { ephemeral } from "@/utils/messages" import { once } from "@/utils/once" import type { ContextWith } from "@/utils/types" +import { wait } from "@/utils/wait" import type { CommandsCollection } from "./collection" import type { AnyCommand, @@ -100,7 +100,7 @@ export interface IManagedCommandsOptions + adapter?: ConversationStorage /** * A function to get externally defined roles for a specific user. @@ -123,7 +123,7 @@ export interface IManagedCommandsOptions Promise + getUserRoles?: (userId: number) => Promise /** * Additional plugins to apply to the conversation inner composer. @@ -133,7 +133,7 @@ export interface IManagedCommandsOptions + hooks?: ManagedCommandsHooks } export type ManagedCommandsOptions = string extends TRole @@ -645,7 +645,10 @@ export class ManagedCommands< code`/help ${Array.isArray(cmd.trigger) ? cmd.trigger[0] : cmd.trigger}`, ]) ) - if (!isPrivate) void ephemeral(msg, 10_000) // delete the error message after some time in groups, no need to keep it + if (!isPrivate) + void wait(10_000) + .then(() => msg.delete()) + .catch(() => {}) return } diff --git a/src/utils/once.ts b/src/utils/once.ts index 65574a3..9805a3c 100644 --- a/src/utils/once.ts +++ b/src/utils/once.ts @@ -1,5 +1,4 @@ import type { MaybePromise } from "./types" -import { Awaiter } from "./wait" /** * Wraps a function so that it can only be invoked once. @@ -16,14 +15,10 @@ import { Awaiter } from "./wait" * @returns A wrapped version of `fn` that only runs on the first call */ export function once(fn: (...args: A) => MaybePromise) { - const result: Awaiter = new Awaiter() - let called = false + let result: Promise> | undefined - return async (...args: A) => { - if (!called) { - called = true - result.resolve(await fn(...args)) - } - return await result + return (...args: A) => { + result ??= Promise.resolve(fn(...args)) + return result } } diff --git a/tests/common/dummy-bot.ts b/tests/common/dummy-bot.ts new file mode 100644 index 0000000..82966ca --- /dev/null +++ b/tests/common/dummy-bot.ts @@ -0,0 +1,150 @@ +import { type ApiCallFn, Bot, type Context, type RawApi } from "grammy" +import type { Update } from "grammy/types" + +type ApiFunction = ApiCallFn +export type ResultType = Awaited> +type Params = Parameters +type PayloadType = Params[1] +export type OutgoingRequest = { + method: string + payload: PayloadType +} + +export async function createDummyBot() { + const bot = new Bot("token") + const outgoingRequests: OutgoingRequest[] = [] + + bot.api.config.use(async (_, method, payload) => { + outgoingRequests.push({ method, payload }) + return { ok: true, result: true as ResultType } + }) + + bot.botInfo = { + id: 42, + first_name: "Dummy Bot", + is_bot: true, + username: "dummy_bot", + can_join_groups: true, + can_read_all_group_messages: false, + supports_inline_queries: false, + can_connect_to_business: false, + has_main_web_app: false, + } + + await bot.init() + + return { + bot, + outgoingRequests, + } +} + +export function generateCommandCall(trigger: string, id: number = 0): Update { + return { + update_id: 0, + message: { + text: `/${trigger}`, + message_id: 0, + date: Date.now(), + entities: [ + { + type: "bot_command", + offset: 0, + length: trigger.length + 1, + }, + ], + chat: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + type: "private", + }, + from: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + is_bot: false, + }, + }, + } +} + +export function generateGroupCommandCall(trigger: string, id: number = 0): Update { + return { + update_id: 0, + message: { + text: `/${trigger}`, + message_id: 0, + date: Date.now(), + entities: [ + { + type: "bot_command", + offset: 0, + length: trigger.length + 1, + }, + ], + chat: { + id, + title: "Test Group", + type: "group", + }, + from: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + is_bot: false, + }, + }, + } +} + +export function generateMessage(text: string, id: number = 0): Update { + return { + update_id: 0, + message: { + text, + message_id: 0, + date: Date.now(), + chat: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + type: "private", + }, + from: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + is_bot: false, + }, + }, + } +} + +export function generateGroupMessage(text: string, id: number = 0): Update { + return { + update_id: 0, + message: { + text, + message_id: 0, + date: Date.now(), + chat: { + id, + title: "Test Group", + type: "group", + }, + from: { + id, + first_name: "Test", + last_name: "Lastest", + username: "testuser", + is_bot: false, + }, + }, + } +} diff --git a/tests/managed-commands/permissions.test.ts b/tests/managed-commands/permissions.test.ts new file mode 100644 index 0000000..c9df46d --- /dev/null +++ b/tests/managed-commands/permissions.test.ts @@ -0,0 +1,312 @@ +import { hydrate } from "@grammyjs/hydrate" +import { hydrateReply, parseMode } from "@grammyjs/parse-mode" +import { MemorySessionStorage } from "grammy" +import { beforeEach, describe, expect, it } from "vitest" +import { ManagedCommands, type ManagedCommandsFlavor } from "@/lib/managed-commands" +import { + createDummyBot, + generateCommandCall, + generateGroupCommandCall, + type OutgoingRequest, + type ResultType, +} from "../common/dummy-bot" + +let wasMissingPermissions = false +const { bot, outgoingRequests } = await createDummyBot() + +type Role = "admin" | "mod" | "banned" + +const commands = new ManagedCommands({ + adapter: new MemorySessionStorage(), + getUserRoles: async (userId) => { + if (userId === 1) return ["admin"] + if (userId === 2) return ["mod"] + if (userId === 3) return ["banned"] + if (userId === 4) return ["admin", "banned"] + return [] + }, + plugins: [ + async (ctx, next) => { + ctx.api.config.use(async (_, method, payload) => { + outgoingRequests.push({ method, payload }) + return { ok: true, result: true as ResultType } + }) + await next() + }, + ], + hooks: { + overrideGroupAdminCheck: async (userId) => { + return userId === 1 || userId === 99 + }, + missingPermissions: async () => { + wasMissingPermissions = true + }, + }, +}) + .createCommand({ + trigger: "public", + handler: async ({ context }) => { + await context.reply("Public command executed") + }, + }) + .createCommand({ + trigger: "private", + scope: "private", + handler: async ({ context }) => { + await context.reply("Private command executed") + }, + }) + .createCommand({ + trigger: "group", + scope: "group", + permissions: { + allowGroupAdmins: false, + }, + handler: async ({ context }) => { + await context.reply("Group command executed") + }, + }) + .createCommand({ + trigger: "role_admin", + permissions: { + allowedRoles: ["admin"], + }, + handler: async ({ context }) => { + await context.reply("Role admin command executed") + }, + }) + .createCommand({ + trigger: "role_mod", + permissions: { + allowedRoles: ["mod"], + }, + handler: async ({ context }) => { + await context.reply("Role mod command executed") + }, + }) + .createCommand({ + trigger: "role_admin_or_mod", + permissions: { + allowedRoles: ["admin", "mod"], + }, + handler: async ({ context }) => { + await context.reply("Role admin or mod command executed") + }, + }) + .createCommand({ + trigger: "excluded_banned", + permissions: { + excludedRoles: ["banned"], + }, + handler: async ({ context }) => { + await context.reply("Excluded banned command executed") + }, + }) + .createCommand({ + trigger: "group_admin", + scope: "group", + permissions: { + allowedRoles: [], + allowGroupAdmins: true, + }, + handler: async ({ context }) => { + await context.reply("Group admin command executed") + }, + }) + .createCommand({ + trigger: "group_allowed_only", + scope: "group", + permissions: { + allowGroupAdmins: false, + allowedGroupsId: [50], + }, + handler: async ({ context }) => { + await context.reply("Group allowed-only command executed") + }, + }) + .createCommand({ + trigger: "group_excluded", + scope: "group", + permissions: { + allowGroupAdmins: false, + excludedGroupsId: [60], + }, + handler: async ({ context }) => { + await context.reply("Group excluded command executed") + }, + }) + .createCommand({ + trigger: "group_allowed_and_excluded", + scope: "group", + permissions: { + allowGroupAdmins: false, + allowedGroupsId: [70], + excludedGroupsId: [70], + }, + handler: async ({ context }) => { + await context.reply("Group allowed-and-excluded command executed") + }, + }) + +bot.use(hydrate()) +bot.use(hydrateReply) +bot.api.config.use(parseMode("MarkdownV2")) +bot.use(commands) + +beforeEach(() => { + outgoingRequests.length = 0 + wasMissingPermissions = false +}) + +function payloadText(request?: OutgoingRequest): string | undefined { + if (!!request && "text" in request.payload) { + return request.payload.text + } + return undefined +} + +function sendMessages(): OutgoingRequest[] { + return outgoingRequests.filter((request) => request.method === "sendMessage") +} + +function lastSentText(): string | undefined { + const request = sendMessages().at(-1) + return payloadText(request) +} + +function expectNoMessageWithText(text: string): void { + expect(sendMessages().some((request) => payloadText(request) === text)).toBe(false) +} + +function normalizeMarkdownEscapes(text?: string): string { + return (text ?? "").replaceAll("\\_", "_") +} + +function expectMissingPermissions(): void { + expect(wasMissingPermissions).toBe(true) + wasMissingPermissions = false +} + +describe("ManagedCommands - Permissions", () => { + it("executes command without permissions", async () => { + await bot.handleUpdate(generateCommandCall("public")) + expect(lastSentText()).toBe("Public command executed") + }) + + it("allows command when user has a required role", async () => { + await bot.handleUpdate(generateCommandCall("role_admin", 1)) + expect(lastSentText()).toBe("Role admin command executed") + }) + + it("denies command when user misses required role", async () => { + await bot.handleUpdate(generateCommandCall("role_admin", 2)) + expectNoMessageWithText("Role admin command executed") + expectMissingPermissions() + }) + + it("allows command when at least one allowed role matches", async () => { + await bot.handleUpdate(generateCommandCall("role_admin_or_mod", 2)) + expect(lastSentText()).toBe("Role admin or mod command executed") + }) + + it("denies command when all allowed roles are missing", async () => { + await bot.handleUpdate(generateCommandCall("role_admin_or_mod")) + expectNoMessageWithText("Role admin or mod command executed") + expectMissingPermissions() + }) + + it("denies command when user has an excluded role", async () => { + await bot.handleUpdate(generateCommandCall("excluded_banned", 3)) + expectNoMessageWithText("Excluded banned command executed") + expectMissingPermissions() + }) + + it("denies command when excluded role is present with an allowed one", async () => { + await bot.handleUpdate(generateCommandCall("excluded_banned", 4)) + expectNoMessageWithText("Excluded banned command executed") + expectMissingPermissions() + }) + + it("allows group-admin command for group admins without external roles", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_admin", 99)) + expect(lastSentText()).toBe("Group admin command executed") + }) + + it("denies group-admin command for non-admin users without required roles", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_admin")) + expectNoMessageWithText("Group admin command executed") + expectMissingPermissions() + }) + + it("allows command only in explicitly allowed groups", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_allowed_only", 50)) + expect(lastSentText()).toBe("Group allowed-only command executed") + }) + + it("denies command outside explicitly allowed groups", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_allowed_only", 51)) + expectNoMessageWithText("Group allowed-only command executed") + expectMissingPermissions() + }) + + it("denies command in excluded groups", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_excluded", 60)) + expectNoMessageWithText("Group excluded command executed") + expectMissingPermissions() + }) + + it("allows command in non-excluded groups", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_excluded", 61)) + expect(lastSentText()).toBe("Group excluded command executed") + }) + + it("gives exclusion precedence when group is both allowed and excluded", async () => { + await bot.handleUpdate(generateGroupCommandCall("group_allowed_and_excluded", 70)) + expectNoMessageWithText("Group allowed-and-excluded command executed") + expectMissingPermissions() + }) + + it("shows only commands allowed by role in help for regular users", async () => { + await bot.handleUpdate(generateCommandCall("help", 10)) + const text = normalizeMarkdownEscapes(lastSentText()) + expect(text).toContain("Available commands") + expect(text).toContain("/public") + expect(text).toContain("/private") + expect(text).toContain("/group") + expect(text).toContain("/excluded_banned") + expect(text).toContain("/group_admin") + expect(text).not.toContain("/role_admin") + expect(text).not.toContain("/role_mod") + expect(text).not.toContain("/role_admin_or_mod") + }) + + it("shows role-gated commands in help for admins", async () => { + await bot.handleUpdate(generateCommandCall("help", 1)) + const text = normalizeMarkdownEscapes(lastSentText()) + expect(text).toContain("/role_admin") + expect(text).toContain("/role_admin_or_mod") + expect(text).not.toContain("/role_mod") + expect(text).toContain("/excluded_banned") + }) + + it("hides excluded commands in help for excluded users", async () => { + await bot.handleUpdate(generateCommandCall("help", 3)) + const text = normalizeMarkdownEscapes(lastSentText()) + expect(text).toContain("Available commands") + expect(text).not.toContain("/excluded_banned") + }) + + it("hides group-restricted command in help when current group is not allowed", async () => { + await bot.handleUpdate(generateGroupCommandCall("help", 51)) + const text = normalizeMarkdownEscapes(lastSentText()) + expect(text).toContain("Available commands") + expect(text).not.toContain("/group_allowed_only") + }) + + it("shows group-restricted command in help when current group is allowed", async () => { + await bot.handleUpdate(generateGroupCommandCall("help", 50)) + const text = normalizeMarkdownEscapes(lastSentText()) + expect(text).toContain("Available commands") + expect(text).toContain("/group_allowed_only") + }) +}) diff --git a/tests/once.test.ts b/tests/once.test.ts new file mode 100644 index 0000000..46c5439 --- /dev/null +++ b/tests/once.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it, vi } from "vitest" +import { once } from "@/utils/once" + +describe("once", () => { + it("executes the wrapped function only once for sync results", async () => { + const fn = vi.fn((value: number) => value * 2) + const wrapped = once(fn) + + const first = await wrapped(2) + const second = await wrapped(7) + const third = await wrapped(11) + + expect(first).toBe(4) + expect(second).toBe(4) + expect(third).toBe(4) + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith(2) + }) + + it("returns the same promise for repeated async calls", async () => { + const fn = vi.fn(async (name: string) => ({ name, createdAt: Date.now() })) + const wrapped = once(fn) + + const promise1 = wrapped("first") + const promise2 = wrapped("second") + const promise3 = wrapped("third") + + expect(promise1).toBe(promise2) + expect(promise2).toBe(promise3) + + const result1 = await promise1 + const result2 = await promise2 + const result3 = await promise3 + + expect(result1).toEqual({ name: "first", createdAt: expect.any(Number) }) + expect(result2).toEqual(result1) + expect(result3).toEqual(result1) + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith("first") + }) + + it("preserves the original rejection for later calls", async () => { + const error = new Error("boom") + const fn = vi.fn(async () => { + throw error + }) + const wrapped = once(fn) + + await expect(wrapped()).rejects.toThrow(error) + // @ts-expect-error: This is testing that the same error is thrown on subsequent calls, even if the arguments are different + await expect(wrapped("ignored")).rejects.toThrow(error) + + expect(fn).toHaveBeenCalledTimes(1) + }) + + it("keeps the first resolved value even if later calls pass different arguments", async () => { + const fn = vi.fn((value: string, suffix: string) => `${value}-${suffix}`) + const wrapped = once(fn) + + await expect(wrapped("alpha", "one")).resolves.toBe("alpha-one") + await expect(wrapped("beta", "two")).resolves.toBe("alpha-one") + + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith("alpha", "one") + }) +}) From f7ef125b24f89c3604a38f61a71dda3582b67c50 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Sun, 26 Apr 2026 16:07:58 +0200 Subject: [PATCH 4/9] refactor: folders in tests --- tests/{ => utils}/awaiter.test.ts | 0 tests/{ => utils}/format.test.ts | 0 tests/{ => utils}/once.test.ts | 0 tests/{ => utils}/throttle.test.ts | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename tests/{ => utils}/awaiter.test.ts (100%) rename tests/{ => utils}/format.test.ts (100%) rename tests/{ => utils}/once.test.ts (100%) rename tests/{ => utils}/throttle.test.ts (100%) diff --git a/tests/awaiter.test.ts b/tests/utils/awaiter.test.ts similarity index 100% rename from tests/awaiter.test.ts rename to tests/utils/awaiter.test.ts diff --git a/tests/format.test.ts b/tests/utils/format.test.ts similarity index 100% rename from tests/format.test.ts rename to tests/utils/format.test.ts diff --git a/tests/once.test.ts b/tests/utils/once.test.ts similarity index 100% rename from tests/once.test.ts rename to tests/utils/once.test.ts diff --git a/tests/throttle.test.ts b/tests/utils/throttle.test.ts similarity index 100% rename from tests/throttle.test.ts rename to tests/utils/throttle.test.ts From 8999f3a776d9fd5f81e0f991dac9068c60ca595b Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Sun, 26 Apr 2026 16:15:53 +0200 Subject: [PATCH 5/9] fix: cleanup Co-authored-by: Copilot --- src/lib/managed-commands/index.ts | 2 +- tests/common/dummy-bot.ts | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 90bc61a..7cd18f4 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -87,7 +87,7 @@ export type ManagedCommandsHooks /** - * A function to externally cache wether a user has had the commands menu generated for them or not + * A function to externally cache whether a user has had the commands menu generated for them or not * @returns true if the user has had the commands menu generated, false otherwise */ cachedUserSetCommands?: (userId: number, chatId: number) => Promise diff --git a/tests/common/dummy-bot.ts b/tests/common/dummy-bot.ts index 82966ca..e16c89f 100644 --- a/tests/common/dummy-bot.ts +++ b/tests/common/dummy-bot.ts @@ -10,6 +10,15 @@ export type OutgoingRequest = { payload: PayloadType } +/** Returns the current timestamp in seconds since the Unix epoch. */ +function now() { + return Math.floor(Date.now() / 1000) +} + +/** + * Creates a dummy bot instance for testing purposes. + * @returns An object containing the dummy bot and an array to capture outgoing API requests + */ export async function createDummyBot() { const bot = new Bot("token") const outgoingRequests: OutgoingRequest[] = [] @@ -39,13 +48,14 @@ export async function createDummyBot() { } } +/** Generates a dummy command call `Update` for testing purposes. */ export function generateCommandCall(trigger: string, id: number = 0): Update { return { update_id: 0, message: { text: `/${trigger}`, message_id: 0, - date: Date.now(), + date: now(), entities: [ { type: "bot_command", @@ -71,13 +81,14 @@ export function generateCommandCall(trigger: string, id: number = 0): Update { } } +/** Generates a dummy command call `Update` for testing purposes, from a group chat */ export function generateGroupCommandCall(trigger: string, id: number = 0): Update { return { update_id: 0, message: { text: `/${trigger}`, message_id: 0, - date: Date.now(), + date: now(), entities: [ { type: "bot_command", @@ -101,13 +112,14 @@ export function generateGroupCommandCall(trigger: string, id: number = 0): Updat } } +/** Generates a dummy text message `Update` for testing purposes. */ export function generateMessage(text: string, id: number = 0): Update { return { update_id: 0, message: { text, message_id: 0, - date: Date.now(), + date: now(), chat: { id, first_name: "Test", @@ -126,13 +138,14 @@ export function generateMessage(text: string, id: number = 0): Update { } } +/** Generates a dummy text message `Update` for testing purposes, from a group chat */ export function generateGroupMessage(text: string, id: number = 0): Update { return { update_id: 0, message: { text, message_id: 0, - date: Date.now(), + date: now(), chat: { id, title: "Test Group", From 3cc0de62e171d73e34eae8c808ca49634099ff33 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Fri, 29 May 2026 21:33:51 +0200 Subject: [PATCH 6/9] fix: check permissions on `/help command` --- src/lib/managed-commands/index.ts | 20 ++++++++++++-------- tests/common/dummy-bot.ts | 8 ++++---- tests/managed-commands/permissions.test.ts | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 7cd18f4..90027ba 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -416,21 +416,25 @@ export class ManagedCommands< const userId = ctx.from.id const text = ctx.message?.text ?? "" + const getUserRoles = once(async () => await this.getUserRoles(userId)) + const isFromGroupAdmin = once(async () => { + if (ctx.chat.type === "private") return true + return await this.isFromGroupAdmin(ctx) + }) + const [_, cmdArg] = text.replaceAll("/", "").split(" ") if (cmdArg) { const cmd = this.getCommands().find((c) => Array.isArray(c.trigger) ? c.trigger.includes(cmdArg) : c.trigger === cmdArg ) - if (!cmd) return ctx.reply(fmt(() => "Command not found. See /help for available commands.")) - return ctx.reply(ManagedCommands.formatCommandUsage(cmd)) - } + if (cmd) { + const allowed = await this.checkPermissionsCached(cmd, ctx, getUserRoles, isFromGroupAdmin) + if (allowed) return ctx.reply(ManagedCommands.formatCommandUsage(cmd)) + } - const getUserRoles = once(async () => await this.getUserRoles(userId)) - const isFromGroupAdmin = once(async () => { - if (ctx.chat.type === "private") return true - return await this.isFromGroupAdmin(ctx) - }) + return ctx.reply(fmt(() => "Command not found. See /help for available commands.")) + } const rawCollections = await asyncMap(Object.entries(this.commands), async ([collection, cmds]) => ({ collection, diff --git a/tests/common/dummy-bot.ts b/tests/common/dummy-bot.ts index e16c89f..c7dc8c6 100644 --- a/tests/common/dummy-bot.ts +++ b/tests/common/dummy-bot.ts @@ -49,11 +49,11 @@ export async function createDummyBot() { } /** Generates a dummy command call `Update` for testing purposes. */ -export function generateCommandCall(trigger: string, id: number = 0): Update { +export function generateCommandCall(trigger: string, id: number = 0, args: string = ""): Update { return { update_id: 0, message: { - text: `/${trigger}`, + text: `/${trigger} ${args}`.trim(), message_id: 0, date: now(), entities: [ @@ -82,11 +82,11 @@ export function generateCommandCall(trigger: string, id: number = 0): Update { } /** Generates a dummy command call `Update` for testing purposes, from a group chat */ -export function generateGroupCommandCall(trigger: string, id: number = 0): Update { +export function generateGroupCommandCall(trigger: string, id: number = 0, args: string = ""): Update { return { update_id: 0, message: { - text: `/${trigger}`, + text: `/${trigger} ${args}`.trim(), message_id: 0, date: now(), entities: [ diff --git a/tests/managed-commands/permissions.test.ts b/tests/managed-commands/permissions.test.ts index c9df46d..971f47b 100644 --- a/tests/managed-commands/permissions.test.ts +++ b/tests/managed-commands/permissions.test.ts @@ -187,6 +187,11 @@ function expectMissingPermissions(): void { wasMissingPermissions = false } +function expectHelpCommandNotFound(): void { + expect(lastSentText()).toBe("Command not found\\. See /help for available commands\\.") + expect(wasMissingPermissions).toBe(false) +} + describe("ManagedCommands - Permissions", () => { it("executes command without permissions", async () => { await bot.handleUpdate(generateCommandCall("public")) @@ -309,4 +314,14 @@ describe("ManagedCommands - Permissions", () => { expect(text).toContain("Available commands") expect(text).toContain("/group_allowed_only") }) + + it("returns not found for role-gated commands in help when permissions are missing", async () => { + await bot.handleUpdate(generateCommandCall("help", 2, "role_admin")) + expectHelpCommandNotFound() + }) + + it("returns not found for group-gated commands in help when the group is not allowed", async () => { + await bot.handleUpdate(generateGroupCommandCall("help", 51, "group_allowed_only")) + expectHelpCommandNotFound() + }) }) From 5a62a386a349b1c5498807705e4131706a4ec90a Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Fri, 29 May 2026 22:22:31 +0200 Subject: [PATCH 7/9] fix: remove hardocded magic number for cmd with groups whitelist --- src/lib/managed-commands/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index 90027ba..c2a7b28 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -387,7 +387,7 @@ export class ManagedCommands< .concat([{ command: "help", description: "Show available commands" }]) await ctx.api.setMyCommands(privateCommands, { scope: { type: "all_private_chats" } }).catch(() => {}) const groupCommands: BotCommand[] = freeCommands - .filter((cmd) => isAllowedInGroups(cmd) && this.isCommandAllowedInGroup(cmd, -100)) // only include commands that are allowed in all groups + .filter((cmd) => isAllowedInGroups(cmd) && !cmd.permissions?.allowedGroupsId) // only include commands without whitelist .flatMap((cmd) => toBotCommands(cmd)) .concat([{ command: "help", description: "Show available commands" }]) await ctx.api.setMyCommands(groupCommands, { scope: { type: "all_group_chats" } }).catch(() => {}) From b21580280005a1c144adfcad33f6e77a850f40f6 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Mon, 2 Nov 2026 17:40:56 +0100 Subject: [PATCH 8/9] feat(commands): truthful /help and per-user commands menus /help and the Telegram commands menu now show each user the commands they can actually run, using the same decision that gates execution instead of a parallel permission check that could drift from it. - The `authorize` hook receives an `isGroupAdmin` oracle from ManagedCommands rather than querying Telegram itself. It is false outside groups, so the group admin shortcut can never apply in a private chat, and it is asked at most once per update. - /help in private chat also lists the group commands the user could run: it decides as if they were not a group admin and, only if that was denied after asking, as if they were; such commands are marked as available only where the user is an admin. - /help in a group lists the commands runnable there, as an ephemeral message, and /help only describes commands the user can run. - Default menus hold the commands anyone can run; a user gets their own menu in a chat only when their commands differ, recomputed hourly or on /help, and stored so Telegram is called only on changes. - The sender's IdP access is resolved once per update and shared by all the commands evaluated for /help and the menu. - Group-only and private-only checks treat channels as out of scope. --- src/access/index.ts | 4 +- src/commands/access.ts | 35 ++- src/commands/index.ts | 15 +- src/lib/managed-commands/command.ts | 23 +- src/lib/managed-commands/help.ts | 174 +++++++++++ src/lib/managed-commands/index.ts | 437 ++++++++++++++++++++++------ 6 files changed, 577 insertions(+), 111 deletions(-) create mode 100644 src/lib/managed-commands/help.ts diff --git a/src/access/index.ts b/src/access/index.ts index 34c9482..795974f 100644 --- a/src/access/index.ts +++ b/src/access/index.ts @@ -34,10 +34,12 @@ export async function authorizeAction(options: { required: readonly Permission[] /** Set only where the chat's native admins may act too (RFC v3 ยง4 decision 2). */ isChatAdmin?: () => Promise + /** The person's access, if already looked up; otherwise it is resolved through `backend`. */ + actor?: () => Promise }): Promise { return idpDecision({ required: options.required, - actor: () => resolveOne(options.backend, options.actorId), + actor: options.actor ?? (() => resolveOne(options.backend, options.actorId)), isChatAdmin: options.isChatAdmin, }).catch((error: unknown) => { const { check, actorId, chatId } = options diff --git a/src/commands/access.ts b/src/commands/access.ts index f03f162..ff518b6 100644 --- a/src/commands/access.ts +++ b/src/commands/access.ts @@ -1,7 +1,6 @@ -import { authorizeAction, DENIED, type Decision, type Permission } from "@/access" +import { type AccessEntry, authorizeAction, DENIED, type Decision, type Permission, resolveOne } from "@/access" import { backendFor } from "@/backend" import { type Authorize, ManagedCommands } from "@/lib/managed-commands" -import { isFromGroupChat } from "@/utils/chat" import type { Context } from "@/utils/types" /** How commands declare IdP permissions, and what their handlers receive. */ @@ -19,24 +18,38 @@ export type CommandAccess = { authorization: Decision } -export const authorizeCommand: Authorize = async ({ context, command }) => { +/** + * The sender's IdP access, looked up once per update: `/help` and the commands menu decide on every command at once. + * A failed lookup is shared too, and denies every command of the update. + */ +const senderAccess = new WeakMap>() + +/** + * Whether the sender of an update may run a command. ManagedCommands also uses it to build `/help` and the commands + * menu, so it must take group admin status only from `isGroupAdmin`, see {@link Authorize}. + */ +export const authorizeCommand: Authorize = async ({ context, command, isGroupAdmin }) => { const { permissions } = command if (!permissions?.requiredPermissions?.length) return { allowed: true, basis: null } const from = context.from if (!from) return DENIED + const backend = backendFor(from) return authorizeAction({ check: `command:/${ManagedCommands.commandID(command)}`, actorId: from.id, chatId: context.chat.id, - backend: backendFor(from), + backend, required: permissions.requiredPermissions, - isChatAdmin: - permissions.allowTelegramChatAdmins && isFromGroupChat(context) - ? async () => { - const { status } = await context.getChatMember(from.id) - return status === "administrator" || status === "creator" - } - : undefined, + actor: () => { + let access = senderAccess.get(context) + if (!access) { + access = resolveOne(backend, from.id) + senderAccess.set(context, access) + } + return access + }, + // false outside of groups, so the shortcut only ever applies in groups + isChatAdmin: permissions.allowTelegramChatAdmins ? isGroupAdmin : undefined, }) } diff --git a/src/commands/index.ts b/src/commands/index.ts index 849566d..6882d6c 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,6 +1,6 @@ import type { ConversationData, VersionedState } from "@grammyjs/conversations" import { Point } from "@influxdata/influxdb-client" -import { type CommandScopedContext, ManagedCommands } from "@/lib/managed-commands" +import { type CommandScopedContext, ManagedCommands, type StoredCommandsMenu } from "@/lib/managed-commands" import { RedisFallbackAdapter } from "@/lib/redis-fallback-adapter" import { logger } from "@/logger" import { modules } from "@/modules" @@ -24,10 +24,23 @@ const adapter = new RedisFallbackAdapter>({ logger, }) +const menuStorage = new RedisFallbackAdapter({ + redis, + prefix: "managed-commands:menus", + // a missing entry is taken as the default menu, keep entries long after they are refreshed + ttl: 60 * 60 * 24 * 30, + logger, +}) + type ConversationContext = TelemetryContextFlavor export const commands = new ManagedCommands({ adapter, + menus: { + storage: menuStorage, + refreshAfterMs: 60 * 60 * 1000, + onError: (error) => logger.warn({ error }, "[ManagedCommands] could not update the commands menu"), + }, plugins: [ (ctx, next) => { ctx.point = new Point("command_execution") diff --git a/src/lib/managed-commands/command.ts b/src/lib/managed-commands/command.ts index 933d702..5e90796 100644 --- a/src/lib/managed-commands/command.ts +++ b/src/lib/managed-commands/command.ts @@ -220,7 +220,21 @@ export function isAllowedInGroups< } /** - * Type guard to check if a command is allowed in private chats. + * Type guard to check if a command is allowed in private chats (scope "private" or "both"). + * @param cmd The command to check + * @returns A boolean indicating if the command is allowed in private chats. + */ +export function isAllowedInPrivate< + A extends CommandArgs, + R extends CommandReplyTo, + C extends Context = Context, + TAccess extends AccessControl = DefaultAccessControl, +>(cmd: Command): cmd is Command { + return cmd.scope !== "group" +} + +/** + * Type guard to check if a command is allowed only in private chats. * @param cmd The command to check * @returns A boolean indicating if the command is allowed in private chats. * @@ -245,3 +259,10 @@ export function isAllowedInPrivateOnly< >(cmd: Command): cmd is Command { return cmd.scope === "private" } + +/** + * All the triggers of a command, including its aliases + */ +export function commandTriggers(cmd: AnyCommand): string[] { + return Array.isArray(cmd.trigger) ? [...cmd.trigger] : [cmd.trigger] +} diff --git a/src/lib/managed-commands/help.ts b/src/lib/managed-commands/help.ts new file mode 100644 index 0000000..1e18769 --- /dev/null +++ b/src/lib/managed-commands/help.ts @@ -0,0 +1,174 @@ +import type { Context } from "grammy" +import type { BotCommand } from "grammy/types" +import { fmt } from "@/utils/format" +import type { AccessControl, AnyCommand } from "./command" +import { commandTriggers, isAllowedInGroups } from "./command" + +/** + * Whether a user may run a command in groups: + * - `yes`: in every group where the command is enabled + * - `if_group_admin`: only in groups where the user is a group admin, which the bot cannot know in advance + * - `no`: in no group + */ +export type GroupAvailability = "yes" | "if_group_admin" | "no" + +/** Where a user may run a command, as far as the bot can tell from a private chat */ +export type CommandAvailability = { + private: boolean + groups: GroupAvailability +} + +export type HelpSection = { collection: string; entries: T[] } + +export const HELP_TRIGGER = "help" +export const HELP_BOT_COMMAND: BotCommand = { command: HELP_TRIGGER, description: "Show the commands you can use" } + +const MARK = { + private: "๐Ÿ‘ค", + groups: "๐Ÿ‘ฅ", + everywhere: "๐ŸŒ", + groupAdmin: "๐Ÿ›ก๏ธ", +} as const + +type AnyCmd = AnyCommand + +export function isAvailable(availability: CommandAvailability): boolean { + return availability.private || availability.groups !== "no" +} + +function formatTriggers(cmd: AnyCmd): string { + return commandTriggers(cmd) + .map((t) => `/${t}`) + .join(" | ") +} + +function isLimitedToSomeGroups(cmd: AnyCmd): boolean { + return isAllowedInGroups(cmd) && cmd.permissions?.allowedGroupsId !== undefined +} + +function availabilityMark(availability: CommandAvailability): string { + const where = !availability.private ? MARK.groups : availability.groups === "no" ? MARK.private : MARK.everywhere + return availability.groups === "if_group_admin" ? `${where}${MARK.groupAdmin}` : where +} + +/** A sentence telling the user where they can run the command */ +function describeAvailability(cmd: AnyCmd, availability: CommandAvailability): string { + const parts: string[] = [] + if (availability.private) parts.push("in private chat with the bot") + if (availability.groups === "yes") parts.push("in groups") + if (availability.groups === "if_group_admin") parts.push("in groups where you are an admin") + const where = parts.join(" and ") + const limited = availability.groups !== "no" && isLimitedToSomeGroups(cmd) ? " (only some groups)" : "" + return `${where.charAt(0).toUpperCase()}${where.slice(1)}${limited}` +} + +function formatCommandShort(cmd: AnyCmd, mark?: string): string { + const args = cmd.args ?? [] + return fmt(({ i, n }) => [ + formatTriggers(cmd), + ...args.map(({ key, optional }) => (optional ? i` [${key}]` : i` <${key}>`)), + n`\n\t${mark ? `${mark} ` : ""}${cmd.description ?? "No description"}`, + ]) +} + +/** + * Creates a formatted message to display the usage of a command to the user + * @param cmd The command to print usage for + * @param availableTo Where the user can run the command + * @returns A markdown formatted string representing the usage of the command + */ +function formatCommandUsage(cmd: AnyCmd, availableTo: string): string { + const args = cmd.args ?? [] + const scope = cmd.scope === "private" ? "Private Chat" : cmd.scope === "group" ? "Groups" : "Groups and Private Chat" + + return fmt(({ n, b, i }) => [ + formatTriggers(cmd), + ...args.map(({ key, optional }) => (optional ? n`[${i`${key}`}]` : n`<${i`${key}`}>`)), + i`\nDesc:`, + b`${cmd.description ?? "No description"}`, + i`\nScope:`, + b`${scope}`, + i`\nAvailable to you:`, + b`${availableTo}`, + ...(cmd.reply ? [i`\nCall while replying to a message:`, b`${cmd.reply.toUpperCase()}`] : []), + args.length ? i`\nArgs:` : ``, + ...args.flatMap(({ key, description }) => [`\n-`, i`${key}:`, description ?? "No description"]), + ]) +} + +export function formatUsageFromPrivate(cmd: AnyCmd, availability: CommandAvailability): string { + return formatCommandUsage(cmd, describeAvailability(cmd, availability)) +} + +export function formatUsageInGroup(cmd: AnyCmd): string { + return formatCommandUsage(cmd, "In this group") +} + +function formatSections( + sections: HelpSection[], + header: (collection: string) => string, + format: (entry: T) => string +): string[] { + return sections.flatMap(({ collection, entries }) => [ + ...(collection === "default" ? [] : [header(collection)]), + ...entries.map(format), + ]) +} + +/** The /help message in private chat: every command the user can run, in private chat or in groups */ +export function formatHelpFromPrivate(sections: HelpSection<{ cmd: AnyCmd; availability: CommandAvailability }>[]) { + const all = sections.flatMap((s) => s.entries.map((e) => e.availability)) + const legend = [ + all.some((a) => a.private && a.groups === "no") ? `${MARK.private} private chat only` : null, + all.some((a) => !a.private) ? `${MARK.groups} groups only` : null, + all.some((a) => a.private && a.groups !== "no") ? `${MARK.everywhere} private chat and groups` : null, + ].filter((l) => l !== null) + const anyGroupAdmin = all.some((a) => a.groups === "if_group_admin") + + return fmt( + ({ b, i, n, u, code, skip }) => [ + b`Commands you can use:`, + ...formatSections( + sections, + (collection) => u`${b`\n${collection}:`}`, + ({ cmd, availability }) => skip`${formatCommandShort(cmd, availabilityMark(availability))}` + ), + "", + ...(legend.length ? [i`${legend.join(", ")}`] : []), + ...(anyGroupAdmin ? [i`${MARK.groupAdmin} only in groups where you are an admin`] : []), + n`Type ${code`/help `} for more details on a specific command.`, + ], + { sep: "\n" } + ) +} + +/** The /help message in a group: the commands the user can run in that group */ +export function formatHelpInGroup(sections: HelpSection[]) { + return fmt( + ({ b, n, u, code, skip }) => [ + b`Commands you can use in this group:`, + ...formatSections( + sections, + (collection) => u`${b`\n${collection}:`}`, + (cmd) => skip`${formatCommandShort(cmd)}` + ), + "", + n`Type ${code`/help `} for more details on a specific command, or send ${code`/help`} in private chat with the bot to see all of your commands.`, + ], + { sep: "\n" } + ) +} + +/** The entries of the Telegram commands menu for a list of commands, aliases included, followed by /help */ +export function toMenu(cmds: AnyCmd[]): BotCommand[] { + return [ + ...cmds.flatMap((cmd) => + commandTriggers(cmd).map((command) => ({ + command, + // Telegram limits descriptions to 256 characters + description: (cmd.description ?? "No description").slice(0, 256), + })) + ), + HELP_BOT_COMMAND, + ] +} diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index cf43a94..91f7305 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -1,19 +1,20 @@ export { CommandsCollection } from "./collection" export type { AccessControl, CommandScopedContext, DefaultAccessControl, PermissionCheck } from "./command" -export { isAllowedInGroups, isAllowedInPrivateOnly } from "./command" +export { isAllowedInGroups, isAllowedInPrivate, isAllowedInPrivateOnly } from "./command" export * from "./context" +export type { CommandAvailability, GroupAvailability } from "./help" import type { ConversationData, ConversationStorage } from "@grammyjs/conversations" import { conversations, createConversation } from "@grammyjs/conversations" import { hydrate } from "@grammyjs/hydrate" import { hydrateReply, parseMode } from "@grammyjs/parse-mode" -import type { CommandContext, Context, Middleware, MiddlewareObj } from "grammy" +import type { Api, CommandContext, Context, Middleware, MiddlewareObj, StorageAdapter } from "grammy" import { Composer, MemorySessionStorage } from "grammy" -import type { Message } from "grammy/types" +import type { BotCommand, BotCommandScope, Chat, Message } from "grammy/types" import type { Result } from "neverthrow" import { err, ok } from "neverthrow" import z from "zod" -import { isFromGroupChat, isFromPrivateChat } from "@/utils/chat" +import { isFromPrivateChat } from "@/utils/chat" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" import type { CommandsCollection } from "./collection" @@ -32,8 +33,20 @@ import type { PermissionCheck, RepliedTo, } from "./command" -import { isAllowedInGroups, isTypedArgumentOptions } from "./command" +import { commandTriggers, isAllowedInGroups, isAllowedInPrivate, isTypedArgumentOptions } from "./command" import type { ManagedCommandsFlavor } from "./context" +import { + type CommandAvailability, + formatHelpFromPrivate, + formatHelpInGroup, + formatUsageFromPrivate, + formatUsageInGroup, + type GroupAvailability, + HELP_TRIGGER, + type HelpSection, + isAvailable, + toMenu, +} from "./help" export type Hook = ( params: Params & { @@ -78,7 +91,7 @@ export type ManagedCommandsHooks< * "administrator" or "creator" as group admins, but you can override this to implement your own logic, * for example by checking an external database of admins */ - overrideGroupAdminCheck?: (userId: number, chatId: number, context: CommandContext) => Promise + overrideGroupAdminCheck?: (userId: number, chatId: number, context: OC) => Promise /** * Called when a command is invoked, before any processing is done, can be used to implement custom logic that should * run before checking permissions or requirements, for example logging or analytics @@ -91,10 +104,24 @@ export type ManagedCommandsHooks< commandMiddlewareEnd?: Hook } +/** + * Decides whether the sender of an update may run a command. + * + * The same function decides both whether a command runs and what `/help` and the commands menu show, so they cannot + * drift apart. To make that possible it must not look at the chat of the update to decide whether group admin + * privileges apply: `/help` in private chat asks it about running group commands, and answers `isGroupAdmin` + * hypothetically, since the bot cannot know in advance which groups the user administers. + */ export type Authorize = (params: { + /** The update being handled, to identify the user */ context: CommandContext command: AnyCommand - /** The built-in group admin and group ID check */ + /** + * Whether the user is an admin of the group where the command would run (see `overrideGroupAdminCheck`), always + * false outside of groups. Only call it when the answer matters: it may query Telegram. + */ + isGroupAdmin: () => Promise + /** The built-in group admin check */ check: () => Promise }) => Promise @@ -119,7 +146,7 @@ export interface IManagedCommandsOptions< * - {@link https://grammy.dev/plugins/session sessions documentation} * @default MemorySessionStorage */ - adapter: ConversationStorage + adapter?: ConversationStorage /** * Additional plugins to apply to the conversation inner composer. @@ -129,7 +156,44 @@ export interface IManagedCommandsOptions< /** * Hooks to execute on specific events */ - hooks: ManagedCommandsHooks + hooks?: ManagedCommandsHooks + + /** + * Keeps the Telegram commands menu of each user in line with the commands they can run, or `false` to leave the + * menus alone. See {@link CommandsMenuOptions}. + */ + menus?: CommandsMenuOptions | false +} + +/** The menu last given to a user in a chat: their own commands, or `null` for the default menu of the chat type */ +export type StoredCommandsMenu = { commands: BotCommand[] | null; checkedAt: number } + +/** + * Every chat type gets a default menu with the commands anyone can run (the ones without `permissions`). When a user + * sends a message, the commands they can run in that chat are computed with the same checks that gate their + * execution, and if they differ from the default the user gets their own menu in that chat. + */ +export interface CommandsMenuOptions { + /** + * Remembers the menu last given to each user in each chat, so that it is sent to Telegram only when it changes. + * + * Keep entries for a long time (weeks): a missing entry is taken to mean the user has the default menu. + * @default MemorySessionStorage + */ + storage?: StorageAdapter + /** + * How long a user's menu is trusted before it is computed again, to pick up changes in their permissions. + * @default 1 hour + */ + refreshAfterMs?: number + /** + * Waits for the menu to be updated before handling the rest of the update, instead of doing it in the background. + * Meant for tests. + * @default false + */ + blocking?: boolean + /** Called when updating a menu fails, the menu is retried the next time */ + onError?: (error: unknown) => void } export type ManagedCommandsOptions< @@ -174,6 +238,9 @@ export class ManagedCommands< private hooks: ManagedCommandsHooks private adapter: ConversationStorage private registeredTriggers = new Set() + private menus: Required | null + private defaultMenus: Promise | null = null + private groupAdminChecks = new WeakMap>() /** * Parses the `reply_to_message` field from the message object @@ -264,38 +331,6 @@ export class ManagedCommands< return err(errors) } - /** - * Creates a formatted message to display the usage of a command to the user - * @param cmd The command to print usage for - * @returns A markdown formatted string representing the usage of the command - */ - private static formatCommandUsage(cmd: AnyCommand): string { - const args = cmd.args ?? [] - const scope = - cmd.scope === "private" ? "Private Chat" : cmd.scope === "group" ? "Groups" : "Groups and Private Chat" - - return fmt(({ n, b, i }) => [ - typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | "), - ...args.map(({ key, optional }) => (optional ? n`[${i`${key}`}]` : n`<${i`${key}`}>`)), - i`\nDesc:`, - b`${cmd.description ?? "No description"}`, - i`\nScope:`, - b`${scope}`, - ...(cmd.reply ? [i`\nCall while replying to a message:`, b`${cmd.reply.toUpperCase()}`] : []), - args.length ? i`\nArgs:` : ``, - ...args.flatMap(({ key, description }) => [`\n-`, i`${key}:`, description ?? "No description"]), - ]) - } - - private static formatCommandShort(cmd: AnyCommand): string { - const args = cmd.args ?? [] - return fmt(({ i, n }) => [ - typeof cmd.trigger === "string" ? `/${cmd.trigger}` : cmd.trigger.map((t) => `/${t}`).join(" | "), - ...args.map(({ key, optional }) => (optional ? i` [${key}]` : i` <${key}>`)), - n`\n\t${cmd.description ?? "No description"}`, - ]) - } - /** * Generate a unique ID for a command based on its trigger(s), used for conversation IDs. * @param cmd The command @@ -330,6 +365,27 @@ export class ManagedCommands< this.authorize = options?.authorize ?? ((({ check }) => check()) as Authorize) this.hooks = options?.hooks ?? {} this.adapter = options?.adapter ?? new MemorySessionStorage() + this.menus = + options?.menus === false + ? null + : { + storage: options?.menus?.storage ?? new MemorySessionStorage(), + refreshAfterMs: options?.menus?.refreshAfterMs ?? 60 * 60 * 1000, + blocking: options?.menus?.blocking ?? false, + onError: options?.menus?.onError ?? (() => {}), + } + // /help is handled below, no command can take its trigger + this.registeredTriggers.add(HELP_TRIGGER) + + if (this.menus) { + const { blocking } = this.menus + this.composer.use(async (ctx, next) => { + const defaults = this.setDefaultMenus(ctx.api) + const user = ctx.message ? this.syncUserMenu(ctx) : Promise.resolve() + if (blocking) await Promise.all([defaults, user]) + return next() + }) + } this.composer.use( conversations({ @@ -346,39 +402,7 @@ export class ManagedCommands< }) ) - this.composer.command("help", async (ctx) => { - if (ctx.chat.type !== "private") - return void ephemeral( - ctx, - fmt(({ n, code }) => n`You can only send ${code`/help`} in private chat with the bot.`) - ) - - const text = ctx.message?.text ?? "" - - const [_, cmdArg] = text.replaceAll("/", "").split(" ") - if (cmdArg) { - const cmd = this.getCommands().find((c) => - Array.isArray(c.trigger) ? c.trigger.includes(cmdArg) : c.trigger === cmdArg - ) - if (!cmd) return ctx.reply(fmt(() => "Command not found. See /help for available commands.")) - - return ctx.reply(ManagedCommands.formatCommandUsage(cmd)) - } - - const reply = fmt( - ({ u, b, skip, n, code }) => [ - b`Available commands:`, - ...Object.entries(this.commands).flatMap(([collection, cmds]) => [ - collection === "default" ? "" : u`${b`\n${collection}:`}`, - ...cmds.flatMap((cmd) => [skip`${ManagedCommands.formatCommandShort(cmd)}`]), - ]), - n`\n\nType ${code`\/help `} for more details on a specific command.`, - ], - { sep: "\n" } - ) - - return ctx.reply(reply) - }) + this.composer.command(HELP_TRIGGER, (ctx) => this.help(ctx)) } public getCommands() { @@ -389,40 +413,261 @@ export class ManagedCommands< return cmds } - /** Group allow/deny lists: where a command may run, whoever runs it. */ - private static isAllowedInChat( + private findCommand(trigger: string): AnyCommand | undefined { + return this.getCommands().find((cmd) => commandTriggers(cmd).includes(trigger)) + } + + /** Whether the command can run in this type of chat at all */ + private static isInScope( + command: AnyCommand, + chatType: Chat["type"] + ): boolean { + if (chatType === "private") return isAllowedInPrivate(command) + if (chatType === "group" || chatType === "supergroup") return isAllowedInGroups(command) + return false + } + + /** Group allow/deny lists: whether the command is enabled in a group, whoever runs it */ + private static isEnabledInGroup( command: AnyCommand, - ctx: CommandContext + chatId: number ): boolean { - if (!command.permissions || !isAllowedInGroups(command)) return true - if (ctx.chat.type !== "group" && ctx.chat.type !== "supergroup") return true - const { allowedGroupsId, excludedGroupsId } = command.permissions - if (allowedGroupsId && !allowedGroupsId.includes(ctx.chatId)) return false - if (excludedGroupsId?.includes(ctx.chatId)) return false + if (!isAllowedInGroups(command)) return false + const { allowedGroupsId, excludedGroupsId } = command.permissions ?? {} + if (allowedGroupsId && !allowedGroupsId.includes(chatId)) return false + if (excludedGroupsId?.includes(chatId)) return false return true } + /** Group allow/deny lists: whether there is any group where the command is enabled */ + private static isEnabledInSomeGroup(command: AnyCommand): boolean { + if (!isAllowedInGroups(command)) return false + const { allowedGroupsId, excludedGroupsId } = command.permissions ?? {} + if (!allowedGroupsId) return true + return allowedGroupsId.some((id) => !excludedGroupsId?.includes(id)) + } + + /** Whether the sender of the update is an admin of its group, asked to Telegram at most once per update */ + private isGroupAdminHere(ctx: OC): () => Promise { + return () => { + const from = ctx.from + const chat = ctx.chat + if (!from || !chat || (chat.type !== "group" && chat.type !== "supergroup")) return Promise.resolve(false) + let check = this.groupAdminChecks.get(ctx) + if (!check) { + check = this.hooks.overrideGroupAdminCheck + ? this.hooks.overrideGroupAdminCheck(from.id, chat.id, ctx) + : ctx.getChatMember(from.id).then(({ status }) => status === "administrator" || status === "creator") + this.groupAdminChecks.set(ctx, check) + } + return check + } + } + /** The built-in group admin check */ private async checkPermissions( command: AnyCommand, - ctx: CommandContext + ctx: CommandContext, + isGroupAdmin: () => Promise ): Promise { if (!command.permissions) return { allowed: true, via: "unrestricted" } if (!ctx.from) return { allowed: false } + if (isAllowedInGroups(command) && command.permissions.allowGroupAdmins && (await isGroupAdmin())) + return { allowed: true, via: "group_admin" } + return { allowed: true, via: "unrestricted" } + } - if (isAllowedInGroups(command) && (ctx.chat.type === "group" || ctx.chat.type === "supergroup")) { - if (command.permissions.allowGroupAdmins) { - if (this.hooks.overrideGroupAdminCheck) { - const isAdmin = await this.hooks.overrideGroupAdminCheck(ctx.from.id, ctx.chatId, ctx) - if (isAdmin) return { allowed: true, via: "group_admin" } - } else { - const { status: groupRole } = await ctx.getChatMember(ctx.from.id) - if (groupRole === "administrator" || groupRole === "creator") return { allowed: true, via: "group_admin" } - } + private authorizeWith( + command: AnyCommand, + ctx: CommandContext, + isGroupAdmin: () => Promise + ): Promise { + return this.authorize({ + context: ctx, + command, + isGroupAdmin, + check: () => this.checkPermissions(command, ctx, isGroupAdmin), + }) + } + + /** + * The decision on running a command in the chat of the update, `null` when it is not enabled in that group. + * Scope is checked separately, see {@link ManagedCommands.isInScope}. + * + * This is the only path to running a command, and `/help` and the menus use it too. + */ + private async decideHere( + command: AnyCommand, + ctx: CommandContext + ): Promise { + const chat = ctx.chat + if ((chat.type === "group" || chat.type === "supergroup") && !ManagedCommands.isEnabledInGroup(command, chat.id)) + return null + return this.authorizeWith(command, ctx, this.isGroupAdminHere(ctx)) + } + + /** Whether the sender of the update can run the command in the chat of the update, exactly as when invoking it */ + private async isAvailableHere(command: AnyCommand, ctx: CommandContext): Promise { + if (!ManagedCommands.isInScope(command, ctx.chat.type)) return false + try { + return (await this.decideHere(command, ctx))?.allowed ?? false + } catch { + return false + } + } + + /** + * Whether the sender of the update could run the command in a group, from anywhere (e.g. a private chat). + * + * Runs the same decision as {@link ManagedCommands.decideHere}, but as the bot doesn't know which groups the user + * administers, it first decides as if they were not an admin, and if that is denied after asking, as if they were. + */ + private async availabilityInGroups( + command: AnyCommand, + ctx: CommandContext + ): Promise { + if (!ManagedCommands.isEnabledInSomeGroup(command)) return "no" + try { + let asked = false + const notAdmin = async () => { + asked = true + return false } + if ((await this.authorizeWith(command, ctx, notAdmin)).allowed) return "yes" + if (!asked) return "no" + if ((await this.authorizeWith(command, ctx, async () => true)).allowed) return "if_group_admin" + return "no" + } catch { + return "no" } + } - return { allowed: true, via: "unrestricted" } + /** Where the sender of the update can run the command, as known from a private chat */ + private async availabilityFromPrivate( + command: AnyCommand, + ctx: CommandContext + ): Promise { + const [inPrivate, groups] = await Promise.all([ + isAllowedInPrivate(command) ? this.isAvailableHere(command, ctx) : false, + this.availabilityInGroups(command, ctx), + ]) + return { private: inPrivate, groups } + } + + /** Commands grouped by collection, keeping those for which `evaluate` gives a value */ + private async sections( + evaluate: (cmd: AnyCommand) => Promise + ): Promise[]> { + const sections = await Promise.all( + Object.entries(this.commands).map(async ([collection, cmds]) => ({ + collection, + entries: (await Promise.all(cmds.map(evaluate))).filter((e): e is Awaited => e !== null), + })) + ) + return sections.filter((s) => s.entries.length > 0) + } + + /** The commands the sender of the update can run in the chat of the update */ + private async commandsAvailableHere(ctx: CommandContext): Promise[]> { + const sections = await this.sections(async (cmd) => ((await this.isAvailableHere(cmd, ctx)) ? cmd : null)) + return sections.flatMap((s) => s.entries) + } + + private async help(ctx: CommandContext) { + const isPrivate = ctx.chat.type === "private" + if (!ctx.from || ctx.chat.type === "channel") return + // the user is looking for their commands, make sure their menu is up to date too + if (this.menus) { + const sync = this.syncUserMenu(ctx, true) + if (this.menus.blocking) await sync + } + + const reply = (text: string) => (isPrivate ? ctx.reply(text) : ephemeral(ctx, text)) + if (!isPrivate) await ctx.deleteMessage().catch(() => {}) + + const trigger = ctx.match.trim().split(/\s+/)[0]?.replace(/^\//, "").toLowerCase() + if (trigger) { + const cmd = this.findCommand(trigger) + const notFound = fmt(({ n, code }) => n`Command not found. See ${code`/help`} for the commands you can use.`) + if (!cmd) return reply(notFound) + if (isPrivate) { + const availability = await this.availabilityFromPrivate(cmd, ctx) + return reply(isAvailable(availability) ? formatUsageFromPrivate(cmd, availability) : notFound) + } + return reply((await this.isAvailableHere(cmd, ctx)) ? formatUsageInGroup(cmd) : notFound) + } + + if (isPrivate) { + const sections = await this.sections(async (cmd) => { + const availability = await this.availabilityFromPrivate(cmd, ctx) + return isAvailable(availability) ? { cmd, availability } : null + }) + return reply(formatHelpFromPrivate(sections)) + } + const sections = await this.sections(async (cmd) => ((await this.isAvailableHere(cmd, ctx)) ? cmd : null)) + return reply(formatHelpInGroup(sections)) + } + + /** The menu for users who can run only the commands that anyone can run (the ones without `permissions`) */ + private defaultMenu(chatType: "private" | "group"): BotCommand[] { + return toMenu( + this.getCommands().filter( + (cmd) => !cmd.permissions && (chatType === "private" ? isAllowedInPrivate(cmd) : isAllowedInGroups(cmd)) + ) + ) + } + + /** Sets the default menus, once, retrying on the next update if it fails */ + private setDefaultMenus(api: Api): Promise { + this.defaultMenus ??= Promise.all([ + api.setMyCommands(this.defaultMenu("private"), { scope: { type: "all_private_chats" } }), + api.setMyCommands(this.defaultMenu("group"), { scope: { type: "all_group_chats" } }), + ]).then( + () => {}, + (error: unknown) => { + this.defaultMenus = null + this.menus?.onError(error) + } + ) + return this.defaultMenus + } + + /** + * Gives the sender of the update their own menu in its chat, if their commands differ from the default. + * Never throws. + * @param force recompute the menu even if it was checked recently + */ + private async syncUserMenu(ctx: OC, force = false): Promise { + const menus = this.menus + const { from, chat } = ctx + if (!menus || !from || from.is_bot || !chat) return + const chatType = chat.type === "private" ? "private" : chat.type === "channel" ? null : "group" + if (!chatType) return + + try { + const key = `${chat.id}:${from.id}` + const now = Date.now() + const saved = await menus.storage.read(key) + if (!force && saved && now - saved.checkedAt < menus.refreshAfterMs) return + + // the update may not be a command, but only its sender and chat are looked at + const available = await this.commandsAvailableHere(ctx as CommandContext) + const menu = toMenu(available) + const commands = JSON.stringify(menu) === JSON.stringify(this.defaultMenu(chatType)) ? null : menu + + // without a saved menu, the user is assumed to have the default one + if (JSON.stringify(commands) !== JSON.stringify(saved?.commands ?? null)) { + const scope: BotCommandScope = + chatType === "private" + ? { type: "chat", chat_id: chat.id } + : { type: "chat_member", chat_id: chat.id, user_id: from.id } + if (commands) await ctx.api.setMyCommands(commands, { scope }) + else await ctx.api.deleteMyCommands({ scope }) + } + await menus.storage.write(key, { commands, checkedAt: now }) + } catch (error) { + menus.onError(error) + } } /** @@ -495,15 +740,13 @@ export class ManagedCommands< // silently delete the command call if the scope is invalid const isPrivate = isFromPrivateChat(ctx) - if ((cmd.scope === "private" && !isPrivate) || (cmd.scope === "group" && !isFromGroupChat(ctx))) { + if (!ManagedCommands.isInScope(cmd, ctx.chat.type)) { if (this.hooks.wrongScope) await this.hooks.wrongScope({ context: ctx, command: cmd }) return } // delete the command call if the user is not allowed to use it - const authorization = ManagedCommands.isAllowedInChat(cmd, ctx) - ? await this.authorize({ context: ctx, command: cmd, check: () => this.checkPermissions(cmd, ctx) }) - : null + const authorization = await this.decideHere(cmd, ctx) if (!authorization?.allowed) { if (this.hooks.missingPermissions) await this.hooks.missingPermissions({ context: ctx, command: cmd }) return From 2a2e6a3e50458847e2bd91d852ec0a6a81db6612 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Mon, 2 Nov 2026 17:41:05 +0100 Subject: [PATCH 9/9] test(commands): fake Telegram harness and /help and menu consistency tests Add a fake Telegram that runs the middleware stack on simulated updates. It sits below grammY as the API client's fetch, so it also sees the calls made from inside conversations, answers getChatMember from the admins it is told about, and resolves commands menus per user like Telegram does. Test that /help (private and group) and the menus list exactly the commands that run, by running every command for every user, chat and admin status, both on a synthetic command table and on the bot's real commands with their real access control and a fake IdP. --- tests/commands-access.test.ts | 267 +++++++++++++++++++ tests/harness/telegram.ts | 322 ++++++++++++++++++++++ tests/managed-commands.test.ts | 471 +++++++++++++++++++++++++++++++++ 3 files changed, 1060 insertions(+) create mode 100644 tests/commands-access.test.ts create mode 100644 tests/harness/telegram.ts create mode 100644 tests/managed-commands.test.ts diff --git a/tests/commands-access.test.ts b/tests/commands-access.test.ts new file mode 100644 index 0000000..4228019 --- /dev/null +++ b/tests/commands-access.test.ts @@ -0,0 +1,267 @@ +import { hydrate } from "@grammyjs/hydrate" +import { hydrateReply } from "@grammyjs/parse-mode" +import type { Bot } from "grammy" +import type { Chat, User } from "grammy/types" +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest" +import { PERMISSION, type Permission } from "@/access" +import { commands } from "@/commands" +import { authorizeCommand } from "@/commands/access" +import { commandTriggers } from "@/lib/managed-commands/command" +import { telemetry } from "@/modules/telemetry/middleware" +import type { Context } from "@/utils/types" +import { type Exchange, FakeTelegram } from "./harness/telegram" + +/** + * Runs the bot's real commands, with their real access control and hooks, against a fake Telegram and a fake IdP: + * what /help and the commands menu show must be exactly what each user can run. + */ + +const idp = vi.hoisted(() => ({ + permissions: new Map(), + resolves: 0, + offline: false, +})) + +vi.mock("@/backend", () => { + const backend = { + tg: { + access: { + resolve: { + query: async ({ telegramIds }: { telegramIds: number[] }) => { + idp.resolves++ + if (idp.offline) throw new Error("IdP offline") + return Object.fromEntries( + telegramIds.map((id) => [ + String(id), + { sub: `user-${id}`, permissions: [...(idp.permissions.get(id) ?? [])], grant: null }, + ]) + ) + }, + }, + }, + }, + } + return { backendFor: () => backend, backendAs: () => backend, serviceBackend: backend } +}) +vi.mock("@/env", () => ({ + env: { NODE_ENV: "development", BOT_TOKEN: "x", BACKEND_URL: "localhost", INFLUXDB_URL: "http://localhost" }, +})) +// offline Redis: storage adapters fall back to memory +vi.mock("@/redis", async () => { + const { EventEmitter } = await import("node:events") + return { redis: Object.assign(new EventEmitter(), { isOpen: false, isReady: false }) } +}) +vi.mock("@/modules", () => { + const noop: object = new Proxy({}, { get: () => async () => {} }) + return { modules: { get: () => noop, shared: { api: { deleteMessage: async () => true } } } } +}) +vi.mock("@/logger", () => { + const logger = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {}, fatal: () => {} } + return { logger } +}) + +type Outcome = "ran" | "denied" | "wrong_scope" + +function outcome(exchange: Exchange): Outcome { + const texts = exchange.replies.map((r) => r.text) + if (texts.some((t) => t.includes("You are not allowed to execute this command"))) return "denied" + if (texts.some((t) => t.includes("This command must be run in"))) return "wrong_scope" + return "ran" +} + +const tg = new FakeTelegram() +let bot: Bot +const group = tg.group("Network group") +const otherGroup = tg.group("Another group") + +beforeAll(async () => { + bot = await tg.createBot((b) => { + b.use(hydrate()) + b.use(hydrateReply) + b.use(telemetry()) + b.use(commands) + }) +}) + +beforeEach(() => { + idp.permissions.clear() + idp.offline = false +}) + +function withPermissions(name: string, permissions: Permission[]): User { + const user = tg.user(name) + idp.permissions.set(user.id, permissions) + return user +} + +/** Every trigger of every command, aliases included */ +const triggers = commands.getCommands().flatMap((cmd) => commandTriggers(cmd)) + +async function run(user: User, trigger: string, chat?: Chat): Promise { + return outcome(await tg.send(bot, user, `/${trigger}`, { chat })) +} + +function parsePrivateHelp(text: string): Map { + const lines = text.split("\n") + const entries = new Map() + for (const [i, line] of lines.entries()) { + const match = /^\/(\w+)/.exec(line) + if (!match) continue + const triggersOnLine = [...line.matchAll(/\/(\w+)/g)].map((m) => m[1]) + const mark = /^\t(\S+) /.exec(lines[i + 1] ?? "")?.[1] ?? "" + for (const t of triggersOnLine) entries.set(t, mark) + } + return entries +} + +function parseGroupHelp(text: string): string[] { + return text + .split("\n") + .filter((line) => line.startsWith("/")) + .flatMap((line) => [...line.matchAll(/\/(\w+)/g)].map((m) => m[1])) + .filter((t) => t !== "help") +} + +async function waitForMenu(user: User, chat: Chat | undefined, expected: string[]) { + await vi.waitFor(() => { + expect( + tg + .menuCommandsOf(user, chat) + .filter((c) => c !== "help") + .sort() + ).toEqual([...expected].sort()) + }) +} + +describe("bot commands: /help and menus match what each user can run", () => { + const profiles: [string, Permission[]][] = [ + ["no permissions", []], + ["moderator", [PERMISSION.moderate]], + ["global moderator", [PERMISSION.moderateGlobal]], + ["message manager", [PERMISSION.messagesDelete, PERMISSION.messagesPin]], + ["staff", [PERMISSION.auditRead, PERMISSION.usersRead, PERMISSION.groupsManage]], + ["only trusted", [PERMISSION.trusted, PERMISSION.immune]], + ["everything", Object.values(PERMISSION)], + ] + + it.each(profiles)("%s", async (name, permissions) => { + const user = withPermissions(name, permissions) + + const inPrivate = new Set() + const asMember = new Set() + const asAdmin = new Set() + for (const trigger of triggers) if ((await run(user, trigger)) === "ran") inPrivate.add(trigger) + + for (const admin of [false, true]) { + if (admin) tg.setAdmin(group, user) + else tg.removeAdmin(group, user) + const here = admin ? asAdmin : asMember + for (const trigger of triggers) if ((await run(user, trigger, group)) === "ran") here.add(trigger) + + const help = await tg.send(bot, user, "/help", { chat: group }) + expect(help.replies[0]?.ephemeralTo).toBe(user.id) + expect(parseGroupHelp(help.reply).sort(), `group /help as ${admin ? "admin" : "member"}`).toEqual( + [...here].sort() + ) + await waitForMenu(user, group, [...here]) + } + + await tg.send(bot, user, "/help") + await waitForMenu(user, undefined, [...inPrivate]) + + const help = parsePrivateHelp((await tg.send(bot, user, "/help")).reply) + for (const trigger of triggers) { + const groups = asMember.has(trigger) ? "yes" : asAdmin.has(trigger) ? "admin" : "no" + const expected = + !inPrivate.has(trigger) && groups === "no" + ? undefined + : `${inPrivate.has(trigger) ? (groups === "no" ? "๐Ÿ‘ค" : "๐ŸŒ") : "๐Ÿ‘ฅ"}${groups === "admin" ? "๐Ÿ›ก๏ธ" : ""}` + expect(help.get(trigger), `/${trigger} in private /help`).toBe(expected) + } + }) +}) + +describe("bot commands: access", () => { + it("shows a user without permissions the public commands and those open to group admins", async () => { + const user = withPermissions("nobody", []) + const help = parsePrivateHelp((await tg.send(bot, user, "/help")).reply) + + expect(help.get("start")).toBe("๐Ÿ‘ค") + expect(help.get("search")).toBe("๐ŸŒ") + expect(help.get("report")).toBe("๐Ÿ‘ฅ") + for (const trigger of ["ban", "tban", "unban", "kick", "mute", "tmute", "unmute", "del", "pin", "unpin"]) + expect(help.get(trigger), trigger).toBe("๐Ÿ‘ฅ๐Ÿ›ก๏ธ") + for (const trigger of [ + "ban_all", + "unban_all", + "audit", + "userid", + "getroles", + "updategroup", + "regenerate_group_links", + ]) + expect(help.has(trigger), trigger).toBe(false) + }) + + it("lets Telegram chat admins moderate only in their groups, and never grants global commands", async () => { + const admin = withPermissions("chat admin", []) + tg.setAdmin(group, admin) + + expect(await run(admin, "ban", group)).toBe("ran") + expect(await run(admin, "ban", otherGroup)).toBe("denied") + expect(await run(admin, "ban_all")).toBe("denied") + expect(await run(admin, "audit")).toBe("denied") + }) + + it("looks up the user's IdP permissions once per update", async () => { + const user = withPermissions("lookups", [PERMISSION.moderate]) + tg.setAdmin(group, user) + + idp.resolves = 0 + await tg.send(bot, user, "/help") + expect(idp.resolves).toBe(1) + + idp.resolves = 0 + await tg.send(bot, user, "/help", { chat: group }) + // the forced menu refresh runs in the background on the same update + await vi.waitFor(() => expect(tg.menuCommandsOf(user, group)).toContain("ban")) + expect(idp.resolves).toBe(1) + }) + + it("denies and hides restricted commands while the IdP is unavailable, except for group admins", async () => { + const user = withPermissions("offline", Object.values(PERMISSION)) + idp.offline = true + + expect(await run(user, "ban_all")).toBe("denied") + expect(await run(user, "ban", otherGroup)).toBe("denied") + const help = parsePrivateHelp((await tg.send(bot, user, "/help")).reply) + expect(help.has("ban_all")).toBe(false) + expect(help.get("ban")).toBe("๐Ÿ‘ฅ๐Ÿ›ก๏ธ") + + tg.setAdmin(otherGroup, user) + expect(await run(user, "ban", otherGroup)).toBe("ran") + }) + + it("applies the group admin shortcut only to commands that allow it", async () => { + const user = withPermissions("admin elsewhere", []) + const context = { from: user, chat: group } as unknown as Parameters[0]["context"] + const isGroupAdmin = vi.fn(async () => true) + const check = async () => ({ allowed: true, via: "unrestricted" }) as const + const command = (allowTelegramChatAdmins?: boolean) => ({ + trigger: "x", + scope: "group" as const, + permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins }, + handler: async () => {}, + }) + + expect(await authorizeCommand({ context, command: command(), isGroupAdmin, check })).toEqual({ + allowed: false, + basis: null, + }) + expect(isGroupAdmin).not.toHaveBeenCalled() + expect(await authorizeCommand({ context, command: command(true), isGroupAdmin, check })).toEqual({ + allowed: true, + basis: "telegram_chat_admin", + }) + }) +}) diff --git a/tests/harness/telegram.ts b/tests/harness/telegram.ts new file mode 100644 index 0000000..a504034 --- /dev/null +++ b/tests/harness/telegram.ts @@ -0,0 +1,322 @@ +import { Bot, type Context } from "grammy" +import type { + BotCommand, + BotCommandScope, + Chat, + Message, + MessageEntity, + Update, + User, + UserFromGetMe, +} from "grammy/types" + +/** + * A fake Telegram to run the bot's middleware stack against simulated updates. + * + * It sits below grammY (as the `fetch` of the API client), so every API call is seen, including the ones made from + * inside conversations, which build their own `Api` instances. It answers like Telegram would for the state it keeps: + * chats, group admins and the commands menus, which it resolves per user exactly like Telegram does. + * + * @example + * ```ts + * const tg = new FakeTelegram() + * const bot = await tg.createBot((bot) => bot.use(commands)) + * const alice = tg.user("Alice") + * const group = tg.group("Test group") + * tg.setAdmin(group, alice) + * + * const { replies } = await tg.send(bot, alice, "/help") + * expect(tg.menuOf(alice, group).map((c) => c.command)).toContain("ban") + * ``` + */ + +export type ApiCall = { method: string; payload: Record } + +/** A message sent by the bot during an exchange */ +export type SentMessage = { + chatId: number + /** The text, without MarkdownV2 escapes and formatting */ + text: string + /** The raw text as sent */ + raw: string + /** The user who can see the message, if sent as an ephemeral message */ + ephemeralTo: number | null +} + +/** What the bot did while handling one update */ +export class Exchange { + constructor(readonly calls: ApiCall[]) {} + + /** The calls to a specific API method */ + called(method: string): ApiCall[] { + return this.calls.filter((c) => c.method === method) + } + + /** The messages the bot sent */ + get replies(): SentMessage[] { + return this.called("sendMessage").map(({ payload }) => { + const raw = String(payload.text ?? "") + const ephemeral = payload.ephemeral_message_parameters as { receiver_user_id?: number } | undefined + return { + chatId: Number(payload.chat_id), + raw, + text: plain(raw), + ephemeralTo: ephemeral?.receiver_user_id ?? null, + } + }) + } + + /** The text of the only message the bot sent, fails if it sent none or more than one */ + get reply(): string { + const replies = this.replies + if (replies.length !== 1) + throw new Error(`expected exactly one reply, got ${replies.length}: ${JSON.stringify(replies)}`) + return replies[0].text + } +} + +/** Removes MarkdownV2 escapes and formatting markers from a text */ +export function plain(markdown: string): string { + let out = "" + for (let i = 0; i < markdown.length; i++) { + const char = markdown[i] + if (char === "\\") { + out += markdown[++i] ?? "" + } else if (!"*_~`|".includes(char)) { + out += char + } + } + return out +} + +type Responder = (payload: Record) => unknown + +/** Thrown by a responder to make Telegram answer with an error */ +export class FakeTelegramError extends Error { + constructor( + readonly description: string, + readonly errorCode = 400 + ) { + super(description) + } +} + +type GroupChat = Extract +type MemberStatus = "creator" | "administrator" + +export class FakeTelegram { + /** Every API call made by any bot attached to this fake, in order */ + readonly calls: ApiCall[] = [] + readonly me: UserFromGetMe = { + id: 42, + is_bot: true, + first_name: "Test Bot", + username: "test_bot", + can_join_groups: true, + can_read_all_group_messages: true, + supports_inline_queries: false, + can_connect_to_business: false, + has_main_web_app: false, + has_topics_enabled: false, + allows_users_to_create_topics: false, + can_manage_bots: false, + supports_join_request_queries: false, + } + + private chats = new Map() + private admins = new Map>() + private menus = new Map() + private responders = new Map() + private nextId = 1000 + private nextUpdateId = 1 + private nextMessageId = 1 + + /** The `fetch` implementation for grammY's API client */ + readonly fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + const method = url.slice(url.lastIndexOf("/") + 1) + const body = init?.body + const payload = typeof body === "string" && body.length > 0 ? (JSON.parse(body) as Record) : {} + this.calls.push({ method, payload }) + + try { + const result = await this.respond(method, payload) + return new Response(JSON.stringify({ ok: true, result }), { headers: { "content-type": "application/json" } }) + } catch (error) { + if (!(error instanceof FakeTelegramError)) throw error + return new Response(JSON.stringify({ ok: false, error_code: error.errorCode, description: error.description }), { + headers: { "content-type": "application/json" }, + }) + } + }) as typeof fetch + + /** Creates a bot talking to this fake, `setup` installs its middleware */ + async createBot(setup?: (bot: Bot) => void): Promise> { + const bot = new Bot("123:TEST", { botInfo: this.me, client: { fetch: this.fetch } }) + setup?.(bot) + await bot.init() + return bot + } + + /** Answers calls to an API method with a custom function, throw {@link FakeTelegramError} to fail the call */ + on(method: string, responder: Responder): this { + this.responders.set(method, responder) + return this + } + + user(firstName: string, id: number = this.nextId++): User { + return { id, is_bot: false, first_name: firstName } + } + + group(title: string, id: number = -(1_000_000_000_000 + this.nextId++)): GroupChat { + const chat: GroupChat = { id, type: "supergroup", title } + this.chats.set(id, chat) + return chat + } + + privateChat(user: User): Chat { + const chat: Chat = { id: user.id, type: "private", first_name: user.first_name } + this.chats.set(chat.id, chat) + return chat + } + + /** Makes a user an admin (or the creator) of a group, as Telegram's getChatMember will report */ + setAdmin(group: Chat, user: User, status: MemberStatus = "administrator"): this { + const admins = this.admins.get(group.id) ?? new Map() + admins.set(user.id, status) + this.admins.set(group.id, admins) + return this + } + + removeAdmin(group: Chat, user: User): this { + this.admins.get(group.id)?.delete(user.id) + return this + } + + isAdmin(chatId: number, userId: number): boolean { + return this.admins.get(chatId)?.has(userId) ?? false + } + + /** + * The commands menu the user sees in a chat (private chat by default), resolved like Telegram does: + * https://core.telegram.org/bots/api#determining-list-of-commands + */ + menuOf(user: User, chat?: Chat): BotCommand[] { + const target = chat ?? this.privateChat(user) + const scopes: BotCommandScope[] = + target.type === "private" + ? [{ type: "chat", chat_id: target.id }, { type: "all_private_chats" }, { type: "default" }] + : [ + { type: "chat_member", chat_id: target.id, user_id: user.id }, + ...(this.isAdmin(target.id, user.id) ? [{ type: "chat_administrators", chat_id: target.id } as const] : []), + { type: "chat", chat_id: target.id }, + ...(this.isAdmin(target.id, user.id) ? [{ type: "all_chat_administrators" } as const] : []), + { type: "all_group_chats" }, + { type: "default" }, + ] + for (const scope of scopes) { + const menu = this.menus.get(scopeKey(scope)) + if (menu) return menu + } + return [] + } + + /** Just the command names of {@link FakeTelegram.menuOf} */ + menuCommandsOf(user: User, chat?: Chat): string[] { + return this.menuOf(user, chat).map((c) => c.command) + } + + /** A message update from `from`, in its private chat unless `options.chat` is given */ + messageUpdate(from: User, text: string, options: { chat?: Chat; replyTo?: Message } = {}): Update { + const chat = options.chat ?? this.privateChat(from) + this.chats.set(chat.id, chat) + const entities: MessageEntity[] = [] + const command = /^\/[a-zA-Z0-9_]+(@[a-zA-Z0-9_]+)?/.exec(text) + if (command) entities.push({ type: "bot_command", offset: 0, length: command[0].length }) + const message = { + message_id: this.nextMessageId++, + date: Math.floor(Date.now() / 1000), + chat, + from, + text, + ...(entities.length ? { entities } : {}), + ...(options.replyTo ? { reply_to_message: options.replyTo } : {}), + } as Message + return { update_id: this.nextUpdateId++, message } as Update + } + + /** A message to reply to in commands that require one */ + message(from: User, chat: Chat, text = "a message"): Message { + return { + message_id: this.nextMessageId++, + date: Math.floor(Date.now() / 1000), + chat, + from, + text, + } as Message + } + + /** Lets the bot handle an update, returns what it did */ + async handle(bot: Bot, update: Update): Promise { + const start = this.calls.length + await bot.handleUpdate(update) + return new Exchange(this.calls.slice(start)) + } + + /** Sends a message from `from` to the bot, in its private chat unless `options.chat` is given */ + async send( + bot: Bot, + from: User, + text: string, + options: { chat?: Chat; replyTo?: Message } = {} + ): Promise { + return this.handle(bot, this.messageUpdate(from, text, options)) + } + + private async respond(method: string, payload: Record): Promise { + const responder = this.responders.get(method) + if (responder) return responder(payload) + + switch (method) { + case "getMe": + return this.me + case "sendMessage": + return { + message_id: this.nextMessageId++, + date: Math.floor(Date.now() / 1000), + chat: this.chatById(Number(payload.chat_id)), + from: this.me, + text: payload.text, + } + case "getChatMember": { + const chatId = Number(payload.chat_id) + const userId = Number(payload.user_id) + const status = this.admins.get(chatId)?.get(userId) ?? "member" + const user = { id: userId, is_bot: false, first_name: "User" } + return status === "member" ? { status, user } : { status, user, is_anonymous: false } + } + case "setMyCommands": + this.menus.set(scopeKey(payload.scope as BotCommandScope | undefined), payload.commands as BotCommand[]) + return true + case "deleteMyCommands": + this.menus.delete(scopeKey(payload.scope as BotCommandScope | undefined)) + return true + case "getMyCommands": + return this.menus.get(scopeKey(payload.scope as BotCommandScope | undefined)) ?? [] + default: + return true + } + } + + private chatById(id: number): Chat { + return ( + this.chats.get(id) ?? + (id > 0 ? { id, type: "private", first_name: "User" } : { id, type: "supergroup", title: "Group" }) + ) + } +} + +function scopeKey(scope: BotCommandScope | undefined): string { + const s = (scope ?? { type: "default" }) as { type: string; chat_id?: number | string; user_id?: number } + return [s.type, s.chat_id ?? "", s.user_id ?? ""].join(":") +} diff --git a/tests/managed-commands.test.ts b/tests/managed-commands.test.ts new file mode 100644 index 0000000..ae88fce --- /dev/null +++ b/tests/managed-commands.test.ts @@ -0,0 +1,471 @@ +import type { Bot, Context } from "grammy" +import type { Chat, User } from "grammy/types" +import { beforeEach, describe, expect, it, vi } from "vitest" +import { + type AccessControl, + type CommandScopedContext, + ManagedCommands, + type ManagedCommandsFlavor, + type ManagedCommandsHooks, +} from "@/lib/managed-commands" +import { FakeTelegram } from "./harness/telegram" + +vi.mock("@/modules", () => ({ modules: {} })) + +type Ctx = ManagedCommandsFlavor + +/** Mirrors the shape of the bot's own access control: permissions to hold, or the group admin shortcut */ +interface TestAccess extends AccessControl { + permissions: { required?: string[]; groupAdminsToo?: boolean } + authorization: { allowed: boolean; basis: "permission" | "group_admin" | null } +} + +type Scope = "private" | "group" | "both" +type Spec = { + trigger: string + scope: Scope + collection?: string + permissions?: TestAccess["permissions"] & { allowedGroupsId?: number[]; excludedGroupsId?: number[] } +} + +function setup( + options: { + hooks?: ManagedCommandsHooks + refreshAfterMs?: number + /** Leave out the commands limited by group allow/deny lists */ + withoutGroupLists?: boolean + } = {} +) { + const tg = new FakeTelegram() + const users = { + nobody: tg.user("Nobody"), + secretHolder: tg.user("SecretHolder"), + mod: tg.user("Mod"), + admin: tg.user("Admin"), + pinner: tg.user("Pinner"), + } + const groups = { + allowed: tg.group("Allowed"), + excluded: tg.group("Excluded"), + plain: tg.group("Plain"), + } + + const idp = new Map([ + [users.secretHolder.id, ["secret"]], + [users.mod.id, ["mod"]], + [users.pinner.id, ["pin"]], + ]) + const failingLookups = new Set() + let lookups = 0 + + const allSpecs: Spec[] = [ + { trigger: "start", scope: "private" }, + { trigger: "search", scope: "both" }, + { trigger: "report", scope: "group" }, + { trigger: "secret", scope: "private", collection: "Management", permissions: { required: ["secret"] } }, + { trigger: "audit", scope: "both", collection: "Management", permissions: { required: ["secret"] } }, + { + trigger: "ban", + scope: "group", + collection: "Moderation", + permissions: { required: ["mod"], groupAdminsToo: true }, + }, + { + trigger: "warn", + scope: "both", + collection: "Moderation", + permissions: { required: ["mod"], groupAdminsToo: true }, + }, + { trigger: "local", scope: "group", permissions: { allowedGroupsId: [groups.allowed.id] } }, + { trigger: "notexcluded", scope: "group", permissions: { excludedGroupsId: [groups.excluded.id] } }, + { + trigger: "nowhere", + scope: "group", + permissions: { allowedGroupsId: [groups.excluded.id], excludedGroupsId: [groups.excluded.id] }, + }, + { + trigger: "pin", + scope: "group", + collection: "Moderation", + permissions: { required: ["pin"], groupAdminsToo: true, allowedGroupsId: [groups.allowed.id] }, + }, + ] + + const specs = options.withoutGroupLists + ? allSpecs.filter((s) => !s.permissions?.allowedGroupsId && !s.permissions?.excludedGroupsId) + : allSpecs + + const ran: { trigger: string; userId: number; chatId: number; authorization: TestAccess["authorization"] }[] = [] + const commands = new ManagedCommands({ + hooks: options.hooks ?? {}, + menus: { blocking: true, refreshAfterMs: options.refreshAfterMs ?? 0 }, + authorize: async ({ context, command, isGroupAdmin }) => { + const required = command.permissions?.required ?? [] + if (!required.length) return { allowed: true, basis: null } + const userId = context.from?.id ?? 0 + lookups++ + const held = failingLookups.has(userId) ? null : (idp.get(userId) ?? []) + if (held && required.every((p) => held.includes(p))) return { allowed: true, basis: "permission" } + if (command.permissions?.groupAdminsToo && (await isGroupAdmin())) return { allowed: true, basis: "group_admin" } + return { allowed: false, basis: null } + }, + }) + for (const spec of specs) { + commands.createCommand( + { + trigger: spec.trigger, + scope: spec.scope, + description: `desc-${spec.trigger}`, + permissions: spec.permissions, + handler: async ({ context, authorization }) => { + ran.push({ trigger: spec.trigger, userId: context.from.id, chatId: context.chat.id, authorization }) + }, + }, + spec.collection + ) + } + + return { + tg, + users, + groups, + specs, + idp, + failingLookups, + ran, + lookups: () => lookups, + bot: tg.createBot((bot) => bot.use(commands)), + } +} + +/** Parses the private /help into trigger โ†’ availability mark */ +function parsePrivateHelp(text: string): Map { + const lines = text.split("\n") + const entries = new Map() + for (const [i, line] of lines.entries()) { + const match = /^\/(\w+)/.exec(line) + if (!match) continue + const mark = /^\t(\S+) desc-/.exec(lines[i + 1] ?? "") + entries.set(match[1], mark?.[1] ?? "") + } + return entries +} + +function parseGroupHelp(text: string): string[] { + return text + .split("\n") + .map((line) => /^\/(\w+)/.exec(line)?.[1]) + .filter((t): t is string => t !== undefined && t !== "help") +} + +async function runs(env: ReturnType, bot: Bot, user: User, trigger: string, chat?: Chat) { + const before = env.ran.length + await env.tg.send(bot, user, `/${trigger}`, { chat }) + return env.ran.length > before +} + +describe("ManagedCommands: /help and menus tell exactly what can run", () => { + it("agrees with execution for every user, chat, admin status and command", async () => { + const env = setup() + const { tg, users, groups, specs } = env + const bot = await env.bot + const allGroups = Object.values(groups) + + for (const user of Object.values(users)) { + const truth = new Map() + for (const { trigger } of specs) truth.set(trigger, { private: false, asMember: false, asAdmin: false }) + + // ground truth: actually run every command, in private and in each group, as a member and as an admin + for (const { trigger } of specs) { + const t = truth.get(trigger) + if (!t) throw new Error("unreachable") + t.private = await runs(env, bot, user, trigger) + } + for (const asAdmin of [false, true]) { + for (const group of allGroups) { + if (asAdmin) tg.setAdmin(group, user) + else tg.removeAdmin(group, user) + + const inGroup = new Set() + for (const { trigger } of specs) if (await runs(env, bot, user, trigger, group)) inGroup.add(trigger) + for (const trigger of inGroup) { + const t = truth.get(trigger) + if (t && asAdmin) t.asAdmin = true + if (t && !asAdmin) t.asMember = true + } + + // group /help and the menu in the group list exactly what runs there + const help = await tg.send(bot, user, "/help", { chat: group }) + expect(help.replies).toHaveLength(1) + expect(help.replies[0].ephemeralTo).toBe(user.id) + const label = `${user.first_name} in ${group.title} (${asAdmin ? "admin" : "member"})` + expect(parseGroupHelp(help.reply).sort(), label).toEqual([...inGroup].sort()) + expect( + tg + .menuCommandsOf(user, group) + .filter((c) => c !== "help") + .sort(), + label + ).toEqual([...inGroup].sort()) + } + } + + // the private menu lists what runs in private + await tg.send(bot, user, "hello") + expect( + tg + .menuCommandsOf(user) + .filter((c) => c !== "help") + .sort(), + `${user.first_name} private menu` + ).toEqual( + specs + .map((s) => s.trigger) + .filter((t) => truth.get(t)?.private) + .sort() + ) + + // the private /help lists what runs somewhere, marking what needs group admin rights + const help = parsePrivateHelp((await tg.send(bot, user, "/help")).reply) + for (const { trigger } of specs) { + const t = truth.get(trigger) + if (!t) throw new Error("unreachable") + const groupsMark = t.asMember ? "yes" : t.asAdmin ? "admin" : "no" + const expected = + !t.private && groupsMark === "no" + ? undefined + : `${t.private ? (groupsMark === "no" ? "๐Ÿ‘ค" : "๐ŸŒ") : "๐Ÿ‘ฅ"}${groupsMark === "admin" ? "๐Ÿ›ก๏ธ" : ""}` + expect(help.get(trigger), `${user.first_name}: /${trigger} in private /help`).toBe(expected) + } + } + }) + + it("lists for an ordinary user the commands they could run as a group admin", async () => { + const env = setup() + const bot = await env.bot + const help = await env.tg.send(bot, env.users.nobody, "/help") + const entries = parsePrivateHelp(help.reply) + + expect(Object.fromEntries(entries)).toEqual({ + start: "๐Ÿ‘ค", + search: "๐ŸŒ", + report: "๐Ÿ‘ฅ", + ban: "๐Ÿ‘ฅ๐Ÿ›ก๏ธ", + warn: "๐Ÿ‘ฅ๐Ÿ›ก๏ธ", + local: "๐Ÿ‘ฅ", + notexcluded: "๐Ÿ‘ฅ", + pin: "๐Ÿ‘ฅ๐Ÿ›ก๏ธ", + }) + expect(help.reply).toContain("๐Ÿ›ก๏ธ only in groups where you are an admin") + expect(help.reply).toContain("Moderation:") + expect(help.reply).not.toContain("Management:") + }) + + it("never applies the group admin shortcut outside of groups, even if the admin check says yes", async () => { + const overrideGroupAdminCheck = vi.fn(async () => true) + const env = setup({ hooks: { overrideGroupAdminCheck } }) + const bot = await env.bot + + expect(await runs(env, bot, env.users.nobody, "warn")).toBe(false) + expect(overrideGroupAdminCheck).not.toHaveBeenCalled() + + expect(await runs(env, bot, env.users.nobody, "warn", env.groups.plain)).toBe(true) + expect(env.ran.at(-1)?.authorization).toEqual({ allowed: true, basis: "group_admin" }) + expect(overrideGroupAdminCheck).toHaveBeenCalledWith(env.users.nobody.id, env.groups.plain.id, expect.anything()) + }) + + it("passes the decision that allowed the command to the handler", async () => { + const env = setup() + const bot = await env.bot + env.tg.setAdmin(env.groups.plain, env.users.admin) + + await runs(env, bot, env.users.mod, "ban", env.groups.plain) + await runs(env, bot, env.users.admin, "ban", env.groups.plain) + await runs(env, bot, env.users.nobody, "search", env.groups.plain) + + expect(env.ran.map((r) => [r.trigger, r.userId, r.authorization.basis])).toEqual([ + ["ban", env.users.mod.id, "permission"], + ["ban", env.users.admin.id, "group_admin"], + ["search", env.users.nobody.id, null], + ]) + }) + + it("asks Telegram about the user's admin status at most once per update", async () => { + const env = setup() + const bot = await env.bot + const help = await env.tg.send(bot, env.users.nobody, "/help", { chat: env.groups.allowed }) + expect(help.called("getChatMember")).toHaveLength(1) + + const ban = await env.tg.send(bot, env.users.nobody, "/ban", { chat: env.groups.plain }) + expect(ban.called("getChatMember")).toHaveLength(1) + }) + + it("hides commands whose permissions cannot be checked, and denies running them", async () => { + const env = setup() + const bot = await env.bot + env.failingLookups.add(env.users.mod.id) + + expect(await runs(env, bot, env.users.mod, "ban", env.groups.plain)).toBe(false) + expect(parsePrivateHelp((await env.tg.send(bot, env.users.mod, "/help")).reply).get("ban")).toBe("๐Ÿ‘ฅ๐Ÿ›ก๏ธ") + }) + + it("shows the usage only of commands the user can run", async () => { + const env = setup() + const bot = await env.bot + + expect((await env.tg.send(bot, env.users.nobody, "/help secret")).reply).toContain("Command not found") + expect((await env.tg.send(bot, env.users.nobody, "/help doesnotexist")).reply).toContain("Command not found") + + const secret = (await env.tg.send(bot, env.users.secretHolder, "/help /secret")).reply + expect(secret).toContain("desc-secret") + expect(secret).toContain("Available to you: In private chat with the bot") + + const ban = (await env.tg.send(bot, env.users.nobody, "/help ban")).reply + expect(ban).toContain("Available to you: In groups where you are an admin") + + const pin = (await env.tg.send(bot, env.users.pinner, "/help pin")).reply + expect(pin).toContain("Available to you: In groups (only some groups)") + + const inGroup = await env.tg.send(bot, env.users.nobody, "/help ban", { chat: env.groups.plain }) + expect(inGroup.reply).toContain("Command not found") + env.tg.setAdmin(env.groups.plain, env.users.nobody) + const asAdmin = await env.tg.send(bot, env.users.nobody, "/help ban", { chat: env.groups.plain }) + expect(asAdmin.reply).toContain("Available to you: In this group") + expect(asAdmin.replies[0].ephemeralTo).toBe(env.users.nobody.id) + expect(asAdmin.called("deleteMessage")).toHaveLength(1) + }) +}) + +describe("ManagedCommands: commands menus", () => { + let env: ReturnType + let bot: Bot + + beforeEach(async () => { + env = setup({ refreshAfterMs: 60_000, withoutGroupLists: true }) + bot = await env.bot + }) + + it("sets default menus with the commands anyone can run", async () => { + const first = await env.tg.send(bot, env.users.nobody, "hello") + expect(first.called("setMyCommands").map((c) => (c.payload.scope as { type: string }).type)).toEqual([ + "all_private_chats", + "all_group_chats", + ]) + expect(env.tg.menuCommandsOf(env.users.nobody)).toEqual(["start", "search", "help"]) + expect(env.tg.menuCommandsOf(env.users.nobody, env.groups.plain)).toEqual(["search", "report", "help"]) + + // only once + const second = await env.tg.send(bot, env.users.mod, "hello", { chat: env.groups.plain }) + expect(second.called("setMyCommands").map((c) => (c.payload.scope as { type: string }).type)).toEqual([ + "chat_member", + ]) + }) + + it("gives users who can run more commands their own menu, only where it differs", async () => { + const inPrivate = await env.tg.send(bot, env.users.nobody, "hello") + expect(inPrivate.called("setMyCommands")).toHaveLength(2) // the defaults only + const inGroup = await env.tg.send(bot, env.users.nobody, "hello", { chat: env.groups.plain }) + expect(inGroup.called("getChatMember")).toHaveLength(1) + expect(inGroup.called("setMyCommands")).toEqual([]) + expect(inGroup.called("deleteMyCommands")).toEqual([]) + + await env.tg.send(bot, env.users.mod, "hello", { chat: env.groups.plain }) + expect(env.tg.menuCommandsOf(env.users.mod, env.groups.plain)).toEqual(["search", "report", "ban", "warn", "help"]) + await env.tg.send(bot, env.users.mod, "hello") + expect(env.tg.menuCommandsOf(env.users.mod)).toEqual(["start", "search", "warn", "help"]) + // other chats are untouched + expect(env.tg.menuCommandsOf(env.users.mod, env.groups.allowed)).toEqual(["search", "report", "help"]) + }) + + it("does not recompute a menu until it is due, unless the user asks for /help", async () => { + env.tg.setAdmin(env.groups.plain, env.users.admin) + const first = await env.tg.send(bot, env.users.admin, "hello", { chat: env.groups.plain }) + expect(first.called("getChatMember")).toHaveLength(1) + expect(env.tg.menuCommandsOf(env.users.admin, env.groups.plain)).toContain("ban") + + env.tg.removeAdmin(env.groups.plain, env.users.admin) + const second = await env.tg.send(bot, env.users.admin, "hello", { chat: env.groups.plain }) + expect(second.calls).toEqual([]) + expect(env.tg.menuCommandsOf(env.users.admin, env.groups.plain)).toContain("ban") + + // /help refreshes the menu, back to the default one + const help = await env.tg.send(bot, env.users.admin, "/help", { chat: env.groups.plain }) + expect(help.called("deleteMyCommands")).toHaveLength(1) + expect(env.tg.menuCommandsOf(env.users.admin, env.groups.plain)).toEqual(["search", "report", "help"]) + }) + + it("picks up permission changes once the menu is due again", async () => { + vi.useFakeTimers({ toFake: ["Date"] }) + try { + await env.tg.send(bot, env.users.nobody, "hello") + expect(env.tg.menuCommandsOf(env.users.nobody)).not.toContain("secret") + + env.idp.set(env.users.nobody.id, ["secret"]) + vi.setSystemTime(Date.now() + 61_000) + await env.tg.send(bot, env.users.nobody, "hello") + expect(env.tg.menuCommandsOf(env.users.nobody)).toEqual(["start", "search", "secret", "audit", "help"]) + + env.idp.delete(env.users.nobody.id) + vi.setSystemTime(Date.now() + 61_000) + await env.tg.send(bot, env.users.nobody, "hello") + expect(env.tg.menuCommandsOf(env.users.nobody)).toEqual(["start", "search", "help"]) + } finally { + vi.useRealTimers() + } + }) + + it("retries the default menus if setting them fails", async () => { + let fail = true + env.tg.on("setMyCommands", () => { + if (fail) throw new Error("network down") + return true + }) + await env.tg.send(bot, env.users.nobody, "hello").catch(() => {}) + fail = false + const retry = await env.tg.send(bot, env.users.nobody, "hello") + expect(retry.called("setMyCommands").length).toBeGreaterThanOrEqual(2) + }) +}) + +describe("ManagedCommands: registration", () => { + it("reserves the /help trigger", () => { + const commands = new ManagedCommands() + expect(() => commands.createCommand({ trigger: "help", handler: async () => {} })).toThrow(/already registered/) + }) + + it("still reports commands run in the wrong chat type", async () => { + const wrongScope = vi.fn(async () => {}) + const env = setup({ hooks: { wrongScope } }) + const bot = await env.bot + await env.tg.send(bot, env.users.secretHolder, "/secret", { chat: env.groups.plain }) + await env.tg.send(bot, env.users.mod, "/ban") + expect(wrongScope).toHaveBeenCalledTimes(2) + expect(env.ran).toEqual([]) + }) + + it("the default authorization reports group admins through the built-in check", async () => { + const tg = new FakeTelegram() + const ran: unknown[] = [] + const commands = new ManagedCommands({ menus: false }).createCommand({ + trigger: "kick", + scope: "group", + permissions: { allowGroupAdmins: true }, + handler: async ({ authorization }) => { + ran.push(authorization) + }, + }) + const bot = await tg.createBot((b) => b.use(commands)) + const group = tg.group("Group") + const admin = tg.user("Admin") + const member = tg.user("Member") + tg.setAdmin(group, admin) + + await tg.send(bot, admin, "/kick", { chat: group }) + const memberRun = await tg.send(bot, member, "/kick", { chat: group }) + expect(ran).toEqual([ + { allowed: true, via: "group_admin" }, + { allowed: true, via: "unrestricted" }, + ]) + expect(memberRun.called("setMyCommands")).toEqual([]) + }) +})