Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/access/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>
/** The person's access, if already looked up; otherwise it is resolved through `backend`. */
actor?: () => Promise<AccessEntry>
}): Promise<Decision> {
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
Expand Down
35 changes: 24 additions & 11 deletions src/commands/access.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -19,24 +18,38 @@ export type CommandAccess = {
authorization: Decision
}

export const authorizeCommand: Authorize<Context, CommandAccess> = 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<object, Promise<AccessEntry>>()

/**
* 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<Context, CommandAccess> = 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,
})
}
15 changes: 14 additions & 1 deletion src/commands/index.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -24,10 +24,23 @@ const adapter = new RedisFallbackAdapter<VersionedState<ConversationData>>({
logger,
})

const menuStorage = new RedisFallbackAdapter<StoredCommandsMenu>({
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<CommandScopedContext>

export const commands = new ManagedCommands<Context, ConversationContext, CommandAccess>({
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")
Expand Down
23 changes: 22 additions & 1 deletion src/lib/managed-commands/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<A, R, CommandScope, C, TAccess>): cmd is Command<A, R, "private" | "both", C, TAccess> {
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.
*
Expand All @@ -245,3 +259,10 @@ export function isAllowedInPrivateOnly<
>(cmd: Command<A, R, CommandScope, C, TAccess>): cmd is Command<A, R, "private", C, TAccess> {
return cmd.scope === "private"
}

/**
* All the triggers of a command, including its aliases
*/
export function commandTriggers<TAccess extends AccessControl>(cmd: AnyCommand<Context, TAccess>): string[] {
return Array.isArray(cmd.trigger) ? [...cmd.trigger] : [cmd.trigger]
}
174 changes: 174 additions & 0 deletions src/lib/managed-commands/help.ts
Original file line number Diff line number Diff line change
@@ -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<T> = { 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<Context, AccessControl>

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<T>(
sections: HelpSection<T>[],
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 <command>`} 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<AnyCmd>[]) {
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 <command>`} 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,
]
}
Loading
Loading