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 diff --git a/src/utils/once.ts b/src/utils/once.ts index a6ae914..9805a3c 100644 --- a/src/utils/once.ts +++ b/src/utils/once.ts @@ -15,14 +15,10 @@ 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) { - let called = false - let result: R + let result: Promise> | undefined - return async (...args: A) => { - if (!called) { - called = true - result = await fn(...args) - } + return (...args: A) => { + result ??= Promise.resolve(fn(...args)) return result } } 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([]) + }) +}) 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") + }) +})