From 577c16d64031a9590ab3d16c2583174c5f55f25e Mon Sep 17 00:00:00 2001 From: Bianca Date: Thu, 22 Oct 2026 17:59:50 +0200 Subject: [PATCH 1/2] refactor(telegram): use backend SDK v2 and drop legacy actor fallbacks Moves @polinetwork/backend from ^1.4.0 to ^2.3.0. The backend has sent the actor on every grant log and leaveChat event since Phase 5, and migration 0021 copied admin_id into actor_tg_id for older audit rows, so the bot no longer reads `adminId` or `performerId`. --- package.json | 2 +- pnpm-lock.yaml | 10 ++++---- src/commands/management/audit.ts | 4 +-- src/modules/websocket.ts | 44 +++++++++++++++----------------- 4 files changed, 28 insertions(+), 32 deletions(-) diff --git a/package.json b/package.json index d691c54..4a68681 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "@grammyjs/runner": "^2.0.3", "@influxdata/influxdb-client": "^1.35.0", "@polinetwork/auth-kit": "^1.1.0", - "@polinetwork/backend": "^1.4.0", + "@polinetwork/backend": "^2.3.0", "@socket.io/devalue-parser": "^0.1.0", "@t3-oss/env-core": "^0.13.4", "@trpc/client": "^11.5.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 98bb496..94f4682 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,8 +33,8 @@ importers: specifier: ^1.1.0 version: 1.1.0 '@polinetwork/backend': - specifier: ^1.4.0 - version: 1.4.0 + specifier: ^2.3.0 + version: 2.3.0 '@socket.io/devalue-parser': specifier: ^0.1.0 version: 0.1.0 @@ -612,8 +612,8 @@ packages: resolution: {integrity: sha512-SAf/cVSF4wW7UqP3EP/3IFPAJgYTL9po9qOXcJ9OvbRPCi9X4bmMTDDHYzuPCKMAQkHybuPbI6tzcKFBekw0Ag==} engines: {node: '>=20.19'} - '@polinetwork/backend@1.4.0': - resolution: {integrity: sha512-wXvngodOakPV521G4+zCMvgKSiNITNxVUtEA6ZRM1oNR0mKF2Bp7GDYWd7YvT19cV5i8HrvZ5DpbConDFHHdtQ==} + '@polinetwork/backend@2.3.0': + resolution: {integrity: sha512-FqoJ0qL5OHP6UZ3Hrm9DfwgQaAWjHWwsThF9Mu18oO265OL41+ZS9JqN+ILejTE3P8ohOutXj/0NcV4VP4IuJA==} '@redis/bloom@1.2.0': resolution: {integrity: sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==} @@ -2179,7 +2179,7 @@ snapshots: jose: 6.2.12 zod: 4.1.11 - '@polinetwork/backend@1.4.0': {} + '@polinetwork/backend@2.3.0': {} '@redis/bloom@1.2.0(@redis/client@1.6.1)': dependencies: diff --git a/src/commands/management/audit.ts b/src/commands/management/audit.ts index a9b8add..07ce976 100644 --- a/src/commands/management/audit.ts +++ b/src/commands/management/audit.ts @@ -31,8 +31,8 @@ export const audit = new CommandsCollection("Auditing").c ({ b, n, i, u, link, code }) => [ b`🧾 Audit Log: ${args.username}\n`, ...list.flatMap((el) => { - // Automatic actions have no human actor (RFC v3 §9.2); older rows only have adminId. - const actorId = el.actorTgId ?? el.adminId + // Automatic actions have no human actor (RFC v3 §9.2). + const actorId = el.actorTgId return [ `------------------------------------`, n`${u`${b`${el.type.toUpperCase()}`}`} ${i`at ${fmtDate(el.createdAt)}`}`, diff --git a/src/modules/websocket.ts b/src/modules/websocket.ts index 7d17e18..c62a885 100644 --- a/src/modules/websocket.ts +++ b/src/modules/websocket.ts @@ -18,13 +18,12 @@ type SocketActor = { sub: string | null; telegramId: string | null; displayName: /** * The author of a grant for the log: their stored Telegram user when there is one, else the name - * the backend sent. `actor` is optional for backends that still send only `adminId`. + * the backend sent. */ -async function grantActor(data: { actor?: SocketActor; adminId: number | null }): Promise { - const telegramId = data.actor ? (data.actor.telegramId === null ? null : Number(data.actor.telegramId)) : data.adminId +async function grantActor({ actor }: { actor: SocketActor }): Promise { + const telegramId = actor.telegramId === null ? null : Number(actor.telegramId) const stored: User | null = telegramId ? await MessageUserStorage.getInstance().getStoredUser(telegramId) : null - if (stored) return stored - return data.actor ? { displayName: data.actor.displayName, telegramId } : null + return stored ?? { displayName: actor.displayName, telegramId } } type SocketError = { @@ -112,9 +111,9 @@ export class WebSocketClient extends Module { const target = await MessageUserStorage.getInstance().getStoredUser(data.userId) const admin = await grantActor(data) - if (!target || !admin) { - logger.error("[WS] grant interrupt log ERROR -- cannot retrieve users") - cb("Cannot retrieve the users") + if (!target) { + logger.error("[WS] grant interrupt log ERROR -- cannot retrieve the target user") + cb("Cannot retrieve the target user") return } @@ -166,19 +165,16 @@ export class WebSocketClient extends Module { - const { chatId, performer } = data - const ok = await this.shared.api.leaveChat(chatId).catch(() => false) - - const performedBy = performer - ? { performerTelegramId: performer.telegramId, performerSub: performer.sub } - : { performerTelegramId: data.performerId } - if (ok) logger.info({ chatId, ...performedBy }, "[WS] leave chat performed") - cb(ok) - } - ) + this.io.on("leaveChat", async ({ chatId, performer }: { chatId: number; performer: SocketActor }, cb) => { + const ok = await this.shared.api.leaveChat(chatId).catch(() => false) + + if (ok) + logger.info( + { chatId, performerTelegramId: performer.telegramId, performerSub: performer.sub }, + "[WS] leave chat performed" + ) + cb(ok) + }) } override async start() { From 72d124863c59193b347fafbec36ad5f5b11468f7 Mon Sep 17 00:00:00 2001 From: Bianca Date: Mon, 26 Oct 2026 19:58:19 +0100 Subject: [PATCH 2/2] refactor(commands): use backend SDK v4 and drop role-based command checks Backend 4.0.0 (RFC v3 Phase 6) removed the legacy login and permission tables; the bot already authorizes commands with IdP permissions. The managed-commands library still carried the old role model: `allowedRoles` / `excludedRoles`, the `getUserRoles` option and the `TRole` type parameter. The bot never passed `getUserRoles` and no command declared roles, so the check always fell through. Remove them; the built-in check keeps only the group admin shortcut, and commands declare `requiredPermissions` through the bot's access control. --- package.json | 2 +- pnpm-lock.yaml | 10 +- src/commands/access.ts | 2 +- src/commands/index.ts | 2 +- src/commands/invite.ts | 2 +- src/commands/management/audit.ts | 2 +- src/commands/management/groups.ts | 2 +- src/commands/management/index.ts | 2 +- src/commands/management/role.ts | 2 +- src/commands/management/userid.ts | 2 +- src/commands/moderation/ban.ts | 2 +- src/commands/moderation/banall.ts | 2 +- src/commands/moderation/del.ts | 2 +- src/commands/moderation/index.ts | 2 +- src/commands/moderation/kick.ts | 2 +- src/commands/moderation/mute.ts | 2 +- src/commands/pin.ts | 2 +- src/commands/report.ts | 2 +- src/commands/search.ts | 2 +- src/commands/test/args.ts | 2 +- src/commands/test/conversation.ts | 2 +- src/commands/test/format.ts | 2 +- src/commands/test/index.ts | 2 +- src/commands/test/menu.ts | 2 +- src/lib/managed-commands/collection.ts | 12 +- src/lib/managed-commands/command.ts | 48 +++----- src/lib/managed-commands/index.ts | 162 ++++++------------------- 27 files changed, 93 insertions(+), 185 deletions(-) diff --git a/package.json b/package.json index 4a68681..16039fd 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "@grammyjs/runner": "^2.0.3", "@influxdata/influxdb-client": "^1.35.0", "@polinetwork/auth-kit": "^1.1.0", - "@polinetwork/backend": "^2.3.0", + "@polinetwork/backend": "^4.0.0", "@socket.io/devalue-parser": "^0.1.0", "@t3-oss/env-core": "^0.13.4", "@trpc/client": "^11.5.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 94f4682..b498035 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -33,8 +33,8 @@ importers: specifier: ^1.1.0 version: 1.1.0 '@polinetwork/backend': - specifier: ^2.3.0 - version: 2.3.0 + specifier: ^4.0.0 + version: 4.0.0 '@socket.io/devalue-parser': specifier: ^0.1.0 version: 0.1.0 @@ -612,8 +612,8 @@ packages: resolution: {integrity: sha512-SAf/cVSF4wW7UqP3EP/3IFPAJgYTL9po9qOXcJ9OvbRPCi9X4bmMTDDHYzuPCKMAQkHybuPbI6tzcKFBekw0Ag==} engines: {node: '>=20.19'} - '@polinetwork/backend@2.3.0': - resolution: {integrity: sha512-FqoJ0qL5OHP6UZ3Hrm9DfwgQaAWjHWwsThF9Mu18oO265OL41+ZS9JqN+ILejTE3P8ohOutXj/0NcV4VP4IuJA==} + '@polinetwork/backend@4.0.0': + resolution: {integrity: sha512-hKvjzwMMm8qZJojEhIGOA9sHg29xlw2Tu/XH2Wlq9xdkyucEFHp5QNLzGWccjzjHd8fja4qF20OQJppaFrEVtA==} '@redis/bloom@1.2.0': resolution: {integrity: sha512-HG2DFjYKbpNmVXsa0keLHp/3leGJz1mjh09f2RLGGLQZzSHpkmZWuwJbAvo3QcRY8p80m5+ZdXZdYOSBLlp7Cg==} @@ -2179,7 +2179,7 @@ snapshots: jose: 6.2.12 zod: 4.1.11 - '@polinetwork/backend@2.3.0': {} + '@polinetwork/backend@4.0.0': {} '@redis/bloom@1.2.0(@redis/client@1.6.1)': dependencies: diff --git a/src/commands/access.ts b/src/commands/access.ts index 52eac64..f03f162 100644 --- a/src/commands/access.ts +++ b/src/commands/access.ts @@ -19,7 +19,7 @@ export type CommandAccess = { authorization: Decision } -export const authorizeCommand: Authorize = async ({ context, command }) => { +export const authorizeCommand: Authorize = async ({ context, command }) => { const { permissions } = command if (!permissions?.requiredPermissions?.length) return { allowed: true, basis: null } const from = context.from diff --git a/src/commands/index.ts b/src/commands/index.ts index 1a0d642..849566d 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -26,7 +26,7 @@ const adapter = new RedisFallbackAdapter>({ type ConversationContext = TelemetryContextFlavor -export const commands = new ManagedCommands({ +export const commands = new ManagedCommands({ adapter, plugins: [ (ctx, next) => { diff --git a/src/commands/invite.ts b/src/commands/invite.ts index a33929e..b6c9430 100644 --- a/src/commands/invite.ts +++ b/src/commands/invite.ts @@ -4,7 +4,7 @@ import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" -export const invite = new CommandsCollection().createCommand({ +export const invite = new CommandsCollection().createCommand({ trigger: "invite", description: "Display the bot's invite link of the group", scope: "group", diff --git a/src/commands/management/audit.ts b/src/commands/management/audit.ts index 07ce976..5e23a00 100644 --- a/src/commands/management/audit.ts +++ b/src/commands/management/audit.ts @@ -5,7 +5,7 @@ import { CommandsCollection } from "@/lib/managed-commands" import { fmt, fmtDate } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -export const audit = new CommandsCollection("Auditing").createCommand({ +export const audit = new CommandsCollection("Auditing").createCommand({ trigger: "audit", scope: "private", description: "Get the audit log of a user", diff --git a/src/commands/management/groups.ts b/src/commands/management/groups.ts index 5f96493..f6fef34 100644 --- a/src/commands/management/groups.ts +++ b/src/commands/management/groups.ts @@ -5,7 +5,7 @@ import { GroupManagement } from "@/lib/group-management" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -export const groups = new CommandsCollection("Groups") +export const groups = new CommandsCollection("Groups") .createCommand({ trigger: "updategroup", scope: "private", diff --git a/src/commands/management/index.ts b/src/commands/management/index.ts index dd503c0..50d6e3f 100644 --- a/src/commands/management/index.ts +++ b/src/commands/management/index.ts @@ -5,7 +5,7 @@ import { groups } from "./groups" import { role } from "./role" import { userid } from "./userid" -export const management = new CommandsCollection("Management").withCollection( +export const management = new CommandsCollection("Management").withCollection( audit, groups, role, diff --git a/src/commands/management/role.ts b/src/commands/management/role.ts index 62004c4..7e9daa4 100644 --- a/src/commands/management/role.ts +++ b/src/commands/management/role.ts @@ -7,7 +7,7 @@ import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" import { numberOrString } from "@/utils/types" -export const role = new CommandsCollection("Roles").createCommand({ +export const role = new CommandsCollection("Roles").createCommand({ trigger: "getroles", scope: "private", description: "Get roles of an user", diff --git a/src/commands/management/userid.ts b/src/commands/management/userid.ts index a7b6b1f..8e27798 100644 --- a/src/commands/management/userid.ts +++ b/src/commands/management/userid.ts @@ -5,7 +5,7 @@ import { logger } from "@/logger" import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -export const userid = new CommandsCollection("User IDs").createCommand({ +export const userid = new CommandsCollection("User IDs").createCommand({ trigger: "userid", scope: "private", description: "Gets the ID of a username", diff --git a/src/commands/moderation/ban.ts b/src/commands/moderation/ban.ts index e4431a6..4973457 100644 --- a/src/commands/moderation/ban.ts +++ b/src/commands/moderation/ban.ts @@ -10,7 +10,7 @@ import { getTelegramId } from "@/utils/telegram-id" import { numberOrString } from "@/utils/types" import { getOverloadUser, getUser } from "@/utils/users" -export const ban = new CommandsCollection("Banning") +export const ban = new CommandsCollection("Banning") .createCommand({ trigger: "ban", args: [ diff --git a/src/commands/moderation/banall.ts b/src/commands/moderation/banall.ts index 12c431f..6cdb225 100644 --- a/src/commands/moderation/banall.ts +++ b/src/commands/moderation/banall.ts @@ -11,7 +11,7 @@ import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" import { numberOrString } from "@/utils/types" -export const banAll = new CommandsCollection("Ban All") +export const banAll = new CommandsCollection("Ban All") .createCommand({ trigger: "ban_all", description: "PERMA BAN a user from all the Network's groups", diff --git a/src/commands/moderation/del.ts b/src/commands/moderation/del.ts index b07808f..a5e908e 100644 --- a/src/commands/moderation/del.ts +++ b/src/commands/moderation/del.ts @@ -6,7 +6,7 @@ import { Moderation } from "@/modules/moderation" import { fmt } from "@/utils/format" import { ephemeral, getText } from "@/utils/messages" -export const del = new CommandsCollection("Deletion").createCommand({ +export const del = new CommandsCollection("Deletion").createCommand({ trigger: "del", scope: "group", permissions: { diff --git a/src/commands/moderation/index.ts b/src/commands/moderation/index.ts index 2133db3..d1054fa 100644 --- a/src/commands/moderation/index.ts +++ b/src/commands/moderation/index.ts @@ -6,7 +6,7 @@ import { del } from "./del" import { kick } from "./kick" import { mute } from "./mute" -export const moderation = new CommandsCollection("Moderation").withCollection( +export const moderation = new CommandsCollection("Moderation").withCollection( ban, banAll, del, diff --git a/src/commands/moderation/kick.ts b/src/commands/moderation/kick.ts index ea455f6..8f8c846 100644 --- a/src/commands/moderation/kick.ts +++ b/src/commands/moderation/kick.ts @@ -5,7 +5,7 @@ import { logger } from "@/logger" import { Moderation, moderatorFor } from "@/modules/moderation" import { ephemeral } from "@/utils/messages" -export const kick = new CommandsCollection("Kicking").createCommand({ +export const kick = new CommandsCollection("Kicking").createCommand({ trigger: "kick", args: [{ key: "reason", optional: true, description: "Optional reason to kick the user" }], description: "Kick a user from a group", diff --git a/src/commands/moderation/mute.ts b/src/commands/moderation/mute.ts index 9729db6..018b2f3 100644 --- a/src/commands/moderation/mute.ts +++ b/src/commands/moderation/mute.ts @@ -10,7 +10,7 @@ import { getTelegramId } from "@/utils/telegram-id" import { numberOrString } from "@/utils/types" import { getOverloadUser, getUser } from "@/utils/users" -export const mute = new CommandsCollection("Muting") +export const mute = new CommandsCollection("Muting") .createCommand({ trigger: "tmute", args: [ diff --git a/src/commands/pin.ts b/src/commands/pin.ts index 81fd0b1..856b420 100644 --- a/src/commands/pin.ts +++ b/src/commands/pin.ts @@ -4,7 +4,7 @@ import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" -export const pin = new CommandsCollection() +export const pin = new CommandsCollection() .createCommand({ trigger: "pin", description: "Pin a message in a group", diff --git a/src/commands/report.ts b/src/commands/report.ts index fb56616..8e08bfb 100644 --- a/src/commands/report.ts +++ b/src/commands/report.ts @@ -27,7 +27,7 @@ export const logReport = async (context: Filter | CommandSco }) } -export const report = new CommandsCollection().createCommand({ +export const report = new CommandsCollection().createCommand({ trigger: ["report", "admin"], description: "Report a message to admins", scope: "group", diff --git a/src/commands/search.ts b/src/commands/search.ts index f0d59af..4ed5a3b 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -9,7 +9,7 @@ const LIMIT = 9 type Group = Awaited>["groups"][number] type LinkedGroup = Group & { link: string } -export const search = new CommandsCollection().createCommand({ +export const search = new CommandsCollection().createCommand({ trigger: "search", scope: "both", description: "Search groups by title", diff --git a/src/commands/test/args.ts b/src/commands/test/args.ts index 1f0c291..f59a8ac 100644 --- a/src/commands/test/args.ts +++ b/src/commands/test/args.ts @@ -1,7 +1,7 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" -export const testargs = new CommandsCollection().createCommand({ +export const testargs = new CommandsCollection().createCommand({ trigger: "test_args", scope: "private", description: "Test args", diff --git a/src/commands/test/conversation.ts b/src/commands/test/conversation.ts index 35bba41..8ccfdec 100644 --- a/src/commands/test/conversation.ts +++ b/src/commands/test/conversation.ts @@ -2,7 +2,7 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -export const testconvo = new CommandsCollection().createCommand({ +export const testconvo = new CommandsCollection().createCommand({ trigger: "test_convo", scope: "private", description: "Test conversation", diff --git a/src/commands/test/format.ts b/src/commands/test/format.ts index ceca6a8..a6ede29 100644 --- a/src/commands/test/format.ts +++ b/src/commands/test/format.ts @@ -2,7 +2,7 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -export const testformat = new CommandsCollection().createCommand({ +export const testformat = new CommandsCollection().createCommand({ trigger: "test_format", scope: "private", description: "Test the formatting", diff --git a/src/commands/test/index.ts b/src/commands/test/index.ts index ef2133a..f07daac 100644 --- a/src/commands/test/index.ts +++ b/src/commands/test/index.ts @@ -5,7 +5,7 @@ import { testconvo } from "./conversation" import { testformat } from "./format" import { testmenu } from "./menu" -export const test = new CommandsCollection("Test").withCollection( +export const test = new CommandsCollection("Test").withCollection( testargs, testformat, testmenu, diff --git a/src/commands/test/menu.ts b/src/commands/test/menu.ts index 99f80a6..680f8bb 100644 --- a/src/commands/test/menu.ts +++ b/src/commands/test/menu.ts @@ -35,7 +35,7 @@ const generateMenu = MenuGenerator.getInstance().create<{ ], ]) -export const testmenu = new CommandsCollection().createCommand({ +export const testmenu = new CommandsCollection().createCommand({ trigger: "testmenu", scope: "private", description: "Quick conversation", diff --git a/src/lib/managed-commands/collection.ts b/src/lib/managed-commands/collection.ts index f027ef6..f9d5fbc 100644 --- a/src/lib/managed-commands/collection.ts +++ b/src/lib/managed-commands/collection.ts @@ -9,9 +9,9 @@ import type { DefaultAccessControl, } from "./command" -export class CommandsCollection { +export class CommandsCollection { private flushed = false - private commands: AnyCommand[] = [] + private commands: AnyCommand[] = [] constructor(public name?: string) {} @@ -21,8 +21,8 @@ export class CommandsCollection( - cmd: Command - ): CommandsCollection { + cmd: Command + ): CommandsCollection { if (this.flushed) { throw new Error("Cannot add commands after the collection has been flushed") } @@ -30,7 +30,7 @@ export class CommandsCollection[]): CommandsCollection { + withCollection(...collections: CommandsCollection[]): CommandsCollection { if (this.flushed) { throw new Error("Cannot add commands after the collection has been flushed") } @@ -38,7 +38,7 @@ export class CommandsCollection[] { + flush(): AnyCommand[] { if (this.flushed) { throw new Error("The collection has already been flushed") } diff --git a/src/lib/managed-commands/command.ts b/src/lib/managed-commands/command.ts index be7da82..933d702 100644 --- a/src/lib/managed-commands/command.ts +++ b/src/lib/managed-commands/command.ts @@ -46,10 +46,9 @@ export type CommandScope = "private" | "group" | "both" /** * The outcome of the built-in permission check. When allowed, `via` tells what let the user through: * - `group_admin`: the group admin shortcut (`allowGroupAdmins`) - * - `role`: one of the `allowedRoles` - * - `unrestricted`: no role was required + * - `unrestricted`: the built-in check found nothing to restrict */ -export type PermissionCheck = { allowed: false } | { allowed: true; via: "group_admin" | "role" | "unrestricted" } +export type PermissionCheck = { allowed: false } | { allowed: true; via: "group_admin" | "unrestricted" } /** * Extends the built-in permission check with application-defined access control. @@ -61,21 +60,16 @@ export interface AccessControl { authorization: { allowed: boolean } } -/** No extension: commands declare roles only and handlers receive the built-in {@link PermissionCheck}. */ +/** No extension: handlers receive the built-in {@link PermissionCheck}. */ export interface DefaultAccessControl extends AccessControl { permissions: Record authorization: PermissionCheck } -interface PrivatePermissions { - /** The roles that are allowed to use the command */ - allowedRoles?: TRole[] - /** The roles that are excluded from using the command */ - excludedRoles?: TRole[] -} -interface GroupPermissions extends PrivatePermissions { +type PrivatePermissions = Record +interface GroupPermissions { /** - * Whether to allow group admins to use the command, without considering their external role + * Whether to allow group admins to use the command, without considering their other permissions * * You can use hooks to override what is considered a group admin, by default it considers users with * Telegram Chat Role of "administrator" or "creator" as group admins @@ -86,9 +80,9 @@ interface GroupPermissions extends PrivatePermissions = (S extends "private" - ? PrivatePermissions - : GroupPermissions) & +type Permissions = (S extends "private" + ? PrivatePermissions + : GroupPermissions) & TAccess["permissions"] export type CommandScopedContext< @@ -111,14 +105,12 @@ export type CommandConversation { @@ -138,11 +130,11 @@ export interface Command< */ args?: A /** - * The permissions required to use the command, you can either allow or exclude specific roles. + * The permissions required to use the command, as defined by the application's {@link AccessControl}. * * If the command is allowed in groups, you can also allow or exclude specific group IDs and whether or not to consider permissions for group admins. */ - permissions?: Permissions + permissions?: Permissions /** * The type of reply that the command accepts, can be "required", "optional" or undefined. * If the command accepts a reply, it will be available in the handler as `repliedTo`. @@ -192,11 +184,13 @@ export interface Command< /** * A generic command */ -export type AnyCommand< - TRole extends string = string, - C extends Context = Context, - TAccess extends AccessControl = DefaultAccessControl, -> = Command +export type AnyCommand = Command< + CommandArgs, + CommandReplyTo, + CommandScope, + C, + TAccess +> /** * Type guard to check if a command is allowed in groups. @@ -219,10 +213,9 @@ export type AnyCommand< export function isAllowedInGroups< A extends CommandArgs, R extends CommandReplyTo, - TRole extends string = string, C extends Context = Context, TAccess extends AccessControl = DefaultAccessControl, ->(cmd: Command): cmd is Command { +>(cmd: Command): cmd is Command { return cmd.scope !== "private" } @@ -247,9 +240,8 @@ export function isAllowedInGroups< export function isAllowedInPrivateOnly< A extends CommandArgs, R extends CommandReplyTo, - TRole extends string = string, C extends Context = Context, TAccess extends AccessControl = DefaultAccessControl, ->(cmd: Command): cmd is Command { +>(cmd: Command): cmd is Command { return cmd.scope === "private" } diff --git a/src/lib/managed-commands/index.ts b/src/lib/managed-commands/index.ts index a7d2c0e..cf43a94 100644 --- a/src/lib/managed-commands/index.ts +++ b/src/lib/managed-commands/index.ts @@ -35,55 +35,44 @@ import type { import { isAllowedInGroups, isTypedArgumentOptions } from "./command" import type { ManagedCommandsFlavor } from "./context" -export type Hook< - C extends Context, - TRole extends string = string, - Params = unknown, - TAccess extends AccessControl = DefaultAccessControl, -> = ( +export type Hook = ( params: Params & { context: CommandContext - command: AnyCommand + command: AnyCommand } ) => Promise -export type InternalHook< - C extends Context, - TRole extends string = string, - Params = unknown, - TAccess extends AccessControl = DefaultAccessControl, -> = ( +export type InternalHook = ( params: Params & { context: CommandContext - command: AnyCommand + command: AnyCommand conversation: CommandConversation } ) => Promise | void export type ManagedCommandsHooks< OC extends Context, C extends Context, - TRole extends string = string, TAccess extends AccessControl = DefaultAccessControl, > = { /** * Called when a command is invoked in the wrong scope (e.g. a private-only command is invoked in a group) */ - wrongScope?: Hook + wrongScope?: Hook /** * Called when a user without the required permissions invokes a command */ - missingPermissions?: Hook + missingPermissions?: Hook /** * Called before executing the command handler, can be used to implement custom pre-handler logic, for example logging or analytics */ - conversationBegin?: InternalHook + conversationBegin?: InternalHook /** * Called when an error is thrown in the command handler */ - handlerError?: InternalHook + handlerError?: InternalHook /** * Called after executing the command handler, can be used to implement custom post-handler logic, for example logging or analytics */ - conversationEnd?: InternalHook + conversationEnd?: InternalHook /** * A function to override what counts as a "Group Admin", by default it considers users with Telegram Chat Role of * "administrator" or "creator" as group admins, but you can override this to implement your own logic, @@ -94,37 +83,32 @@ export type ManagedCommandsHooks< * 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 */ - commandMiddlewareStart?: Hook + commandMiddlewareStart?: Hook /** * Called when a command is invoked, after the conversation has entered and the first update is fully processed * (i.e after `await ctx.conversation.enter()` returns) */ - commandMiddlewareEnd?: Hook + commandMiddlewareEnd?: Hook } -export type Authorize< - OC extends Context, - TRole extends string = string, - TAccess extends AccessControl = DefaultAccessControl, -> = (params: { +export type Authorize = (params: { context: CommandContext - command: AnyCommand - /** The built-in role and group admin check, see {@link IManagedCommandsOptions.getUserRoles} */ + command: AnyCommand + /** The built-in group admin and group ID check */ check: () => Promise }) => Promise -type AuthorizeOptions = { +type AuthorizeOptions = { /** * Decides whether the user may run a command, its result is passed to the handler as `authorization`. - * Defaults to the built-in role and group admin check, which it receives as `check`. + * Defaults to the built-in group admin check, which it receives as `check`. * * Required when {@link AccessControl} is extended, to read the additional `permissions` and build the `authorization`. */ - authorize: Authorize + authorize: Authorize } export interface IManagedCommandsOptions< - TRole extends string, OC extends Context, C extends Context, TAccess extends AccessControl = DefaultAccessControl, @@ -137,29 +121,6 @@ export interface IManagedCommandsOptions< */ adapter: ConversationStorage - /** - * A function to get externally defined roles for a specific user. - * - * @example - * ```ts - * const commands = new ManagedCommands({ - * getUserRoles: async (userId, context) => { - * const roles = await db.getUserRoles(userId) // Array<"admin" | "user">[] - * return roles - * }, - * }).createCommand({ - * trigger: "admincmd", - * permissions: { - * allowedRoles: ["admin"], - * }, - * handler: async ({ context }) => { - * await context.reply("You are an admin!") - * }), - * }) - * ``` - */ - getUserRoles: (userId: number, context: CommandContext) => Promise - /** * Additional plugins to apply to the conversation inner composer. */ @@ -168,20 +129,15 @@ export interface IManagedCommandsOptions< /** * Hooks to execute on specific events */ - hooks: ManagedCommandsHooks + hooks: ManagedCommandsHooks } export type ManagedCommandsOptions< - TRole extends string, OC extends Context, C extends Context, TAccess extends AccessControl = DefaultAccessControl, -> = (string extends TRole - ? Omit, "getUserRoles"> & { getUserRoles?: never } - : IManagedCommandsOptions) & - (DefaultAccessControl extends TAccess - ? Partial> - : AuthorizeOptions) +> = IManagedCommandsOptions & + (DefaultAccessControl extends TAccess ? Partial> : AuthorizeOptions) /** * A class to manage commands in a grammY bot, with support for argument parsing, permission handling, and hooks for various events. @@ -202,23 +158,20 @@ export type ManagedCommandsOptions< * bot.use(commands) * ``` * - * @typeParam TRole A string type representing the possible roles for command permissions. This is used in the `permissions` field of the command options and in the `permissionHandler`. * @typeParam C The context type for the bot, used in the hooks and permission handler. Defaults to `Context`. * @typeParam TAccess The application-defined access control, see {@link AccessControl} * @see Command for the options available when creating a command */ export class ManagedCommands< - TRole extends string = string, OC extends ManagedCommandsFlavor = ManagedCommandsFlavor, C extends CommandScopedContext = CommandScopedContext, TAccess extends AccessControl = DefaultAccessControl, > implements MiddlewareObj { private composer = new Composer() - private commands: Record[]> = {} - private getUserRoles: (userId: number, context: CommandContext) => Promise - private authorize: Authorize - private hooks: ManagedCommandsHooks + private commands: Record[]> = {} + private authorize: Authorize + private hooks: ManagedCommandsHooks private adapter: ConversationStorage private registeredTriggers = new Set() @@ -230,7 +183,7 @@ export class ManagedCommands< */ private static parseReplyTo( msg: Message, - cmd: Command + cmd: Command ): Result, string> { if (cmd.reply === "required" && !msg.reply_to_message) { return err("This command requires a reply") @@ -271,7 +224,7 @@ export class ManagedCommands< */ private static parseArgs( msgText: string, - cmd: Command + cmd: Command ): Result { const args: ArgumentMap = {} if (!cmd.args || cmd.args.length === 0) return ok(args) @@ -296,7 +249,7 @@ export class ManagedCommands< */ private static parseCommand( msg: Message, - cmd: Command + cmd: Command ): Result<{ args: ArgumentMap; repliedTo: RepliedTo }, string[]> { const text = msg.text ?? msg.caption if (!text) return err(["Cannot parse arguments"]) @@ -316,7 +269,7 @@ export class ManagedCommands< * @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 { + 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" @@ -334,7 +287,7 @@ export class ManagedCommands< ]) } - private static formatCommandShort(cmd: AnyCommand): string { + 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(" | "), @@ -348,7 +301,7 @@ export class ManagedCommands< * @param cmd The command * @returns a unique ID for the command based on its trigger(s) */ - public static commandID(cmd: AnyCommand) { + public static commandID(cmd: AnyCommand) { // only available characters in command triggers are a-z, 0-9 and _ // https://core.telegram.org/bots/features#commands return typeof cmd.trigger === "string" ? cmd.trigger : cmd.trigger.join("-") @@ -370,39 +323,11 @@ export class ManagedCommands< * bot.use(commands) * ``` * - * @param TRole You can pass a custom role type that extends string, for example: - * @example - * ```ts - * type MyRole = "cool" | "not_cool" - * const commands = new ManagedCommands({ - * permissionHandler: async ({ command, context }) => { - * const { allowedRoles, excludedRoles } = command.permissions - * if (allowedRoles && !allowedRoles.includes("cool")) return false - * return true - * }, - * }) - * - * commands.createCommand({ - * trigger: "ping", - * description: "Replies with pong", - * permissions: { - * allowedRoles: ["cool"], - * excludedRoles: ["not_cool"], - * }, - * handler: async ({ context }) => { - * await context.reply("pong") - * }, - * }) - * - * bot.use(commands) - * ``` - * * @param options The options to use for the ManagedCommands instance */ - constructor(options?: ManagedCommandsOptions) { - this.getUserRoles = options?.getUserRoles ?? (async () => []) + constructor(options?: ManagedCommandsOptions) { // without an `authorize` option, TAccess is the default and its authorization is the PermissionCheck - this.authorize = options?.authorize ?? ((({ check }) => check()) as Authorize) + this.authorize = options?.authorize ?? ((({ check }) => check()) as Authorize) this.hooks = options?.hooks ?? {} this.adapter = options?.adapter ?? new MemorySessionStorage() @@ -457,7 +382,7 @@ export class ManagedCommands< } public getCommands() { - const cmds: AnyCommand[] = [] + const cmds: AnyCommand[] = [] for (const collection in this.commands) { cmds.push(...this.commands[collection]) } @@ -466,7 +391,7 @@ export class ManagedCommands< /** Group allow/deny lists: where a command may run, whoever runs it. */ private static isAllowedInChat( - command: AnyCommand, + command: AnyCommand, ctx: CommandContext ): boolean { if (!command.permissions || !isAllowedInGroups(command)) return true @@ -477,16 +402,14 @@ export class ManagedCommands< return true } - /** The built-in role and group admin check */ + /** The built-in group admin check */ private async checkPermissions( - command: AnyCommand, + command: AnyCommand, ctx: CommandContext ): Promise { if (!command.permissions) return { allowed: true, via: "unrestricted" } if (!ctx.from) return { allowed: false } - const { allowedRoles, excludedRoles } = command.permissions - if (isAllowedInGroups(command) && (ctx.chat.type === "group" || ctx.chat.type === "supergroup")) { if (command.permissions.allowGroupAdmins) { if (this.hooks.overrideGroupAdminCheck) { @@ -499,14 +422,7 @@ export class ManagedCommands< } } - if (!allowedRoles && !excludedRoles) return { allowed: true, via: "unrestricted" } - const roles = await this.getUserRoles(ctx.from.id, ctx) - - // blacklist is stronger than whitelist - if (allowedRoles?.every((r) => !roles.includes(r))) return { allowed: false } - if (excludedRoles?.some((r) => roles.includes(r))) return { allowed: false } - - return { allowed: true, via: allowedRoles ? "role" : "unrestricted" } + return { allowed: true, via: "unrestricted" } } /** @@ -515,7 +431,7 @@ export class ManagedCommands< * @returns The ManagedCommands instance for chaining */ createCommand( - cmd: Command, + cmd: Command, collection: string = "default" ): this { const triggers = Array.isArray(cmd.trigger) ? cmd.trigger : [cmd.trigger] @@ -545,7 +461,7 @@ export class ManagedCommands< repliedTo: RepliedTo, authorization: TAccess["authorization"] ) => { - const hookParams: Parameters>[0] = { + const hookParams: Parameters>[0] = { context: ctx as CommandContext, command: cmd, // We cast the conversation type to unknown cause hooks cannot be aware of the scope of the specific command @@ -656,7 +572,7 @@ export class ManagedCommands< * bot.use(commands) * ``` */ - withCollection(...collections: CommandsCollection[]): this { + withCollection(...collections: CommandsCollection[]): this { collections.forEach((c) => { c.flush().forEach((cmd) => { this.createCommand(cmd, c.name)