From 31fdca64a1dde86dbd93a17f9971dd799479f602 Mon Sep 17 00:00:00 2001 From: Bianca Date: Wed, 21 Oct 2026 20:18:16 +0200 Subject: [PATCH] refactor(telegram)!: drop legacy anonymous backend calls and shadow decisions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes RFC v3 Phase 4b step 4 and prepares the bot for Phase 5 (LEGACY_ANONYMOUS=deny). - Remove /addrole, /delrole, /link and /test_db. - Drop overrideGroupAdminCheck: per RFC §4 decision 5, tg_group_admins is replaced by the native Telegram admin shortcut (decision 2). - Remove the shadow/anonymous decision modes, IDP_DECISIONS and legacyBackend; every check applies the IdP decision. - The socket always authenticates with its token. BREAKING CHANGE: IDP_PUBLIC_URL, OAUTH_BACKEND_RESOURCE_URI, OAUTH_BOT_CLIENT_ID and OAUTH_BOT_PRIVATE_JWK are required; IDP_DECISIONS is removed. Deploy before setting backend LEGACY_ANONYMOUS=deny. --- .env.example | 13 +- README.md | 54 +++--- docs/idp-phase4b-handoff.md | 6 + src/access/decision.ts | 52 ------ src/access/index.ts | 60 ++----- src/backend.ts | 35 ++-- src/commands/access.ts | 30 +--- src/commands/index.ts | 19 +-- src/commands/invite.ts | 3 +- src/commands/link-admin-dashboard.ts | 115 ------------- src/commands/management/audit.ts | 13 +- src/commands/management/groups.ts | 5 +- src/commands/management/index.ts | 3 +- src/commands/management/role.ts | 154 ++++-------------- src/commands/management/userid.ts | 3 +- src/commands/moderation/ban.ts | 13 +- src/commands/moderation/banall.ts | 6 +- src/commands/moderation/del.ts | 5 +- src/commands/moderation/index.ts | 3 +- src/commands/moderation/kick.ts | 6 +- src/commands/moderation/mute.ts | 13 +- src/commands/pin.ts | 7 +- src/commands/report.ts | 3 +- src/commands/search.ts | 3 +- src/commands/test/args.ts | 3 +- src/commands/test/conversation.ts | 3 +- src/commands/test/db.ts | 25 --- src/commands/test/format.ts | 3 +- src/commands/test/index.ts | 5 +- src/commands/test/menu.ts | 3 +- src/env.ts | 17 +- src/idp/config.ts | 36 ++-- src/lib/group-management/index.ts | 11 +- src/lib/managed-commands/command.ts | 2 +- .../campaign-spam/authorization.ts | 6 - src/middlewares/campaign-spam/index.ts | 20 +-- src/middlewares/campaign-spam/review.ts | 5 +- src/middlewares/group-specific-actions.ts | 21 +-- src/middlewares/message-trust.ts | 26 +-- src/modules/audit/index.ts | 36 ++-- src/modules/moderation/ban-all-immunity.ts | 17 +- src/modules/moderation/ban-all.ts | 5 +- src/modules/tg-logger/grants.ts | 48 ++---- src/modules/tg-logger/index.ts | 2 +- src/modules/tg-logger/report.ts | 6 +- src/modules/websocket.ts | 10 +- src/utils/types.ts | 3 +- tests/ban-all-audit.test.ts | 22 --- tests/ban-all-immunity.test.ts | 48 ++---- tests/campaign-spam-authorization.test.ts | 12 -- tests/campaign-spam-guard.test.ts | 7 +- tests/idp-decisions.test.ts | 83 +++------- tests/idp-fetch.test.ts | 11 +- tests/tg-logger-resilience.test.ts | 6 + 54 files changed, 239 insertions(+), 887 deletions(-) delete mode 100644 src/commands/link-admin-dashboard.ts delete mode 100644 src/commands/test/db.ts delete mode 100644 src/middlewares/campaign-spam/authorization.ts delete mode 100644 tests/campaign-spam-authorization.test.ts diff --git a/.env.example b/.env.example index 6b23b8c..cb84f37 100644 --- a/.env.example +++ b/.env.example @@ -8,14 +8,11 @@ BACKEND_URL=localhost:3000 # INFLUXDB_TOKEN=your influxdb token goes here # INFLUXDB_URL=http://localhost:8086 -# Phase 4b: set all four required values to authenticate the bot. With all absent, -# requests stay anonymous. Partial configuration is a startup error. -# IDP_PUBLIC_URL=https://auth.polinetwork.org +# PoliNetwork IdP (required): the bot calls the backend only with its service token. +IDP_PUBLIC_URL=https://auth.polinetwork.org # Optional transport URL inside the cluster; issuer/audience still use the public URL. # IDP_INTERNAL_URL=http://auth:3000 -# OAUTH_BACKEND_RESOURCE_URI=https://backend.internal.polinetwork.org -# OAUTH_BOT_CLIENT_ID= +OAUTH_BACKEND_RESOURCE_URI=https://backend.internal.polinetwork.org +OAUTH_BOT_CLIENT_ID=#registered telegram-bot client ID # Private JWK JSON, with kid/alg/d; inject from the bot's Key Vault secret. -# OAUTH_BOT_PRIVATE_JWK= -# Defaults to shadow: keep legacy decisions and log IdP differences. -IDP_DECISIONS=shadow +OAUTH_BOT_PRIVATE_JWK=#private JWK JSON diff --git a/README.md b/README.md index 2785494..fee4410 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ first-post classifications with reasons and cross-chat counts, join decisions an review delivery, local bans, network BanAll starts, moderator decisions, and dependency failures. Identifiers let operators correlate actions without logging raw message text, contact details, or the fingerprint secret. -## IdP migration (Phase 4b) +## IdP authorization The bot uses `@polinetwork/auth-kit` to obtain a cached `client_credentials` token with `private_key_jwt`. Register a separate `telegram-bot` client in the IdP and link it to the backend @@ -90,11 +90,11 @@ resource. Its scopes are `backend:tg:read`, `backend:tg:ingest`, `backend:tg:gro inject the private JWK from the bot's Key Vault as `OAUTH_BOT_PRIVATE_JWK` (JSON with `kid`, `alg` and private key material). Never put the key in the repository or logs. -Set `IDP_PUBLIC_URL`, `OAUTH_BACKEND_RESOURCE_URI`, `OAUTH_BOT_CLIENT_ID` and -`OAUTH_BOT_PRIVATE_JWK` together. `IDP_INTERNAL_URL` optionally routes token requests inside the -cluster; assertion audiences retain the public token URL. An entirely absent configuration -keeps anonymous calls. A partial configuration fails startup. `BACKEND_URL` continues to be a -host and port, without a URL scheme, matching the existing backend transport. +`IDP_PUBLIC_URL`, `OAUTH_BACKEND_RESOURCE_URI`, `OAUTH_BOT_CLIENT_ID` and +`OAUTH_BOT_PRIVATE_JWK` are required; startup fails without them. The bot never calls the backend +anonymously. `IDP_INTERNAL_URL` optionally routes token requests inside the cluster; assertion +audiences retain the public token URL. `BACKEND_URL` continues to be a host and port, without a URL +scheme, matching the existing backend transport. Each human update gets an isolated actor client (`ctx.backend`, `X-PN-Actor: telegram:`). Service-only operations, including buffered message/user ingestion, group synchronization, @@ -105,29 +105,18 @@ persist a tRPC client. A batch belongs to one client and cannot mix actors. Back fall back to anonymous transport. The socket authenticates with `auth.token`; a server expiry disconnect triggers reconnect, and rejected handshakes invalidate the token with retry backoff. -`IDP_DECISIONS=shadow` is the default. It computes both checks, logs `[ACCESS] shadow` differences, -and acts exclusively on the original role decision. Legacy roles and group administrators are -read anonymously; grant interruption also stays on the anonymous legacy path with -`interruptedById`. `/audit` uses the service read path during shadow, so the backend's actor -permission check cannot override the legacy command decision. The backend must keep -`LEGACY_ANONYMOUS=allow` throughout shadow. Grants are read through the backend's migration -helper, which includes active grants from both tables. An IdP lookup failure is logged and never -changes a successful shadow decision. - -After comparing differences for roughly a week and reconciling roles and Telegram links, set -`IDP_DECISIONS=enforce` to apply IdP permissions. An unavailable actor check denies actions; -native chat administrators retain the documented chat-local shortcut. Immunity applies to every +Commands, callback menus and target checks act on the IdP permissions resolved through +`tg.access.resolve` (RFC v3 §10.2). An unavailable actor check denies actions; native chat +administrators (Telegram status `administrator` or `creator`) retain the documented chat-local +shortcut, which replaces the removed `tg_group_admins` table. Immunity (`tg:immune`) applies to every ban-all entry point at enqueue; jobs already accepted continue without permission rechecks. -`/getroles` lists the legacy roles until enforcement, then the IdP permissions. `/addrole`, -`/delrole`, `/link` and the unregistered test commands remain in this transitional source tree; -remove them and the legacy role/group-admin checks in the coordinated cleanup before setting -`LEGACY_ANONYMOUS=deny`. -Switching the mode alone does not remove those legacy commands. +`/getroles` lists the IdP permissions. Roles are managed in the IdP, so the bot no longer has +`/addrole`, `/delrole` or `/link`. Moderation audit records use `tg.auditLog.record` and a Redis outbox with stable idempotency keys, actor IDs and the basis (`idp_permission`, `telegram_chat_admin`, `automatic`, `telegram_ui`). -Automatic actions have no human actor. During shadow, a legacy role pass uses the permission -path basis; the backend flags cases where the snapshot does not back that claim for review. +Automatic actions have no human actor; the backend flags `idp_permission` records that the +snapshot does not back for review. Redis hashes and a due-time sorted set are changed atomically. Backend outages retry with capped exponential backoff; permanent input errors move to `audit-outbox:dead` for inspection. Enable Redis AOF, use persistent storage and a non-evicting policy for the audit data. Shutdown keeps @@ -135,18 +124,17 @@ Redis alive until the runner, buffered storage and module workers stop. If Redis record, the bot attempts direct delivery; if both systems fail the full record is logged as lost. This fallback is best effort: durability requires functioning persistent Redis, and a crash between a Telegram action and its outbox write can still lose that action's audit record. Ban-all -token-authenticated flow creation persists audit recovery data atomically with the job. Audit delivery starts only +flow creation persists audit recovery data atomically with the job. Audit delivery starts only after a confirmed insertion; caller retries and the resumed orchestrator deliver the same key, so a crash in between is recovered without duplicate history. Older jobs without this recovery -data keep their original behavior. Anonymous flows record once and do not replay because the -legacy audit endpoint has no idempotency support. +data keep their original behavior. Grant socket messages accept both the legacy `adminId` and the new `{ sub, telegramId, displayName }` actor. A dashboard user without a linked Telegram account can therefore be shown by display name in the grants topic. -Deploy the Phase 3 backend API/SDK before enabling these variables. Validate token acquisition, -service-only ingestion, actor isolation, socket expiry/reconnect, audit retry/deduplication and -shadow differences in a test environment. Unit tests do not verify real IdP, Telegram or Key -Vault connectivity. Roll back the bot image/configuration while keeping backend anonymous -compatibility enabled; keep Redis persistence so pending audits survive a rollback/restart. +Validate token acquisition, service-only ingestion, actor isolation, socket expiry/reconnect and +audit retry/deduplication in a test environment. Unit tests do not verify real IdP, Telegram or Key +Vault connectivity. Keep Redis persistence so pending audits survive a rollback/restart. Bot images +from before this cleanup still call the backend anonymously; rolling back to one needs the +backend's `LEGACY_ANONYMOUS=allow`. diff --git a/docs/idp-phase4b-handoff.md b/docs/idp-phase4b-handoff.md index 233a776..1bf1dea 100644 --- a/docs/idp-phase4b-handoff.md +++ b/docs/idp-phase4b-handoff.md @@ -1,5 +1,11 @@ # Phase 4b Telegram handoff +> **Superseded by the Phase 5 bot cleanup.** Cutover step 7 is done: `/addrole`, `/delrole`, +> `/link`, `/test_db`, the shadow mode and every anonymous backend call are removed, so +> `IDP_DECISIONS` no longer exists and the IdP variables are required. The bot always applies IdP +> decisions; native chat admins replace `tg_group_admins`. This document is kept as the +> record of Phase 4b; see the README for the current behaviour. + Branch: `feat/idp-phase4b-bot`. The working tree contains the completed local implementation; no commit, staging, push, PR or deployment was performed during continuation. diff --git a/src/access/decision.ts b/src/access/decision.ts index b0c8598..87fb25c 100644 --- a/src/access/decision.ts +++ b/src/access/decision.ts @@ -1,13 +1,5 @@ -import type { Logger } from "pino" import { PERMISSION, type Permission } from "./catalog" -/** - * - `anonymous`: the IdP is not configured; only the legacy role checks exist. - * - `shadow`: both checks run, the legacy one is applied and differences are logged (RFC v3 §13). - * - `enforce`: the IdP decision is applied. - */ -export type DecisionMode = "anonymous" | "shadow" | "enforce" - /** A Telegram user as `tg.access.resolve` describes them. */ export type AccessEntry = { sub: string | null @@ -55,47 +47,3 @@ export async function idpDecision(options: { if (failure) throw failure.error return DENIED } - -export type DecideOptions = { - mode: DecisionMode - /** Names the check in logs, e.g. `command:/ban`. */ - check: string - /** Telegram IDs that identify the case in logs. Nothing else about the people is logged. */ - ids: Record - legacy: () => Promise - idp: () => Promise - /** Whether two outcomes are the same decision. Default: `Object.is`. */ - same?: (legacy: T, idp: T) => boolean - logger: Pick -} - -export const sameAllowed = (a: Decision, b: Decision) => a.allowed === b.allowed - -/** - * Runs the check the mode calls for. In shadow mode both run, the legacy outcome is returned (or - * its error thrown) and any difference is logged; the IdP outcome is never acted on, and never - * combined with the legacy one. - */ -export async function decide(options: DecideOptions): Promise { - if (options.mode === "anonymous") return options.legacy() - if (options.mode === "enforce") return options.idp() - - const [legacy, idp] = await Promise.allSettled([options.legacy(), options.idp()]) - const context = { check: options.check, ...options.ids } - const legacyOutcome = legacy.status === "fulfilled" ? legacy.value : "error" - if (idp.status === "rejected") { - options.logger.warn( - { ...context, legacy: legacyOutcome, idpError: errorMessage(idp.reason) }, - "[ACCESS] shadow: IdP decision unavailable" - ) - } else if (legacy.status === "rejected" || !(options.same ?? Object.is)(legacy.value, idp.value)) { - options.logger.warn({ ...context, legacy: legacyOutcome, idp: idp.value }, "[ACCESS] shadow: decisions differ") - } - - if (legacy.status === "rejected") throw legacy.reason - return legacy.value -} - -function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error) -} diff --git a/src/access/index.ts b/src/access/index.ts index 00271f1..34c9482 100644 --- a/src/access/index.ts +++ b/src/access/index.ts @@ -1,29 +1,11 @@ -import { type Backend, idpConfig, legacyBackend } from "@/backend" -import { env } from "@/env" +import type { Backend } from "@/backend" import { logger } from "@/logger" -import type { Role } from "@/utils/types" import type { Permission } from "./catalog" -import { - type AccessEntry, - DENIED, - type DecideOptions, - type Decision, - type DecisionMode, - decide, - idpDecision, - NO_ACCESS, - sameAllowed, -} from "./decision" +import { type AccessEntry, DENIED, type Decision, idpDecision, NO_ACCESS } from "./decision" export { PERMISSION, type Permission } from "./catalog" export * from "./decision" -if (!idpConfig && env.IDP_DECISIONS === "enforce") - throw new Error("IDP_DECISIONS=enforce needs the IdP configuration (IDP_PUBLIC_URL, OAUTH_BOT_*)") - -/** How the bot decides who may do what (RFC v3 §13 Phase 4). */ -export const decisionMode: DecisionMode = idpConfig ? env.IDP_DECISIONS : "anonymous" - /** IdP access of Telegram users, from the backend's snapshot. Unlinked users hold nothing. */ export async function resolveAccess(backend: Backend, telegramIds: number[]): Promise> { const resolved = await backend.tg.access.resolve.query({ telegramIds }) @@ -39,14 +21,9 @@ export async function resolveOne(backend: Backend, telegramId: number): Promise< return (await resolveAccess(backend, [telegramId])).get(telegramId) ?? NO_ACCESS } -/** {@link decide} in the configured mode. */ -export function decideAccess(options: Omit, "mode" | "logger">): Promise { - return decide({ ...options, mode: decisionMode, logger }) -} - /** - * Whether a person may run a command or press a button (RFC v3 §10.2), in the configured mode. - * Once IdP decisions apply, an unavailable decision denies; legacy failures surface as before. + * Whether a person may run a command or press a button (RFC v3 §10.2). An unavailable decision + * denies. */ export async function authorizeAction(options: { check: string @@ -57,31 +34,14 @@ 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 - legacy: () => Promise }): Promise { - return decideAccess({ - check: options.check, - ids: { actorId: options.actorId, chatId: options.chatId }, - legacy: options.legacy, - idp: () => - idpDecision({ - required: options.required, - actor: () => resolveOne(options.backend, options.actorId), - isChatAdmin: options.isChatAdmin, - }), - same: sameAllowed, + return idpDecision({ + required: options.required, + actor: () => resolveOne(options.backend, options.actorId), + isChatAdmin: options.isChatAdmin, }).catch((error: unknown) => { - if (decisionMode !== "enforce") throw error - logger.error({ error, check: options.check, actorId: options.actorId }, "[ACCESS] IdP decision unavailable, denied") + const { check, actorId, chatId } = options + logger.error({ error, check, actorId, chatId }, "[ACCESS] IdP decision unavailable, denied") return DENIED }) } - -/** - * Roles from the legacy `tg_permissions` table. Used only by the legacy side of a decision and the - * legacy role commands; goes away with the switch to IdP decisions. - */ -export async function legacyRoles(userId: number): Promise { - const { roles } = await legacyBackend.tg.permissions.getRoles.query({ userId }) - return roles ?? [] -} diff --git a/src/backend.ts b/src/backend.ts index 9abee69..9335197 100644 --- a/src/backend.ts +++ b/src/backend.ts @@ -17,25 +17,20 @@ export type Backend = TRPCClient export type ApiOutput = inferRouterOutputs export type ApiInput = inferRouterInputs -/** The bot's IdP client configuration; null while it still calls the backend anonymously. */ -export const idpConfig = parseIdpConfig(env) - /** The `telegram-bot` service token (RFC v3 §10.1), cached and renewed at half its lifetime. */ -export const serviceTokens: TokenSource | null = idpConfig - ? serviceTokenSource({ - ...idpConfig, - onError: (error) => logger.warn({ error }, "[IDP] service token renewal failed, using the cached token"), - }) - : null +export const serviceTokens: TokenSource = serviceTokenSource({ + ...parseIdpConfig(env), + onError: (error) => logger.warn({ error }, "[IDP] service token renewal failed, using the cached token"), +}) -function createBackendClient(tokens: TokenSource | null, actorTelegramId: number | null = null): Backend { +function createBackendClient(tokens: TokenSource, actorTelegramId: number | null = null): Backend { return createTRPCClient({ links: [ trpcTelemetryLink, httpBatchLink({ url, transformer: SuperJSON, - fetch: tokens ? authenticatedFetch(tokens, actorTelegramId) : undefined, + fetch: authenticatedFetch(tokens, actorTelegramId), }), ], }) @@ -43,24 +38,17 @@ function createBackendClient(tokens: TokenSource | null, actorTelegramId: number /** * Acts as the bot itself: background work (storage flush, ban-all, cron, startup) and every lookup - * the backend grants only to the service (RFC v3 §8.1). Anonymous when the IdP is not configured. + * the backend grants only to the service (RFC v3 §8.1). */ export const serviceBackend: Backend = createBackendClient(serviceTokens) -/** - * Always anonymous. Only for the procedures the RFC removes and the backend refuses to token - * callers (`tg.permissions.*`, `tg.link.link`, `tg.auditLog.create`, `test.dbQuery`), which keep - * working while the backend allows legacy calls (RFC v3 §13). - */ -export const legacyBackend: Backend = serviceTokens ? createBackendClient(null) : serviceBackend - /** * Acts for a Telegram user through `X-PN-Actor` (RFC v3 §6.3). The backend accepts such an actor * only on `tg.access.resolve`, `tg.grants.interrupt` and `tg.auditLog.getById`, and checks the * person's IdP permissions there. */ export function backendAs(telegramId: number): Backend { - return serviceTokens ? createBackendClient(serviceTokens, telegramId) : serviceBackend + return createBackendClient(serviceTokens, telegramId) } /** One client per update: acting for its human sender, otherwise the service (RFC v3 §10.1). */ @@ -68,12 +56,11 @@ export function backendFor(from: User | undefined): Backend { return from && !from.is_bot ? backendAs(from.id) : serviceBackend } -/** Startup check; with a token it also proves the IdP issues one the backend accepts. */ +/** Startup check; it also proves the IdP issues a token the backend accepts. */ export async function backendHealthCheck(botId: number) { try { - if (serviceTokens) await serviceBackend.tg.access.resolve.query({ telegramIds: [botId] }) - else await legacyBackend.test.dbQuery.query({ dbName: "tg" }) - logger.info(`[BACKEND] connected${serviceTokens ? " with the IdP service token" : ""}`) + await serviceBackend.tg.access.resolve.query({ telegramIds: [botId] }) + logger.info("[BACKEND] connected with the IdP service token") } catch (err) { if (err instanceof TRPCClientError && err.message.startsWith("fetch failed")) logger.error(`[BACKEND] can't connect`) diff --git a/src/commands/access.ts b/src/commands/access.ts index 91c4d16..52eac64 100644 --- a/src/commands/access.ts +++ b/src/commands/access.ts @@ -1,10 +1,10 @@ import { authorizeAction, DENIED, type Decision, type Permission } from "@/access" import { backendFor } from "@/backend" -import { type Authorize, ManagedCommands, type PermissionCheck } from "@/lib/managed-commands" +import { type Authorize, ManagedCommands } from "@/lib/managed-commands" import { isFromGroupChat } from "@/utils/chat" -import type { Context, Role } from "@/utils/types" +import type { Context } from "@/utils/types" -/** How commands declare IdP permissions next to the legacy roles, and what their handlers receive. */ +/** How commands declare IdP permissions, and what their handlers receive. */ export type CommandAccess = { permissions: { /** The IdP permissions the user must all hold (RFC v3 §10.2) */ @@ -19,28 +19,11 @@ export type CommandAccess = { authorization: Decision } -/** - * The legacy role check as a decision. A pass through the group admin shortcut is reported as - * `telegram_chat_admin`, a pass through a listed role as `idp_permission` (the permission path). - */ -function legacyDecision(check: PermissionCheck): Decision { - if (!check.allowed) return DENIED - switch (check.via) { - case "group_admin": - return { allowed: true, basis: "telegram_chat_admin" } - case "role": - return { allowed: true, basis: "idp_permission" } - case "unrestricted": - return { allowed: true, basis: null } - } -} - -export const authorizeCommand: Authorize = async ({ context, command, check }) => { - const legacy = async () => legacyDecision(await check()) +export const authorizeCommand: Authorize = async ({ context, command }) => { const { permissions } = command - // Commands without IdP permissions (/addrole, /delrole) keep the legacy check until they are removed (RFC v3 §10.4). - if (!permissions?.requiredPermissions || !context.from) return legacy() + if (!permissions?.requiredPermissions?.length) return { allowed: true, basis: null } const from = context.from + if (!from) return DENIED return authorizeAction({ check: `command:/${ManagedCommands.commandID(command)}`, @@ -55,6 +38,5 @@ export const authorizeCommand: Authorize = async ( return status === "administrator" || status === "creator" } : undefined, - legacy, }) } diff --git a/src/commands/index.ts b/src/commands/index.ts index d5f3a9b..1a0d642 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,7 +1,5 @@ import type { ConversationData, VersionedState } from "@grammyjs/conversations" import { Point } from "@influxdata/influxdb-client" -import { legacyRoles } from "@/access" -import { legacyBackend } from "@/backend" import { type CommandScopedContext, ManagedCommands } from "@/lib/managed-commands" import { RedisFallbackAdapter } from "@/lib/redis-fallback-adapter" import { logger } from "@/logger" @@ -10,11 +8,10 @@ import type { TelemetryContextFlavor } from "@/modules/telemetry" import { redis } from "@/redis" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" -import type { Context, Role } from "@/utils/types" +import type { Context } from "@/utils/types" import { printCtxFrom } from "@/utils/users" import { authorizeCommand, type CommandAccess } from "./access" import { invite } from "./invite" -import { linkAdminDashboard } from "./link-admin-dashboard" import { management } from "./management" import { moderation } from "./moderation" import { pin } from "./pin" @@ -29,7 +26,7 @@ const adapter = new RedisFallbackAdapter>({ type ConversationContext = TelemetryContextFlavor -export const commands = new ManagedCommands({ +export const commands = new ManagedCommands({ adapter, plugins: [ (ctx, next) => { @@ -95,12 +92,6 @@ export const commands = new ManagedCommands { - const { status: groupRole } = await ctx.getChatMember(userId) - if (groupRole === "administrator" || groupRole === "creator") return true - const isDbAdmin = await legacyBackend.tg.permissions.checkGroup.query({ userId, groupId }) - return isDbAdmin - }, commandMiddlewareStart: async ({ context, command }) => { context.stackTimes = { managedCommands: Date.now() } context.point.tag("command", ManagedCommands.commandID(command)).tag("chat_type", context.chat.type) @@ -110,10 +101,6 @@ export const commands = new ManagedCommands { - // TODO: cache this to avoid hitting the db on every command - return await legacyRoles(userId) - }, authorize: authorizeCommand, }) .createCommand({ @@ -145,4 +132,4 @@ export const commands = new ManagedCommands().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/link-admin-dashboard.ts b/src/commands/link-admin-dashboard.ts deleted file mode 100644 index 467293b..0000000 --- a/src/commands/link-admin-dashboard.ts +++ /dev/null @@ -1,115 +0,0 @@ -import type { ConversationMenuContext } from "@grammyjs/conversations" -import { legacyBackend } from "@/backend" -import type { CommandAccess } from "@/commands/access" -import type { ConversationContext } from "@/lib/managed-commands" -import { CommandsCollection } from "@/lib/managed-commands" -import type { CommandConversation } from "@/lib/managed-commands/command" -import { logger } from "@/logger" -import { fmt } from "@/utils/format" -import { scheduleDelete } from "@/utils/messages" -import type { Role } from "@/utils/types" - -const mainMsg = fmt(({ b }) => [b`🔗 Admin dashboard link`, b`\nStatus: ⏳ WAITING FOR CODE`], { sep: "\n" }) - -const warnMsg = fmt( - ({ n, b, u }) => [ - b`🔗 Admin dashboard link`, - b`\n⚠️ ${u`WARN`}: Proceed ONLY if you started the Link from the Admin Dashboard intentionally.`, - b`\nWhat is this?`, - `This is the procedure to link your telegram account (id and username) to your account on PoliNetwork's Admin Dashboard.`, - `Once entered your username in the Admin Dashboard, it will give you a code; while you insert the code here, the link will be completed.`, - b`\nWhy is needed?`, - `For two reasons:`, - `1. It allows us to verify that you have sufficient permissions to use the dashboard`, - n`2. It allows you to perform ${b`Telegram actions`} from the Dashbord (like banning a user)`, - ], - { sep: "\n" } -) - -async function cancel( - conv: CommandConversation<"private">, - ctx: ConversationMenuContext> -) { - await ctx.editMessageText(fmt(({ n, code }) => n`Linking procedure was canceled. Send ${code`/link`} to restart it.`)) - ctx.menu.close() - await conv.halt() -} - -export const linkAdminDashboard = new CommandsCollection().createCommand({ - trigger: "link", - scope: "private", - description: "Verify the login code for the admin dashboard", - handler: async ({ context, conversation }) => { - // we need username - if (context.from.username === undefined) { - await context.reply(fmt(() => `You need to set a username to use this command`)) - return - } - - const cancelMenu = conversation.menu().text("Cancel", (ctx) => cancel(conversation, ctx)) - const warnMenu = conversation - .menu() - .text("Proceed", async (ctx) => { - await ctx.editMessageText(mainMsg, { reply_markup: cancelMenu }) - }) - .row() - .text("Cancel", (ctx) => cancel(conversation, ctx)) - - const msg = await context.reply(warnMsg, { reply_markup: warnMenu }) - let failed = false - let codeMsg = await conversation.waitFor("message:text") - while (!/^\d{6}$/.test(codeMsg.message.text)) { - await codeMsg.deleteMessage() - if (!failed) { - // first time invalid - await msg.editText( - fmt( - ({ b }) => [ - b`🔗 Admin dashboard link`, - b`\nStatus: ⭕️ Invalid Code (must be a 6-digit number), send again`, - ], - { sep: "\n" } - ), - { reply_markup: cancelMenu, parse_mode: "MarkdownV2" } - ) - failed = true - } - codeMsg = await conversation.waitFor("message:text") - } - - const code = codeMsg.message.text - await codeMsg.deleteMessage() - await msg.editText( - fmt(({ b }) => [b`🔗 Admin dashboard link`, b`\nStatus: 🔄 Verifying the code ${code}`], { sep: "\n" }), - { parse_mode: "MarkdownV2" } - ) - - const res = await legacyBackend.tg.link.link.query({ - code, - telegramId: context.from.id, - telegramUsername: context.from.username, - }) - if (res.error) { - logger.error(res.error) - - await msg.editText( - fmt( - ({ b }) => [ - b`🔗 Admin dashboard link`, - b`\nStatus: 🔴 Invalid code or username mismatch`, - `You need to send again the command to try again.`, - ], - { sep: "\n" } - ), - { parse_mode: "MarkdownV2" } - ) - } else if (res.success) { - await msg.editText( - fmt(({ b }) => [b`🔗 Admin dashboard link`, b`\nStatus: ✅ LINKED SUCCESSFULLY`], { sep: "\n" }), - { parse_mode: "MarkdownV2" } - ) - } - - void scheduleDelete(msg) - }, -}) diff --git a/src/commands/management/audit.ts b/src/commands/management/audit.ts index 0590b45..a9b8add 100644 --- a/src/commands/management/audit.ts +++ b/src/commands/management/audit.ts @@ -1,20 +1,17 @@ -import { decisionMode } from "@/access" import { PERMISSION } from "@/access/catalog" -import { backendAs, serviceBackend } from "@/backend" +import { backendAs } from "@/backend" import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt, fmtDate } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -import type { Role } from "@/utils/types" -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", args: [{ key: "username", optional: false, description: "Username or userid" }], permissions: { requiredPermissions: [PERMISSION.auditRead], - allowedRoles: ["hr", "owner", "direttivo"], }, handler: async ({ context, args }) => { let userId: number | null = parseInt(args.username, 10) @@ -27,10 +24,8 @@ export const audit = new CommandsCollection("Auditing").cre return } - // Once IdP decisions apply, the backend checks `tg:audit:read` for the actor as well. In shadow - // mode the legacy decision applies, so the bot reads as itself. - const backend = decisionMode === "enforce" ? backendAs(context.from.id) : serviceBackend - const list = await backend.tg.auditLog.getById.query({ targetId: userId }) + // The backend checks `tg:audit:read` for the actor as well. + const list = await backendAs(context.from.id).tg.auditLog.getById.query({ targetId: userId }) await context.reply( fmt( ({ b, n, i, u, link, code }) => [ diff --git a/src/commands/management/groups.ts b/src/commands/management/groups.ts index d2b3e17..5f96493 100644 --- a/src/commands/management/groups.ts +++ b/src/commands/management/groups.ts @@ -4,9 +4,8 @@ import type { CommandAccess } from "@/commands/access" import { GroupManagement } from "@/lib/group-management" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -import type { Role } from "@/utils/types" -export const groups = new CommandsCollection("Groups") +export const groups = new CommandsCollection("Groups") .createCommand({ trigger: "updategroup", scope: "private", @@ -21,7 +20,6 @@ export const groups = new CommandsCollection("Groups") ], permissions: { requiredPermissions: [PERMISSION.groupsManage], - allowedRoles: ["owner", "direttivo"], }, handler: async ({ context, args }) => { const group = await context.api.getChat(args.chatId).catch(() => null) @@ -73,7 +71,6 @@ export const groups = new CommandsCollection("Groups") ], permissions: { requiredPermissions: [PERMISSION.groupsManage], - allowedRoles: ["owner", "direttivo"], }, handler: async ({ context }) => { const response = await GroupManagement.regenerateInviteLinks(context.from) diff --git a/src/commands/management/index.ts b/src/commands/management/index.ts index 3c76a26..dd503c0 100644 --- a/src/commands/management/index.ts +++ b/src/commands/management/index.ts @@ -1,12 +1,11 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" -import type { Role } from "@/utils/types" import { audit } from "./audit" 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 476f5a6..62004c4 100644 --- a/src/commands/management/role.ts +++ b/src/commands/management/role.ts @@ -1,130 +1,38 @@ -import { z } from "zod" -import { decisionMode, resolveOne } from "@/access" +import { resolveOne } from "@/access" import { PERMISSION } from "@/access/catalog" -import { legacyBackend, serviceBackend } from "@/backend" +import { serviceBackend } from "@/backend" import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -import { numberOrString, type Role } from "@/utils/types" - -export const role = new CommandsCollection("Roles") - .createCommand({ - trigger: "getroles", - scope: "private", - description: "Get roles of an user", - args: [ - { - key: "username", - type: numberOrString, - description: "The username or the user id of the user you want to update the role", - }, - ], - // Open to everyone before the IdP migration; RFC v3 §10.2 restricts it. - permissions: { requiredPermissions: [PERMISSION.usersRead] }, - handler: async ({ context, args }) => { - const userId: number | null = - typeof args.username === "string" ? await getTelegramId(args.username.replaceAll("@", "")) : args.username - - if (userId === null) { - await context.reply(fmt(({ n }) => n`Not a valid userId or username not in our cache`)) - return - } - - // The source the bot decides with: the IdP once its decisions apply, the legacy roles before that. - const permissions = - decisionMode === "enforce" - ? [...(await resolveOne(serviceBackend, userId)).permissions].sort() - : ((await legacyBackend.tg.permissions.getRoles.query({ userId })).roles ?? []) - await context.reply( - fmt(({ b, n }) => - permissions.length ? n`Permissions: ${b`${permissions.join(" ")}`}` : "This user has no permissions" - ) - ) - }, - }) - .createCommand({ - trigger: "addrole", - scope: "private", - description: "Add role to user", - args: [ - { - key: "username", - type: numberOrString, - description: "The username or the user id of the user you want to update the role", - }, - { key: "role", type: z.enum(["owner", "president", "direttivo", "hr", "admin"]) }, - ], - permissions: { - allowedRoles: ["owner", "direttivo"], +import { numberOrString } from "@/utils/types" + +export const role = new CommandsCollection("Roles").createCommand({ + trigger: "getroles", + scope: "private", + description: "Get roles of an user", + args: [ + { + key: "username", + type: numberOrString, + description: "The username or the user id of the user you want to update the role", }, - handler: async ({ context, args }) => { - const userId: number | null = - typeof args.username === "string" ? await getTelegramId(args.username.replaceAll("@", "")) : args.username - - if (userId === null) { - await context.reply(fmt(({ n }) => n`Not a valid userId or username not in our cache`)) - return - } - - const { roles, error } = await legacyBackend.tg.permissions.addRole.mutate({ - userId, - adderId: context.from.id, - role: args.role, - }) - - if (error) { - await context.reply(fmt(({ n }) => n`There was an error: ${error}`)) - return - } - - await context.reply( - fmt(({ b, n }) => [b`✅ Role added!`, n`${b`Username:`} ${args.username}`, n`${b`Updated roles:`} ${roles}`], { - sep: "\n", - }) + ], + permissions: { requiredPermissions: [PERMISSION.usersRead] }, + handler: async ({ context, args }) => { + const userId: number | null = + typeof args.username === "string" ? await getTelegramId(args.username.replaceAll("@", "")) : args.username + + if (userId === null) { + await context.reply(fmt(({ n }) => n`Not a valid userId or username not in our cache`)) + return + } + + const permissions = [...(await resolveOne(serviceBackend, userId)).permissions].sort() + await context.reply( + fmt(({ b, n }) => + permissions.length ? n`Permissions: ${b`${permissions.join(" ")}`}` : "This user has no permissions" ) - }, - }) - .createCommand({ - trigger: "delrole", - scope: "private", - description: "Remove role from an user", - args: [ - { - key: "username", - type: numberOrString, - description: "The username or the user id of the user you want to remove the role from", - }, - { key: "role", type: z.enum(["owner", "president", "direttivo", "hr", "admin"]) }, - ], - permissions: { - allowedRoles: ["owner", "direttivo"], - }, - handler: async ({ context, args }) => { - const userId: number | null = - typeof args.username === "string" ? await getTelegramId(args.username.replaceAll("@", "")) : args.username - - if (userId === null) { - await context.reply(fmt(({ n }) => n`Not a valid userId or username not in our cache`)) - return - } - - const { roles, error } = await legacyBackend.tg.permissions.removeRole.mutate({ - userId, - removerId: context.from.id, - role: args.role, - }) - - if (error) { - await context.reply(fmt(({ n }) => n`There was an error: ${error}`)) - return - } - - await context.reply( - fmt( - ({ b, n }) => [b`✅ Role removed!`, n`${b`Username:`} ${args.username}`, n`${b`Updated roles:`} ${roles}`], - { sep: "\n" } - ) - ) - }, - }) + ) + }, +}) diff --git a/src/commands/management/userid.ts b/src/commands/management/userid.ts index b908f71..a7b6b1f 100644 --- a/src/commands/management/userid.ts +++ b/src/commands/management/userid.ts @@ -4,9 +4,8 @@ import { CommandsCollection } from "@/lib/managed-commands" import { logger } from "@/logger" import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -import type { Role } from "@/utils/types" -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 0dc5a5d..e4431a6 100644 --- a/src/commands/moderation/ban.ts +++ b/src/commands/moderation/ban.ts @@ -7,10 +7,10 @@ import { duration } from "@/utils/duration" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" import { getTelegramId } from "@/utils/telegram-id" -import { numberOrString, type Role } from "@/utils/types" +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: [ @@ -29,9 +29,6 @@ export const ban = new CommandsCollection("Banning") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, repliedTo, authorization }) => { const userOverload = await getOverloadUser(context, repliedTo, args.reasonOrUser, args.reason) @@ -74,9 +71,6 @@ export const ban = new CommandsCollection("Banning") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, repliedTo, authorization }) => { if (!repliedTo.from) { @@ -103,9 +97,6 @@ export const ban = new CommandsCollection("Banning") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, authorization }) => { const userId: number | null = diff --git a/src/commands/moderation/banall.ts b/src/commands/moderation/banall.ts index b9cafb6..12c431f 100644 --- a/src/commands/moderation/banall.ts +++ b/src/commands/moderation/banall.ts @@ -9,16 +9,15 @@ import { modules } from "@/modules" import { moderatorFor } from "@/modules/moderation" import { fmt } from "@/utils/format" import { getTelegramId } from "@/utils/telegram-id" -import { numberOrString, type Role } from "@/utils/types" +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", scope: "private", permissions: { requiredPermissions: [PERMISSION.moderateGlobal], - allowedRoles: ["owner", "direttivo"], }, args: [ { @@ -71,7 +70,6 @@ export const banAll = new CommandsCollection("Ban All") scope: "private", permissions: { requiredPermissions: [PERMISSION.moderateGlobal], - allowedRoles: ["owner", "direttivo"], }, args: [ { diff --git a/src/commands/moderation/del.ts b/src/commands/moderation/del.ts index a4bfae5..b07808f 100644 --- a/src/commands/moderation/del.ts +++ b/src/commands/moderation/del.ts @@ -5,16 +5,13 @@ import { logger } from "@/logger" import { Moderation } from "@/modules/moderation" import { fmt } from "@/utils/format" import { ephemeral, getText } from "@/utils/messages" -import type { Role } from "@/utils/types" -export const del = new CommandsCollection("Deletion").createCommand({ +export const del = new CommandsCollection("Deletion").createCommand({ trigger: "del", scope: "group", permissions: { requiredPermissions: [PERMISSION.messagesDelete], allowTelegramChatAdmins: true, - allowedRoles: ["admin", "owner", "direttivo"], - allowGroupAdmins: true, }, description: "Deletes the replied to message", reply: "required", diff --git a/src/commands/moderation/index.ts b/src/commands/moderation/index.ts index c64f875..2133db3 100644 --- a/src/commands/moderation/index.ts +++ b/src/commands/moderation/index.ts @@ -1,13 +1,12 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" -import type { Role } from "@/utils/types" import { ban } from "./ban" import { banAll } from "./banall" 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 8fbd5c1..ea455f6 100644 --- a/src/commands/moderation/kick.ts +++ b/src/commands/moderation/kick.ts @@ -4,9 +4,8 @@ import { CommandsCollection } from "@/lib/managed-commands" import { logger } from "@/logger" import { Moderation, moderatorFor } from "@/modules/moderation" import { ephemeral } from "@/utils/messages" -import type { Role } from "@/utils/types" -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", @@ -15,9 +14,6 @@ export const kick = new CommandsCollection("Kicking").creat permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, repliedTo, authorization }) => { if (!repliedTo.from) { diff --git a/src/commands/moderation/mute.ts b/src/commands/moderation/mute.ts index 7bfb160..9729db6 100644 --- a/src/commands/moderation/mute.ts +++ b/src/commands/moderation/mute.ts @@ -7,10 +7,10 @@ import { duration } from "@/utils/duration" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" import { getTelegramId } from "@/utils/telegram-id" -import { numberOrString, type Role } from "@/utils/types" +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: [ @@ -28,9 +28,6 @@ export const mute = new CommandsCollection("Muting") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, repliedTo, authorization }) => { if (!repliedTo.from) { @@ -67,9 +64,6 @@ export const mute = new CommandsCollection("Muting") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, repliedTo, authorization }) => { const userOverload = await getOverloadUser(context, repliedTo, args.reasonOrUser, args.reason) @@ -105,9 +99,6 @@ export const mute = new CommandsCollection("Muting") permissions: { requiredPermissions: [PERMISSION.moderate], allowTelegramChatAdmins: true, - allowedRoles: ["owner", "direttivo"], - excludedRoles: ["creator"], - allowGroupAdmins: true, }, handler: async ({ args, context, authorization }) => { const userId: number | null = diff --git a/src/commands/pin.ts b/src/commands/pin.ts index 8f2303b..81fd0b1 100644 --- a/src/commands/pin.ts +++ b/src/commands/pin.ts @@ -3,9 +3,8 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" -import type { Role } from "@/utils/types" -export const pin = new CommandsCollection() +export const pin = new CommandsCollection() .createCommand({ trigger: "pin", description: "Pin a message in a group", @@ -14,8 +13,6 @@ export const pin = new CommandsCollection() permissions: { requiredPermissions: [PERMISSION.messagesPin], allowTelegramChatAdmins: true, - allowGroupAdmins: true, - allowedRoles: ["direttivo", "owner"], }, handler: async ({ context, repliedTo }) => { const member = await context.getChatMember(context.me.id) @@ -52,8 +49,6 @@ export const pin = new CommandsCollection() permissions: { requiredPermissions: [PERMISSION.messagesPin], allowTelegramChatAdmins: true, - allowGroupAdmins: true, - allowedRoles: ["direttivo", "owner"], }, handler: async ({ context, repliedTo }) => { const member = await context.getChatMember(context.me.id) diff --git a/src/commands/report.ts b/src/commands/report.ts index a4a4250..fb56616 100644 --- a/src/commands/report.ts +++ b/src/commands/report.ts @@ -7,7 +7,6 @@ import { logger } from "@/logger" import { modules } from "@/modules" import { fmt } from "@/utils/format" import { ephemeral } from "@/utils/messages" -import type { Role } from "@/utils/types" export const logReport = async (context: Filter | CommandScopedContext, repliedTo: Message) => { const reportSent = await modules.get("tgLogger").report(repliedTo, context.from) @@ -28,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 273055c..f0d59af 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -3,14 +3,13 @@ import { serviceBackend } from "@/backend" import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -import type { Role } from "@/utils/types" 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 9273e00..1f0c291 100644 --- a/src/commands/test/args.ts +++ b/src/commands/test/args.ts @@ -1,8 +1,7 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" -import type { Role } from "@/utils/types" -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 98e066c..35bba41 100644 --- a/src/commands/test/conversation.ts +++ b/src/commands/test/conversation.ts @@ -1,9 +1,8 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -import type { Role } from "@/utils/types" -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/db.ts b/src/commands/test/db.ts deleted file mode 100644 index 4827b74..0000000 --- a/src/commands/test/db.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { legacyBackend } from "@/backend" -import type { CommandAccess } from "@/commands/access" -import { CommandsCollection } from "@/lib/managed-commands" -import { fmt } from "@/utils/format" -import type { Role } from "@/utils/types" - -export const testdb = new CommandsCollection().createCommand({ - trigger: "test_db", - scope: "private", - description: "Test postgres db through the backend", - handler: async ({ context }) => { - try { - const res = await legacyBackend.test.dbQuery.query({ dbName: "tg" }) - await context.reply( - fmt(({ code }) => - res.length > 0 - ? [`Elements inside`, code`tg_test`, `table:`, ...res.map((r) => `\n- ${r}`)] - : [`No elements inside`, code`tg_test`, `table`] - ) - ) - } catch (err) { - await context.reply(`There was an error: \n${String(err)}`) - } - }, -}) diff --git a/src/commands/test/format.ts b/src/commands/test/format.ts index 831dfc4..ceca6a8 100644 --- a/src/commands/test/format.ts +++ b/src/commands/test/format.ts @@ -1,9 +1,8 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { fmt } from "@/utils/format" -import type { Role } from "@/utils/types" -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 fa8835b..ef2133a 100644 --- a/src/commands/test/index.ts +++ b/src/commands/test/index.ts @@ -1,15 +1,12 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" -import type { Role } from "@/utils/types" import { testargs } from "./args" import { testconvo } from "./conversation" -import { testdb } from "./db" import { testformat } from "./format" import { testmenu } from "./menu" -export const test = new CommandsCollection("Test").withCollection( +export const test = new CommandsCollection("Test").withCollection( testargs, - testdb, testformat, testmenu, testconvo diff --git a/src/commands/test/menu.ts b/src/commands/test/menu.ts index 2e0c9cd..99f80a6 100644 --- a/src/commands/test/menu.ts +++ b/src/commands/test/menu.ts @@ -2,7 +2,6 @@ import type { CommandAccess } from "@/commands/access" import { CommandsCollection } from "@/lib/managed-commands" import { MenuGenerator } from "@/lib/menu" import { logger } from "@/logger" -import type { Role } from "@/utils/types" const generateMenu = MenuGenerator.getInstance().create<{ messageId: number @@ -36,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/env.ts b/src/env.ts index 00312f3..c9d386e 100644 --- a/src/env.ts +++ b/src/env.ts @@ -14,21 +14,14 @@ export const env = createEnv({ INFLUXDB_TOKEN: z.string().optional(), INFLUXDB_URL: z.string().default("http://localhost:8086"), - // PoliNetwork IdP (RFC v3 §10.1, §12). The bot calls the backend with its service token when - // IDP_PUBLIC_URL, OAUTH_BACKEND_RESOURCE_URI, OAUTH_BOT_CLIENT_ID and OAUTH_BOT_PRIVATE_JWK are - // all set. With none of them it calls anonymously, as before; anything in between is an error. - IDP_PUBLIC_URL: z.url().optional(), + // PoliNetwork IdP (RFC v3 §10.1, §12). The bot calls the backend only with its service token. + IDP_PUBLIC_URL: z.url(), /** In-cluster address for requests; identifiers always come from IDP_PUBLIC_URL. */ IDP_INTERNAL_URL: z.url().optional(), - OAUTH_BACKEND_RESOURCE_URI: z.url().optional(), - OAUTH_BOT_CLIENT_ID: z.string().min(1).optional(), + OAUTH_BACKEND_RESOURCE_URI: z.url(), + OAUTH_BOT_CLIENT_ID: z.string().min(1), /** The bot client's private signing key as a JWK (JSON), with `kid` and `alg`. */ - OAUTH_BOT_PRIVATE_JWK: z.string().min(1).optional(), - /** - * RFC v3 §13 Phase 4: "shadow" acts on the legacy role checks and logs where the IdP decision - * differs; "enforce" acts on the IdP decision. Ignored when the IdP is not configured. - */ - IDP_DECISIONS: z.enum(["shadow", "enforce"]).default("shadow"), + OAUTH_BOT_PRIVATE_JWK: z.string().min(1), }, runtimeEnv: process.env, diff --git a/src/idp/config.ts b/src/idp/config.ts index 82bdf4b..b032dfb 100644 --- a/src/idp/config.ts +++ b/src/idp/config.ts @@ -13,11 +13,11 @@ export const BOT_SCOPES = [ ] as const export type IdpEnv = { - IDP_PUBLIC_URL?: string + IDP_PUBLIC_URL: string IDP_INTERNAL_URL?: string - OAUTH_BACKEND_RESOURCE_URI?: string - OAUTH_BOT_CLIENT_ID?: string - OAUTH_BOT_PRIVATE_JWK?: string + OAUTH_BACKEND_RESOURCE_URI: string + OAUTH_BOT_CLIENT_ID: string + OAUTH_BOT_PRIVATE_JWK: string } export type IdpConfig = { @@ -29,27 +29,11 @@ export type IdpConfig = { scopes: readonly string[] } -const REQUIRED = [ - "IDP_PUBLIC_URL", - "OAUTH_BACKEND_RESOURCE_URI", - "OAUTH_BOT_CLIENT_ID", - "OAUTH_BOT_PRIVATE_JWK", -] as const - -/** - * The bot's token configuration, or null when every IdP variable is unset and the bot keeps calling - * the backend anonymously (RFC v3 §13). A partial configuration throws, so a deployment that meant - * to authenticate never silently falls back to the legacy path. - */ -export function parseIdpConfig(env: IdpEnv): IdpConfig | null { - const set = [...REQUIRED, "IDP_INTERNAL_URL" as const].filter((key) => env[key] !== undefined) - if (set.length === 0) return null - const missing = REQUIRED.filter((key) => env[key] === undefined) - if (missing.length > 0) throw new Error(`Incomplete IdP configuration, missing: ${missing.join(", ")}`) - +/** The bot's token configuration (RFC v3 §10.1). */ +export function parseIdpConfig(env: IdpEnv): IdpConfig { let privateKey: unknown try { - privateKey = JSON.parse(env.OAUTH_BOT_PRIVATE_JWK as string) + privateKey = JSON.parse(env.OAUTH_BOT_PRIVATE_JWK) } catch { // Never echo the value: it is the private key. throw new Error("OAUTH_BOT_PRIVATE_JWK is not valid JSON") @@ -57,13 +41,13 @@ export function parseIdpConfig(env: IdpEnv): IdpConfig | null { if (typeof privateKey !== "object" || privateKey === null || Array.isArray(privateKey)) throw new Error("OAUTH_BOT_PRIVATE_JWK must be a JWK object") - const endpoints = idpEndpoints({ publicUrl: env.IDP_PUBLIC_URL as string, internalUrl: env.IDP_INTERNAL_URL }) + const endpoints = idpEndpoints({ publicUrl: env.IDP_PUBLIC_URL, internalUrl: env.IDP_INTERNAL_URL }) return { - clientId: env.OAUTH_BOT_CLIENT_ID as string, + clientId: env.OAUTH_BOT_CLIENT_ID, privateKey: privateKey as JWK, tokenUrl: endpoints.tokenUrl, tokenAudience: endpoints.tokenAudience, - resource: env.OAUTH_BACKEND_RESOURCE_URI as string, + resource: env.OAUTH_BACKEND_RESOURCE_URI, scopes: BOT_SCOPES, } } diff --git a/src/lib/group-management/index.ts b/src/lib/group-management/index.ts index c2daf60..0f9f69d 100644 --- a/src/lib/group-management/index.ts +++ b/src/lib/group-management/index.ts @@ -6,8 +6,8 @@ import type { Result } from "neverthrow" import { err, ok } from "neverthrow" -import { decideAccess, hasPermission, PERMISSION, resolveOne } from "@/access" -import { type Backend, legacyBackend, serviceBackend } from "@/backend" +import { hasPermission, PERMISSION, resolveOne } from "@/access" +import { type Backend, serviceBackend } from "@/backend" import { logger } from "@/logger" import { modules } from "@/modules" import type { GroupLinkRegenerationFailure } from "@/modules/tg-logger/types" @@ -369,12 +369,7 @@ export const GroupManagement = { async checkAdderPermission(chat: Chat, addedBy: User, backend: Backend): Promise { let allowed: boolean try { - allowed = await decideAccess({ - check: "bot_add", - ids: { actorId: addedBy.id, chatId: chat.id }, - legacy: async () => (await legacyBackend.tg.permissions.canAddBot.query({ userId: addedBy.id })).allowed, - idp: async () => hasPermission(await resolveOne(backend, addedBy.id), PERMISSION.botAdd), - }) + allowed = hasPermission(await resolveOne(backend, addedBy.id), PERMISSION.botAdd) } catch (error) { logger.error( { error, chat, addedBy: printUsername(addedBy) }, diff --git a/src/lib/managed-commands/command.ts b/src/lib/managed-commands/command.ts index b163f64..be7da82 100644 --- a/src/lib/managed-commands/command.ts +++ b/src/lib/managed-commands/command.ts @@ -80,7 +80,7 @@ interface GroupPermissions extends PrivatePermissions CAMPAIGN_REVIEW_ROLES.has(role))) -} diff --git a/src/middlewares/campaign-spam/index.ts b/src/middlewares/campaign-spam/index.ts index 6d0b3cc..4e56452 100644 --- a/src/middlewares/campaign-spam/index.ts +++ b/src/middlewares/campaign-spam/index.ts @@ -1,6 +1,6 @@ import type { Filter } from "grammy" import type { ChatPermissions, Message } from "grammy/types" -import { decideAccess, hasPermission, legacyRoles, PERMISSION, resolveOne } from "@/access" +import { hasPermission, PERMISSION, resolveOne } from "@/access" import { serviceBackend } from "@/backend" import { logger } from "@/logger" import { modules } from "@/modules" @@ -37,7 +37,6 @@ import { type CampaignSpamReview, createCampaignSpamReview } from "./review-payl import { campaignSpamConfig } from "./runtime-config" import { campaignSpamReputation } from "./service" -const NETWORK_PRIVILEGED_ROLES = new Set(["president", "owner", "direttivo"]) const FIRST_POST_PERMISSIONS = { can_send_messages: true, can_send_audios: false, @@ -130,21 +129,8 @@ export class CampaignSpamGuard> extend */ private async isJoinExempt(userId: number): Promise { try { - return await decideAccess({ - check: "campaign_join_exemption", - ids: { targetId: userId }, - legacy: async () => { - const [roles, grant] = await Promise.all([ - legacyRoles(userId), - serviceBackend.tg.grants.checkUser.query({ userId }), - ]) - return roles.some((role) => NETWORK_PRIVILEGED_ROLES.has(role)) || grant.isGranted - }, - idp: async () => { - const entry = await resolveOne(serviceBackend, userId) - return hasPermission(entry, PERMISSION.immune) || entry.grant !== null - }, - }) + const entry = await resolveOne(serviceBackend, userId) + return hasPermission(entry, PERMISSION.immune) || entry.grant !== null } catch (error) { reportDependencyError(error, "join exemption check") return null diff --git a/src/middlewares/campaign-spam/review.ts b/src/middlewares/campaign-spam/review.ts index 4143f94..e8afc11 100644 --- a/src/middlewares/campaign-spam/review.ts +++ b/src/middlewares/campaign-spam/review.ts @@ -1,4 +1,4 @@ -import { authorizeAction, DENIED, type Decision, legacyRoles, PERMISSION } from "@/access" +import { authorizeAction, type Decision, PERMISSION } from "@/access" import { type CallbackCtx, MenuGenerator } from "@/lib/menu" import { logger } from "@/logger" import { modules } from "@/modules" @@ -6,7 +6,6 @@ import { Moderation, moderatorFor } from "@/modules/moderation" import type { Moderator } from "@/modules/moderation/types" import { fmt, fmtChat, fmtUser } from "@/utils/format" import type { Context } from "@/utils/types" -import { hasCampaignReviewRole } from "./authorization" import { CAMPAIGN_REVIEW_RETENTION_SECONDS, campaignActorFromUser } from "./reputation" import { type CampaignSpamReview, @@ -38,8 +37,6 @@ async function authorizeAndOpenReview( actorId: userId, backend: ctx.backend, required: [PERMISSION.moderateGlobal], - legacy: async () => - hasCampaignReviewRole(await legacyRoles(userId)) ? { allowed: true, basis: "idp_permission" } : DENIED, }) if (!decision.allowed) return { feedback: "You are not authorized for this action" } } catch (error) { diff --git a/src/middlewares/group-specific-actions.ts b/src/middlewares/group-specific-actions.ts index 277e2d6..97f5637 100644 --- a/src/middlewares/group-specific-actions.ts +++ b/src/middlewares/group-specific-actions.ts @@ -1,6 +1,6 @@ import type { Filter } from "grammy" import { err, ok, type Result } from "neverthrow" -import { decideAccess, hasPermission, legacyRoles, PERMISSION, resolveOne } from "@/access" +import { hasPermission, PERMISSION, resolveOne } from "@/access" import { logger } from "@/logger" import { Moderation } from "@/modules/moderation" import { type TelemetryContextFlavor, TrackedMiddleware } from "@/modules/telemetry" @@ -37,17 +37,14 @@ export class GroupSpecificActions> ext .on("message:text", async (ctx, next) => { if (ctx.from.id === ctx.me.id) return next() // skip if bot const userId = ctx.from.id - // RFC v3 §10.2: `tg:trusted` (legacy: any role) is exempt from the hashtag rules - const exempt = await decideAccess({ - check: "hashtag_exemption", - ids: { actorId: userId, chatId: ctx.chatId }, - legacy: async () => (await legacyRoles(userId)).length > 0, - idp: async () => hasPermission(await resolveOne(ctx.backend, userId), PERMISSION.trusted), - }).catch((error: unknown) => { - // Not knowing is no reason to delete someone's message. - logger.warn({ error, userId }, "GroupSpecificActions: cannot check the hashtag exemption") - return true - }) + // RFC v3 §10.2: `tg:trusted` is exempt from the hashtag rules + const exempt = await resolveOne(ctx.backend, userId) + .then((entry) => hasPermission(entry, PERMISSION.trusted)) + .catch((error: unknown) => { + // Not knowing is no reason to delete someone's message. + logger.warn({ error, userId }, "GroupSpecificActions: cannot check the hashtag exemption") + return true + }) if (exempt) return next() const chatMember = await ctx.getChatMember(ctx.from.id) diff --git a/src/middlewares/message-trust.ts b/src/middlewares/message-trust.ts index 8282ef7..6926081 100644 --- a/src/middlewares/message-trust.ts +++ b/src/middlewares/message-trust.ts @@ -1,10 +1,9 @@ import type { ChatMember, User } from "grammy/types" -import { decideAccess, hasPermission, PERMISSION, resolveOne } from "@/access" -import { type Backend, legacyBackend, serviceBackend } from "@/backend" +import { hasPermission, PERMISSION, resolveOne } from "@/access" +import type { Backend } from "@/backend" type MessageTrustContext = { from: User - chatId: number backend: Backend getAuthor(): Promise } @@ -18,17 +17,6 @@ type Trust = Exclude const trustChecks = new WeakMap>() -/** The legacy rule: an admin stored in `tg_group_admins`, or an active grant. */ -async function legacyTrust(ctx: MessageTrustContext): Promise { - const [isGroupAdmin, grant] = await Promise.all([ - legacyBackend.tg.permissions.checkGroup.query({ userId: ctx.from.id, groupId: ctx.chatId }), - serviceBackend.tg.grants.checkUser.query({ userId: ctx.from.id }), - ]) - if (isGroupAdmin) return { status: "trusted", role: "admin" } - if (grant.isGranted) return { status: "trusted", role: "user" } - return { status: "untrusted" } -} - /** RFC v3 §10.2: `tg:trusted` (implied by `tg:immune`) or an active grant. */ async function idpTrust(ctx: MessageTrustContext): Promise { const entry = await resolveOne(ctx.backend, ctx.from.id) @@ -43,18 +31,12 @@ export function inspectMessageTrust(ctx: MessageTrustContext): Promise => { try { - // Native chat admins are trusted under both rules. + // RFC v3 §10.2: native chat admins are trusted. const { status } = await ctx.getAuthor() if (status === "creator") return { status: "trusted", role: "creator" } if (status === "administrator") return { status: "trusted", role: "admin" } - return await decideAccess({ - check: "message_trust", - ids: { actorId: ctx.from.id, chatId: ctx.chatId }, - legacy: () => legacyTrust(ctx), - idp: () => idpTrust(ctx), - same: (a, b) => a.status === b.status, - }) + return await idpTrust(ctx) } catch (error) { return { status: "unavailable", error } } diff --git a/src/modules/audit/index.ts b/src/modules/audit/index.ts index 659f6ca..770c4ac 100644 --- a/src/modules/audit/index.ts +++ b/src/modules/audit/index.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto" import { TRPCClientError } from "@trpc/client" -import { legacyBackend, serviceBackend, serviceTokens } from "@/backend" +import { serviceBackend } from "@/backend" import { Module } from "@/lib/modules" import { logger } from "@/logger" import { redis } from "@/redis" @@ -49,39 +49,25 @@ export function toRecordInput(entry: AuditEntry, idempotencyKey: string): AuditR /** * Records moderation actions in the backend's audit log (RFC v3 §9.2, §10.2): through the outbox - * and `tg.auditLog.record` with the service token, or `tg.auditLog.create` while the bot still - * calls the backend anonymously. + * and `tg.auditLog.record` with the service token. */ export class AuditLog extends Module { - private outbox = serviceTokens - ? new AuditOutbox({ - store: new RedisOutboxStore(redis), - send: (input) => serviceBackend.tg.auditLog.record.mutate(input), - isPermanent, - logger, - }) - : null + private outbox = new AuditOutbox({ + store: new RedisOutboxStore(redis), + send: (input) => serviceBackend.tg.auditLog.record.mutate(input), + isPermanent, + logger, + }) async record(entry: AuditEntry, idempotencyKey = `tg-bot:${randomUUID()}`): Promise { - if (this.outbox) return this.outbox.enqueue(toRecordInput(entry, idempotencyKey)) - - await legacyBackend.tg.auditLog.create - .mutate({ - adminId: entry.actorId, - targetId: entry.targetId, - type: entry.type, - groupId: entry.groupId, - until: entry.until, - reason: entry.reason, - }) - .catch((error: unknown) => logger.warn({ error, type: entry.type }, "[AUDIT] failed to create audit log")) + return this.outbox.enqueue(toRecordInput(entry, idempotencyKey)) } override start() { - this.outbox?.start() + this.outbox.start() } override async stop() { - await this.outbox?.stop() + await this.outbox.stop() } } diff --git a/src/modules/moderation/ban-all-immunity.ts b/src/modules/moderation/ban-all-immunity.ts index 527b14a..97bc35b 100644 --- a/src/modules/moderation/ban-all-immunity.ts +++ b/src/modules/moderation/ban-all-immunity.ts @@ -1,22 +1,13 @@ -import { decideAccess, hasPermission, legacyRoles, PERMISSION, resolveOne } from "@/access" +import { hasPermission, PERMISSION, resolveOne } from "@/access" import { serviceBackend } from "@/backend" -import type { Role } from "@/utils/types" -const BYPASS_ROLES: Role[] = ["president", "owner", "direttivo"] - -/** Where a ban-all was requested. Only `/ban_all` checked immunity before the IdP migration. */ +/** Where a ban-all was requested. */ export type BanAllEntryPoint = "command" | "report_menu" | "campaign_review" | "campaign_automatic" /** * Whether the target may not be banned from the whole network: `tg:immune`, at every entry point * (RFC v3 §10.2, §10.3). Throws when it cannot be decided, so callers can refuse to start. */ -export async function isBanAllImmune(targetId: number, entryPoint: BanAllEntryPoint): Promise { - return decideAccess({ - check: `ban_all_immunity:${entryPoint}`, - ids: { targetId }, - legacy: async () => - entryPoint === "command" && (await legacyRoles(targetId)).some((role) => BYPASS_ROLES.includes(role)), - idp: async () => hasPermission(await resolveOne(serviceBackend, targetId), PERMISSION.immune), - }) +export async function isBanAllImmune(targetId: number): Promise { + return hasPermission(await resolveOne(serviceBackend, targetId), PERMISSION.immune) } diff --git a/src/modules/moderation/ban-all.ts b/src/modules/moderation/ban-all.ts index ea7361a..4565bde 100644 --- a/src/modules/moderation/ban-all.ts +++ b/src/modules/moderation/ban-all.ts @@ -1,6 +1,6 @@ import { createHash, randomUUID } from "node:crypto" import { type ConnectionOptions, FlowProducer, type Job, Queue, Worker } from "bullmq" -import { serviceBackend, serviceTokens } from "@/backend" +import { serviceBackend } from "@/backend" import { env } from "@/env" import { Module } from "@/lib/modules" import { logger } from "@/logger" @@ -140,8 +140,7 @@ export class BanAllQueue extends Module { ? `tg-bot:ban-all:${createHash("sha256").update(banAllFlowId(banAll.type, idempotencyKey)).digest("hex")}` : `tg-bot:ban-all:${randomUUID()}`, } - // The anonymous legacy endpoint has no idempotency support, so it must never replay. - const flow = createBanAllFlow(banAll, messageId, chats, idempotencyKey, serviceTokens ? audit : undefined) + const flow = createBanAllFlow(banAll, messageId, chats, idempotencyKey, audit) // Store the recovery data atomically with the flow. Do not audit an insertion that failed. await this.flowProducer.add(flow) await this.auditFlow({ ...flow.data, audit }) diff --git a/src/modules/tg-logger/grants.ts b/src/modules/tg-logger/grants.ts index e7bd6bb..97f4d68 100644 --- a/src/modules/tg-logger/grants.ts +++ b/src/modules/tg-logger/grants.ts @@ -1,17 +1,8 @@ import { TRPCClientError } from "@trpc/client" import type { Context } from "grammy" import type { Message, User } from "grammy/types" -import { - authorizeAction, - DENIED, - decideAccess, - decisionMode, - hasPermission, - legacyRoles, - PERMISSION, - resolveOne, -} from "@/access" -import { type ApiOutput, backendAs, backendFor, legacyBackend } from "@/backend" +import { authorizeAction, PERMISSION } from "@/access" +import { type ApiOutput, backendAs, backendFor } from "@/backend" import { type CallbackCtx, MenuGenerator } from "@/lib/menu" import { logger } from "@/logger" import { modules } from ".." @@ -28,29 +19,17 @@ type GrantedMessage = { type InterruptResult = ApiOutput["tg"]["grants"]["interrupt"] /** - * Interrupting is checked by the backend (RFC v3 §10.2): with IdP decisions it acts for the user, - * who needs `tg:grants:manage`; before that the legacy path checks the stored roles, and in shadow - * mode the IdP decision is only compared. + * Interrupting is checked by the backend (RFC v3 §10.2): it acts for the user, who needs + * `tg:grants:manage`. */ async function interruptGrant(from: User, target: User): Promise { - if (decisionMode === "enforce") - return backendAs(from.id) - .tg.grants.interrupt.mutate({ userId: target.id }) - .catch((error: unknown) => { - if (error instanceof TRPCClientError && error.data?.code === "FORBIDDEN") - return { success: false, error: "UNAUTHORIZED" } as const - throw error - }) - - const legacy = legacyBackend.tg.grants.interrupt.mutate({ interruptedById: from.id, userId: target.id }) - if (decisionMode === "shadow") - await decideAccess({ - check: "grants_menu:interrupt", - ids: { actorId: from.id, targetId: target.id }, - legacy: async () => (await legacy).error !== "UNAUTHORIZED", - idp: async () => hasPermission(await resolveOne(backendFor(from), from.id), PERMISSION.grantsManage), - }).catch(() => {}) - return legacy + return backendAs(from.id) + .tg.grants.interrupt.mutate({ userId: target.id }) + .catch((error: unknown) => { + if (error instanceof TRPCClientError && error.data?.code === "FORBIDDEN") + return { success: false, error: "UNAUTHORIZED" } as const + throw error + }) } async function handleInterrupt(ctx: CallbackCtx, target: User) { @@ -83,14 +62,11 @@ const getFeedback = (error: Error): string | null => { } async function handleDelete(ctx: CallbackCtx, data: GrantedMessage): Promise<{ error: Error }> { - const userId = ctx.from.id const authorization = await authorizeAction({ check: "grants_menu:delete", - actorId: userId, + actorId: ctx.from.id, backend: backendFor(ctx.from), required: [PERMISSION.grantsManage], - legacy: async () => - (await legacyRoles(userId)).includes("direttivo") ? { allowed: true, basis: "idp_permission" } : DENIED, }) if (!authorization.allowed) return { error: "UNAUTHORIZED" } diff --git a/src/modules/tg-logger/index.ts b/src/modules/tg-logger/index.ts index 6346b3c..9efeeae 100644 --- a/src/modules/tg-logger/index.ts +++ b/src/modules/tg-logger/index.ts @@ -219,7 +219,7 @@ export class TgLogger extends Module { ): Promise { if (type === "BAN") { const targetId = typeof target === "number" ? target : target.id - const immune = await isBanAllImmune(targetId, entryPoint).catch((error: unknown) => { + const immune = await isBanAllImmune(targetId).catch((error: unknown) => { logger.error({ error, targetId, entryPoint }, "[banall] Cannot check the target's immunity") return null }) diff --git a/src/modules/tg-logger/report.ts b/src/modules/tg-logger/report.ts index c76c228..32eccc3 100644 --- a/src/modules/tg-logger/report.ts +++ b/src/modules/tg-logger/report.ts @@ -65,17 +65,13 @@ async function editReportMessage(report: Report, ctx: Callbac const NOT_ALLOWED = { feedback: "❌ You don't have enough permissions" } -/** - * RFC v3 §10.2: the report menu had no checks of its own, as only the admin group sees it. That stays - * the legacy decision; the IdP decision needs the action's permission. - */ +/** RFC v3 §10.2: each report-menu action needs its own permission. */ function authorizeReportAction(ctx: CallbackCtx, button: string, permission: Permission): Promise { return authorizeAction({ check: `report_menu:${button}`, actorId: ctx.from.id, backend: backendFor(ctx.from), required: [permission], - legacy: async () => ({ allowed: true, basis: "idp_permission" }), }) } diff --git a/src/modules/websocket.ts b/src/modules/websocket.ts index 50f2836..7d17e18 100644 --- a/src/modules/websocket.ts +++ b/src/modules/websocket.ts @@ -55,18 +55,18 @@ type SocketError = { export class WebSocketClient extends Module { private io: TelegramSocket private lastErrorCode: string | null = null - private tokenAuth = serviceTokens ? new SocketTokenAuth(serviceTokens, { logger }) : null + private tokenAuth = new SocketTokenAuth(serviceTokens, { logger }) constructor() { super() this.io = io(`http://${env.BACKEND_URL}`, { path: WS_PATH, - // With the IdP the bot is identified by its token (RFC v3 §8.3); before, by the query. - ...(this.tokenAuth ? { auth: this.tokenAuth.auth } : { query: { type: "telegram" } }), + // The bot is identified by its token (RFC v3 §8.3). + auth: this.tokenAuth.auth, autoConnect: false, parser, }) - this.tokenAuth?.attach(this.io) + this.tokenAuth.attach(this.io) this.io.on("connect", () => { logger.info("[WS] connected") this.lastErrorCode = null @@ -186,7 +186,7 @@ export class WebSocketClient extends Module = T | T[] export type BackendFlavor = { backend: Backend } export type Context = TelemetryContextFlavor> & BackendFlavor -export type Role = ApiInput["tg"]["permissions"]["addRole"]["role"] export type ModuleShared = { api: Api diff --git a/tests/ban-all-audit.test.ts b/tests/ban-all-audit.test.ts index 6da45ad..92fb2fb 100644 --- a/tests/ban-all-audit.test.ts +++ b/tests/ban-all-audit.test.ts @@ -3,7 +3,6 @@ import type { BanAllFlow } from "@/modules/moderation/ban-all-flow" import type { BanAll } from "@/modules/tg-logger/ban-all" const state = vi.hoisted(() => ({ - authenticated: true, add: vi.fn(), audit: vi.fn(), getJob: vi.fn(), @@ -31,9 +30,6 @@ vi.mock("bullmq", () => ({ })) vi.mock("@/env", () => ({ env: { REDIS_PORT: 6379 } })) vi.mock("@/backend", () => ({ - get serviceTokens() { - return state.authenticated ? {} : null - }, serviceBackend: { tg: { groups: { getAll: { query: state.getGroups } } } }, })) vi.mock("@/modules", () => ({ modules: { get: () => ({ record: state.audit }) } })) @@ -50,7 +46,6 @@ const banAll: BanAll = { beforeEach(() => { vi.clearAllMocks() - state.authenticated = true state.getJob.mockResolvedValue(null) state.getGroups.mockResolvedValue([{ telegramId: -1001, hide: false }]) state.add.mockResolvedValue(undefined) @@ -87,23 +82,6 @@ describe("ban-all enqueue audit recovery", () => { expect(state.audit.mock.calls[1]).toEqual(state.audit.mock.calls[0]) }) - it("anonymous flow records once and does not replay the non-idempotent legacy audit", async () => { - state.authenticated = false - const queue = new BanAllQueue() - await queue.initiateBanAll(banAll, 99, "automatic", "operation") - const flow = state.add.mock.calls[0]?.[0] as BanAllFlow - expect(flow.data.audit).toBeUndefined() - await state.workers.get("[ban_all.orchestrator]")?.({ - data: flow.data, - name: "ban_all", - getDependenciesCount: async () => ({ processed: 1 }), - updateProgress: vi.fn(async () => undefined), - }) - state.getJob.mockResolvedValue({ data: flow.data }) - await queue.initiateBanAll(banAll, 100, "automatic", "operation") - expect(state.audit).toHaveBeenCalledOnce() - }) - it("the resumed orchestrator recovers the original actor and audit key", async () => { const queue = new BanAllQueue() await queue.initiateBanAll(banAll, 99, "automatic", "operation") diff --git a/tests/ban-all-immunity.test.ts b/tests/ban-all-immunity.test.ts index 008fd7f..f557aef 100644 --- a/tests/ban-all-immunity.test.ts +++ b/tests/ban-all-immunity.test.ts @@ -1,61 +1,33 @@ import { beforeEach, describe, expect, it, vi } from "vitest" -import { type DecisionMode, decide, NO_ACCESS } from "@/access/decision" +import { NO_ACCESS } from "@/access/decision" -const state = vi.hoisted(() => ({ mode: "shadow" as DecisionMode, legacyRoles: vi.fn(), resolveOne: vi.fn() })) +const state = vi.hoisted(() => ({ resolveOne: vi.fn() })) vi.mock("@/access", async () => { const actual = await import("@/access/decision") const catalog = await import("@/access/catalog") - return { - ...actual, - ...catalog, - legacyRoles: state.legacyRoles, - resolveOne: state.resolveOne, - decideAccess: (options: Parameters[0]) => - decide({ ...options, mode: state.mode, logger: { warn: vi.fn() } }), - } + return { ...actual, ...catalog, resolveOne: state.resolveOne } }) vi.mock("@/backend", () => ({ serviceBackend: {} })) import { isBanAllImmune } from "@/modules/moderation/ban-all-immunity" beforeEach(() => { - state.mode = "shadow" - state.legacyRoles.mockReset() state.resolveOne.mockReset() }) describe("ban-all immunity at enqueue", () => { - it.each([ - "command", - "report_menu", - "campaign_review", - "campaign_automatic", - ] as const)("enforces immunity for %s", async (entryPoint) => { - state.mode = "enforce" + it("`tg:immune` makes the target immune", async () => { state.resolveOne.mockResolvedValue({ ...NO_ACCESS, permissions: new Set(["tg:immune"]) }) - expect(await isBanAllImmune(42, entryPoint)).toBe(true) - expect(state.legacyRoles).not.toHaveBeenCalled() + expect(await isBanAllImmune(42)).toBe(true) }) - it.each([ - "report_menu", - "campaign_review", - "campaign_automatic", - ] as const)("shadow preserves the original lack of immunity for %s", async (entryPoint) => { - state.resolveOne.mockResolvedValue({ ...NO_ACCESS, permissions: new Set(["tg:immune"]) }) - expect(await isBanAllImmune(42, entryPoint)).toBe(false) - expect(state.legacyRoles).not.toHaveBeenCalled() - }) - - it("shadow preserves the command's legacy immunity even when the IdP disagrees", async () => { - state.legacyRoles.mockResolvedValue(["owner"]) - state.resolveOne.mockResolvedValue(NO_ACCESS) - expect(await isBanAllImmune(42, "command")).toBe(true) + it("a target without `tg:immune` is not immune", async () => { + state.resolveOne.mockResolvedValue({ ...NO_ACCESS, permissions: new Set(["tg:trusted", "tg:moderate:global"]) }) + expect(await isBanAllImmune(42)).toBe(false) }) - it("enforcement propagates an unavailable lookup so the enqueue can refuse to start", async () => { - state.mode = "enforce" + it("propagates an unavailable lookup so the enqueue can refuse to start", async () => { state.resolveOne.mockRejectedValue(new Error("snapshot unavailable")) - await expect(isBanAllImmune(42, "campaign_automatic")).rejects.toThrow("snapshot unavailable") + await expect(isBanAllImmune(42)).rejects.toThrow("snapshot unavailable") }) }) diff --git a/tests/campaign-spam-authorization.test.ts b/tests/campaign-spam-authorization.test.ts deleted file mode 100644 index bfc2fa5..0000000 --- a/tests/campaign-spam-authorization.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, expect, it } from "vitest" -import { hasCampaignReviewRole } from "@/middlewares/campaign-spam/authorization" - -describe("campaign spam review authorization", () => { - it("allows only roles trusted with network-wide moderation", () => { - expect(hasCampaignReviewRole(["owner"])).toBe(true) - expect(hasCampaignReviewRole(["direttivo"])).toBe(true) - expect(hasCampaignReviewRole(["admin"])).toBe(false) - expect(hasCampaignReviewRole([])).toBe(false) - expect(hasCampaignReviewRole(undefined)).toBe(false) - }) -}) diff --git a/tests/campaign-spam-guard.test.ts b/tests/campaign-spam-guard.test.ts index 6fce3de..5a5125e 100644 --- a/tests/campaign-spam-guard.test.ts +++ b/tests/campaign-spam-guard.test.ts @@ -12,15 +12,14 @@ import type { Context } from "@/utils/types" vi.mock("@/env", () => ({ env: { BOT_TOKEN: "test-token-for-campaign-fingerprints-123456" } })) vi.mock("@/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } })) vi.mock("@/backend", () => { - // Anonymous mode: the service and legacy clients are the same. + // Nobody holds IdP permissions or grants. const client = { tg: { - permissions: { getRoles: { query: vi.fn().mockResolvedValue({ roles: [] }) } }, - grants: { checkUser: { query: vi.fn().mockResolvedValue({ isGranted: false }) } }, + access: { resolve: { query: vi.fn().mockResolvedValue({}) } }, auditLog: { getById: { query: vi.fn().mockResolvedValue([]) } }, }, } - return { idpConfig: null, serviceBackend: client, legacyBackend: client, backendFor: () => client } + return { serviceBackend: client, backendFor: () => client } }) vi.mock("@/modules", () => ({ modules: {} })) vi.mock("@/modules/moderation", () => ({ Moderation: {} })) diff --git a/tests/idp-decisions.test.ts b/tests/idp-decisions.test.ts index 7c88952..4e2fe60 100644 --- a/tests/idp-decisions.test.ts +++ b/tests/idp-decisions.test.ts @@ -1,65 +1,16 @@ import { describe, expect, it, vi } from "vitest" +import { authorizeAction } from "@/access" import { PERMISSION } from "@/access/catalog" -import { DENIED, decide, hasPermission, idpDecision, NO_ACCESS, sameAllowed } from "@/access/decision" +import { DENIED, hasPermission, idpDecision, NO_ACCESS } from "@/access/decision" +import type { Backend } from "@/backend" -const allowed = { allowed: true, basis: "idp_permission" as const } -const base = { check: "command:ban", ids: { actorId: 42 }, logger: { warn: vi.fn() }, same: sameAllowed } +vi.mock("@/logger", () => ({ logger: { error: vi.fn() } })) -describe("migration authorization", () => { - it.each([ - [allowed, DENIED], - [DENIED, allowed], - ])("shadow always applies the legacy decision", async (legacy, idp) => { - const warn = vi.fn() - const result = await decide({ - ...base, - logger: { warn }, - mode: "shadow", - legacy: async () => legacy, - idp: async () => idp, - }) - expect(result).toBe(legacy) - expect(warn).toHaveBeenCalledOnce() - }) - - it("an unavailable IdP never changes a shadow decision", async () => { - expect( - await decide({ - ...base, - mode: "shadow", - legacy: async () => allowed, - idp: async () => { - throw new Error("offline") - }, - }) - ).toBe(allowed) - }) - - it("shadow preserves a failed legacy check", async () => { - await expect( - decide({ - ...base, - mode: "shadow", - legacy: async () => { - throw new Error("legacy offline") - }, - idp: async () => allowed, - }) - ).rejects.toThrow("legacy offline") - }) - - it("enforcement never reads the legacy roles", async () => { - const legacy = vi.fn(async () => allowed) - expect(await decide({ ...base, mode: "enforce", legacy, idp: async () => DENIED })).toBe(DENIED) - expect(legacy).not.toHaveBeenCalled() - }) - - it("anonymous mode never contacts the IdP", async () => { - const idp = vi.fn(async () => DENIED) - expect(await decide({ ...base, mode: "anonymous", legacy: async () => allowed, idp })).toBe(allowed) - expect(idp).not.toHaveBeenCalled() - }) +function backendResolving(query: () => Promise): Backend { + return { tg: { access: { resolve: { query } } } } as unknown as Backend +} +describe("IdP authorization", () => { it("native chat admins can moderate when the IdP is unavailable", async () => { expect( await idpDecision({ @@ -87,4 +38,22 @@ describe("migration authorization", () => { expect(hasPermission(entry, PERMISSION.trusted)).toBe(true) expect(hasPermission(entry, PERMISSION.moderateGlobal)).toBe(false) }) + + it("an unavailable IdP decision denies the action", async () => { + const backend = backendResolving(async () => { + throw new Error("offline") + }) + expect( + await authorizeAction({ check: "command:/ban", actorId: 42, backend, required: [PERMISSION.moderate] }) + ).toEqual(DENIED) + }) + + it("the actor's resolved permissions authorize the action", async () => { + const backend = backendResolving(async () => ({ + "42": { sub: "user", permissions: [PERMISSION.moderate], grant: null }, + })) + expect( + await authorizeAction({ check: "command:/ban", actorId: 42, backend, required: [PERMISSION.moderate] }) + ).toEqual({ allowed: true, basis: "idp_permission" }) + }) }) diff --git a/tests/idp-fetch.test.ts b/tests/idp-fetch.test.ts index 39f7612..dc1b56b 100644 --- a/tests/idp-fetch.test.ts +++ b/tests/idp-fetch.test.ts @@ -68,11 +68,6 @@ describe("service and actor requests", () => { }) describe("IdP deployment configuration", () => { - it("only an entirely absent configuration selects anonymous mode", () => { - expect(parseIdpConfig({})).toBeNull() - expect(() => parseIdpConfig({ IDP_INTERNAL_URL: "http://auth:3000" })).toThrow("Incomplete IdP configuration") - }) - it("keeps the public assertion audience when using an internal token transport", () => { const config = parseIdpConfig({ IDP_PUBLIC_URL: "https://auth.test", @@ -81,9 +76,9 @@ describe("IdP deployment configuration", () => { OAUTH_BOT_CLIENT_ID: "bot-id", OAUTH_BOT_PRIVATE_JWK: JSON.stringify({ alg: "EdDSA", kid: "test" }), }) - expect(config?.tokenUrl).toBe("http://auth:3000/api/auth/oauth2/token") - expect(config?.tokenAudience).toBe("https://auth.test/api/auth/oauth2/token") - expect(config?.scopes).toEqual(BOT_SCOPES) + expect(config.tokenUrl).toBe("http://auth:3000/api/auth/oauth2/token") + expect(config.tokenAudience).toBe("https://auth.test/api/auth/oauth2/token") + expect(config.scopes).toEqual(BOT_SCOPES) }) it("never echoes malformed private key material", () => { diff --git a/tests/tg-logger-resilience.test.ts b/tests/tg-logger-resilience.test.ts index cb30bec..b98186a 100644 --- a/tests/tg-logger-resilience.test.ts +++ b/tests/tg-logger-resilience.test.ts @@ -7,8 +7,14 @@ vi.hoisted(() => { process.env.BOT_TOKEN = "test-token" process.env.BACKEND_URL = "backend.test" process.env.NODE_ENV = "development" + process.env.IDP_PUBLIC_URL = "https://auth.test" + process.env.OAUTH_BACKEND_RESOURCE_URI = "https://backend.test" + process.env.OAUTH_BOT_CLIENT_ID = "bot-id" + process.env.OAUTH_BOT_PRIVATE_JWK = JSON.stringify({ alg: "EdDSA", kid: "test" }) }) +vi.mock("@/backend", () => ({ serviceBackend: {}, backendAs: vi.fn(), backendFor: vi.fn() })) + vi.mock("@/lib/redis-fallback-adapter", () => ({ RedisFallbackAdapter: class {}, }))