limixbot 0.3.79 → 0.3.81
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.
- package/dist/assets/{ActivityPanel-BVNkqBIC.js → ActivityPanel-BXFEtu90.js} +1 -1
- package/dist/assets/{App-CvsehEe_.js → App-Di_RKfDE.js} +63 -63
- package/dist/assets/{AppEventEditor-BYguwqDN.js → AppEventEditor-Bxo59GaM.js} +1 -1
- package/dist/assets/BotSettingsDialog-BtdhqHMV.js +16 -0
- package/dist/assets/{BrowserPanel-BTCGczPf.js → BrowserPanel-8mHeGOLP.js} +1 -1
- package/dist/assets/{BrowserProfilesManager-DZ2gX0y2.js → BrowserProfilesManager-DNDenex_.js} +1 -1
- package/dist/assets/{CloudAddDialog-DuhiNoO8.js → CloudAddDialog-B3mItSdo.js} +1 -1
- package/dist/assets/{ComputerFilesPane-CGP2MSqh.js → ComputerFilesPane-DUM3BGn5.js} +1 -1
- package/dist/assets/{ComputerPanel-C3jYTvzh.js → ComputerPanel-B1ProOmB.js} +2 -2
- package/dist/assets/{DataPanel-B5sek_0y.js → DataPanel-B9dG-xFC.js} +1 -1
- package/dist/assets/{DesktopViewer-DBMUDqPa.js → DesktopViewer-CxgTWyru.js} +1 -1
- package/dist/assets/{FilesView-CGdJc4B8.js → FilesView-BdErJPbS.js} +1 -1
- package/dist/assets/{GrokMoveDialog-BxE7bO-C.js → GrokMoveDialog-DmZmbC5L.js} +1 -1
- package/dist/assets/{InspectorPanel-CKLUT8oB.js → InspectorPanel-B1sIo1J5.js} +1 -1
- package/dist/assets/{KeyboardShortcutsModal-DxL0bhz0.js → KeyboardShortcutsModal-C5hjzxvv.js} +1 -1
- package/dist/assets/{LiveDesktop-DZHAgYhr.js → LiveDesktop-CN8YTqUZ.js} +1 -1
- package/dist/assets/{LocalVmWorkspace-5FdM1GcK.js → LocalVmWorkspace-C3kwGTKa.js} +1 -1
- package/dist/assets/{MacLocalControl-COa2bTeU.js → MacLocalControl-OTlnJ0ZN.js} +1 -1
- package/dist/assets/{MarkdownFilePreview-wV4LMjz6.js → MarkdownFilePreview-Da65BUFR.js} +1 -1
- package/dist/assets/{MenuMotion-CcuJn489.js → MenuMotion-B5n2ZkGC.js} +1 -1
- package/dist/assets/{NewBotDialog-BTHPAm-H.js → NewBotDialog-yIDxcMQJ.js} +1 -1
- package/dist/assets/{PhoneAppDialog-Dqcmnx_B.js → PhoneAppDialog-Bl38QRBo.js} +1 -1
- package/dist/assets/{PlacesRail-CRmtzh8u.js → PlacesRail-PNE_Y9GC.js} +1 -1
- package/dist/assets/{PluginsPanel-XaOSjVze.js → PluginsPanel-uBfd1z73.js} +1 -1
- package/dist/assets/{ProIntroduction-BlMy0JGo.js → ProIntroduction-CJI7fYhZ.js} +1 -1
- package/dist/assets/{RemoteAgentSettingsPanel-BYE04c1Y.js → RemoteAgentSettingsPanel-B5JBGc4J.js} +1 -1
- package/dist/assets/{RoomPanel-Dlzb2mxc.js → RoomPanel-B8o0-I0t.js} +1 -1
- package/dist/assets/{RoutinesPage-esNzRfID.js → RoutinesPage-K_BfBMn8.js} +1 -1
- package/dist/assets/{SettingsModal-_yGtX6l0.js → SettingsModal-DXSZCYBo.js} +1 -1
- package/dist/assets/{ShareTeamDialog-NiBljKHE.js → ShareTeamDialog-DTyuq4lx.js} +1 -1
- package/dist/assets/{SignedInSites-L4aSrXYW.js → SignedInSites-C-qamp3R.js} +1 -1
- package/dist/assets/{TeamLibraryPanel-CXiA_ll-.js → TeamLibraryPanel-D18289iU.js} +1 -1
- package/dist/assets/{TeamMapPage-C-qti0hy.js → TeamMapPage-CtEOY0Vl.js} +1 -1
- package/dist/assets/{TriggersPage-C497fuYj.js → TriggersPage-Cjpc4tVU.js} +1 -1
- package/dist/assets/{VisibilitySection-BGZ0rqTi.js → VisibilitySection-BFDrnzbh.js} +1 -1
- package/dist/assets/{WebhookTrigger-BH1BByzy.js → WebhookTrigger-YBoFyBq8.js} +1 -1
- package/dist/assets/{WorksOnGrid-DWH93kqg.js → WorksOnGrid-CAcjXdeB.js} +1 -1
- package/dist/assets/{abnfDiagram-YUKMZFIV-65Eq1Je6.js → abnfDiagram-YUKMZFIV-B5MGbjZP.js} +1 -1
- package/dist/assets/{activity-ZDWVxHRW.js → activity-i4SOTxBA.js} +1 -1
- package/dist/assets/{architectureDiagram-47P4ROYG-DrG8Yma0.js → architectureDiagram-47P4ROYG-z1L1R8jr.js} +1 -1
- package/dist/assets/{blockDiagram-E7TT5TSB-D54NTWSM.js → blockDiagram-E7TT5TSB-BgCJ5XqR.js} +1 -1
- package/dist/assets/{c4Diagram-CRA5TL53-3og_-YU_.js → c4Diagram-CRA5TL53-BxQ3fhnE.js} +1 -1
- package/dist/assets/{calendar-days-BMi-5cJi.js → calendar-days-D81dmGeW.js} +1 -1
- package/dist/assets/channel-Nvi2Z0SJ.js +1 -0
- package/dist/assets/{chunk-2Q5K7J3B-r3qgqOqv.js → chunk-2Q5K7J3B-CSVcU4dl.js} +1 -1
- package/dist/assets/{chunk-5VM5RSS4-DR43CCkD.js → chunk-5VM5RSS4-HqrufCgf.js} +1 -1
- package/dist/assets/{chunk-7TKQ45FW-Cjbd6ZLp.js → chunk-7TKQ45FW-D6I-6CLD.js} +1 -1
- package/dist/assets/{chunk-AW2ZBBNX-CmpcWqjE.js → chunk-AW2ZBBNX-nl3ozUZV.js} +1 -1
- package/dist/assets/{chunk-FVRAUYC3--y-kcX08.js → chunk-FVRAUYC3-wr6Np7EE.js} +2 -2
- package/dist/assets/{chunk-HTAEGDNF-dBj3y-VC.js → chunk-HTAEGDNF-XZGyfK8y.js} +1 -1
- package/dist/assets/{chunk-JWPE2WC7-B3uOSoFW.js → chunk-JWPE2WC7-pVRLXa0H.js} +1 -1
- package/dist/assets/{chunk-KQW6MTUR-DfT1IF3I.js → chunk-KQW6MTUR-Cb22vGIM.js} +1 -1
- package/dist/assets/{chunk-XXDRQBXY-CygLCvpM.js → chunk-XXDRQBXY-CmETcGZq.js} +1 -1
- package/dist/assets/{classDiagram-v2-K4WV4PDN-DGTDBVvN.js → classDiagram-v2-K4WV4PDN-eKf7q2Qc.js} +1 -1
- package/dist/assets/{coins-2Ipg9jSL.js → coins-GsXVRnl_.js} +1 -1
- package/dist/assets/{core-D_78Ynu8.js → core-B-k_7y0P.js} +1 -1
- package/dist/assets/{cose-bilkent-JH36ORCC-Bb0KgTtB.js → cose-bilkent-JH36ORCC-D4VzuikC.js} +1 -1
- package/dist/assets/{cynefin-EF2NZ3EQ-qGBA_DIq.js → cynefin-EF2NZ3EQ-CeoYk0bd.js} +1 -1
- package/dist/assets/{cynefinDiagram-3GCD6N5R-hF9YSVOq.js → cynefinDiagram-3GCD6N5R-ru8_qbbj.js} +1 -1
- package/dist/assets/{dagre-W4DXFKR2-3q_zIjPm.js → dagre-W4DXFKR2-wL6sYRlF.js} +1 -1
- package/dist/assets/{diagram-2UJZ2QOL-BOTHlOcq.js → diagram-2UJZ2QOL-BbNSoiqa.js} +1 -1
- package/dist/assets/{diagram-OVF4WLC6-Dnya3JUJ.js → diagram-OVF4WLC6-k8AAT5zq.js} +1 -1
- package/dist/assets/{diagram-PFPMY2P6-Bm2_1jj-.js → diagram-PFPMY2P6-ifjP4RXu.js} +1 -1
- package/dist/assets/{diagram-UMYRVEAY-CQrHk9Kj.js → diagram-UMYRVEAY-Ew2tVPDg.js} +1 -1
- package/dist/assets/{diagram-YEKJPTXX-DLdp-cKw.js → diagram-YEKJPTXX-Dovy7WaK.js} +1 -1
- package/dist/assets/{diagram-ZIFT7M5P-C542U79M.js → diagram-ZIFT7M5P-rtKhjRxK.js} +1 -1
- package/dist/assets/{ebnfDiagram-VR2GEFS7-DsKKpNma.js → ebnfDiagram-VR2GEFS7-BE67RFVg.js} +1 -1
- package/dist/assets/{elk-IJKZMXRS-DZL2zCKo.js → elk-IJKZMXRS-By_AEbig.js} +1 -1
- package/dist/assets/{erDiagram-O2IAPWRE-D4IGRyB_.js → erDiagram-O2IAPWRE-NMF3USSg.js} +1 -1
- package/dist/assets/{file-up-CZXyq-v_.js → file-up-CwVtVDwM.js} +1 -1
- package/dist/assets/{flowDiagram-OXPTDLAJ-xHZwGby9.js → flowDiagram-OXPTDLAJ-7VJ7i6mz.js} +1 -1
- package/dist/assets/{ganttDiagram-R7TSEDQI-eCuinfuc.js → ganttDiagram-R7TSEDQI-BsGUeaLq.js} +1 -1
- package/dist/assets/{gitGraphDiagram-XJZIOB7I-Cyhck_tc.js → gitGraphDiagram-XJZIOB7I-B5SdxDl8.js} +1 -1
- package/dist/assets/{import-name-k9CSvERS.js → import-name-CF2rJETO.js} +1 -1
- package/dist/assets/{index-BMsqhtYl.js → index-BOBBoSRI.js} +3 -3
- package/dist/assets/{index-C3-UCB9t.js → index-BoIJ2PWD.js} +1 -1
- package/dist/assets/{infoDiagram-5W2HQ5XZ-Cz9xYKn8.js → infoDiagram-5W2HQ5XZ-BqpdF76u.js} +1 -1
- package/dist/assets/{ishikawaDiagram-K3B6WC7H-Cms6sZIz.js → ishikawaDiagram-K3B6WC7H-ChPuwoRo.js} +1 -1
- package/dist/assets/{journeyDiagram-COXZFDF6-C918DJxn.js → journeyDiagram-COXZFDF6-AJsQ9Sal.js} +1 -1
- package/dist/assets/{kanban-definition-P3RFRI5V-Dh4rnCl5.js → kanban-definition-P3RFRI5V-Cbf53EMp.js} +1 -1
- package/dist/assets/{mcp-servers-R17O9xFq.js → mcp-servers-BjChYca1.js} +1 -1
- package/dist/assets/{mermaid.core-nsP0cVsp.js → mermaid.core-5XOzwbA1.js} +4 -4
- package/dist/assets/{mindmap-definition-LZFPQGKD-CFrq5gkA.js → mindmap-definition-LZFPQGKD-CD-WwEpo.js} +1 -1
- package/dist/assets/{minimize-OWlsq-0s.js → minimize-BBAOsm2F.js} +1 -1
- package/dist/assets/{monitor-76fhlY80.js → monitor-ByVtOtHb.js} +1 -1
- package/dist/assets/{new-bot-D4-p5E80.js → new-bot-Brnt-vsQ.js} +1 -1
- package/dist/assets/{org-library-IoJj_iDs.js → org-library-BqPtAtfm.js} +1 -1
- package/dist/assets/{package-format-Dek_P3eO.js → package-format-DswU6LQA.js} +1 -1
- package/dist/assets/{pegDiagram-BGZESJAR-CpRYFAU1.js → pegDiagram-BGZESJAR-p2NJ2LJo.js} +1 -1
- package/dist/assets/{pieDiagram-CAPJLFHJ-BaqH4FaB.js → pieDiagram-CAPJLFHJ-BiLTUs2q.js} +1 -1
- package/dist/assets/{quadrantDiagram-GDMTTRAM-CGj6xfEM.js → quadrantDiagram-GDMTTRAM-BLtReWzy.js} +1 -1
- package/dist/assets/{rail-Dil29FKU.js → rail-B292SI4O.js} +1 -1
- package/dist/assets/{railroadDiagram-SM67HX2B-T8YW5IRA.js → railroadDiagram-SM67HX2B-CmU-L8x-.js} +1 -1
- package/dist/assets/{remote-desktop-panel-CmslCBxy.js → remote-desktop-panel-C320nXM7.js} +1 -1
- package/dist/assets/{requirementDiagram-X7JNWC4A-vX99IzDT.js → requirementDiagram-X7JNWC4A-C7POybJi.js} +1 -1
- package/dist/assets/{sankeyDiagram-UM26HJRW-BfgAMAiw.js → sankeyDiagram-UM26HJRW-Bh1astOc.js} +1 -1
- package/dist/assets/{sequenceDiagram-ZO4K6R2Y-BxqhI_5G.js → sequenceDiagram-ZO4K6R2Y-j_M4G1u_.js} +1 -1
- package/dist/assets/{sizeCapture-INFHLROL-DivsEQN9.js → sizeCapture-INFHLROL-Ca-8iWQF.js} +1 -1
- package/dist/assets/{stateDiagram-v2-TBUQTH76-gvw7v1YG.js → stateDiagram-v2-TBUQTH76-BEwcaRZx.js} +1 -1
- package/dist/assets/styles-fasgTjLK.css +1 -0
- package/dist/assets/{swimlanes-N4OXWK64-BHxjZqDS.js → swimlanes-N4OXWK64-DmlmxFf2.js} +1 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-rbSiIYPg.js +8 -0
- package/dist/assets/{team-share-DzmYPtMt.js → team-share-DI90Vqwa.js} +1 -1
- package/dist/assets/{timeline-definition-YOQAKGHF-CkrkdnYL.js → timeline-definition-YOQAKGHF-CHX-HOfh.js} +1 -1
- package/dist/assets/{usecaseDiagram-VIAY4XPW-D4LWhANl.js → usecaseDiagram-VIAY4XPW-eeJvKlcE.js} +1 -1
- package/dist/assets/{vennDiagram-BLWOH2XV-CX4YR6o_.js → vennDiagram-BLWOH2XV-DylhYeUG.js} +1 -1
- package/dist/assets/{wardleyDiagram-YMQ3BMBF-BXx0E2ta.js → wardleyDiagram-YMQ3BMBF-CUUtluRt.js} +1 -1
- package/dist/assets/{xychartDiagram-TAQBALBS-DxVI0fYE.js → xychartDiagram-TAQBALBS-C-gwkNiy.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/rail.html +5 -5
- package/dist-server/index.js +7234 -5599
- package/dist-server/package.json +1 -1
- package/dist-server/server/bot-api-host.js +1 -1
- package/dist-server/server/bot-channels/adapters.js +6 -0
- package/dist-server/server/bot-channels/discord.js +152 -0
- package/dist-server/server/bot-channels/engine.js +424 -0
- package/dist-server/server/bot-channels/facebook.js +94 -0
- package/dist-server/server/bot-channels/telegram.js +79 -0
- package/dist-server/server/bot-channels/zalo.js +111 -0
- package/dist-server/server/index.js +6 -5
- package/package.json +1 -1
- package/dist/assets/BotSettingsDialog-Be44NFrp.js +0 -16
- package/dist/assets/channel-BhUqydpo.js +0 -1
- package/dist/assets/styles-BABP9ycC.css +0 -1
- package/dist/assets/swimlanesDiagram-K3J5GTZL-CynVazVQ.js +0 -8
- package/dist-server/server/limix-telegram.js +0 -329
- /package/dist/assets/{styles-1Sa7mQdy.js → styles-DdM6yn_a.js} +0 -0
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{c as r,s as e}from"./flowDiagram-OXPTDLAJ-xHZwGby9.js";import{_ as o}from"./mermaid.core-nsP0cVsp.js";import"./chunk-5VM5RSS4-DR43CCkD.js";import"./chunk-XXDRQBXY-CygLCvpM.js";import"./chunk-KQW6MTUR-DfT1IF3I.js";import"./chunk-7TKQ45FW-Cjbd6ZLp.js";import"./channel-BhUqydpo.js";import"./styles-1Sa7mQdy.js";import"./step-CkmJJ7wq.js";var a=o(t=>`${e(t)}
|
|
2
|
-
.swimlane.cluster:not([data-color-id]) rect {
|
|
3
|
-
stroke: ${t.clusterBorder} !important;
|
|
4
|
-
}
|
|
5
|
-
[data-look="neo"].cluster rect {
|
|
6
|
-
filter: none;
|
|
7
|
-
}
|
|
8
|
-
`,"getStyles"),m=a,y=r({styles:m});export{y as diagram};
|
|
@@ -1,329 +0,0 @@
|
|
|
1
|
-
// Limix Bot: a bot answers on Telegram once its owner pastes the token from @BotFather in the bot's settings. This server
|
|
2
|
-
// reads the bot's messages itself (Telegram long polling, no webhook, no address to open) and answers in the same chat.
|
|
3
|
-
// The owner links their own Telegram with a one-time code (/link CODE) and then talks to the bot as from the app, at Full
|
|
4
|
-
// access, in a conversation of its own; other people are answered only when the owner allows it, through the confined
|
|
5
|
-
// Bot API path. Nothing here is reachable from outside: the token is sealed on disk and only this server calls Telegram.
|
|
6
|
-
import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
7
|
-
import { mkdirSync, readFileSync } from "node:fs";
|
|
8
|
-
import { dirname, join } from "node:path";
|
|
9
|
-
import { z } from "zod";
|
|
10
|
-
import { writeFileAtomic } from "./atomic.js";
|
|
11
|
-
import { PASS } from "./routes/table.js";
|
|
12
|
-
export const TELEGRAM_TEXT_MAX = 4096;
|
|
13
|
-
const LINK_MS = 15 * 60_000;
|
|
14
|
-
const POLL_S = 25;
|
|
15
|
-
const BACKOFF_MS = [2_000, 5_000, 15_000, 60_000];
|
|
16
|
-
const TOKEN = /^\d{5,15}:[\w-]{30,60}$/;
|
|
17
|
-
const botSchema = z.object({
|
|
18
|
-
sealed: z.string(),
|
|
19
|
-
username: z.string().default(""),
|
|
20
|
-
name: z.string().default(""),
|
|
21
|
-
enabled: z.boolean().default(true),
|
|
22
|
-
access: z.enum(["owner", "everyone"]).default("owner"),
|
|
23
|
-
owner: z.object({ id: z.number(), name: z.string() }).optional(),
|
|
24
|
-
link: z.object({ hash: z.string(), expiresAt: z.number() }).optional(),
|
|
25
|
-
offset: z.number().default(0),
|
|
26
|
-
chats: z.record(z.string(), z.string()).default({}),
|
|
27
|
-
error: z.string().optional(),
|
|
28
|
-
});
|
|
29
|
-
const fileSchema = z.object({ v: z.literal(1), bots: z.record(z.string(), botSchema) });
|
|
30
|
-
const TEXT = {
|
|
31
|
-
start: "Chào bạn! Đây là bot Limix. Nhắn tin để trò chuyện. Chủ bot: gửi /link MÃ để liên kết.",
|
|
32
|
-
linked: "Đã liên kết. Từ giờ bạn nhắn ở đây như nhắn trong app Limix.",
|
|
33
|
-
badCode: "Mã không đúng hoặc đã hết hạn. Tạo mã mới trong app Limix: bot → Cài đặt → Telegram.",
|
|
34
|
-
ownerOnly: "Bot này hiện chỉ trả lời chủ bot.",
|
|
35
|
-
textOnly: "Hiện bot chỉ đọc tin nhắn chữ.",
|
|
36
|
-
fresh: "Đã bắt đầu cuộc trò chuyện mới.",
|
|
37
|
-
approval: "Bot đang chờ bạn duyệt một bước trong app Limix.",
|
|
38
|
-
working: "Bot vẫn đang làm việc này. Xem kết quả trong app Limix.",
|
|
39
|
-
failed: "Bot chưa trả lời được lúc này. Thử lại sau.",
|
|
40
|
-
empty: "Bot đã làm xong nhưng không có câu trả lời bằng chữ.",
|
|
41
|
-
};
|
|
42
|
-
/** Splits a reply at paragraph, then line, then word boundaries so each piece fits one Telegram message. */
|
|
43
|
-
export function telegramChunks(text, max = TELEGRAM_TEXT_MAX) {
|
|
44
|
-
const out = [];
|
|
45
|
-
let rest = text.trim();
|
|
46
|
-
while (rest.length > max) {
|
|
47
|
-
const window = rest.slice(0, max);
|
|
48
|
-
const cut = Math.max(window.lastIndexOf("\n\n"), window.lastIndexOf("\n"), window.lastIndexOf(" "));
|
|
49
|
-
const at = cut > max / 2 ? cut : max;
|
|
50
|
-
out.push(rest.slice(0, at).trimEnd());
|
|
51
|
-
rest = rest.slice(at).trimStart();
|
|
52
|
-
}
|
|
53
|
-
if (rest)
|
|
54
|
-
out.push(rest);
|
|
55
|
-
return out;
|
|
56
|
-
}
|
|
57
|
-
const hashCode = (code) => createHash("sha256").update(code.trim().toUpperCase()).digest("hex");
|
|
58
|
-
export function createLimixTelegram(deps) {
|
|
59
|
-
const file = join(deps.dataDir, "limix-telegram.json");
|
|
60
|
-
const keyFile = join(deps.dataDir, "limix-telegram.key");
|
|
61
|
-
const base = (deps.apiBase ?? "https://api.telegram.org").replace(/\/$/, "");
|
|
62
|
-
const call = deps.fetch ?? fetch;
|
|
63
|
-
const now = deps.now ?? Date.now;
|
|
64
|
-
const log = deps.log ?? (() => { });
|
|
65
|
-
const loops = new Map();
|
|
66
|
-
const chatQueues = new Map();
|
|
67
|
-
let running = false;
|
|
68
|
-
function read() {
|
|
69
|
-
try {
|
|
70
|
-
const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
|
|
71
|
-
if (parsed.success)
|
|
72
|
-
return parsed.data;
|
|
73
|
-
}
|
|
74
|
-
catch { }
|
|
75
|
-
return { v: 1, bots: {} };
|
|
76
|
-
}
|
|
77
|
-
function write(data) { mkdirSync(dirname(file), { recursive: true }); writeFileAtomic(file, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 }); }
|
|
78
|
-
function patch(botId, change) {
|
|
79
|
-
const data = read();
|
|
80
|
-
const entry = data.bots[botId];
|
|
81
|
-
if (!entry)
|
|
82
|
-
return;
|
|
83
|
-
const next = change(entry);
|
|
84
|
-
if (next)
|
|
85
|
-
data.bots[botId] = next;
|
|
86
|
-
else
|
|
87
|
-
delete data.bots[botId];
|
|
88
|
-
write(data);
|
|
89
|
-
}
|
|
90
|
-
function key(create) {
|
|
91
|
-
try {
|
|
92
|
-
const hex = readFileSync(keyFile, "utf8").trim();
|
|
93
|
-
if (/^[0-9a-f]{64}$/.test(hex))
|
|
94
|
-
return Buffer.from(hex, "hex");
|
|
95
|
-
}
|
|
96
|
-
catch { }
|
|
97
|
-
if (!create)
|
|
98
|
-
return null;
|
|
99
|
-
const made = randomBytes(32);
|
|
100
|
-
mkdirSync(dirname(keyFile), { recursive: true });
|
|
101
|
-
writeFileAtomic(keyFile, `${made.toString("hex")}\n`, { mode: 0o600 });
|
|
102
|
-
return made;
|
|
103
|
-
}
|
|
104
|
-
function seal(token) {
|
|
105
|
-
const nonce = randomBytes(12);
|
|
106
|
-
const cipher = createCipheriv("aes-256-gcm", key(true), nonce);
|
|
107
|
-
const body = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]);
|
|
108
|
-
return Buffer.concat([nonce, body, cipher.getAuthTag()]).toString("base64");
|
|
109
|
-
}
|
|
110
|
-
function unseal(sealed) {
|
|
111
|
-
const k = key(false);
|
|
112
|
-
if (!k)
|
|
113
|
-
return null;
|
|
114
|
-
try {
|
|
115
|
-
const data = Buffer.from(sealed, "base64");
|
|
116
|
-
const decipher = createDecipheriv("aes-256-gcm", k, data.subarray(0, 12));
|
|
117
|
-
decipher.setAuthTag(data.subarray(data.length - 16));
|
|
118
|
-
return Buffer.concat([decipher.update(data.subarray(12, data.length - 16)), decipher.final()]).toString("utf8");
|
|
119
|
-
}
|
|
120
|
-
catch {
|
|
121
|
-
return null;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
async function api(token, method, body, signal) {
|
|
125
|
-
const response = await call(`${base}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
126
|
-
const data = await response.json().catch(() => ({}));
|
|
127
|
-
return { ok: response.ok && data.ok === true, status: response.status, result: data.result, ...(data.description ? { description: data.description } : {}) };
|
|
128
|
-
}
|
|
129
|
-
const send = (token, chatId, text) => (async () => {
|
|
130
|
-
for (const piece of telegramChunks(text))
|
|
131
|
-
await api(token, "sendMessage", { chat_id: chatId, text: piece });
|
|
132
|
-
})().catch((error) => log(`telegram: send failed (${error instanceof Error ? error.message : String(error)})`));
|
|
133
|
-
async function handle(botId, token, update) {
|
|
134
|
-
const message = update?.message;
|
|
135
|
-
if (!message || message.chat?.type !== "private" || !message.from || message.from.is_bot)
|
|
136
|
-
return;
|
|
137
|
-
const chatId = message.chat.id, from = message.from;
|
|
138
|
-
const who = [from.first_name, from.last_name].filter(Boolean).join(" ") || from.username || String(from.id);
|
|
139
|
-
const text = typeof message.text === "string" ? message.text : typeof message.caption === "string" ? message.caption : "";
|
|
140
|
-
const entry = read().bots[botId];
|
|
141
|
-
if (!entry)
|
|
142
|
-
return;
|
|
143
|
-
const command = /^\/(\w+)(?:@\w+)?(?:\s+(.*))?$/s.exec(text.trim());
|
|
144
|
-
if (command?.[1] === "start" && !command[2])
|
|
145
|
-
return void await send(token, chatId, TEXT.start);
|
|
146
|
-
if (command?.[1] === "link") {
|
|
147
|
-
const code = (command[2] ?? "").trim();
|
|
148
|
-
const ok = entry.link && entry.link.expiresAt > now() && code && timingSafeEqual(Buffer.from(hashCode(code)), Buffer.from(entry.link.hash));
|
|
149
|
-
if (!ok)
|
|
150
|
-
return void await send(token, chatId, TEXT.badCode);
|
|
151
|
-
patch(botId, (current) => { const { link: _used, ...rest } = current; return { ...rest, owner: { id: from.id, name: who } }; });
|
|
152
|
-
return void await send(token, chatId, TEXT.linked);
|
|
153
|
-
}
|
|
154
|
-
const owner = entry.owner?.id === from.id;
|
|
155
|
-
if (!owner && entry.access !== "everyone")
|
|
156
|
-
return void await send(token, chatId, TEXT.ownerOnly);
|
|
157
|
-
if (command?.[1] === "new") {
|
|
158
|
-
patch(botId, (current) => { const chats = { ...current.chats }; delete chats[String(chatId)]; return { ...current, chats }; });
|
|
159
|
-
return void await send(token, chatId, TEXT.fresh);
|
|
160
|
-
}
|
|
161
|
-
if (!text.trim())
|
|
162
|
-
return void await send(token, chatId, TEXT.textOnly);
|
|
163
|
-
const typing = setInterval(() => { void api(token, "sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => { }); }, 4_000);
|
|
164
|
-
void api(token, "sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => { });
|
|
165
|
-
try {
|
|
166
|
-
const known = read().bots[botId]?.chats[String(chatId)];
|
|
167
|
-
const answer = await deps.ask(botId, { text, ...(known ? { threadId: known } : {}), title: `Telegram · ${who}`, owner });
|
|
168
|
-
patch(botId, (current) => ({ ...current, chats: { ...current.chats, [String(chatId)]: answer.threadId } }));
|
|
169
|
-
await send(token, chatId, answer.reply.trim() || (answer.status === "needs_approval" ? TEXT.approval : answer.status === "working" ? TEXT.working : TEXT.empty));
|
|
170
|
-
}
|
|
171
|
-
catch (error) {
|
|
172
|
-
log(`telegram: ${error instanceof Error ? error.message : String(error)}`);
|
|
173
|
-
await send(token, chatId, TEXT.failed);
|
|
174
|
-
}
|
|
175
|
-
finally {
|
|
176
|
-
clearInterval(typing);
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
/** One chat's messages run one after another; different chats run side by side. */
|
|
180
|
-
function enqueue(botId, token, update) {
|
|
181
|
-
const chat = `${botId}:${update?.message?.chat?.id ?? "?"}`;
|
|
182
|
-
const next = (chatQueues.get(chat) ?? Promise.resolve()).then(() => handle(botId, token, update)).catch(() => { });
|
|
183
|
-
chatQueues.set(chat, next);
|
|
184
|
-
void next.finally(() => { if (chatQueues.get(chat) === next)
|
|
185
|
-
chatQueues.delete(chat); });
|
|
186
|
-
}
|
|
187
|
-
async function loop(botId, abort) {
|
|
188
|
-
let failures = 0;
|
|
189
|
-
while (!abort.signal.aborted) {
|
|
190
|
-
const entry = read().bots[botId];
|
|
191
|
-
const token = entry ? unseal(entry.sealed) : null;
|
|
192
|
-
if (!entry || !entry.enabled || !token || !deps.botExists(botId))
|
|
193
|
-
break;
|
|
194
|
-
try {
|
|
195
|
-
const answer = await api(token, "getUpdates", { offset: entry.offset, timeout: POLL_S, allowed_updates: ["message"] }, abort.signal);
|
|
196
|
-
if (!answer.ok) {
|
|
197
|
-
const error = answer.status === 401 || answer.status === 404 ? "Token không còn dùng được. Dán token mới từ @BotFather."
|
|
198
|
-
: answer.status === 409 ? "Bot Telegram này đang được nơi khác nhận tin (máy khác, Cloud hoặc webhook). Chỉ để một nơi nhận tin."
|
|
199
|
-
: `Telegram báo lỗi ${answer.status}.`;
|
|
200
|
-
patch(botId, (current) => ({ ...current, error }));
|
|
201
|
-
if (answer.status === 401 || answer.status === 404)
|
|
202
|
-
break;
|
|
203
|
-
await wait(BACKOFF_MS[Math.min(failures++, BACKOFF_MS.length - 1)], abort.signal);
|
|
204
|
-
continue;
|
|
205
|
-
}
|
|
206
|
-
failures = 0;
|
|
207
|
-
const updates = Array.isArray(answer.result) ? answer.result : [];
|
|
208
|
-
if (updates.length) {
|
|
209
|
-
const offset = Math.max(...updates.map((update) => Number(update?.update_id) || 0)) + 1;
|
|
210
|
-
patch(botId, (current) => ({ ...current, offset, error: undefined }));
|
|
211
|
-
for (const update of updates)
|
|
212
|
-
enqueue(botId, token, update);
|
|
213
|
-
}
|
|
214
|
-
else if (entry.error)
|
|
215
|
-
patch(botId, (current) => ({ ...current, error: undefined }));
|
|
216
|
-
}
|
|
217
|
-
catch (error) {
|
|
218
|
-
if (abort.signal.aborted)
|
|
219
|
-
break;
|
|
220
|
-
log(`telegram: ${error instanceof Error ? error.message : String(error)}`);
|
|
221
|
-
await wait(BACKOFF_MS[Math.min(failures++, BACKOFF_MS.length - 1)], abort.signal);
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
if (loops.get(botId) === abort)
|
|
225
|
-
loops.delete(botId);
|
|
226
|
-
}
|
|
227
|
-
function ensure(botId) {
|
|
228
|
-
if (!running || loops.has(botId))
|
|
229
|
-
return;
|
|
230
|
-
const entry = read().bots[botId];
|
|
231
|
-
if (!entry?.enabled)
|
|
232
|
-
return;
|
|
233
|
-
const abort = new AbortController();
|
|
234
|
-
loops.set(botId, abort);
|
|
235
|
-
void loop(botId, abort);
|
|
236
|
-
}
|
|
237
|
-
function halt(botId) { loops.get(botId)?.abort(); loops.delete(botId); }
|
|
238
|
-
function view(botId) {
|
|
239
|
-
const entry = read().bots[botId];
|
|
240
|
-
if (!entry)
|
|
241
|
-
return { connected: false };
|
|
242
|
-
return {
|
|
243
|
-
connected: true, username: entry.username, enabled: entry.enabled, access: entry.access,
|
|
244
|
-
...(entry.owner ? { owner: entry.owner.name } : {}),
|
|
245
|
-
...(entry.link && entry.link.expiresAt > now() ? { linkExpiresAt: entry.link.expiresAt } : {}),
|
|
246
|
-
...(entry.error ? { error: entry.error } : {}),
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
async function connect(botId, token) {
|
|
250
|
-
const clean = token.trim();
|
|
251
|
-
if (!TOKEN.test(clean))
|
|
252
|
-
throw Object.assign(new Error("Token không đúng dạng. Copy nguyên dòng token từ @BotFather."), { status: 400 });
|
|
253
|
-
const me = await api(clean, "getMe", {}).catch(() => null);
|
|
254
|
-
if (!me?.ok || !me.result?.username)
|
|
255
|
-
throw Object.assign(new Error("Telegram không nhận token này."), { status: 400 });
|
|
256
|
-
halt(botId);
|
|
257
|
-
const data = read();
|
|
258
|
-
const kept = data.bots[botId];
|
|
259
|
-
data.bots[botId] = botSchema.parse({ sealed: seal(clean), username: me.result.username, name: me.result.first_name ?? "", enabled: true, access: kept?.access ?? "owner", ...(kept?.owner ? { owner: kept.owner } : {}), offset: 0, chats: kept?.chats ?? {} });
|
|
260
|
-
write(data);
|
|
261
|
-
ensure(botId);
|
|
262
|
-
return view(botId);
|
|
263
|
-
}
|
|
264
|
-
const PATH = /^\/api\/bots\/([\w-]{1,128})\/telegram(?:\/(link|unlink))?$/;
|
|
265
|
-
const changeSchema = z.object({ token: z.string().max(200).optional(), enabled: z.boolean().optional(), access: z.enum(["owner", "everyone"]).optional() }).strict();
|
|
266
|
-
const routes = async ({ req, res, path, method, auth, json, readBody }) => {
|
|
267
|
-
const match = PATH.exec(path);
|
|
268
|
-
if (!match)
|
|
269
|
-
return PASS;
|
|
270
|
-
const botId = match[1];
|
|
271
|
-
if (!deps.botExists(botId))
|
|
272
|
-
return json(res, 404, { error: "no such bot" });
|
|
273
|
-
const refusal = deps.manageRefusal(auth, botId);
|
|
274
|
-
if (refusal)
|
|
275
|
-
return json(res, 403, { error: refusal });
|
|
276
|
-
try {
|
|
277
|
-
if (method === "GET" && !match[2])
|
|
278
|
-
return json(res, 200, view(botId));
|
|
279
|
-
if (method === "DELETE" && !match[2]) {
|
|
280
|
-
halt(botId);
|
|
281
|
-
const data = read();
|
|
282
|
-
delete data.bots[botId];
|
|
283
|
-
write(data);
|
|
284
|
-
return json(res, 200, view(botId));
|
|
285
|
-
}
|
|
286
|
-
if (method !== "POST")
|
|
287
|
-
return json(res, 405, { error: "method not allowed" });
|
|
288
|
-
if (match[2] === "link") {
|
|
289
|
-
if (!read().bots[botId])
|
|
290
|
-
return json(res, 409, { error: "Kết nối Telegram trước." });
|
|
291
|
-
const code = randomBytes(4).toString("hex").toUpperCase().slice(0, 6);
|
|
292
|
-
patch(botId, (current) => ({ ...current, link: { hash: hashCode(code), expiresAt: now() + LINK_MS } }));
|
|
293
|
-
return json(res, 200, { code, ...view(botId) });
|
|
294
|
-
}
|
|
295
|
-
if (match[2] === "unlink") {
|
|
296
|
-
patch(botId, (current) => { const { owner: _gone, ...rest } = current; return rest; });
|
|
297
|
-
return json(res, 200, view(botId));
|
|
298
|
-
}
|
|
299
|
-
const parsed = changeSchema.safeParse(await readBody(req));
|
|
300
|
-
if (!parsed.success)
|
|
301
|
-
return json(res, 400, { error: "invalid request" });
|
|
302
|
-
if (parsed.data.token !== undefined)
|
|
303
|
-
await connect(botId, parsed.data.token);
|
|
304
|
-
if (parsed.data.enabled !== undefined || parsed.data.access !== undefined) {
|
|
305
|
-
patch(botId, (current) => ({ ...current, ...(parsed.data.enabled !== undefined ? { enabled: parsed.data.enabled } : {}), ...(parsed.data.access ? { access: parsed.data.access } : {}) }));
|
|
306
|
-
if (parsed.data.enabled === false)
|
|
307
|
-
halt(botId);
|
|
308
|
-
else
|
|
309
|
-
ensure(botId);
|
|
310
|
-
}
|
|
311
|
-
return json(res, 200, view(botId));
|
|
312
|
-
}
|
|
313
|
-
catch (error) {
|
|
314
|
-
const status = typeof error?.status === "number" ? error.status : 500;
|
|
315
|
-
return json(res, status, { error: error instanceof Error ? error.message : String(error) });
|
|
316
|
-
}
|
|
317
|
-
};
|
|
318
|
-
return {
|
|
319
|
-
routes,
|
|
320
|
-
view,
|
|
321
|
-
start() { running = true; for (const botId of Object.keys(read().bots))
|
|
322
|
-
ensure(botId); },
|
|
323
|
-
stop() { running = false; for (const abort of loops.values())
|
|
324
|
-
abort.abort(); loops.clear(); },
|
|
325
|
-
};
|
|
326
|
-
}
|
|
327
|
-
function wait(ms, signal) {
|
|
328
|
-
return new Promise((resolve) => { const timer = setTimeout(resolve, ms); signal.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true }); });
|
|
329
|
-
}
|
|
File without changes
|