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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/people/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { decryptUser } from "@/utils/users"
import { provisionMember, setMemberNumber } from "./azure-members"
import { peopleConfig } from "./config"
import { transferType } from "./files"
import { fail, receiptEligible } from "./model"
import { fail, receiptEligible, telegramGroupsWithAdmins } from "./model"
import { createPeopleService } from "./service"
import { createPeoplePgStore } from "./store-pg"

Expand All @@ -26,10 +26,11 @@ export const people = createPeopleService({
telegramId: idp?.snapshot?.current()?.bySub(a.sub)?.telegramId ?? null,
}))
},
// Group admins are native Telegram status (RFC v3 decision 2), which the backend does not store.
// Group admins are native Telegram status (RFC v3 decision 2): the bot reads them, the backend never stores them.
async telegramGroups() {
const groups = await DB.select().from(SCHEMA.TG.groups)
return groups.map((g) => ({ chatId: String(g.telegramId), title: g.title, admins: null }))
const { WSS } = await import("@/server")
return telegramGroupsWithAdmins(groups, await WSS.getGroupAdmins(groups.map((g) => g.telegramId)))
},
async telegramUsers() {
const users = await DB.select().from(SCHEMA.TG.users)
Expand Down
26 changes: 25 additions & 1 deletion src/people/model.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { createHash, randomUUID } from "node:crypto"
import { TRPCError } from "@trpc/server"
import * as C from "./contract"
import type { Officer, PeopleConfig, PeopleState, Person, StoredReceipt, UnitOfWork, Viewer } from "./types"
import type {
Officer,
PeopleConfig,
PeopleState,
Person,
StoredReceipt,
TelegramGroup,
UnitOfWork,
Viewer,
} from "./types"

export function fail(
code: "BAD_REQUEST" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "PRECONDITION_FAILED",
Expand Down Expand Up @@ -252,3 +261,18 @@ export function validateFields(team: C.TeamId, fields: C.TeamFields) {
export function newFileId() {
return randomUUID()
}

/**
* Telegram groups with their native admins (RFC v3 decision 2), which only Telegram owns: the bot reads them and the
* backend asks it, without storing them. A group the bot has not read yet, or every group while the bot does not
* answer, has `admins: null`, so People keeps what it last knew instead of reading "no admins".
*/
export function telegramGroupsWithAdmins(
groups: { telegramId: number; title: string }[],
admins: ReadonlyMap<number, number[]> | null
): TelegramGroup[] {
return groups.map((g) => {
const userIds = admins?.get(g.telegramId)
return { chatId: String(g.telegramId), title: g.title, admins: userIds ? userIds.map(String) : null }
})
}
2 changes: 1 addition & 1 deletion src/people/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,5 @@ export type Account = {
emailVerified?: boolean
}
export type TelegramUser = { id: string; name: string; username: string | null }
/** `admins` is null while the group's admin list is unknown: People then keeps the groups it last knew. */
/** `admins` is null while the bot cannot tell the group's Telegram admins: People then keeps the groups it last knew. */
export type TelegramGroup = { chatId: string; title: string; admins: string[] | null }
19 changes: 19 additions & 0 deletions src/websocket/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ export type WebSocketServerOptions = {

/** A missing acknowledgement must not hang the request that triggered the emit. */
const ACK_TIMEOUT_MS = 10_000
/** People pages wait on this read: without the bot, they show groups without admins instead of hanging. */
const READ_TIMEOUT_MS = 3_000

export const engine = new Engine()

Expand Down Expand Up @@ -123,6 +125,23 @@ export class WebSocketServer {
})
}

/** Each group's Telegram admins as the bot knows them, or null when the bot does not answer. */
async getGroupAdmins(chatIds: number[]): Promise<Map<number, number[]> | null> {
const tgSocket = this.telegramSocket("getGroupAdmins")
if (!tgSocket) return null

return new Promise((res) => {
tgSocket.timeout(READ_TIMEOUT_MS).emit("getGroupAdmins", { chatIds }, (timeout, groups) => {
if (timeout) {
logger.error({ err: timeout }, "[WS] Cannot read the groups' admins from the bot")
res(null)
} else {
res(new Map(groups.map((group) => [group.chatId, group.userIds])))
}
})
})
}

async leaveChat(data: Parameters<ServerToClientEvents["leaveChat"]>[0]): Promise<boolean> {
const tgSocket = this.telegramSocket("leaveChat")
if (!tgSocket) return false
Expand Down
5 changes: 5 additions & 0 deletions src/websocket/telegram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ export interface ToClient {
},
cb: (error: string | null) => void
) => void
/**
* The native Telegram admins of the given groups (RFC v3 decision 2), from the bot's cache of Telegram. Groups the
* bot has not read yet are left out.
*/
getGroupAdmins: (data: { chatIds: number[] }, cb: (groups: { chatId: number; userIds: number[] }[]) => void) => void
leaveChat: (
data: {
chatId: number
Expand Down
24 changes: 23 additions & 1 deletion tests/people.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from "vitest"
import { myAreaSchema } from "@/people/contract"
import { isValidIban } from "@/people/iban"
import { academicYear, csvCell, today } from "@/people/model"
import { academicYear, csvCell, telegramGroupsWithAdmins, today } from "@/people/model"
import { samplePdf } from "./esign-fixtures"
import { admit, harness, issue, master, permissions, vice, viewer } from "./people-fixtures"

Expand Down Expand Up @@ -489,3 +489,25 @@ it("keeps groups and pending removals while Telegram group admins are unknown",
expect(person.discrepancies).toContainEqual(expect.objectContaining({ kind: "admin-removal" }))
expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(1)
})

it("reads Telegram group admins from the bot, and none while it does not answer", () => {
const groups = [
{ telegramId: -1001, title: "Read" },
{ telegramId: -1002, title: "Read, no admins" },
{ telegramId: -1003, title: "Not read yet" },
]
expect(
telegramGroupsWithAdmins(
groups,
new Map([
[-1001, [103, 104]],
[-1002, []],
])
)
).toEqual([
{ chatId: "-1001", title: "Read", admins: ["103", "104"] },
{ chatId: "-1002", title: "Read, no admins", admins: [] },
{ chatId: "-1003", title: "Not read yet", admins: null },
])
expect(telegramGroupsWithAdmins(groups, null).map((g) => g.admins)).toEqual([null, null, null])
})
Loading