Personal Telegram developer console for GitHub
feat: add mobile read-only GitHub browser
* test: define mobile GitHub browser behavior * feat: add read-only mobile repository browser
davoodmehraban89 committed
Oct 2, 2026 at 19:19 UTC
d8c10fb91ec6306fdb4e5978baa62f4e834d419e
2 files changed
+420
-27
src/index.js
+224
-27
@@ -35,6 +35,10 @@ async function sendMessage(env, chatId, message, extra = {}) {
35
});
36
}
37
38
+async function answerCallback(env, callbackQueryId) {
39
+ return telegramApi(env, "answerCallbackQuery", { callback_query_id: callbackQueryId });
40
+}
41
+
42
function isOwner(env, from) {
43
if (!from || !env.OWNER_TELEGRAM_ID) return false;
44
return String(from.id) === String(env.OWNER_TELEGRAM_ID);
@@ -49,18 +53,45 @@ function githubHeaders(env) {
53
};
54
}
55
56
+async function githubJson(env, url, label) {
57
+ const response = await fetch(url, { headers: githubHeaders(env) });
58
+ if (!response.ok) {
59
+ const body = await response.text();
60
+ const error = new Error(`${label} failed: ${response.status} ${body}`);
61
+ error.status = response.status;
62
+ throw error;
63
+ }
64
+ return response.json();
65
+}
66
+
67
async function fetchRepos(env) {
53
- const response = await fetch(
68
+ return githubJson(
69
+ env,
70
"https://api.github.com/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member",
55
- { headers: githubHeaders(env) }
71
+ "GitHub repos"
72
);
73
+}
74
58
- if (!response.ok) {
59
- const body = await response.text();
60
- throw new Error(`GitHub repos failed: ${response.status} ${body}`);
61
- }
75
+async function fetchRepoById(env, repoId) {
76
+ return githubJson(env, `https://api.github.com/repositories/${repoId}`, "GitHub repository");
77
+}
78
63
- return response.json();
79
+function repoPath(fullName) {
80
+ return fullName.split("/").map(encodeURIComponent).join("/");
81
+}
82
+
83
+function escapeHtml(value = "") {
84
+ return String(value)
85
+ .replaceAll("&", "&")
86
+ .replaceAll("<", "<")
87
+ .replaceAll(">", ">")
88
+ .replaceAll('"', """);
89
+}
90
+
91
+function decodeBase64Utf8(value) {
92
+ const binary = atob(String(value || "").replace(/\s/g, ""));
93
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
94
+ return new TextDecoder().decode(bytes);
95
}
96
97
function startMessage() {
@@ -68,17 +99,164 @@ function startMessage() {
99
"<b>Nexa Dev</b>",
100
"دستیار شخصی توسعه و مدیریت GitHub از داخل تلگرام.",
101
"",
71
- "فرمانهای نسخه اول:",
72
- "/repos — نمایش مخزنهای قابل دسترس",
102
+ "فرمانها:",
103
+ "/repos — مرور مخزنها با دکمههای لمسی",
104
"/status — وضعیت سرویس",
105
].join("\n");
106
}
107
108
+function repoButtons(repos) {
109
+ return repos.slice(0, 20).map((repo) => [{
110
+ text: `${repo.private ? "🔒" : "🌐"} ${repo.name}`,
111
+ callback_data: `repo:${repo.id}`,
112
+ }]);
113
+}
114
+
115
+async function showRepos(env, chatId) {
116
+ if (!env.GITHUB_TOKEN) {
117
+ await sendMessage(env, chatId, "⚠️ اتصال GitHub هنوز با Secret نهایی نشده است.");
118
+ return;
119
+ }
120
+
121
+ const repos = await fetchRepos(env);
122
+ if (!repos.length) {
123
+ await sendMessage(env, chatId, "هیچ مخزنی پیدا نشد.");
124
+ return;
125
+ }
126
+
127
+ await sendMessage(env, chatId, "<b>Repositories</b>\nیک مخزن را انتخاب کن:", {
128
+ reply_markup: { inline_keyboard: repoButtons(repos) },
129
+ });
130
+}
131
+
132
+function repoMenu(repo) {
133
+ return {
134
+ inline_keyboard: [
135
+ [{ text: "📁 فایلها", callback_data: `files:${repo.id}` }],
136
+ [
137
+ { text: "🧾 کامیتها", callback_data: `commits:${repo.id}` },
138
+ { text: "🔀 Pull Requestها", callback_data: `prs:${repo.id}` },
139
+ ],
140
+ [{ text: "⬅️ مخزنها", callback_data: "repos" }],
141
+ ],
142
+ };
143
+}
144
+
145
+async function showRepo(env, chatId, repoId) {
146
+ const repo = await fetchRepoById(env, repoId);
147
+ const visibility = repo.private ? "🔒 خصوصی" : "🌐 عمومی";
148
+ const description = repo.description ? `\n${escapeHtml(repo.description)}` : "";
149
+ await sendMessage(
150
+ env,
151
+ chatId,
152
+ `<b>${escapeHtml(repo.full_name)}</b>\n${visibility}\nbranch: <code>${escapeHtml(repo.default_branch)}</code>${description}`,
153
+ { reply_markup: repoMenu(repo) }
154
+ );
155
+}
156
+
157
+function fileButtons(repoId, items, back = `repo:${repoId}`) {
158
+ const rows = items.slice(0, 30).map((item) => {
159
+ const isDir = item.type === "dir" || item.type === "tree";
160
+ const isFile = item.type === "file" || item.type === "blob";
161
+ const callback = isDir
162
+ ? `tree:${repoId}:${item.sha}`
163
+ : isFile
164
+ ? `blob:${repoId}:${item.sha}`
165
+ : null;
166
+ return callback ? [{ text: `${isDir ? "📁" : "📄"} ${item.name || item.path}`, callback_data: callback }] : [];
167
+ }).filter((row) => row.length);
168
+ rows.push([{ text: "⬅️ برگشت", callback_data: back }]);
169
+ return { inline_keyboard: rows };
170
+}
171
+
172
+async function showRootFiles(env, chatId, repoId) {
173
+ const repo = await fetchRepoById(env, repoId);
174
+ const full = repoPath(repo.full_name);
175
+ const branch = encodeURIComponent(repo.default_branch);
176
+ const items = await githubJson(
177
+ env,
178
+ `https://api.github.com/repos/${full}/contents?ref=${branch}`,
179
+ "GitHub contents"
180
+ );
181
+
182
+ await sendMessage(env, chatId, `📁 <b>${escapeHtml(repo.full_name)}</b> /`, {
183
+ reply_markup: fileButtons(repoId, Array.isArray(items) ? items : [], `repo:${repoId}`),
184
+ });
185
+}
186
+
187
+async function showTree(env, chatId, repoId, sha) {
188
+ const repo = await fetchRepoById(env, repoId);
189
+ const full = repoPath(repo.full_name);
190
+ const tree = await githubJson(
191
+ env,
192
+ `https://api.github.com/repos/${full}/git/trees/${encodeURIComponent(sha)}`,
193
+ "GitHub tree"
194
+ );
195
+
196
+ await sendMessage(env, chatId, `📁 <b>${escapeHtml(repo.full_name)}</b>`, {
197
+ reply_markup: fileButtons(repoId, tree.tree || [], `files:${repoId}`),
198
+ });
199
+}
200
+
201
+async function showBlob(env, chatId, repoId, sha) {
202
+ const repo = await fetchRepoById(env, repoId);
203
+ const full = repoPath(repo.full_name);
204
+ const blob = await githubJson(
205
+ env,
206
+ `https://api.github.com/repos/${full}/git/blobs/${encodeURIComponent(sha)}`,
207
+ "GitHub blob"
208
+ );
209
+
210
+ if (blob.encoding !== "base64" || blob.size > 100000) {
211
+ await sendMessage(env, chatId, "این فایل برای نمایش مستقیم در تلگرام مناسب نیست.", {
212
+ reply_markup: { inline_keyboard: [[{ text: "⬅️ فایلها", callback_data: `files:${repoId}` }]] },
213
+ });
214
+ return;
215
+ }
216
+
217
+ const decoded = decodeBase64Utf8(blob.content);
218
+ const preview = decoded.length > 3000 ? `${decoded.slice(0, 3000)}\n…` : decoded;
219
+ await sendMessage(env, chatId, `<pre>${escapeHtml(preview)}</pre>`, {
220
+ reply_markup: { inline_keyboard: [[{ text: "⬅️ فایلها", callback_data: `files:${repoId}` }]] },
221
+ });
222
+}
223
+
224
+async function showCommits(env, chatId, repoId) {
225
+ const repo = await fetchRepoById(env, repoId);
226
+ const full = repoPath(repo.full_name);
227
+ const commits = await githubJson(
228
+ env,
229
+ `https://api.github.com/repos/${full}/commits?per_page=5&sha=${encodeURIComponent(repo.default_branch)}`,
230
+ "GitHub commits"
231
+ );
232
+ const lines = commits.map((commit) => {
233
+ const title = String(commit.commit?.message || "").split("\n")[0];
234
+ const author = commit.author?.login || commit.commit?.author?.name || "unknown";
235
+ return `• <code>${escapeHtml(String(commit.sha).slice(0, 7))}</code> ${escapeHtml(title)} — ${escapeHtml(author)}`;
236
+ });
237
+ await sendMessage(env, chatId, `<b>آخرین کامیتها</b>\n\n${lines.join("\n") || "کامیتی پیدا نشد."}`, {
238
+ reply_markup: { inline_keyboard: [[{ text: "⬅️ مخزن", callback_data: `repo:${repoId}` }]] },
239
+ });
240
+}
241
+
242
+async function showPullRequests(env, chatId, repoId) {
243
+ const repo = await fetchRepoById(env, repoId);
244
+ const full = repoPath(repo.full_name);
245
+ const prs = await githubJson(
246
+ env,
247
+ `https://api.github.com/repos/${full}/pulls?state=open&per_page=5`,
248
+ "GitHub pull requests"
249
+ );
250
+ const lines = prs.map((pr) => `• <b>#${pr.number}</b> ${escapeHtml(pr.title)} — ${escapeHtml(pr.user?.login || "unknown")}`);
251
+ await sendMessage(env, chatId, `<b>Pull Requestهای باز</b>\n\n${lines.join("\n") || "PR بازی وجود ندارد."}`, {
252
+ reply_markup: { inline_keyboard: [[{ text: "⬅️ مخزن", callback_data: `repo:${repoId}` }]] },
253
+ });
254
+}
255
+
256
async function handleCommand(env, message) {
257
const chatId = message.chat?.id;
258
const command = (message.text || "").trim().split(/\s+/)[0].split("@")[0].toLowerCase();
259
81
- // Personal bot: fail silently for every Telegram user except the owner.
260
if (!isOwner(env, message.from)) return;
261
262
if (command === "/start") {
@@ -87,32 +265,39 @@ async function handleCommand(env, message) {
265
}
266
267
if (command === "/status") {
90
- await sendMessage(env, chatId, "✅ Nexa Dev آنلاین است.\nGitHub integration: آماده بررسی");
268
+ await sendMessage(env, chatId, "✅ Nexa Dev آنلاین است.\nGitHub integration: آماده");
269
return;
270
}
271
272
if (command === "/repos") {
95
- if (!env.GITHUB_TOKEN) {
96
- await sendMessage(env, chatId, "⚠️ اتصال GitHub هنوز با Secret نهایی نشده است.");
97
- return;
98
- }
273
+ await showRepos(env, chatId);
274
+ return;
275
+ }
276
100
- const repos = await fetchRepos(env);
101
- if (!repos.length) {
102
- await sendMessage(env, chatId, "هیچ مخزنی پیدا نشد.");
103
- return;
104
- }
277
+ await sendMessage(env, chatId, "فرمان شناخته نشد. /start را بزن.");
278
+}
279
106
- const lines = repos.slice(0, 20).map((repo, i) => {
107
- const visibility = repo.private ? "🔒" : "🌐";
108
- return `${i + 1}. ${visibility} <b>${repo.full_name}</b>\n branch: <code>${repo.default_branch}</code>`;
109
- });
280
+async function handleCallbackQuery(env, query) {
281
+ if (!isOwner(env, query.from)) return;
282
+
283
+ const chatId = query.message?.chat?.id;
284
+ const data = String(query.data || "");
285
+ await answerCallback(env, query.id);
286
111
- await sendMessage(env, chatId, `<b>Repositories</b>\n\n${lines.join("\n\n")}`);
287
+ if (data === "repos") {
288
+ await showRepos(env, chatId);
289
return;
290
}
291
115
- await sendMessage(env, chatId, "فرمان شناخته نشد. /start را بزن.");
292
+ const [action, repoId, sha] = data.split(":");
293
+ if (!/^\d+$/.test(repoId || "")) return;
294
+
295
+ if (action === "repo") return showRepo(env, chatId, repoId);
296
+ if (action === "files") return showRootFiles(env, chatId, repoId);
297
+ if (action === "tree" && /^[a-f0-9]{40}$/i.test(sha || "")) return showTree(env, chatId, repoId, sha);
298
+ if (action === "blob" && /^[a-f0-9]{40}$/i.test(sha || "")) return showBlob(env, chatId, repoId, sha);
299
+ if (action === "commits") return showCommits(env, chatId, repoId);
300
+ if (action === "prs") return showPullRequests(env, chatId, repoId);
301
}
302
303
async function handleTelegramWebhook(request, env) {
@@ -125,6 +310,18 @@ async function handleTelegramWebhook(request, env) {
310
const update = await request.json();
311
if (update.message?.text) {
312
await handleCommand(env, update.message);
313
+ } else if (update.callback_query) {
314
+ try {
315
+ await handleCallbackQuery(env, update.callback_query);
316
+ } catch (error) {
317
+ console.error(error);
318
+ if (isOwner(env, update.callback_query.from) && update.callback_query.message?.chat?.id) {
319
+ const hint = error?.status === 403
320
+ ? "⚠️ توکن GitHub مجوز Read لازم برای این بخش را ندارد."
321
+ : "⚠️ دریافت اطلاعات GitHub ناموفق بود.";
322
+ await sendMessage(env, update.callback_query.message.chat.id, hint);
323
+ }
324
+ }
325
}
326
327
return text("OK");
@@ -138,7 +335,7 @@ export default {
335
return json({
336
name: "Nexa Dev",
337
status: "ok",
141
- version: "0.1.0",
338
+ version: "0.2.0",
339
});
340
}
341
test/navigation.test.js
new
+196
@@ -0,0 +1,196 @@
1
+import test from "node:test";
2
+import assert from "node:assert/strict";
3
+import worker from "../src/index.js";
4
+
5
+const env = {
6
+ TELEGRAM_WEBHOOK_SECRET: "right",
7
+ OWNER_TELEGRAM_ID: "123",
8
+ TELEGRAM_BOT_TOKEN: "token",
9
+ GITHUB_TOKEN: "gh-token",
10
+};
11
+
12
+function webhook(update) {
13
+ return new Request("https://example.com/telegram/webhook", {
14
+ method: "POST",
15
+ headers: {
16
+ "content-type": "application/json",
17
+ "X-Telegram-Bot-Api-Secret-Token": "right",
18
+ },
19
+ body: JSON.stringify(update),
20
+ });
21
+}
22
+
23
+function telegramOk() {
24
+ return new Response(JSON.stringify({ ok: true, result: {} }), {
25
+ status: 200,
26
+ headers: { "content-type": "application/json" },
27
+ });
28
+}
29
+
30
+test("/repos renders repositories as tappable inline buttons", async () => {
31
+ const calls = [];
32
+ globalThis.fetch = async (url, options = {}) => {
33
+ const u = String(url);
34
+ if (u.includes("api.github.com/user/repos")) {
35
+ return new Response(JSON.stringify([
36
+ { id: 101, full_name: "davood/demo", name: "demo", private: true, default_branch: "main" },
37
+ ]), { status: 200, headers: { "content-type": "application/json" } });
38
+ }
39
+ calls.push({ url: u, body: options.body ? JSON.parse(options.body) : null });
40
+ return telegramOk();
41
+ };
42
+
43
+ const res = await worker.fetch(webhook({
44
+ message: { text: "/repos", from: { id: 123 }, chat: { id: 123 } },
45
+ }), env);
46
+
47
+ assert.equal(res.status, 200);
48
+ const sent = calls.find((c) => c.url.includes("sendMessage"));
49
+ assert.ok(sent);
50
+ assert.equal(sent.body.reply_markup.inline_keyboard[0][0].text, "🔒 demo");
51
+ assert.equal(sent.body.reply_markup.inline_keyboard[0][0].callback_data, "repo:101");
52
+});
53
+
54
+test("repository callback opens a mobile action menu", async () => {
55
+ const telegramCalls = [];
56
+ globalThis.fetch = async (url, options = {}) => {
57
+ const u = String(url);
58
+ if (u === "https://api.github.com/repositories/101") {
59
+ return new Response(JSON.stringify({
60
+ id: 101,
61
+ full_name: "davood/demo",
62
+ private: true,
63
+ default_branch: "main",
64
+ description: "Demo repo",
65
+ }), { status: 200, headers: { "content-type": "application/json" } });
66
+ }
67
+ telegramCalls.push({ url: u, body: options.body ? JSON.parse(options.body) : null });
68
+ return telegramOk();
69
+ };
70
+
71
+ const res = await worker.fetch(webhook({
72
+ callback_query: {
73
+ id: "cb1",
74
+ from: { id: 123 },
75
+ data: "repo:101",
76
+ message: { chat: { id: 123 }, message_id: 50 },
77
+ },
78
+ }), env);
79
+
80
+ assert.equal(res.status, 200);
81
+ assert.ok(telegramCalls.some((c) => c.url.includes("answerCallbackQuery")));
82
+ const sent = telegramCalls.find((c) => c.url.includes("sendMessage"));
83
+ assert.match(sent.body.text, /davood\/demo/);
84
+ const buttons = sent.body.reply_markup.inline_keyboard.flat().map((b) => b.callback_data);
85
+ assert.deepEqual(buttons, ["files:101", "commits:101", "prs:101", "repos"]);
86
+});
87
+
88
+test("files callback lists folders and files using compact SHA callbacks", async () => {
89
+ const telegramCalls = [];
90
+ globalThis.fetch = async (url, options = {}) => {
91
+ const u = String(url);
92
+ if (u === "https://api.github.com/repositories/101") {
93
+ return new Response(JSON.stringify({ id: 101, full_name: "davood/demo", default_branch: "main" }), { status: 200, headers: { "content-type": "application/json" } });
94
+ }
95
+ if (u.startsWith("https://api.github.com/repos/davood/demo/contents")) {
96
+ return new Response(JSON.stringify([
97
+ { name: "src", type: "dir", sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" },
98
+ { name: "README.md", type: "file", sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" },
99
+ ]), { status: 200, headers: { "content-type": "application/json" } });
100
+ }
101
+ telegramCalls.push({ url: u, body: options.body ? JSON.parse(options.body) : null });
102
+ return telegramOk();
103
+ };
104
+
105
+ await worker.fetch(webhook({
106
+ callback_query: {
107
+ id: "cb2",
108
+ from: { id: 123 },
109
+ data: "files:101",
110
+ message: { chat: { id: 123 }, message_id: 51 },
111
+ },
112
+ }), env);
113
+
114
+ const sent = telegramCalls.find((c) => c.url.includes("sendMessage"));
115
+ const buttons = sent.body.reply_markup.inline_keyboard.flat();
116
+ assert.equal(buttons[0].text, "📁 src");
117
+ assert.equal(buttons[0].callback_data, "tree:101:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
118
+ assert.equal(buttons[1].text, "📄 README.md");
119
+ assert.equal(buttons[1].callback_data, "blob:101:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
120
+});
121
+
122
+test("blob callback shows escaped text content and a back button", async () => {
123
+ const telegramCalls = [];
124
+ globalThis.fetch = async (url, options = {}) => {
125
+ const u = String(url);
126
+ if (u === "https://api.github.com/repositories/101") {
127
+ return new Response(JSON.stringify({ id: 101, full_name: "davood/demo", default_branch: "main" }), { status: 200, headers: { "content-type": "application/json" } });
128
+ }
129
+ if (u === "https://api.github.com/repos/davood/demo/git/blobs/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") {
130
+ const content = Buffer.from("<hello> & goodbye").toString("base64");
131
+ return new Response(JSON.stringify({ encoding: "base64", content, size: 17 }), { status: 200, headers: { "content-type": "application/json" } });
132
+ }
133
+ telegramCalls.push({ url: u, body: options.body ? JSON.parse(options.body) : null });
134
+ return telegramOk();
135
+ };
136
+
137
+ await worker.fetch(webhook({
138
+ callback_query: {
139
+ id: "cb3",
140
+ from: { id: 123 },
141
+ data: "blob:101:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
142
+ message: { chat: { id: 123 }, message_id: 52 },
143
+ },
144
+ }), env);
145
+
146
+ const sent = telegramCalls.find((c) => c.url.includes("sendMessage"));
147
+ assert.match(sent.body.text, /<hello> & goodbye/);
148
+ assert.equal(sent.body.reply_markup.inline_keyboard.at(-1)[0].callback_data, "files:101");
149
+});
150
+
151
+test("commits and pull requests callbacks render concise repository activity", async () => {
152
+ const sentTexts = [];
153
+ globalThis.fetch = async (url, options = {}) => {
154
+ const u = String(url);
155
+ if (u === "https://api.github.com/repositories/101") {
156
+ return new Response(JSON.stringify({ id: 101, full_name: "davood/demo", default_branch: "main" }), { status: 200, headers: { "content-type": "application/json" } });
157
+ }
158
+ if (u.includes("/commits?")) {
159
+ return new Response(JSON.stringify([{ sha: "1234567890", commit: { message: "fix mobile menu" }, author: { login: "davood" } }]), { status: 200, headers: { "content-type": "application/json" } });
160
+ }
161
+ if (u.includes("/pulls?")) {
162
+ return new Response(JSON.stringify([{ number: 7, title: "Improve bot UI", user: { login: "davood" } }]), { status: 200, headers: { "content-type": "application/json" } });
163
+ }
164
+ if (u.includes("sendMessage")) sentTexts.push(JSON.parse(options.body).text);
165
+ return telegramOk();
166
+ };
167
+
168
+ for (const data of ["commits:101", "prs:101"]) {
169
+ await worker.fetch(webhook({
170
+ callback_query: { id: data, from: { id: 123 }, data, message: { chat: { id: 123 }, message_id: 53 } },
171
+ }), env);
172
+ }
173
+
174
+ assert.ok(sentTexts.some((t) => t.includes("fix mobile menu")));
175
+ assert.ok(sentTexts.some((t) => t.includes("#7") && t.includes("Improve bot UI")));
176
+});
177
+
178
+test("callback queries from non-owner users are ignored", async () => {
179
+ let calls = 0;
180
+ globalThis.fetch = async () => {
181
+ calls += 1;
182
+ return telegramOk();
183
+ };
184
+
185
+ const res = await worker.fetch(webhook({
186
+ callback_query: {
187
+ id: "bad",
188
+ from: { id: 999 },
189
+ data: "repo:101",
190
+ message: { chat: { id: 999 }, message_id: 1 },
191
+ },
192
+ }), env);
193
+
194
+ assert.equal(res.status, 200);
195
+ assert.equal(calls, 0);
196
+});
\ No newline at end of file