-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtelegram-bot.js
More file actions
4153 lines (3634 loc) · 163 KB
/
telegram-bot.js
File metadata and controls
4153 lines (3634 loc) · 163 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ─── Telegram Bot Module for Claude Code Studio ─────────────────────────────
// Long-polling bot that runs alongside the main server.
// No external dependencies — uses Node 20 built-in fetch.
// Security: Telegram User ID whitelist via pairing codes, content sanitization.
'use strict';
const EventEmitter = require('events');
const crypto = require('crypto');
const TELEGRAM_API = 'https://api.telegram.org/bot';
const PAIRING_CODE_TTL = 5 * 60 * 1000; // 5 minutes
const PAIRING_CODE_LENGTH = 6;
const MAX_FAILED_ATTEMPTS = 3;
const BLOCK_DURATION = 15 * 60 * 1000; // 15 minutes after too many wrong codes
const POLL_TIMEOUT = 30; // seconds (Telegram long-polling)
const MAX_MESSAGE_LENGTH = 4000; // Telegram max ~4096, keep margin
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const RATE_LIMIT_MAX = 30; // commands per minute
// Patterns that indicate sensitive content — never sent through Telegram
const SENSITIVE_FILE_PATTERNS = [
/\.env$/i, /\.env\.\w+$/i,
/auth\.json$/i, /sessions-auth\.json$/i,
/config\.json$/i,
/credentials/i, /secrets?\./i,
/\.pem$/i, /\.key$/i, /\.p12$/i, /\.pfx$/i,
/id_rsa/i, /id_ed25519/i,
];
const SECRET_PATTERNS = [
/(?:api[_-]?key|token|secret|password|passwd|pwd)\s*[:=]\s*['"]?[\w\-\.]{8,}/gi,
/sk-[a-zA-Z0-9]{20,}/g,
/ghp_[a-zA-Z0-9]{36}/g,
/glpat-[a-zA-Z0-9\-_]{20,}/g,
/xoxb-[a-zA-Z0-9\-]+/g,
/AKIA[0-9A-Z]{16}/g,
/Bearer\s+[a-zA-Z0-9\-_.~+/]{20,}/g,
];
// ─── FSM States ─────────────────────────────────────────────────────────────
const FSM_STATES = {
IDLE: 'IDLE',
COMPOSING: 'COMPOSING',
AWAITING_TASK_TITLE: 'AWAITING_TASK_TITLE',
AWAITING_TASK_DESCRIPTION: 'AWAITING_TASK_DESCRIPTION',
AWAITING_ASK_RESPONSE: 'AWAITING_ASK_RESPONSE',
};
// ─── Screen Registry ────────────────────────────────────────────────────────
// Defines the navigation hierarchy: each screen has a handler method and a parent.
// parent can be a string (static) or a function (dynamic, e.g. depends on context).
const SCREENS = {
MAIN: { parent: null, handler: '_screenMainMenu' },
PROJECTS: { parent: 'MAIN', handler: '_screenProjects' },
PROJECT: { parent: 'PROJECTS', handler: '_screenProjectSelect' },
CHATS: { parent: (ctx) => ctx.projectWorkdir ? 'PROJECT' : 'MAIN', handler: '_screenChats' },
DIALOG: { parent: 'CHATS', handler: '_screenDialog' },
DIALOG_FULL: { parent: 'DIALOG', handler: '_screenDialogFull' },
FILES: { parent: (ctx) => ctx.projectWorkdir ? 'PROJECT' : 'MAIN', handler: '_screenFiles' },
TASKS: { parent: (ctx) => ctx.projectWorkdir ? 'PROJECT' : 'MAIN', handler: '_screenTasks' },
STATUS: { parent: 'MAIN', handler: '_screenStatus' },
TUNNEL: { parent: 'MAIN', handler: '_cmdTunnel' },
SETTINGS: { parent: 'MAIN', handler: '_screenSettings' },
};
// Maps callback_data prefixes to SCREENS keys for routing lookup.
// Preserves backward compatibility — old buttons in chat history still route correctly.
const CALLBACK_TO_SCREEN = {
'm:menu': 'MAIN',
'p:list': 'PROJECTS',
'p:sel:': 'PROJECT',
'c:list:': 'CHATS',
'd:overview': 'DIALOG',
'd:all:': 'DIALOG_FULL',
'f:': 'FILES',
't:list': 'TASKS',
't:all': 'TASKS',
'm:status': 'STATUS',
'tn:menu': 'TUNNEL',
's:menu': 'SETTINGS',
};
// Reverse map: SCREENS key -> callback_data for Back button navigation.
// Used by _buildBackButton to generate reliable parent callback_data.
const SCREEN_TO_CALLBACK = {
MAIN: 'm:menu',
PROJECTS: 'p:list',
PROJECT: 'p:list', // back to projects list (project detail needs index we don't have)
CHATS: 'c:list:0',
DIALOG: 'd:overview',
DIALOG_FULL: 'd:all:0',
FILES: 'f:.',
TASKS: 't:list',
STATUS: 'm:status',
TUNNEL: 'tn:menu',
SETTINGS: 's:menu',
};
// ─── Telegram message constants (used by TelegramProxy) ─────────────────────
const TG_COLLAPSE_THRESHOLD = 800;
const TG_PREVIEW_LENGTH = 600;
// ─── Bot Internationalization ───────────────────────────────────────────────
const BOT_I18N = require('./telegram-bot-i18n');
class TelegramBot extends EventEmitter {
/**
* @param {import('better-sqlite3').Database} db
* @param {object} opts
* @param {object} opts.log - Logger instance { info, warn, error, debug }
*/
constructor(db, opts = {}) {
super();
this.db = db;
this.log = opts.log || console;
this.token = null;
this.running = false;
this._pollTimer = null;
this._offset = 0;
this._acceptNewConnections = true;
this.lang = opts.lang || 'uk';
// In-memory state
this._pairingCodes = new Map(); // code → { createdAt, expiresAt }
this._failedAttempts = new Map(); // telegramUserId → { count, blockedUntil }
this._userContext = new Map(); // telegramUserId → { sessionId, projectWorkdir }
this._rateLimit = new Map(); // telegramUserId → { count, resetAt }
this._currentThreadId = null; // Legacy: used by shared commands for forum-aware button generation. Will be removed in Phase 4.
this._botId = null; // bot's own user ID (set on start)
// DB setup
this._initDb();
this._prepareStmts();
// Forum module (composition pattern — receives API facade, not bot instance)
const TelegramBotForum = require('./telegram-bot-forum');
this._forum = new TelegramBotForum({
db: this.db,
log: this.log,
callApi: this._callApi.bind(this),
sendMessage: this._sendMessage.bind(this),
editScreen: this._editScreen.bind(this),
showScreen: this._showScreen.bind(this),
t: this._t.bind(this),
escHtml: this._escHtml.bind(this),
sanitize: this._sanitize.bind(this),
mdToHtml: this._mdToHtml.bind(this),
chunkForTelegram: this._chunkForTelegram.bind(this),
timeAgo: this._timeAgo.bind(this),
stmts: this._stmts,
emit: this.emit.bind(this),
getDirectContext: this._getContext.bind(this),
saveDeviceContext: this._saveDeviceContext.bind(this),
botId: () => this._botId,
botUsername: () => this._botInfo?.username || 'your_bot',
cmdStatus: this._cmdStatus.bind(this),
cmdFiles: this._cmdFiles.bind(this),
cmdCat: this._cmdCat.bind(this),
cmdLast: this._cmdLast.bind(this),
cmdFull: this._cmdFull.bind(this),
cmdDiff: this._cmdDiff.bind(this),
cmdLog: this._cmdLog.bind(this),
cmdStop: this._cmdStop.bind(this),
handleMediaMessage: this._handleMediaMessage.bind(this),
});
}
// ─── i18n ─────────────────────────────────────────────────────────────────
_t(key, params = {}) {
const dict = BOT_I18N[this.lang] || BOT_I18N.uk;
let text = dict[key] || BOT_I18N.uk[key] || key;
for (const [k, v] of Object.entries(params)) {
text = text.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
}
return text;
}
// ─── Database ──────────────────────────────────────────────────────────────
_initDb() {
this.db.exec(`
CREATE TABLE IF NOT EXISTS telegram_devices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_id INTEGER NOT NULL UNIQUE,
telegram_chat_id INTEGER NOT NULL,
display_name TEXT,
username TEXT,
paired_at TEXT NOT NULL DEFAULT (datetime('now')),
last_active TEXT,
notifications_enabled INTEGER DEFAULT 1
);
`);
// Phase 2: session persistence columns
try { this.db.exec("ALTER TABLE telegram_devices ADD COLUMN last_session_id TEXT"); } catch(e) {}
try { this.db.exec("ALTER TABLE telegram_devices ADD COLUMN last_workdir TEXT"); } catch(e) {}
// Forum mode: forum_chat_id on device (the supergroup ID)
try { this.db.exec("ALTER TABLE telegram_devices ADD COLUMN forum_chat_id INTEGER"); } catch(e) {}
// Forum topics mapping table
this.db.exec(`
CREATE TABLE IF NOT EXISTS forum_topics (
thread_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
type TEXT NOT NULL,
workdir TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (thread_id, chat_id)
);
`);
}
_prepareStmts() {
this._stmts = {
getDevice: this.db.prepare('SELECT * FROM telegram_devices WHERE telegram_user_id = ?'),
getAllDevices: this.db.prepare('SELECT * FROM telegram_devices ORDER BY paired_at DESC'),
addDevice: this.db.prepare('INSERT INTO telegram_devices (telegram_user_id, telegram_chat_id, display_name, username) VALUES (?, ?, ?, ?)'),
removeDevice: this.db.prepare('DELETE FROM telegram_devices WHERE id = ?'),
removeByUserId: this.db.prepare('DELETE FROM telegram_devices WHERE telegram_user_id = ?'),
updateLastActive: this.db.prepare('UPDATE telegram_devices SET last_active = datetime(\'now\') WHERE telegram_user_id = ?'),
getDeviceById: this.db.prepare('SELECT * FROM telegram_devices WHERE id = ?'),
updateNotifications: this.db.prepare('UPDATE telegram_devices SET notifications_enabled = ? WHERE telegram_user_id = ?'),
// Forum mode
setForumChatId: this.db.prepare('UPDATE telegram_devices SET forum_chat_id = ? WHERE telegram_user_id = ?'),
getForumDevice: this.db.prepare('SELECT * FROM telegram_devices WHERE forum_chat_id = ? AND telegram_user_id = ?'),
getForumDevices: this.db.prepare('SELECT * FROM telegram_devices WHERE forum_chat_id IS NOT NULL AND notifications_enabled = 1'),
addForumTopic: this.db.prepare('INSERT OR REPLACE INTO forum_topics (thread_id, chat_id, type, workdir) VALUES (?, ?, ?, ?)'),
getForumTopic: this.db.prepare('SELECT * FROM forum_topics WHERE thread_id = ? AND chat_id = ?'),
getForumTopics: this.db.prepare('SELECT * FROM forum_topics WHERE chat_id = ?'),
getForumTopicByWorkdir: this.db.prepare('SELECT * FROM forum_topics WHERE chat_id = ? AND type = ? AND workdir = ?'),
deleteForumTopic: this.db.prepare('DELETE FROM forum_topics WHERE thread_id = ? AND chat_id = ?'),
deleteForumTopicsByChatId: this.db.prepare('DELETE FROM forum_topics WHERE chat_id = ?'),
// Forum sessions
insertSession: this.db.prepare("INSERT INTO sessions (id, title, created_at, updated_at, workdir, model, engine) VALUES (?, ?, datetime('now'), datetime('now'), ?, 'sonnet', 'cli')"),
getSessionsByWorkdir: this.db.prepare('SELECT id, title, updated_at, (SELECT COUNT(*) FROM messages WHERE session_id = s.id) as msg_count FROM sessions s WHERE workdir = ? ORDER BY updated_at DESC LIMIT 15'),
// Forum tasks
insertTask: this.db.prepare("INSERT INTO tasks (id, title, description, notes, status, sort_order, workdir) VALUES (?, ?, '', '', 'backlog', 0, ?)"),
listTasksOrdered: this.db.prepare("SELECT id, title, status FROM tasks ORDER BY CASE status WHEN 'in_progress' THEN 0 WHEN 'todo' THEN 1 WHEN 'backlog' THEN 2 WHEN 'blocked' THEN 3 WHEN 'done' THEN 4 END, sort_order ASC LIMIT 30"),
findTaskByIdLike: this.db.prepare('SELECT * FROM tasks WHERE id LIKE ?'),
updateTaskStatus: this.db.prepare("UPDATE tasks SET status = ?, updated_at = datetime('now') WHERE id = ?"),
// Ask notification
getSessionInfo: this.db.prepare('SELECT title, workdir FROM sessions WHERE id = ?'),
};
}
// ─── Lifecycle ─────────────────────────────────────────────────────────────
/**
* Start the bot with the given token.
* @param {string} botToken
*/
async start(botToken) {
if (this.running) return;
this.token = botToken;
if (!this.token) throw new Error('Bot token is required');
// Validate token and ensure clean polling state
try {
const me = await this._callApi('getMe');
this._botInfo = me;
this._botId = me.id;
// Delete any stale webhook — Telegram ignores getUpdates if webhook is set
await this._callApi('deleteWebhook', { drop_pending_updates: false });
// Set bot command menu (only /start, /help, /cancel, /status)
await this._setCommands();
this.log.info(`[telegram] Bot started: @${me.username} (${me.first_name})`);
} catch (err) {
this.log.error(`[telegram] Invalid bot token: ${err.message}`);
throw new Error(`Invalid bot token: ${err.message}`);
}
this.running = true;
this._poll();
// Periodic cleanup of in-memory Maps to prevent unbounded growth
this._cleanupInterval = setInterval(() => {
const now = Date.now();
for (const [k, v] of this._pairingCodes) if (now > v.expiresAt) this._pairingCodes.delete(k);
for (const [k, v] of this._failedAttempts) if (now > v.blockedUntil) this._failedAttempts.delete(k);
for (const [k, v] of this._rateLimit) if (now > v.resetAt) this._rateLimit.delete(k);
}, 10 * 60 * 1000); // every 10 minutes
return this._botInfo;
}
stop() {
this.running = false;
if (this._pollTimer) {
clearTimeout(this._pollTimer);
this._pollTimer = null;
}
if (this._cleanupInterval) {
clearInterval(this._cleanupInterval);
this._cleanupInterval = null;
}
this.log.info('[telegram] Bot stopped');
}
isRunning() { return this.running; }
getBotInfo() { return this._botInfo || null; }
// ─── Lock Mode ─────────────────────────────────────────────────────────────
get acceptNewConnections() { return this._acceptNewConnections; }
set acceptNewConnections(val) {
this._acceptNewConnections = !!val;
if (!val) {
// Clear all pending pairing codes when locking
this._pairingCodes.clear();
}
}
// ─── Polling ───────────────────────────────────────────────────────────────
async _poll() {
if (!this.running) return;
try {
const updates = await this._callApi('getUpdates', {
offset: this._offset,
timeout: POLL_TIMEOUT,
allowed_updates: JSON.stringify(['message', 'callback_query']),
});
if (updates && updates.length > 0) {
for (const update of updates) {
this._offset = update.update_id + 1;
try {
await this._handleUpdate(update);
} catch (err) {
this.log.error(`[telegram] Error handling update: ${err.message}`);
}
}
}
} catch (err) {
// Network errors — retry after delay
if (!err.message?.includes('Invalid bot token')) {
this.log.warn(`[telegram] Poll error (retrying in 5s): ${err.message}`);
this._pollTimer = setTimeout(() => this._poll(), 5000);
return;
}
this.log.error(`[telegram] Fatal poll error: ${err.message}`);
this.stop();
return;
}
// Schedule next poll immediately (long-polling handles the wait)
if (this.running) {
this._pollTimer = setTimeout(() => this._poll(), 100);
}
}
// ─── Telegram API ──────────────────────────────────────────────────────────
async _callApi(method, params = {}) {
const url = `${TELEGRAM_API}${this.token}/${method}`;
const body = {};
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== null) body[k] = v;
}
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(POLL_TIMEOUT * 1000 + 10000), // poll timeout + margin
});
const data = await res.json();
if (!data.ok) {
throw new Error(data.description || `Telegram API error: ${method}`);
}
return data.result;
}
async _sendMessage(chatId, text, options = {}) {
// Truncate long messages
let safeText = text;
if (safeText.length > MAX_MESSAGE_LENGTH) {
safeText = safeText.substring(0, MAX_MESSAGE_LENGTH) + '\n\n' + this._t('files_truncated_short');
}
const params = {
chat_id: chatId,
text: safeText,
parse_mode: 'HTML',
...options,
};
// Auto-inject thread_id for forum topics (unless already specified)
if (this._currentThreadId && !params.message_thread_id) {
params.message_thread_id = this._currentThreadId;
}
try {
return await this._callApi('sendMessage', params);
} catch (err) {
// Retry without parse_mode if HTML parsing fails
if (err.message?.includes("can't parse")) {
params.parse_mode = undefined;
return await this._callApi('sendMessage', params);
}
throw err;
}
}
async _editScreen(chatId, msgId, text, keyboard) {
if (!msgId) {
// No message to edit — send a new one
return this._showScreen(chatId, null, text, keyboard);
}
const params = {
chat_id: chatId,
message_id: msgId,
text: text.length > MAX_MESSAGE_LENGTH ? text.substring(0, MAX_MESSAGE_LENGTH) + '\n\n' + this._t('files_truncated_short') : text,
parse_mode: 'HTML',
};
if (keyboard) params.reply_markup = JSON.stringify({ inline_keyboard: keyboard });
try {
return await this._callApi('editMessageText', params);
} catch (err) {
if (err.message?.includes('message is not modified')) return null;
if (err.message?.includes("can't parse")) {
params.parse_mode = undefined;
try { return await this._callApi('editMessageText', params); } catch { /* fall through */ }
}
// Any edit failure — fall back to sending a new message
this.log.warn(`[telegram] editScreen fallback to new message: ${err.message}`);
return this._showScreen(chatId, null, text, keyboard);
}
}
async _showScreen(chatId, userId, text, keyboard) {
const params = {};
if (keyboard) params.reply_markup = JSON.stringify({ inline_keyboard: keyboard });
const sent = await this._sendMessage(chatId, text, params);
return sent;
}
async _answerCallback(callbackQueryId, text) {
try {
await this._callApi('answerCallbackQuery', { callback_query_id: callbackQueryId, text });
} catch {}
}
/**
* Build a Back button row for the given screen key.
* Uses the SCREENS registry parent chain to determine the back destination.
* @param {string} screenKey - Key from SCREENS registry (e.g. 'PROJECTS', 'DIALOG')
* @param {object} ctx - User context (for dynamic parent resolution)
* @returns {Array|null} Inline keyboard row with back button, or null for MAIN
*/
_buildBackButton(screenKey, ctx) {
const screen = SCREENS[screenKey];
if (!screen) return null;
let parentKey;
if (typeof screen.parent === 'function') {
parentKey = screen.parent(ctx);
} else {
parentKey = screen.parent;
}
if (!parentKey) return null; // MAIN has no back button
const parentCb = SCREEN_TO_CALLBACK[parentKey] || 'm:menu';
return [{ text: this._t('btn_back'), callback_data: parentCb }];
}
/**
* Build a context header line showing active project/chat.
* Prepended to every screen's text body for consistent context visibility.
* @param {object} ctx - User context (projectWorkdir, sessionId)
* @returns {string} Formatted header with trailing double newline
*/
_buildContextHeader(ctx) {
const parts = [];
if (ctx.projectWorkdir) {
const name = ctx.projectWorkdir.split('/').filter(Boolean).pop() || '...';
parts.push(this._t('header_project', { name: this._escHtml(name) }));
}
if (ctx.sessionId) {
try {
const sess = this.db.prepare('SELECT title FROM sessions WHERE id=?').get(ctx.sessionId);
if (sess?.title) {
parts.push(this._t('header_chat', { title: this._escHtml(sess.title.substring(0, 30)) }));
}
} catch { /* ignore DB errors in header */ }
}
if (parts.length === 0) return this._t('header_none') + '\n\n';
return parts.join(this._t('header_separator')) + '\n\n';
}
// ─── Persistent Reply Keyboard ────────────────────────────────────────────
/**
* Build a dynamic context-aware persistent reply keyboard.
* Row 1: Write button (+ chat name if session active), Menu button.
* Row 2: Project button (if project active), Status button.
* @param {object} ctx - User context
* @returns {object} ReplyKeyboardMarkup object
*/
_buildReplyKeyboard(ctx) {
const row1 = [];
// Write button always first — includes chat name when session active
if (ctx.sessionId) {
let chatName;
try {
const sess = this.db.prepare('SELECT title FROM sessions WHERE id=?').get(ctx.sessionId);
chatName = (sess?.title || this._t('chat_untitled')).substring(0, 18);
} catch {
chatName = this._t('chat_untitled');
}
row1.push({ text: `${this._t('kb_write')} · ${chatName}` });
} else {
row1.push({ text: this._t('kb_write') });
}
row1.push({ text: this._t('kb_menu') });
const rows = [row1];
// Second row: project context + status
if (ctx.projectWorkdir) {
const pName = ctx.projectWorkdir.split('/').filter(Boolean).pop() || '...';
rows.push([
{ text: `${this._t('kb_project_prefix')} ${pName}`.substring(0, 28) },
{ text: this._t('kb_status') },
]);
} else {
rows.push([{ text: this._t('kb_status') }]);
}
return {
keyboard: rows,
resize_keyboard: true,
is_persistent: true,
};
}
/**
* Send a message with the dynamic persistent reply keyboard attached.
* Use when context changes (project/chat selection) to refresh the bottom bar.
* @param {number} chatId
* @param {object} ctx - User context
* @param {string} message - Text to send alongside keyboard update
*/
async _sendReplyKeyboard(chatId, ctx, message) {
return this._sendMessage(chatId, message, {
reply_markup: JSON.stringify(this._buildReplyKeyboard(ctx)),
});
}
/**
* Set the bot's command menu via setMyCommands.
* Called once at startup. Only includes /start, /help, /cancel, /status.
* Navigation commands (/project, /chat, etc.) are intentionally excluded.
*/
async _setCommands() {
try {
await this._callApi('setMyCommands', {
commands: [
{ command: 'start', description: this._t('cmd_start_desc') },
{ command: 'help', description: this._t('cmd_help_desc') },
{ command: 'cancel', description: this._t('cmd_cancel_desc') },
{ command: 'status', description: this._t('cmd_status_desc') },
],
});
} catch (err) {
this.log.warn(`[telegram] Failed to set commands: ${err.message}`);
}
}
// ─── Pairing ───────────────────────────────────────────────────────────────
/**
* Generate a new 6-character pairing code.
* @returns {{ code: string, formattedCode: string, expiresAt: number } | { error: string }}
*/
generatePairingCode() {
if (!this._acceptNewConnections) {
return { error: 'New connections are disabled' };
}
if (!this.running) {
return { error: 'Bot is not running' };
}
// Clear expired codes
const now = Date.now();
for (const [code, data] of this._pairingCodes) {
if (now > data.expiresAt) this._pairingCodes.delete(code);
}
// Generate unique code
let code;
do {
code = crypto.randomBytes(4).toString('hex').substring(0, PAIRING_CODE_LENGTH).toUpperCase();
} while (this._pairingCodes.has(code));
const expiresAt = now + PAIRING_CODE_TTL;
this._pairingCodes.set(code, { createdAt: now, expiresAt });
// Format as "XXX·XXX"
const formattedCode = `${code.slice(0, 3)}·${code.slice(3)}`;
return { code, formattedCode, expiresAt };
}
/**
* Validate a pairing code submitted by a Telegram user.
* @returns {boolean}
*/
_validatePairingCode(code) {
const clean = code.replace(/[\s·\-\.]/g, '').toUpperCase();
const data = this._pairingCodes.get(clean);
if (!data) return false;
if (Date.now() > data.expiresAt) {
this._pairingCodes.delete(clean);
return false;
}
// One-time use
this._pairingCodes.delete(clean);
return true;
}
// ─── Rate Limiting ─────────────────────────────────────────────────────────
_checkRateLimit(userId) {
const now = Date.now();
const entry = this._rateLimit.get(userId);
if (!entry || now > entry.resetAt) {
this._rateLimit.set(userId, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
return true;
}
entry.count++;
return entry.count <= RATE_LIMIT_MAX;
}
_isBlocked(userId) {
const entry = this._failedAttempts.get(userId);
if (!entry) return false;
if (Date.now() > entry.blockedUntil) {
this._failedAttempts.delete(userId);
return false;
}
return entry.count >= MAX_FAILED_ATTEMPTS;
}
_recordFailedAttempt(userId) {
const entry = this._failedAttempts.get(userId) || { count: 0, blockedUntil: 0 };
entry.count++;
if (entry.count >= MAX_FAILED_ATTEMPTS) {
entry.blockedUntil = Date.now() + BLOCK_DURATION;
}
this._failedAttempts.set(userId, entry);
return entry.count;
}
// ─── Authorization ─────────────────────────────────────────────────────────
_isAuthorized(userId) {
const device = this._stmts.getDevice.get(userId);
return !!device;
}
// ─── Content Security ──────────────────────────────────────────────────────
_isSensitiveFile(filePath) {
return SENSITIVE_FILE_PATTERNS.some(p => p.test(filePath));
}
_sanitize(text) {
if (!text) return '';
let safe = String(text);
for (const pattern of SECRET_PATTERNS) {
pattern.lastIndex = 0; // safety: reset stale state from global regex
safe = safe.replace(pattern, '[REDACTED]');
}
return safe;
}
// ─── Update Handler ────────────────────────────────────────────────────────
async _handleUpdate(update) {
// Handle callback queries (inline button taps)
if (update.callback_query) {
// Set thread context from callback source message
this._currentThreadId = update.callback_query.message?.message_thread_id || null;
try {
await this._handleCallback(update.callback_query);
} finally {
this._currentThreadId = null;
}
return;
}
const msg = update.message;
if (!msg) return;
const userId = msg.from?.id;
const chatId = msg.chat?.id;
if (!userId || !chatId) return;
// Set thread context for forum topics
this._currentThreadId = msg.message_thread_id || null;
const isForum = msg.chat?.type === 'supergroup' && msg.is_topic_message;
try {
// Supergroup: handle /connect command early (before forum routing and auth)
// Works both with and without @botname suffix, in topics and General
if (msg.chat?.type === 'supergroup' && msg.text) {
const connectText = msg.text.trim().toLowerCase().replace(/@\w+$/, '');
if (connectText === '/connect') {
return await this._forum.handleConnect(msg);
}
}
// Forum mode: route to forum handler if message is from this user's paired forum group
if (isForum && this._isAuthorized(userId)) {
const device = this._stmts.getDevice.get(userId);
if (device?.forum_chat_id !== chatId) return; // Not this user's forum
if (!this._checkRateLimit(userId)) return; // Rate-limit forum too
this._stmts.updateLastActive.run(userId);
this._restoreDeviceContext(userId);
const threadId = msg.message_thread_id || null;
return await this._forum.handleMessage(msg, threadId);
}
// Handle media messages (photos, documents, files)
if (msg.photo || msg.document) {
if (!this._isAuthorized(userId)) return;
if (!this._checkRateLimit(userId)) return;
this._stmts.updateLastActive.run(userId);
this._restoreDeviceContext(userId);
return this._handleMediaMessage(msg);
}
if (!msg.text) return;
const text = msg.text.trim();
// Rate limiting for authorized users
if (this._isAuthorized(userId) && !this._checkRateLimit(userId)) {
await this._sendMessage(chatId, this._t('rate_limit'));
return;
}
// If user is not authorized — only handle pairing
if (!this._isAuthorized(userId)) {
await this._handleUnauthorized(msg);
return;
}
// Update last active
this._stmts.updateLastActive.run(userId);
// Restore persisted context on first interaction
this._restoreDeviceContext(userId);
// Persistent keyboard buttons (prefix match for dynamic labels like "✉ Write · chatName")
if (text === this._t('kb_menu')) { return this._screenMainMenu(chatId, userId); }
if (text.startsWith(this._t('kb_write'))) { return this._handleWriteButton(chatId, userId); }
if (text === this._t('kb_status')) { return this._screenStatus(chatId, userId); }
if (text.startsWith(this._t('kb_project_prefix'))) {
// Project button tap — show project list (current project context)
return this._screenProjects(chatId, userId, 'p:list:0');
}
// Fallback: match keyboard button text from any language (handles encoding/language mismatches)
{
const low = text.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, '').trim();
const menuWords = ['menu', 'меню'];
const statusWords = ['status', 'статус'];
if (menuWords.includes(low)) { return this._screenMainMenu(chatId, userId); }
if (statusWords.includes(low)) { return this._screenStatus(chatId, userId); }
}
// Legacy: 🔔 bell button (replaced by Settings, but keep for backwards compat)
if (text === '🔔') {
const device = this._stmts.getDevice.get(userId);
const newVal = device?.notifications_enabled ? 0 : 1;
this._stmts.updateNotifications.run(newVal, userId);
return this._sendMessage(chatId, newVal ? this._t('notif_on') : this._t('notif_off'));
}
// Intercept: if there's a pending ask_user question, any text resolves it
const ctx = this._getContext(userId);
if (ctx.state === FSM_STATES.AWAITING_ASK_RESPONSE) {
const requestId = ctx.stateData?.askRequestId;
const origAskMsgId = ctx.stateData?.askMsgId;
const origAskChatId = ctx.stateData?.askChatId;
ctx.state = FSM_STATES.IDLE;
ctx.stateData = null;
this.emit('ask_user_response', { requestId, answer: text });
await this._sendMessage(chatId, this._t('ask_answered'));
// Clean up original ask message (remove stale buttons)
if (origAskMsgId && origAskChatId) {
this._callApi('editMessageText', {
chat_id: origAskChatId,
message_id: origAskMsgId,
text: this._t('ask_answered'),
parse_mode: 'HTML',
}).catch(() => {});
}
return;
}
// Route commands
if (text.startsWith('/')) {
await this._handleCommand(msg);
} else {
// Free text — send to active chat session
await this._handleTextMessage(msg);
}
} finally {
this._currentThreadId = null;
}
}
// ─── Unauthorized User (Pairing Flow) ──────────────────────────────────────
async _handleUnauthorized(msg) {
const userId = msg.from.id;
const chatId = msg.chat.id;
const text = msg.text.trim();
// Check if blocked
if (this._isBlocked(userId)) {
await this._sendMessage(chatId, this._t('blocked'));
return;
}
// /start command
if (text === '/start') {
if (!this._acceptNewConnections) {
await this._sendMessage(chatId, this._t('new_conn_disabled'));
return;
}
await this._sendMessage(chatId, this._t('start_pairing'));
return;
}
// Anything else — treat as pairing code attempt
if (!this._acceptNewConnections) {
await this._sendMessage(chatId, this._t('new_conn_off'));
return;
}
// Validate pairing code
const isValid = this._validatePairingCode(text);
if (isValid) {
// Register device
const displayName = [msg.from.first_name, msg.from.last_name].filter(Boolean).join(' ') || 'Unknown';
const username = msg.from.username || null;
try {
this._stmts.addDevice.run(userId, chatId, displayName, username);
} catch (err) {
// UNIQUE constraint — user already paired (shouldn't happen, but handle gracefully)
if (err.message?.includes('UNIQUE')) {
await this._sendMessage(chatId, this._t('already_paired'));
return;
}
throw err;
}
// Reset failed attempts
this._failedAttempts.delete(userId);
this.log.info(`[telegram] Device paired: ${displayName} (@${username || 'no-username'}) [${userId}]`);
await this._sendMessage(chatId, this._t('paired_ok', { name: this._escHtml(displayName) }));
// Set persistent Reply Keyboard (dynamic, context-aware)
const ctx = this._getContext(userId);
await this._sendReplyKeyboard(chatId, ctx, this._t('use_menu'));
// Emit event so UI can update in real-time
this.emit('device_paired', {
telegram_user_id: userId,
telegram_chat_id: chatId,
display_name: displayName,
username,
});
} else {
const attempts = this._recordFailedAttempt(userId);
const remaining = MAX_FAILED_ATTEMPTS - attempts;
if (remaining <= 0) {
await this._sendMessage(chatId, this._t('blocked'));
} else {
await this._sendMessage(chatId, this._t('invalid_code', { remaining }));
}
}
}
// ─── Command Router ────────────────────────────────────────────────────────
async _handleCommand(msg) {
const chatId = msg.chat.id;
const userId = msg.from.id;
const text = msg.text.trim();
const [rawCmd, ...args] = text.split(/\s+/);
const cmd = rawCmd.toLowerCase().replace(/@\w+$/, ''); // strip @botname
// FSM-03: Cancel any in-progress input state before executing command
const ctx = this._getContext(userId);
ctx.state = FSM_STATES.IDLE;
ctx.stateData = null;
switch (cmd) {
case '/help': return this._cmdHelp(chatId, userId);
case '/start': return this._screenMainMenu(chatId, userId); // already authorized
// Legacy command — removed from / menu (KB-03), handler kept for backward compat
case '/projects':return this._cmdProjects(chatId, userId);
// Legacy command — removed from / menu (KB-03), handler kept for backward compat
case '/project': return this._cmdProject(chatId, userId, args);
// Legacy command — removed from / menu (KB-03), handler kept for backward compat
case '/chats': return this._cmdChats(chatId, userId);
// Legacy command — removed from / menu (KB-03), handler kept for backward compat
case '/chat': return this._cmdChat(chatId, userId, args);
case '/last': return this._cmdLast(chatId, userId, args);
case '/full': return this._cmdFull(chatId, userId);
case '/status': return this._cmdStatus(chatId, userId);
case '/tasks': return this._cmdTasks(chatId, userId);
case '/files': return this._cmdFiles(chatId, userId, args);
case '/cat': return this._cmdCat(chatId, userId, args);
case '/diff': return this._cmdDiff(chatId, userId);
case '/log': return this._cmdLog(chatId, userId, args);
case '/notify': return this._cmdNotify(chatId, userId, args);
case '/stop': return this._cmdStop(chatId, userId);
case '/info': return this._cmdInfo(chatId, userId);
case '/new': return this._cmdNew(chatId, userId, args.join(' '));
case '/back': return this._cmdBack(chatId, userId);
case '/unlink': return this._cmdUnlink(chatId, userId);
case '/forum': return this._forum.cmdForum(chatId, userId);
case '/tunnel': return this._cmdTunnel(chatId, userId);
case '/url': return this._cmdUrl(chatId);
default:
await this._sendMessage(chatId, this._t('error_unknown_cmd', { cmd }), {
reply_markup: JSON.stringify({ inline_keyboard: [
[{ text: this._t('btn_back_menu'), callback_data: 'm:menu' }],
] }),
});
}
}
// ─── Commands ──────────────────────────────────────────────────────────────
async _cmdHelp(chatId, userId) {
await this._showScreen(chatId, userId, this._t('help_text'),
[[{ text: this._t('btn_back_menu'), callback_data: 'm:menu' }]]);
}
async _cmdProjects(chatId, userId) {
return this._screenProjects(chatId, userId, 'p:list:0');
}
async _cmdProject(chatId, userId, args) {
const ctx = this._getContext(userId);
if (args.length === 0) {
if (ctx.projectWorkdir) {
const name = this._escHtml(ctx.projectWorkdir.split('/').filter(Boolean).pop());
await this._sendMessage(chatId, this._t('project_current', { name }));
} else {
await this._sendMessage(chatId, this._t('project_hint'));
}
return;
}
const idx = parseInt(args[0], 10) - 1;
if (!ctx.projectList || idx < 0 || idx >= ctx.projectList.length) {
await this._sendMessage(chatId, this._t('project_invalid'));
return;
}
ctx.projectWorkdir = ctx.projectList[idx];
ctx.sessionId = null; // reset chat context
const name = this._escHtml(ctx.projectWorkdir.split('/').filter(Boolean).pop());
await this._sendMessage(chatId, this._t('project_set', { name }));
}
async _cmdChats(chatId, userId) {
// Redirect to button-based screen
return this._screenChats(chatId, userId, 'c:list:0');
}
async _cmdChat(chatId, userId, args) {
const ctx = this._getContext(userId);
if (args.length === 0) {
if (ctx.sessionId) {
const sess = this.db.prepare('SELECT title FROM sessions WHERE id=?').get(ctx.sessionId);
await this._sendMessage(chatId, this._t('chat_active', { title: this._escHtml(sess?.title || ctx.sessionId) }));