@agents24/telegram 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +35 -2
- package/compatibility.json +54 -0
- package/dist/contracts-C3NXzqar.d.cts +212 -0
- package/dist/contracts-C3NXzqar.d.ts +212 -0
- package/dist/gateway.cjs +647 -0
- package/dist/gateway.cjs.map +1 -0
- package/dist/gateway.d.cts +15 -0
- package/dist/gateway.d.ts +15 -0
- package/dist/gateway.js +624 -0
- package/dist/gateway.js.map +1 -0
- package/dist/index.cjs +661 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +60 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +628 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -4
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
// src/contracts.ts
|
|
2
|
+
var TELEGRAM_PROTOCOL = "agents24.telegram.v1";
|
|
3
|
+
var TEXT_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
4
|
+
var PAIRING_TTL_MS = 10 * 60 * 1e3;
|
|
5
|
+
var ACTION_TTL_MS = 15 * 60 * 1e3;
|
|
6
|
+
var HOST_LEASE_MS = 45e3;
|
|
7
|
+
var MAX_TELEGRAM_BUTTONS = 40;
|
|
8
|
+
var TelegramError = class extends Error {
|
|
9
|
+
constructor(code, status = 400) {
|
|
10
|
+
super(code);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
code;
|
|
15
|
+
status;
|
|
16
|
+
};
|
|
17
|
+
function emptyGatewayState() {
|
|
18
|
+
return { version: TELEGRAM_PROTOCOL, installations: {}, pairings: {}, bindings: {}, inbox: {}, deliveries: {}, actions: {}, updates: {}, rates: {}, nextDeliveryOrder: 1 };
|
|
19
|
+
}
|
|
20
|
+
function emptyHostState() {
|
|
21
|
+
return { version: TELEGRAM_PROTOCOL, bindings: {}, accepted: {} };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/portable.ts
|
|
25
|
+
function randomToken(bytes = 24) {
|
|
26
|
+
const value = crypto.getRandomValues(new Uint8Array(bytes));
|
|
27
|
+
return Array.from(value, (n) => n.toString(16).padStart(2, "0")).join("");
|
|
28
|
+
}
|
|
29
|
+
async function digest(text) {
|
|
30
|
+
return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))), (n) => n.toString(16).padStart(2, "0")).join("");
|
|
31
|
+
}
|
|
32
|
+
function equalSecret(a, b) {
|
|
33
|
+
if (a.length !== b.length) return false;
|
|
34
|
+
let different = 0;
|
|
35
|
+
for (let i = 0; i < a.length; i++) different |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
36
|
+
return different === 0;
|
|
37
|
+
}
|
|
38
|
+
function textField(value, max = 255) {
|
|
39
|
+
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u0008]/.test(value)) throw new TelegramError("INVALID_REQUEST");
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function object(value) {
|
|
43
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TelegramError("INVALID_REQUEST");
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
function telegramId(value) {
|
|
47
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return String(value);
|
|
48
|
+
throw new TelegramError("INVALID_TELEGRAM_ID");
|
|
49
|
+
}
|
|
50
|
+
async function boundedJson(request, limit = 65536) {
|
|
51
|
+
if (!request.body) throw new TelegramError("INVALID_REQUEST");
|
|
52
|
+
const reader = request.body.getReader();
|
|
53
|
+
const chunks = [];
|
|
54
|
+
let size = 0;
|
|
55
|
+
try {
|
|
56
|
+
for (; ; ) {
|
|
57
|
+
const next = await reader.read();
|
|
58
|
+
if (next.done) break;
|
|
59
|
+
size += next.value.length;
|
|
60
|
+
if (size > limit) {
|
|
61
|
+
await reader.cancel();
|
|
62
|
+
throw new TelegramError("BODY_TOO_LARGE", 413);
|
|
63
|
+
}
|
|
64
|
+
chunks.push(next.value);
|
|
65
|
+
}
|
|
66
|
+
const bytes = new Uint8Array(size);
|
|
67
|
+
let offset = 0;
|
|
68
|
+
for (const chunk of chunks) {
|
|
69
|
+
bytes.set(chunk, offset);
|
|
70
|
+
offset += chunk.length;
|
|
71
|
+
}
|
|
72
|
+
return object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error instanceof TelegramError) throw error;
|
|
75
|
+
throw new TelegramError("INVALID_REQUEST");
|
|
76
|
+
} finally {
|
|
77
|
+
reader.releaseLock();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function splitTelegramText(text) {
|
|
81
|
+
if (!text.trim()) return [];
|
|
82
|
+
const chunks = [];
|
|
83
|
+
let rest = text;
|
|
84
|
+
while (rest.length) {
|
|
85
|
+
let end = Math.min(rest.length, 4096);
|
|
86
|
+
if (end < rest.length && /[\uD800-\uDBFF]/.test(rest[end - 1])) end--;
|
|
87
|
+
chunks.push(rest.slice(0, end));
|
|
88
|
+
rest = rest.slice(end);
|
|
89
|
+
}
|
|
90
|
+
return chunks;
|
|
91
|
+
}
|
|
92
|
+
function createMemoryTelegramStore(initial) {
|
|
93
|
+
let state = structuredClone(initial), tail = Promise.resolve();
|
|
94
|
+
return { transaction(change) {
|
|
95
|
+
const next = tail.then(() => {
|
|
96
|
+
const candidate = structuredClone(state);
|
|
97
|
+
const result = change(candidate);
|
|
98
|
+
if (result && typeof result.then === "function") throw new Error("Telegram transactions must be synchronous");
|
|
99
|
+
state = candidate;
|
|
100
|
+
return structuredClone(result);
|
|
101
|
+
});
|
|
102
|
+
tail = next.then(() => {
|
|
103
|
+
}, () => {
|
|
104
|
+
});
|
|
105
|
+
return next;
|
|
106
|
+
} };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/gateway-state.ts
|
|
110
|
+
function requireInstallation(state, id) {
|
|
111
|
+
const host = state.installations[id];
|
|
112
|
+
if (!host || host.revoked) throw new TelegramError("UNAUTHORIZED", 401);
|
|
113
|
+
return host;
|
|
114
|
+
}
|
|
115
|
+
function requireBinding(state, installationId, bindingId, generation) {
|
|
116
|
+
requireInstallation(state, installationId);
|
|
117
|
+
const binding = state.bindings[bindingId];
|
|
118
|
+
if (!binding || binding.installationId !== installationId || binding.status !== "active" || generation !== void 0 && binding.generation !== generation) throw new TelegramError("BINDING_UNAVAILABLE", 404);
|
|
119
|
+
return binding;
|
|
120
|
+
}
|
|
121
|
+
function hostOnline(state, binding, now) {
|
|
122
|
+
const host = state.installations[binding.installationId];
|
|
123
|
+
return !!host && !host.revoked && now - host.lastSeenAt < HOST_LEASE_MS;
|
|
124
|
+
}
|
|
125
|
+
function notice(state, sourceId, chatId, text, now) {
|
|
126
|
+
const id = `notice:${sourceId}`;
|
|
127
|
+
if (state.deliveries[id]) return;
|
|
128
|
+
state.deliveries[id] = {
|
|
129
|
+
id,
|
|
130
|
+
sourceId,
|
|
131
|
+
chatId,
|
|
132
|
+
text,
|
|
133
|
+
fingerprint: text,
|
|
134
|
+
createdAt: now,
|
|
135
|
+
retryAt: now,
|
|
136
|
+
attempts: 0,
|
|
137
|
+
status: "pending",
|
|
138
|
+
order: state.nextDeliveryOrder++
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function revokeBinding(state, binding) {
|
|
142
|
+
binding.status = "revoked";
|
|
143
|
+
for (const event of Object.values(state.inbox)) if (event.bindingId === binding.id && event.status === "pending") {
|
|
144
|
+
event.status = "expired";
|
|
145
|
+
delete event.text;
|
|
146
|
+
delete event.actionRef;
|
|
147
|
+
}
|
|
148
|
+
for (const [id, action] of Object.entries(state.actions)) if (action.bindingId === binding.id) delete state.actions[id];
|
|
149
|
+
for (const delivery of Object.values(state.deliveries)) if (delivery.bindingId === binding.id && ["pending", "unknown", "rejected"].includes(delivery.status)) {
|
|
150
|
+
delivery.status = "skipped";
|
|
151
|
+
delivery.text = "";
|
|
152
|
+
delete delivery.buttons;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function expireGateway(state, now, applicationName = "your app") {
|
|
156
|
+
for (const pair of Object.values(state.pairings)) if (pair.status !== "active" && pair.expiresAt <= now) {
|
|
157
|
+
pair.status = "expired";
|
|
158
|
+
delete pair.claimant;
|
|
159
|
+
}
|
|
160
|
+
for (const event of Object.values(state.inbox)) {
|
|
161
|
+
if (event.status === "pending" && event.expiresAt <= now) {
|
|
162
|
+
const binding = state.bindings[event.bindingId];
|
|
163
|
+
if (event.kind === "text" && binding?.status === "active") notice(state, `expired:${event.id}`, binding.chatId, `This message expired before ${applicationName} could accept it. Please send it again.`, now);
|
|
164
|
+
event.status = "expired";
|
|
165
|
+
delete event.text;
|
|
166
|
+
delete event.actionRef;
|
|
167
|
+
}
|
|
168
|
+
if (event.status !== "pending" && event.receivedAt < now - TEXT_TTL_MS * 30) delete state.inbox[event.id];
|
|
169
|
+
}
|
|
170
|
+
for (const [id, action] of Object.entries(state.actions)) if (action.expiresAt <= now) delete state.actions[id];
|
|
171
|
+
for (const delivery of Object.values(state.deliveries)) {
|
|
172
|
+
if (delivery.status === "sending" && (delivery.attemptAt ?? 0) < now - 6e4) {
|
|
173
|
+
delivery.status = delivery.bindingId && state.bindings[delivery.bindingId]?.status === "active" ? "unknown" : "skipped";
|
|
174
|
+
delivery.failureCode = "DELIVERY_UNKNOWN";
|
|
175
|
+
if (delivery.status === "skipped") {
|
|
176
|
+
delivery.text = "";
|
|
177
|
+
delete delivery.buttons;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (["sent", "skipped", "rejected"].includes(delivery.status) && delivery.createdAt < now - TEXT_TTL_MS * 30) delete state.deliveries[delivery.id];
|
|
181
|
+
}
|
|
182
|
+
for (const [id, at] of Object.entries(state.updates)) if (at < now - TEXT_TTL_MS * 30) delete state.updates[id];
|
|
183
|
+
for (const [key, value] of Object.entries(state.rates)) if (value.start < now - TEXT_TTL_MS) delete state.rates[key];
|
|
184
|
+
for (const [id, pair] of Object.entries(state.pairings)) if (pair.expiresAt < now - TEXT_TTL_MS * (pair.status === "active" ? 30 : 1)) delete state.pairings[id];
|
|
185
|
+
for (const [id, binding] of Object.entries(state.bindings)) if (binding.status === "revoked" && binding.createdAt < now - TEXT_TTL_MS * 30 && !Object.values(state.deliveries).some((d) => d.bindingId === id && d.status === "sending")) delete state.bindings[id];
|
|
186
|
+
for (const [id, host] of Object.entries(state.installations)) if (host.createdAt < now - TEXT_TTL_MS * 90 && host.lastSeenAt < now - TEXT_TTL_MS * 90 && !Object.values(state.bindings).some((b) => b.installationId === id && b.status === "active") && !Object.values(state.pairings).some((p) => p.installationId === id && p.expiresAt > now)) delete state.installations[id];
|
|
187
|
+
}
|
|
188
|
+
function rateLimit(state, key, now, max, windowMs) {
|
|
189
|
+
let window = state.rates[key];
|
|
190
|
+
if (!window || now - window.start >= windowMs) window = state.rates[key] = { start: now, count: 0 };
|
|
191
|
+
if (++window.count > max) throw new TelegramError("RATE_LIMITED", 429);
|
|
192
|
+
}
|
|
193
|
+
function addDelivery(state, binding, sourceId, text, buttons, fingerprint, now, replyRef) {
|
|
194
|
+
const chunks = splitTelegramText(text);
|
|
195
|
+
if (!chunks.length || chunks.length > 25) throw new TelegramError("INVALID_DELIVERY");
|
|
196
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
197
|
+
const id = `${binding.id}:${binding.generation}:${sourceId}:${index}`;
|
|
198
|
+
const previous = state.deliveries[id];
|
|
199
|
+
if (previous && previous.fingerprint !== fingerprint) throw new TelegramError("DELIVERY_CONFLICT", 409);
|
|
200
|
+
if (!previous) state.deliveries[id] = {
|
|
201
|
+
id,
|
|
202
|
+
bindingId: binding.id,
|
|
203
|
+
generation: binding.generation,
|
|
204
|
+
sourceId,
|
|
205
|
+
chatId: binding.chatId,
|
|
206
|
+
text: chunk,
|
|
207
|
+
buttons: index === chunks.length - 1 ? buttons : void 0,
|
|
208
|
+
fingerprint,
|
|
209
|
+
status: "pending",
|
|
210
|
+
attempts: 0,
|
|
211
|
+
createdAt: now,
|
|
212
|
+
retryAt: now,
|
|
213
|
+
replyRef: index === chunks.length - 1 ? replyRef : void 0,
|
|
214
|
+
order: state.nextDeliveryOrder++
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function actionButtons(state, delivery, now) {
|
|
219
|
+
return delivery.buttons?.map((button) => {
|
|
220
|
+
const existing = Object.values(state.actions).find((a) => a.bindingId === delivery.bindingId && a.generation === delivery.generation && a.actionRef === button.actionRef && a.expiresAt > now);
|
|
221
|
+
const id = existing?.id ?? randomToken(16);
|
|
222
|
+
state.actions[id] = {
|
|
223
|
+
id,
|
|
224
|
+
bindingId: delivery.bindingId,
|
|
225
|
+
generation: delivery.generation,
|
|
226
|
+
actionRef: button.actionRef,
|
|
227
|
+
kind: button.kind,
|
|
228
|
+
expiresAt: now + 15 * 6e4
|
|
229
|
+
};
|
|
230
|
+
return [{ text: button.label, callback_data: id }];
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// src/telegram-delivery.ts
|
|
235
|
+
function createTelegramSender(options) {
|
|
236
|
+
const now = options.now ?? Date.now, fetcher = options.fetch ?? fetch;
|
|
237
|
+
async function api(method, body) {
|
|
238
|
+
const response = await fetcher(`https://api.telegram.org/bot${options.botToken}/${method}`, {
|
|
239
|
+
method: "POST",
|
|
240
|
+
headers: { "content-type": "application/json" },
|
|
241
|
+
body: JSON.stringify(body),
|
|
242
|
+
redirect: "error",
|
|
243
|
+
signal: AbortSignal.timeout(2e4)
|
|
244
|
+
});
|
|
245
|
+
return await response.json();
|
|
246
|
+
}
|
|
247
|
+
async function flush(limit = 20) {
|
|
248
|
+
for (let count = 0; count < limit; count++) {
|
|
249
|
+
const claimed = await options.store.transaction((state) => {
|
|
250
|
+
if (state.version !== TELEGRAM_PROTOCOL) throw new Error("Telegram storage version is unsupported");
|
|
251
|
+
expireGateway(state, now(), options.applicationName);
|
|
252
|
+
const ordered = Object.values(state.deliveries).sort((a, b) => a.order - b.order);
|
|
253
|
+
for (const row of ordered) {
|
|
254
|
+
if (row.status !== "pending" || row.retryAt > now()) continue;
|
|
255
|
+
if (row.bindingId) {
|
|
256
|
+
const binding = state.bindings[row.bindingId];
|
|
257
|
+
if (!binding || binding.status !== "active" || binding.generation !== row.generation) {
|
|
258
|
+
row.status = "skipped";
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (ordered.some((prior) => prior.chatId === row.chatId && prior !== row && ["pending", "sending", "unknown"].includes(prior.status) && prior.order < row.order)) continue;
|
|
263
|
+
const chatRate = state.rates[`send:${row.chatId}`], botRate = state.rates["send:bot"];
|
|
264
|
+
if (chatRate && now() - chatRate.start < 1e3) continue;
|
|
265
|
+
if (botRate && now() - botRate.start < 1e3 && botRate.count >= 25) continue;
|
|
266
|
+
state.rates[`send:${row.chatId}`] = { start: now(), count: 1 };
|
|
267
|
+
state.rates["send:bot"] = botRate && now() - botRate.start < 1e3 ? { start: botRate.start, count: botRate.count + 1 } : { start: now(), count: 1 };
|
|
268
|
+
row.status = "sending";
|
|
269
|
+
row.attemptAt = now();
|
|
270
|
+
row.attempts++;
|
|
271
|
+
const keyboard = actionButtons(state, row, now());
|
|
272
|
+
return { row: structuredClone(row), keyboard };
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
});
|
|
276
|
+
if (!claimed) return;
|
|
277
|
+
let outcome;
|
|
278
|
+
try {
|
|
279
|
+
const result = await api("sendMessage", {
|
|
280
|
+
chat_id: claimed.row.chatId,
|
|
281
|
+
text: claimed.row.text,
|
|
282
|
+
...claimed.keyboard?.length ? { reply_markup: { inline_keyboard: claimed.keyboard } } : claimed.row.replyRef ? { reply_markup: { force_reply: true, selective: true } } : {}
|
|
283
|
+
});
|
|
284
|
+
if (result.ok === true && Number.isSafeInteger(result.result?.message_id)) outcome = { status: "sent", messageId: String(result.result.message_id) };
|
|
285
|
+
else if (result.ok === false && result.error_code === 429) outcome = { status: "pending", retryAt: now() + Math.max(1, Math.min(3600, Number(result.parameters?.retry_after) || 1)) * 1e3, failureCode: "TELEGRAM_RATE_LIMIT" };
|
|
286
|
+
else if (result.ok === false && result.error_code >= 500) outcome = { status: "pending", retryAt: now() + Math.min(6e4, 1e3 * 2 ** Math.min(6, claimed.row.attempts)), failureCode: "TELEGRAM_UNAVAILABLE" };
|
|
287
|
+
else if (result.ok === false) outcome = { status: "rejected", failureCode: result.error_code === 403 ? "BOT_BLOCKED" : "TELEGRAM_REJECTED" };
|
|
288
|
+
else outcome = { status: "unknown", failureCode: "DELIVERY_UNKNOWN" };
|
|
289
|
+
} catch {
|
|
290
|
+
outcome = { status: "unknown", failureCode: "DELIVERY_UNKNOWN" };
|
|
291
|
+
}
|
|
292
|
+
await options.store.transaction((state) => {
|
|
293
|
+
const row = state.deliveries[claimed.row.id];
|
|
294
|
+
if (!row || row.status !== "sending" || row.attemptAt !== claimed.row.attemptAt) return;
|
|
295
|
+
const revoked = row.bindingId && state.bindings[row.bindingId]?.status !== "active";
|
|
296
|
+
if (!row.bindingId && outcome.status === "unknown" || revoked && outcome.status !== "sent") outcome.status = "skipped";
|
|
297
|
+
Object.assign(row, outcome);
|
|
298
|
+
if (outcome.status === "sent" || outcome.status === "skipped") {
|
|
299
|
+
row.text = "";
|
|
300
|
+
delete row.buttons;
|
|
301
|
+
}
|
|
302
|
+
if (outcome.failureCode === "BOT_BLOCKED" && row.bindingId && state.bindings[row.bindingId]) revokeBinding(state, state.bindings[row.bindingId]);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function acknowledgeCallback(id, text) {
|
|
307
|
+
try {
|
|
308
|
+
await api("answerCallbackQuery", { callback_query_id: id, text });
|
|
309
|
+
} catch {
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return { flush, acknowledgeCallback };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// src/telegram-webhook.ts
|
|
316
|
+
async function acceptTelegramUpdate(options, update) {
|
|
317
|
+
const now = (options.now ?? Date.now)(), app = options.applicationName ?? "your app";
|
|
318
|
+
const updateId = telegramId(update.update_id);
|
|
319
|
+
const pairToken = typeof update.message?.text === "string" ? /^\/start(?:@[A-Za-z0-9_]+)?\s+([a-f0-9]{48})\s*$/.exec(update.message.text)?.[1] : void 0;
|
|
320
|
+
const tokenHash = pairToken ? await digest(pairToken) : null;
|
|
321
|
+
const notifications = [];
|
|
322
|
+
let callback;
|
|
323
|
+
await options.store.transaction((state) => {
|
|
324
|
+
expireGateway(state, now, options.applicationName);
|
|
325
|
+
if (state.updates[updateId]) return;
|
|
326
|
+
state.updates[updateId] = now;
|
|
327
|
+
const message = update.message, query = update.callback_query;
|
|
328
|
+
if (query) {
|
|
329
|
+
callback = { id: String(query.id), text: "This action is no longer available." };
|
|
330
|
+
const action = typeof query.data === "string" ? state.actions[query.data] : void 0;
|
|
331
|
+
const binding2 = action ? state.bindings[action.bindingId] : void 0;
|
|
332
|
+
if (!action || !binding2 || binding2.status !== "active" || action.generation !== binding2.generation || action.expiresAt <= now) return;
|
|
333
|
+
if (query.message?.chat?.type !== "private" || telegramId(query.from?.id) !== binding2.userId || telegramId(query.message?.chat?.id) !== binding2.chatId) return;
|
|
334
|
+
if (!hostOnline(state, binding2, now)) {
|
|
335
|
+
callback.text = `${app} is offline. Reopen it before answering or stopping a run.`;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const id2 = `telegram:${updateId}`;
|
|
339
|
+
state.inbox[id2] = {
|
|
340
|
+
id: id2,
|
|
341
|
+
bindingId: binding2.id,
|
|
342
|
+
generation: binding2.generation,
|
|
343
|
+
kind: "action",
|
|
344
|
+
actionRef: action.actionRef,
|
|
345
|
+
receivedAt: now,
|
|
346
|
+
expiresAt: Math.min(action.expiresAt, now + HOST_LEASE_MS),
|
|
347
|
+
status: "pending"
|
|
348
|
+
};
|
|
349
|
+
callback.text = "Action received.";
|
|
350
|
+
notifications.push(binding2.installationId);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
if (!message || message.chat?.type !== "private" || message.from?.is_bot === true) return;
|
|
354
|
+
const chatId = telegramId(message.chat.id), userId = telegramId(message.from?.id);
|
|
355
|
+
if (tokenHash) {
|
|
356
|
+
const pair = Object.values(state.pairings).find((p) => p.tokenHash === tokenHash && p.expiresAt > now);
|
|
357
|
+
if (!pair || pair.claimant && (pair.claimant.userId !== userId || pair.claimant.chatId !== chatId)) {
|
|
358
|
+
notice(state, updateId, chatId, `This connection link is invalid or expired. Create a new link in ${app}.`, now);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (pair.status === "active") {
|
|
362
|
+
notice(state, updateId, chatId, "Telegram is already connected.", now);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
pair.claimant = { chatId, userId, displayName: [message.from.first_name, message.from.last_name].filter((v) => typeof v === "string").join(" ").slice(0, 200) || "Telegram account" };
|
|
366
|
+
pair.status = "awaiting_confirmation";
|
|
367
|
+
notice(state, updateId, chatId, `Return to ${app} and confirm this Telegram account to finish connecting.`, now);
|
|
368
|
+
notifications.push(pair.installationId);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const binding = Object.values(state.bindings).find((b) => b.chatId === chatId && b.userId === userId && b.status === "active");
|
|
372
|
+
if (!binding) {
|
|
373
|
+
notice(state, updateId, chatId, `Open a conversation in ${app} and choose Connect Telegram.`, now);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const text = typeof message.text === "string" ? message.text : "";
|
|
377
|
+
if (/^\/disconnect(?:@[A-Za-z0-9_]+)?\s*$/.test(text)) {
|
|
378
|
+
revokeBinding(state, binding);
|
|
379
|
+
notice(state, updateId, chatId, `Disconnected from ${app}. Your conversation history is retained.`, now);
|
|
380
|
+
notifications.push(binding.installationId);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (/^\/(?:start|help|status)(?:@[A-Za-z0-9_]+)?\s*$/.test(text)) {
|
|
384
|
+
notice(state, updateId, chatId, hostOnline(state, binding, now) ? `Connected to ${app}. Send text, answer a question, or use /stop. Use /disconnect to remove this connection.` : `${app} is offline. Text will wait for up to 24 hours. Reopen ${app} to continue.`, now);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (/^\/[A-Za-z_]+(?:@[A-Za-z0-9_]+)?(?:\s|$)/.test(text) && !/^\/stop(?:@[A-Za-z0-9_]+)?\s*$/.test(text)) {
|
|
388
|
+
notice(state, updateId, chatId, "This command is unavailable. Use /help, /stop, or /disconnect.", now);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
let actionRef;
|
|
392
|
+
const repliedTo = message.reply_to_message?.message_id;
|
|
393
|
+
if (Number.isSafeInteger(repliedTo)) actionRef = Object.values(state.deliveries).find((d) => d.bindingId === binding.id && d.generation === binding.generation && d.messageId === String(repliedTo) && d.replyRef)?.replyRef;
|
|
394
|
+
if (/^\/stop(?:@[A-Za-z0-9_]+)?\s*$/.test(text)) {
|
|
395
|
+
if (hostOnline(state, binding, now)) actionRef = Object.values(state.actions).filter((a) => a.bindingId === binding.id && a.generation === binding.generation && a.kind === "stop" && a.expiresAt > now).at(-1)?.actionRef;
|
|
396
|
+
if (!actionRef) {
|
|
397
|
+
notice(state, updateId, chatId, `There is no available run to stop. Reopen ${app} if it is offline.`, now);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (actionRef && !hostOnline(state, binding, now)) {
|
|
402
|
+
notice(state, updateId, chatId, `${app} is offline. Reopen it before answering or stopping a run.`, now);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (!text.trim() && !actionRef) {
|
|
406
|
+
notice(state, updateId, chatId, `This release supports text only. Send images, documents, and audio inside ${app}.`, now);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const receivedAt = Number.isSafeInteger(message.date) ? Math.min(now, message.date * 1e3) : now;
|
|
410
|
+
const id = `telegram:${updateId}`;
|
|
411
|
+
const pending = Object.values(state.inbox).filter((e) => e.bindingId === binding.id && e.status === "pending").length;
|
|
412
|
+
if (pending >= 100) {
|
|
413
|
+
notice(state, updateId, chatId, `Your ${app} message queue is full. Wait for it to drain before sending more.`, now);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
state.inbox[id] = {
|
|
417
|
+
id,
|
|
418
|
+
bindingId: binding.id,
|
|
419
|
+
generation: binding.generation,
|
|
420
|
+
kind: actionRef ? "action" : "text",
|
|
421
|
+
text: text || void 0,
|
|
422
|
+
actionRef,
|
|
423
|
+
receivedAt,
|
|
424
|
+
expiresAt: receivedAt + (actionRef ? HOST_LEASE_MS : TEXT_TTL_MS),
|
|
425
|
+
status: "pending"
|
|
426
|
+
};
|
|
427
|
+
if (!actionRef && !hostOnline(state, binding, now)) notice(state, updateId, chatId, `${app} is offline. This message will wait for up to 24 hours; reopen ${app} to run it.`, now);
|
|
428
|
+
expireGateway(state, now, options.applicationName);
|
|
429
|
+
notifications.push(binding.installationId);
|
|
430
|
+
});
|
|
431
|
+
for (const installationId of new Set(notifications)) options.notifyHost?.(installationId);
|
|
432
|
+
return callback;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// src/gateway.ts
|
|
436
|
+
var json = (body, status = 200) => new Response(JSON.stringify(body), {
|
|
437
|
+
status,
|
|
438
|
+
headers: { "content-type": "application/json", "cache-control": "no-store" }
|
|
439
|
+
});
|
|
440
|
+
function createTelegramGateway(options) {
|
|
441
|
+
if (!options.botToken || !/^[A-Za-z0-9_]{5,64}$/.test(options.botUsername) || !/^[A-Za-z0-9_-]{32,256}$/.test(options.webhookSecret)) throw new TelegramError("INVALID_GATEWAY_CONFIGURATION");
|
|
442
|
+
const app = options.applicationName ?? "your app";
|
|
443
|
+
const now = options.now ?? Date.now, sender = createTelegramSender(options);
|
|
444
|
+
const change = (fn) => options.store.transaction((state) => {
|
|
445
|
+
if (state.version !== TELEGRAM_PROTOCOL) throw new TelegramError("PROTOCOL_MISMATCH", 409);
|
|
446
|
+
expireGateway(state, now(), options.applicationName);
|
|
447
|
+
return fn(state);
|
|
448
|
+
});
|
|
449
|
+
async function authenticate(request) {
|
|
450
|
+
const credential = request.headers.get("authorization")?.match(/^Bearer ([a-f0-9]{64})$/)?.[1];
|
|
451
|
+
if (!credential) throw new TelegramError("UNAUTHORIZED", 401);
|
|
452
|
+
const hash = await digest(credential);
|
|
453
|
+
return change((state) => {
|
|
454
|
+
const host = Object.values(state.installations).find((i) => equalSecret(i.credentialHash, hash) && !i.revoked);
|
|
455
|
+
if (!host) throw new TelegramError("UNAUTHORIZED", 401);
|
|
456
|
+
return host.id;
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
async function handle(request) {
|
|
460
|
+
try {
|
|
461
|
+
const path = new URL(request.url).pathname;
|
|
462
|
+
if (path === "/telegram/webhook" && request.method === "POST") {
|
|
463
|
+
if (!equalSecret(request.headers.get("x-telegram-bot-api-secret-token") ?? "", options.webhookSecret)) throw new TelegramError("UNAUTHORIZED", 401);
|
|
464
|
+
const callback = await acceptTelegramUpdate(options, await boundedJson(request));
|
|
465
|
+
if (callback) await sender.acknowledgeCallback(callback.id, callback.text);
|
|
466
|
+
return json({ accepted: true });
|
|
467
|
+
}
|
|
468
|
+
if (path === "/telegram/installations" && request.method === "POST") {
|
|
469
|
+
const key = options.enrollmentKey?.(request);
|
|
470
|
+
if (!key) throw new TelegramError("ENROLLMENT_UNAVAILABLE", 503);
|
|
471
|
+
const networkHash = await digest(key), credential = randomToken(32), credentialHash = await digest(credential);
|
|
472
|
+
const installationId2 = randomToken(16);
|
|
473
|
+
await change((state) => {
|
|
474
|
+
rateLimit(state, `enroll:${networkHash}`, now(), 5, 6e4);
|
|
475
|
+
if (Object.keys(state.installations).length >= 1e4) throw new TelegramError("CAPACITY_EXCEEDED", 503);
|
|
476
|
+
state.installations[installationId2] = { id: installationId2, credentialHash, createdAt: now(), lastSeenAt: 0, revoked: false };
|
|
477
|
+
});
|
|
478
|
+
return json({ protocol: TELEGRAM_PROTOCOL, installationId: installationId2, credential }, 201);
|
|
479
|
+
}
|
|
480
|
+
const installationId = await authenticate(request);
|
|
481
|
+
if (request.headers.get("x-agents24-telegram-protocol") !== TELEGRAM_PROTOCOL) throw new TelegramError("PROTOCOL_MISMATCH", 409);
|
|
482
|
+
if (path === "/telegram/pairings" && request.method === "POST") {
|
|
483
|
+
const body = await boundedJson(request), conversationId = textField(body.conversationId);
|
|
484
|
+
const token = randomToken(), tokenHash = await digest(token), id = randomToken(16);
|
|
485
|
+
await change((state) => {
|
|
486
|
+
requireInstallation(state, installationId);
|
|
487
|
+
rateLimit(state, `pair:${installationId}`, now(), 10, 6e4);
|
|
488
|
+
state.pairings[id] = { id, installationId, conversationId, tokenHash, expiresAt: now() + PAIRING_TTL_MS, status: "pending" };
|
|
489
|
+
});
|
|
490
|
+
return json({ id, conversationId, expiresAt: now() + PAIRING_TTL_MS, url: `https://t.me/${options.botUsername}?start=${token}` }, 201);
|
|
491
|
+
}
|
|
492
|
+
if (path === "/telegram/status" && request.method === "GET") return json(await change((state) => ({
|
|
493
|
+
protocol: TELEGRAM_PROTOCOL,
|
|
494
|
+
bindings: Object.values(state.bindings).filter((b) => b.installationId === installationId),
|
|
495
|
+
pairings: Object.values(state.pairings).filter((p) => p.installationId === installationId).map(({ tokenHash: _, ...pair }) => pair),
|
|
496
|
+
deliveries: Object.values(state.deliveries).filter((d) => d.bindingId && state.bindings[d.bindingId]?.installationId === installationId && ["unknown", "rejected"].includes(d.status)).map(({ text: _, fingerprint: __, buttons: ___, ...delivery }) => delivery)
|
|
497
|
+
})));
|
|
498
|
+
const pairingMatch = /^\/telegram\/pairings\/([a-f0-9]{32})\/confirm$/.exec(path);
|
|
499
|
+
if (pairingMatch && request.method === "POST") {
|
|
500
|
+
const body = await boundedJson(request);
|
|
501
|
+
const binding = await change((state) => {
|
|
502
|
+
requireInstallation(state, installationId);
|
|
503
|
+
const pair = state.pairings[pairingMatch[1]];
|
|
504
|
+
if (!pair || pair.installationId !== installationId) throw new TelegramError("PAIRING_UNAVAILABLE", 404);
|
|
505
|
+
if (pair.status === "active" && pair.bindingId) return requireBinding(state, installationId, pair.bindingId);
|
|
506
|
+
if (pair.status !== "awaiting_confirmation" || !pair.claimant || pair.expiresAt <= now()) throw new TelegramError("PAIRING_UNAVAILABLE", 409);
|
|
507
|
+
const previous = Object.values(state.bindings).filter((b) => b.status === "active" && (b.chatId === pair.claimant.chatId || b.installationId === installationId && b.conversationId === pair.conversationId));
|
|
508
|
+
if (previous.length && body.replace !== true) throw new TelegramError("REPLACEMENT_REQUIRES_CONFIRMATION", 409);
|
|
509
|
+
for (const prior of previous) revokeBinding(state, prior);
|
|
510
|
+
const id = pair.id, generation = randomToken(16);
|
|
511
|
+
const created = {
|
|
512
|
+
id,
|
|
513
|
+
installationId,
|
|
514
|
+
conversationId: pair.conversationId,
|
|
515
|
+
generation,
|
|
516
|
+
...pair.claimant,
|
|
517
|
+
createdAt: now(),
|
|
518
|
+
status: "active"
|
|
519
|
+
};
|
|
520
|
+
state.bindings[id] = created;
|
|
521
|
+
pair.status = "active";
|
|
522
|
+
pair.bindingId = id;
|
|
523
|
+
notice(state, `connected:${id}`, created.chatId, `Connected to ${app}. New replies and approvals from this conversation will appear here.`, now());
|
|
524
|
+
return created;
|
|
525
|
+
});
|
|
526
|
+
options.notifyHost?.(installationId);
|
|
527
|
+
return json({ binding });
|
|
528
|
+
}
|
|
529
|
+
if (path === "/telegram/host/poll" && request.method === "POST") {
|
|
530
|
+
return json(await change((state) => {
|
|
531
|
+
requireInstallation(state, installationId).lastSeenAt = now();
|
|
532
|
+
const bindings = Object.values(state.bindings).filter((b) => b.installationId === installationId && b.status === "active");
|
|
533
|
+
const ids = new Set(bindings.map((b) => b.id));
|
|
534
|
+
return { protocol: TELEGRAM_PROTOCOL, bindings, events: Object.values(state.inbox).filter((e) => ids.has(e.bindingId) && e.status === "pending").sort((a, b) => a.receivedAt - b.receivedAt || Number(a.id.split(":").at(-1)) - Number(b.id.split(":").at(-1))).slice(0, 100) };
|
|
535
|
+
}));
|
|
536
|
+
}
|
|
537
|
+
if (path === "/telegram/host/ack" && request.method === "POST") {
|
|
538
|
+
const body = await boundedJson(request), id = textField(body.eventId);
|
|
539
|
+
await change((state) => {
|
|
540
|
+
requireInstallation(state, installationId);
|
|
541
|
+
const event = state.inbox[id];
|
|
542
|
+
if (!event) throw new TelegramError("EVENT_UNAVAILABLE", 404);
|
|
543
|
+
requireBinding(state, installationId, event.bindingId, event.generation);
|
|
544
|
+
if (event.status === "pending") event.status = "accepted";
|
|
545
|
+
delete event.text;
|
|
546
|
+
delete event.actionRef;
|
|
547
|
+
});
|
|
548
|
+
return json({ accepted: true });
|
|
549
|
+
}
|
|
550
|
+
if (path === "/telegram/outbound" && request.method === "POST") {
|
|
551
|
+
const body = await boundedJson(request, 262144), bindingId = textField(body.bindingId), generation = textField(body.generation), sourceId = textField(body.sourceId);
|
|
552
|
+
const text = textField(body.text, 1e5);
|
|
553
|
+
const replyRef = body.replyRef === void 0 ? void 0 : textField(body.replyRef, 128);
|
|
554
|
+
const buttons = body.buttons === void 0 ? void 0 : (() => {
|
|
555
|
+
if (!Array.isArray(body.buttons) || body.buttons.length > MAX_TELEGRAM_BUTTONS) throw new TelegramError("INVALID_BUTTONS");
|
|
556
|
+
return body.buttons.map((raw) => {
|
|
557
|
+
const item = object(raw);
|
|
558
|
+
if (item.kind !== void 0 && !["stop", "answer"].includes(item.kind)) throw new TelegramError("INVALID_BUTTONS");
|
|
559
|
+
return { label: textField(item.label, 100), actionRef: textField(item.actionRef, 128), kind: item.kind };
|
|
560
|
+
});
|
|
561
|
+
})();
|
|
562
|
+
const fingerprint = await digest(JSON.stringify({ text, buttons, replyRef }));
|
|
563
|
+
await change((state) => {
|
|
564
|
+
const binding = requireBinding(state, installationId, bindingId, generation);
|
|
565
|
+
if (Object.values(state.deliveries).filter((d) => d.bindingId === bindingId && ["pending", "unknown", "sending"].includes(d.status)).length > 500) throw new TelegramError("DELIVERY_BACKLOG_FULL", 429);
|
|
566
|
+
addDelivery(state, binding, sourceId, text, buttons, fingerprint, now(), replyRef);
|
|
567
|
+
});
|
|
568
|
+
return json({ accepted: true });
|
|
569
|
+
}
|
|
570
|
+
if (path === "/telegram/actions/invalidate" && request.method === "POST") {
|
|
571
|
+
const body = await boundedJson(request), bindingId = textField(body.bindingId), generation = textField(body.generation);
|
|
572
|
+
const refs = new Set(Array.isArray(body.actionRefs) ? body.actionRefs.map((v) => textField(v, 128)) : []);
|
|
573
|
+
await change((state) => {
|
|
574
|
+
requireBinding(state, installationId, bindingId, generation);
|
|
575
|
+
for (const [id, action] of Object.entries(state.actions)) if (action.bindingId === bindingId && (!refs.size || refs.has(action.actionRef))) delete state.actions[id];
|
|
576
|
+
});
|
|
577
|
+
return json({ accepted: true });
|
|
578
|
+
}
|
|
579
|
+
const revokeMatch = /^\/telegram\/bindings\/([a-f0-9]{32})\/revoke$/.exec(path);
|
|
580
|
+
if (revokeMatch && request.method === "POST") {
|
|
581
|
+
await change((state) => revokeBinding(state, requireBinding(state, installationId, revokeMatch[1])));
|
|
582
|
+
options.notifyHost?.(installationId);
|
|
583
|
+
return json({ revoked: true });
|
|
584
|
+
}
|
|
585
|
+
if (path === "/telegram/deliveries/resolve" && request.method === "POST") {
|
|
586
|
+
const body = await boundedJson(request), id = textField(body.deliveryId, 1024);
|
|
587
|
+
if (!["retry", "skip"].includes(body.action)) throw new TelegramError("INVALID_ACTION");
|
|
588
|
+
await change((state) => {
|
|
589
|
+
const row = state.deliveries[id];
|
|
590
|
+
if (!row?.bindingId) throw new TelegramError("DELIVERY_UNAVAILABLE", 404);
|
|
591
|
+
requireBinding(state, installationId, row.bindingId, row.generation);
|
|
592
|
+
if (!["unknown", "rejected"].includes(row.status)) throw new TelegramError("DELIVERY_ALREADY_RESOLVED", 409);
|
|
593
|
+
row.status = body.action === "retry" ? "pending" : "skipped";
|
|
594
|
+
row.retryAt = now();
|
|
595
|
+
if (body.action === "skip") {
|
|
596
|
+
row.text = "";
|
|
597
|
+
delete row.buttons;
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
return json({ accepted: true });
|
|
601
|
+
}
|
|
602
|
+
throw new TelegramError("NOT_FOUND", 404);
|
|
603
|
+
} catch (error) {
|
|
604
|
+
return error instanceof TelegramError ? json({ code: error.code }, error.status) : json({ code: "GATEWAY_UNAVAILABLE" }, 503);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return { handle, authenticate, flushDeliveries: sender.flush, sweep: () => change(() => {
|
|
608
|
+
}) };
|
|
609
|
+
}
|
|
610
|
+
export {
|
|
611
|
+
ACTION_TTL_MS,
|
|
612
|
+
HOST_LEASE_MS,
|
|
613
|
+
MAX_TELEGRAM_BUTTONS,
|
|
614
|
+
PAIRING_TTL_MS,
|
|
615
|
+
TELEGRAM_PROTOCOL,
|
|
616
|
+
TEXT_TTL_MS,
|
|
617
|
+
TelegramError,
|
|
618
|
+
createMemoryTelegramStore,
|
|
619
|
+
createTelegramGateway,
|
|
620
|
+
emptyGatewayState,
|
|
621
|
+
emptyHostState,
|
|
622
|
+
splitTelegramText
|
|
623
|
+
};
|
|
624
|
+
//# sourceMappingURL=gateway.js.map
|