blun-king-cli 9.1.653 → 9.1.655

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,388 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { setTimeout as telegramRetrySleep } from "node:timers/promises";
5
+ function canControlTelegramSession(access, chatId) {
6
+ return /^[1-9]\d{0,18}$/u.test(chatId) && (access.dmPolicy === 'pairing' || access.dmPolicy === 'allowlist') && Array.isArray(access.allowFrom) && access.allowFrom.includes(chatId) && Array.isArray(access.sessionControlAllowFrom) && access.sessionControlAllowFrom.includes(chatId);
7
+ }
8
+ const SLOT_NAME = /^\d{16}_([1-9]\d{0,18})_([1-9]\d{0,18})\.json$/u;
9
+ const ACTION_LIFETIME_MS = 15 * 60_000;
10
+ const RECEIPT_LIFETIME_MS = 2 * ACTION_LIFETIME_MS;
11
+ const MAX_PENDING = 32;
12
+ const MAX_CONTROL_SLOTS = 128;
13
+ function readObject(path, limit = 512) {
14
+ try {
15
+ const named = lstatSync(path);
16
+ if (!named.isFile() || named.nlink !== 1 || named.size > limit) return undefined;
17
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
18
+ try {
19
+ const info = fstatSync(fd);
20
+ if (info.dev !== named.dev || info.ino !== named.ino || !info.isFile() || info.nlink !== 1 || info.size !== named.size) return undefined;
21
+ const buffer = Buffer.alloc(info.size + 1);
22
+ let length = 0;
23
+ while(length < buffer.length){
24
+ const count = readSync(fd, buffer, length, buffer.length - length, length);
25
+ if (count === 0) break;
26
+ length += count;
27
+ }
28
+ const after = fstatSync(fd);
29
+ const current = lstatSync(path);
30
+ if (length !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs || current.dev !== info.dev || current.ino !== info.ino || !current.isFile() || current.nlink !== 1) return undefined;
31
+ const value = JSON.parse(new TextDecoder('utf-8', {
32
+ fatal: true
33
+ }).decode(buffer.subarray(0, length)));
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
35
+ } finally{
36
+ closeSync(fd);
37
+ }
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ }
42
+ function hasSessionControlGrant(dir, chatId) {
43
+ const access = readObject(join(dir, 'access.json'), 128 * 1024);
44
+ return access !== undefined && canControlTelegramSession(access, chatId);
45
+ }
46
+ function controlAddress(name) {
47
+ const match = SLOT_NAME.exec(name);
48
+ if (match === null) return undefined;
49
+ const chatId = match[1];
50
+ const messageId = Number(match[2]);
51
+ return Number.isSafeInteger(Number(chatId)) && Number.isSafeInteger(messageId) ? {
52
+ chatId,
53
+ messageId
54
+ } : undefined;
55
+ }
56
+ function controlIsFresh(queuedAt) {
57
+ const age = Date.now() - queuedAt;
58
+ return age >= 0 && age < ACTION_LIFETIME_MS;
59
+ }
60
+ class ConsoleControlState {
61
+ parent;
62
+ root;
63
+ constructor(dir, botId){
64
+ if (!/^[1-9]\d{0,18}$/u.test(botId)) throw new TypeError('Invalid Telegram console control bot');
65
+ this.parent = join(dir, 'console-control');
66
+ this.root = join(this.parent, botId);
67
+ }
68
+ directory(kind, create = false) {
69
+ const dir = join(this.root, kind);
70
+ for (const path of [
71
+ this.parent,
72
+ this.root,
73
+ dir
74
+ ]){
75
+ if (create) {
76
+ try {
77
+ mkdirSync(path, {
78
+ mode: 0o700
79
+ });
80
+ } catch (error) {
81
+ if (error.code !== 'EEXIST') throw error;
82
+ }
83
+ }
84
+ if (!lstatSync(path).isDirectory()) throw new Error('Invalid Telegram console control directory');
85
+ }
86
+ return dir;
87
+ }
88
+ path(kind, name, create = false) {
89
+ if (controlAddress(name) === undefined) throw new TypeError('Invalid Telegram console control address');
90
+ return join(this.directory(kind, create), name);
91
+ }
92
+ names(kind) {
93
+ try {
94
+ return readdirSync(this.directory(kind), {
95
+ withFileTypes: true
96
+ }).filter((entry)=>entry.isFile() && controlAddress(entry.name) !== undefined).map((entry)=>entry.name).sort();
97
+ } catch (error) {
98
+ if (error.code === 'ENOENT') return [];
99
+ throw error;
100
+ }
101
+ }
102
+ read(kind, name) {
103
+ try {
104
+ const value = readObject(this.path(kind, name));
105
+ if (value?.['v'] !== 1 || typeof value['ownerId'] !== 'string' || !/^[a-f0-9]{64}$/u.test(value['ownerId']) || value['command'] !== 'new' && value['command'] !== 'reload' || typeof value['queuedAt'] !== 'number' || !Number.isSafeInteger(value['queuedAt'])) return undefined;
106
+ return {
107
+ ownerId: value['ownerId'],
108
+ command: value['command'],
109
+ queuedAt: value['queuedAt']
110
+ };
111
+ } catch (error) {
112
+ if (error.code === 'ENOENT') return undefined;
113
+ throw error;
114
+ }
115
+ }
116
+ enqueue(name, ownerId, command) {
117
+ if (this.read('pending', name) !== undefined || this.read('accepted', name) !== undefined) return true;
118
+ const pending = this.names('pending').length;
119
+ if (pending >= MAX_PENDING || pending + this.names('accepted').length >= MAX_CONTROL_SLOTS) return false;
120
+ const written = this.writeOnce(this.path('pending', name, true), {
121
+ v: 1,
122
+ ownerId,
123
+ command,
124
+ queuedAt: Date.now()
125
+ });
126
+ if (written || this.read('pending', name) !== undefined || this.read('accepted', name) !== undefined) return true;
127
+ throw new Error('Invalid Telegram console control slot');
128
+ }
129
+ claim(name, control) {
130
+ if (!controlIsFresh(control.queuedAt)) return false;
131
+ const from = this.path('pending', name);
132
+ const current = this.read('pending', name);
133
+ if (current?.ownerId !== control.ownerId || current.queuedAt !== control.queuedAt || current.command !== control.command) return false;
134
+ if (!this.writeOnce(this.path('accepted', name, true), {
135
+ v: 1,
136
+ ...control
137
+ })) return false;
138
+ rmSync(from, {
139
+ force: true
140
+ });
141
+ return true;
142
+ }
143
+ complete(name, ok) {
144
+ this.writeOnce(this.path('replies', name, true), {
145
+ ok
146
+ });
147
+ }
148
+ takeReply(name) {
149
+ const path = this.path('replies', name);
150
+ const result = readObject(path);
151
+ const control = this.read('accepted', name);
152
+ if (control === undefined || control.queuedAt > Date.now() || Date.now() - control.queuedAt >= RECEIPT_LIFETIME_MS || typeof result?.['ok'] !== 'boolean') return undefined;
153
+ try {
154
+ unlinkSync(path);
155
+ } catch (error) {
156
+ if (error.code === 'ENOENT') return undefined;
157
+ throw error;
158
+ }
159
+ return {
160
+ command: control.command,
161
+ ok: result['ok']
162
+ };
163
+ }
164
+ prune() {
165
+ for (const kind of [
166
+ 'pending',
167
+ 'accepted',
168
+ 'replies'
169
+ ]){
170
+ for (const name of this.names(kind)){
171
+ const path = this.path(kind, name);
172
+ const saved = lstatSync(path, {
173
+ throwIfNoEntry: false
174
+ });
175
+ const lifetime = kind === 'pending' ? ACTION_LIFETIME_MS : RECEIPT_LIFETIME_MS;
176
+ if (saved?.isFile() && Date.now() - saved.mtimeMs >= lifetime) rmSync(path, {
177
+ force: true
178
+ });
179
+ }
180
+ }
181
+ }
182
+ writeOnce(path, value) {
183
+ const temp = `${path}.${randomUUID()}.tmp`;
184
+ try {
185
+ writeFileSync(temp, JSON.stringify(value), {
186
+ flag: 'wx',
187
+ mode: 0o600,
188
+ flush: true
189
+ });
190
+ linkSync(temp, path);
191
+ return true;
192
+ } catch (error) {
193
+ if (error.code === 'EEXIST') return false;
194
+ throw error;
195
+ } finally{
196
+ try {
197
+ rmSync(temp, {
198
+ force: true
199
+ });
200
+ } catch {}
201
+ }
202
+ }
203
+ }
204
+ function telegramRequestSignal(signal) {
205
+ return AbortSignal.any([
206
+ signal
207
+ ]);
208
+ }
209
+ async function sendWithTelegramFloodWait(send, signal) {
210
+ while(true){
211
+ signal?.throwIfAborted();
212
+ try {
213
+ return await send();
214
+ } catch (error) {
215
+ signal?.throwIfAborted();
216
+ if (!(isGrammyError(error)) || error.error_code !== 429) throw error;
217
+ const seconds = error.parameters.retry_after;
218
+ if (seconds === undefined || !Number.isSafeInteger(seconds) || seconds <= 0 || seconds > Math.floor(Number.MAX_SAFE_INTEGER / 1_000)) throw error;
219
+ let remaining = seconds * 1_000;
220
+ while(remaining > 0){
221
+ const delay = Math.min(remaining, 2_147_483_647);
222
+ await telegramRetrySleep(delay, undefined, {
223
+ signal
224
+ });
225
+ remaining -= delay;
226
+ }
227
+ }
228
+ }
229
+ }
230
+ async function sendTelegramText(send, parseMode, signal) {
231
+ try {
232
+ return await sendWithTelegramFloodWait(()=>send(parseMode), signal);
233
+ } catch (error) {
234
+ if (parseMode !== 'MarkdownV2' || !(isGrammyError(error)) || error.error_code !== 400 || !/^Bad Request: can't parse entities(?::|$)/i.test(error.description)) throw error;
235
+ return sendWithTelegramFloodWait(()=>send(undefined), signal);
236
+ }
237
+ }
238
+ async function sendNextConsoleControlReply(bot, dir, controls, signal) {
239
+ if (signal.aborted) return;
240
+ for (const name of controls.names('replies')){
241
+ const address = controlAddress(name);
242
+ if (address === undefined) continue;
243
+ const result = controls.takeReply(name);
244
+ if (result === undefined) continue;
245
+ const { chatId, messageId } = address;
246
+ const text = !result.ok ? 'The session command did not complete.' : result.command === 'new' ? 'Started a new session.' : 'Session reloaded.';
247
+ await sendWithTelegramFloodWait(async ()=>{
248
+ if (!hasSessionControlGrant(dir, chatId)) return;
249
+ await bot.api.sendMessage(chatId, text, {
250
+ reply_parameters: {
251
+ message_id: messageId,
252
+ allow_sending_without_reply: false
253
+ }
254
+ }, telegramRequestSignal(signal));
255
+ }, signal);
256
+ return;
257
+ }
258
+ }
259
+ function startConsoleControlReplies(bot, dir, signal) {
260
+ if (signal.aborted) return;
261
+ const controls = new ConsoleControlState(dir, String(bot.botInfo.id));
262
+ let sending = false;
263
+ let nextPrune = 0;
264
+ let warned = false;
265
+ const timer = setInterval(()=>{
266
+ if (signal.aborted || sending) return;
267
+ sending = true;
268
+ void Promise.resolve().then(async ()=>{
269
+ if (Date.now() >= nextPrune) {
270
+ nextPrune = Date.now() + 60_000;
271
+ controls.prune();
272
+ }
273
+ await sendNextConsoleControlReply(bot, dir, controls, signal);
274
+ warned = false;
275
+ }).catch(()=>{
276
+ if (!signal.aborted && !warned) {
277
+ process.stderr.write('telegram channel: could not deliver a console control reply\n');
278
+ warned = true;
279
+ }
280
+ }).finally(()=>{
281
+ sending = false;
282
+ });
283
+ }, 750).unref();
284
+ signal.addEventListener('abort', ()=>clearInterval(timer), {
285
+ once: true
286
+ });
287
+ }
288
+ let isGrammyError = () => false;
289
+ export function setGrammyErrorType(type) { isGrammyError = error => error instanceof type; }
290
+ // Bind controls to the numeric TUI lease and to the same owner, bot and session.
291
+ const BINDING_FILE = 'tui-session-control.json';
292
+ const BINDING_TTL_MS = 90_000;
293
+ const BINDING_REFRESH_MS = 10_000;
294
+ const BOT_ID = /^[1-9]\d{0,18}$/u;
295
+
296
+ function underLease(dir, owner, pid) {
297
+ const value = readObject(join(dir, 'tui-owner.json'));
298
+ if (value?.version !== 1 || value.ownerId !== owner || value.pid !== pid) return false;
299
+ const file = join(dir, 'tui.pid');
300
+ let fd;
301
+ try {
302
+ const named = lstatSync(file);
303
+ const age = Date.now() - Math.floor(named.mtimeMs);
304
+ if (!named.isFile() || named.nlink !== 1 || named.size > 16 || age < 0 || age >= BINDING_TTL_MS) return false;
305
+ fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
306
+ const info = fstatSync(fd);
307
+ if (info.dev !== named.dev || info.ino !== named.ino || info.nlink !== 1 || !info.isFile()) return false;
308
+ const bytes = Buffer.alloc(17);
309
+ const count = readSync(fd, bytes, 0, bytes.length, 0);
310
+ const current = lstatSync(file);
311
+ return current.dev === info.dev && current.ino === info.ino && current.mtimeMs === info.mtimeMs &&
312
+ current.nlink === 1 && current.isFile() && count === info.size && bytes.subarray(0, count).toString() === String(pid);
313
+ } catch {
314
+ return false;
315
+ } finally {
316
+ if (fd !== undefined) closeSync(fd);
317
+ }
318
+ }
319
+
320
+ function isQuietBinding(binding, botId) {
321
+ const age = Date.now() - binding?.publishedAt;
322
+ return binding?.v === 1 && binding.botId === botId && BOT_ID.test(botId) &&
323
+ /^[a-f0-9]{64}$/u.test(binding.ownerId) && typeof binding.channelOwner === 'string' &&
324
+ Number.isSafeInteger(binding.pid) && binding.pid > 1 && Number.isSafeInteger(binding.publishedAt) &&
325
+ age >= 0 && age < BINDING_TTL_MS;
326
+ }
327
+
328
+ export function readBinding(dir, botId) {
329
+ const binding = readObject(join(dir, BINDING_FILE));
330
+ if (!isQuietBinding(binding, botId) || !underLease(dir, binding.channelOwner, binding.pid)) return;
331
+ try { process.kill(binding.pid, 0); } catch { return; }
332
+ return binding;
333
+ }
334
+
335
+ export function readBotId(dir) {
336
+ try {
337
+ const file = join(dir, '.env');
338
+ const named = lstatSync(file);
339
+ if (!named.isFile() || named.nlink !== 1 || named.size > 128 * 1024) return;
340
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
341
+ try {
342
+ const info = fstatSync(fd);
343
+ if (info.dev !== named.dev || info.ino !== named.ino || info.nlink !== 1 || info.size !== named.size) return;
344
+ const bytes = Buffer.alloc(info.size + 1);
345
+ const count = readSync(fd, bytes, 0, bytes.length, 0);
346
+ if (count !== info.size) return;
347
+ const prefix = /^\uFEFF?BLUN_TELEGRAM_BOT_TOKEN[ \t]*=[ \t]*["']?([1-9]\d{0,18}):/mu;
348
+ return prefix.exec(bytes.subarray(0, count).toString('utf8'))?.[1];
349
+ } finally {
350
+ closeSync(fd);
351
+ }
352
+ } catch { /* No valid configured bot. */ }
353
+ }
354
+
355
+ export function publishBinding(dir, channelOwner, botId, sessionId, previous) {
356
+ if (!BOT_ID.test(botId) || !underLease(dir, channelOwner, process.pid)) throw new Error('No active Telegram channel lease');
357
+ const ownerId = createHash('sha256').update(JSON.stringify([channelOwner, botId, sessionId])).digest('hex');
358
+ if (previous?.ownerId === ownerId && Date.now() - previous.publishedAt < BINDING_REFRESH_MS &&
359
+ readBinding(dir, botId)?.ownerId === ownerId) return previous;
360
+ const data = { v: 1, channelOwner, botId, ownerId, pid: process.pid, publishedAt: Date.now() };
361
+ const file = join(dir, BINDING_FILE);
362
+ const temp = file + '.' + randomUUID() + '.tmp';
363
+ try {
364
+ writeFileSync(temp, JSON.stringify(data), { flag: 'wx', mode: 0o600, flush: true });
365
+ if (!underLease(dir, channelOwner, process.pid)) throw new Error('Telegram channel lease changed');
366
+ renameSync(temp, file);
367
+ return data;
368
+ } finally {
369
+ rmSync(temp, { force: true });
370
+ }
371
+ }
372
+
373
+ export function clearBinding(dir, expected) {
374
+ const file = join(dir, BINDING_FILE);
375
+ const record = readObject(file);
376
+ if (record?.ownerId === expected.ownerId && record?.channelOwner === expected.channelOwner &&
377
+ underLease(dir, expected.channelOwner, process.pid)) rmSync(file, { force: true });
378
+ }
379
+
380
+ export function enqueueRequest(dir, botId, request) {
381
+ const binding = readBinding(dir, botId);
382
+ if (binding === undefined || !hasSessionControlGrant(dir, request.chatId)) return;
383
+ const name = String(request.updateId).padStart(16, '0') + '_' + request.chatId + '_' + request.messageId + '.json';
384
+ new ConsoleControlState(dir, botId).enqueue(name, binding.ownerId, request.command);
385
+ }
386
+
387
+
388
+ export { ConsoleControlState, controlAddress, controlIsFresh, hasSessionControlGrant, startConsoleControlReplies };
@@ -73160,6 +73160,7 @@ function readAccess() {
73160
73160
  return {
73161
73161
  dmPolicy: parsed.dmPolicy ?? "pairing",
73162
73162
  allowFrom: normalizeIdList(parsed.allowFrom),
73163
+ sessionControlAllowFrom: Array.isArray(parsed.sessionControlAllowFrom) ? parsed.sessionControlAllowFrom.filter(id => typeof id === "string") : undefined,
73163
73164
  groups: normalizeGroups(parsed.groups),
73164
73165
  pending: parsed.pending ?? {},
73165
73166
  mentionPatterns: parsed.mentionPatterns,