-
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathTelegramClient.js
More file actions
271 lines (257 loc) · 8.37 KB
/
TelegramClient.js
File metadata and controls
271 lines (257 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// @ts-check
const { default: fetch } = require('node-fetch')
const { TelegramStrategy } = require('@rainb0w-clwn/passport-telegram-official')
const passport = require('passport')
const config = require('@rm/config')
const { state } = require('./state')
const { areaPerms } = require('../utils/areaPerms')
const { webhookPerms } = require('../utils/webhookPerms')
const { scannerPerms } = require('../utils/scannerPerms')
const { mergePerms } = require('../utils/mergePerms')
const { AuthClient } = require('./AuthClient')
/**
* @typedef {import('@rainb0w-clwn/passport-telegram-official/dist/types').PassportTelegramUser} TGUser
*/
class TelegramClient extends AuthClient {
/** @param {TGUser} user */
async getUserGroups(user) {
if (!user || !user.id) return []
const groups = [user.id]
await Promise.all(
this.strategy.groups.map(async (group) => {
try {
const response = await fetch(
`https://api.telegram.org/bot${this.strategy.botToken}/getChatMember?chat_id=${group}&user_id=${user.id}`,
)
if (!response) {
throw new Error(
'Unable to query TG API or User is not in the group',
)
}
if (!response.ok) {
throw new Error(
`Telegram API error: ${response.status} ${response.statusText}`,
)
}
const json = await response.json()
if (
json.result.status !== 'left' &&
json.result.status !== 'kicked'
) {
groups.push(group)
}
} catch (e) {
this.log.error(
e,
`Telegram Group: ${group}`,
`User: ${user.id} (${user.username})`,
)
return null
}
}),
)
return groups
}
/**
*
* @param {TGUser} user
* @param {string[]} groups
* @returns {TGUser & { perms: import("@rm/types").Permissions }}
*/
getUserPerms(user, groups) {
const trialActive = this.trialManager.active()
let gainedAccessViaTrial = false
const perms = Object.fromEntries(
Object.entries(this.perms).map(([perm, info]) => [
perm,
info.enabled &&
(this.alwaysEnabledPerms.includes(perm) ||
info.roles.some((role) => {
if (groups.includes(role)) {
return true
}
if (
trialActive &&
info.trialPeriodEligible &&
this.strategy.trialPeriod.roles.some((trialRole) =>
groups.includes(trialRole),
)
) {
gainedAccessViaTrial = true
return true
}
return false
})),
]),
)
/** @type { TGUser & { perms: import("@rm/types").Permissions }} */
const newUserObj = {
...user,
// @ts-ignore
perms: {
...perms,
trial: gainedAccessViaTrial,
admin: false,
areaRestrictions: areaPerms(groups),
webhooks: webhookPerms(groups, 'telegramGroups', trialActive),
scanner: scannerPerms(groups, 'telegramGroups', trialActive),
scannerCooldowns: {},
},
}
if (newUserObj.perms.trial) {
this.log.info(
user.username,
'gained access via',
this.trialManager._forceActive ? 'manually activated' : '',
'trial',
)
}
if (this.strategy.allowedUsers?.includes(newUserObj.id)) {
newUserObj.perms.admin = true
Object.keys(newUserObj.perms.scanner).forEach((x) => {
newUserObj.perms.scannerCooldowns[x] = 0
})
} else {
const scanner = config.getSafe('scanner')
Object.keys(newUserObj.perms.scanner).forEach((mode) => {
newUserObj.perms.scannerCooldowns[mode] = scanner[mode].rules.reduce(
(acc, rule) => {
if (rule.cooldown < acc) {
return rule.cooldown
}
return acc
},
scanner[mode].userCooldownSeconds,
)
})
}
return newUserObj
}
/** @type {import('@rainb0w-clwn/passport-telegram-official/dist/types').CallbackWithRequest} */
async authHandler(req, profile, done) {
const baseUser = { ...profile, rmStrategy: this.rmStrategy }
const groups = await this.getUserGroups(baseUser)
const user = this.getUserPerms(baseUser, groups)
if (!user.perms.map) {
this.log.warn(user.username, 'was not given map perms')
return done(null, false, { message: 'access_denied' })
}
try {
await state.db.models.User.query()
.findOne({ telegramId: user.id })
.then(
async (/** @type {import('@rm/types').FullUser} */ userExists) => {
const selectedWebhook = Object.keys(state.event.webhookObj).find(
(x) => user?.perms?.webhooks.includes(x),
)
if (req.user && userExists?.strategy === 'local') {
await state.db.models.User.query()
.update({
telegramId: user.id,
telegramPerms: JSON.stringify(user.perms),
webhookStrategy: 'telegram',
})
.where('id', req.user.id)
await state.db.models.User.query()
.where('telegramId', user.id)
.whereNot('id', req.user.id)
.delete()
this.log.info(
user.username,
`(${user.id})`,
'Authenticated successfully.',
)
return done(null, {
selectedWebhook,
...user,
...req.user,
username: userExists.username || user.username,
telegramId: user.id,
perms: mergePerms(req.user.perms, user.perms),
})
}
if (!userExists) {
userExists = await state.db.models.User.query().insertAndFetch({
telegramId: user.id,
strategy: user.provider,
tutorial: !config.getSafe('map.misc.forceTutorial'),
selectedWebhook,
})
}
if (userExists.strategy !== 'telegram') {
await state.db.models.User.query()
.update({ strategy: 'telegram' })
.where('id', userExists.id)
userExists.strategy = 'telegram'
}
if (!userExists.selectedWebhook && selectedWebhook) {
await state.db.models.User.query()
.update({ selectedWebhook })
.where('id', userExists.id)
userExists.selectedWebhook = selectedWebhook
}
this.log.info(
user.username,
`(${user.id})`,
'Authenticated successfully.',
)
return done(null, {
...user,
...userExists,
username: userExists.username || user.username,
})
},
)
} catch (e) {
this.log.error('User has failed auth.', e)
}
}
/**
* Send a message to a Telegram Group
*
* @param {import('./AuthClient').MessageEmbed} embed
* @param {keyof AuthClient['loggingChannels']} channel
*/
async sendMessage(embed, channel) {
if (!this.loggingChannels[channel]) return
const text = AuthClient.getHtml(
typeof embed === 'string' ? embed : { ...this.getBaseEmbed(), ...embed },
)
try {
const response = await fetch(
`https://api.telegram.org/bot${this.strategy.botToken}/sendMessage`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: this.loggingChannels[channel],
parse_mode: 'HTML',
disable_web_page_preview: true,
text,
}),
},
)
if (!response.ok) {
throw new Error(
`Telegram API error: ${response.status} ${response.statusText}`,
)
}
this.log.info(`${channel} Log Sent`)
} catch (e) {
this.log.error(`Error sending ${channel} Log`, e)
}
}
initPassport() {
passport.use(
this.rmStrategy,
new TelegramStrategy(
{
botToken: this.strategy.botToken,
passReqToCallback: true,
},
(req, profile, done) => this.authHandler(req, profile, done),
),
)
}
}
module.exports = { TelegramClient }