Skip to content

Commit e771cbe

Browse files
committed
feat: open bot Mini Apps through one-time local handoff
Add an authenticated main Web App request and a loopback redirect that does not print the signed Telegram URL. Document the workflow and test the handoff. Release as 2.11.0.
1 parent ab3a708 commit e771cbe

9 files changed

Lines changed: 151 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ tgcli messages list --chat @username --limit 20
119119
tgcli messages search "course" --chat @channel --source archive
120120
tgcli messages buttons list --chat @BotFather --id 123 --json
121121
tgcli messages buttons click --chat @BotFather --id 123 --row 1 --column 1 --json
122+
tgcli webapp serve --bot @BotFather
122123
tgcli send text --to @username --message "hello"
123124
tgcli send text --to @username --message "**hi**" --parse-mode markdown
124125
tgcli send text --to @username --message "done" --reply-to 123
@@ -154,6 +155,7 @@ tgcli messages List/search messages
154155
tgcli send Send text, photos, or files
155156
tgcli media Download media
156157
tgcli topics Forum topics
158+
tgcli webapp Open an authenticated bot Mini App through a one-time local handoff
157159
tgcli tags Channel tags
158160
tgcli metadata Channel metadata cache
159161
tgcli contacts Contacts and people
@@ -179,6 +181,17 @@ is actionable. Callback payload bytes are never printed. The click command only
179181
executes Telegram callback buttons; it does not open URL or Web App buttons and
180182
does not support password-protected callbacks.
181183

184+
### bot Mini Apps
185+
186+
Use `tgcli webapp serve --bot @BotFather` to request the bot's main Mini App
187+
with the authenticated tgcli session. The command prints a random, one-time
188+
`127.0.0.1` URL. Open it in a browser on the same machine within 90 seconds;
189+
tgcli redirects that single request to Telegram's signed HTTPS URL, then closes
190+
the local server. The signed URL is never printed by tgcli. Keep browser logs
191+
and traces private because they may contain the signed URL after the redirect.
192+
The command requires a bot with a main Mini App and a working tgcli service or
193+
authenticated local session.
194+
182195
### send text
183196

184197
Send a text message to a user, group, or channel.

‎SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ tgcli auth
6262
- Never use `tgcli sync --chat ...`; top-level `sync` only runs workers via `--once` / `--follow`.
6363
- To sync a specific chat: `tgcli channels sync --chat <id|@username> --enable` and/or `tgcli sync jobs add --chat <id|@username>`, then run `tgcli sync --once` or `tgcli sync --follow`.
6464
- If command shape is uncertain, verify it first with `tgcli <command> --help` instead of guessing flags.
65+
- For a bot's main Mini App, run `tgcli webapp serve --bot @BotFather`, then open its one-time loopback URL in an isolated browser on the same machine within 90 seconds. The signed Telegram URL is not printed by tgcli; do not print browser URLs, logs, or traces containing its authentication data. This does not use Telegram Web.
6566
- Select named accounts with the global `--account <id|alias|phone>` option before the command, or with `TGCLI_ACCOUNT`. Selection precedence is `--account` → `TGCLI_ACCOUNT` → `default`.
6667
- The `default` profile keeps the legacy store and existing authorization. Never run `auth logout`, move a session, or copy session files merely because a named profile is not visible.
6768
- Named profiles have physically isolated config, session, messages database, locks, downloads, sync jobs, and service state. Always use the same account selector for auth, reads, writes, sync, and service commands belonging to that profile.

‎cli.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
import { parseLaunchdList, resolveServiceIdentity } from './core/service-identity.js';
5050
import { resolveStoreDir as resolveStoreDirBase } from './core/store.js';
5151
import { formatErrorMessage, parseRequiredWaitSeconds, withSendRetry } from './core/retry.js';
52+
import { startWebAppHandoff } from './core/webapp-handoff.js';
5253

5354
const CLI_PATH = fileURLToPath(import.meta.url);
5455
const SERVICE_STATE_FILE = 'service-state.json';
@@ -433,6 +434,13 @@ function buildProgram() {
433434
.option('--limit <n>', 'Limit results')
434435
.action(withGlobalOptions((globalFlags, options) => runTopicsSearch(globalFlags, options)));
435436

437+
const webapp = program.command('webapp').description('Open an authenticated Telegram Mini App');
438+
webapp
439+
.command('serve')
440+
.description('Serve a one-time local redirect to a bot main Mini App without printing its signed URL')
441+
.requiredOption('--bot <username>', 'Bot username, for example @BotFather')
442+
.action(withGlobalOptions((globalFlags, options) => runWebappServe(globalFlags, options)));
443+
436444
const tags = program.command('tags').description('Channel tags');
437445
tags
438446
.command('set')
@@ -3518,6 +3526,27 @@ async function runMediaDownload(globalFlags, options = {}) {
35183526
}, timeoutMs);
35193527
}
35203528

3529+
async function runWebappServe(globalFlags, options = {}) {
3530+
const bot = String(options.bot ?? '').trim();
3531+
if (!/^@[A-Za-z0-9_]{5,32}$/.test(bot)) {
3532+
throw new Error('--bot must be a Telegram bot username starting with @.');
3533+
}
3534+
const { url } = await runOwnerOperation({
3535+
storeDir: resolveStoreDir(),
3536+
operation: 'webapp.main',
3537+
args: { bot },
3538+
timeoutMs: globalFlags.timeoutMs ?? 30000,
3539+
});
3540+
const handoff = await startWebAppHandoff(url);
3541+
if (globalFlags.json) {
3542+
writeJson({ url: handoff.url, expiresInSeconds: 90, bot });
3543+
} else {
3544+
console.log(`Open ${handoff.url} in an isolated browser within 90 seconds.`);
3545+
console.log('The signed Telegram URL is passed to the browser once and is not printed.');
3546+
}
3547+
await handoff.wait();
3548+
}
3549+
35213550
async function runTopicsList(globalFlags, options = {}) {
35223551
const timeoutMs = globalFlags.timeoutMs;
35233552
return runWithTimeout(async () => {
@@ -4774,6 +4803,7 @@ const localCliCommands = new Set([
47744803
'service logs',
47754804
'doctor',
47764805
'channels list',
4806+
'webapp serve',
47774807
]);
47784808

47794809
export function classifyCliRoute(name) {

‎core/owner-operations.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,12 @@ export function createOwnerOperations({ storeDir, telegramClient, messageSyncSer
8282
? telegramClient.searchDialogs(query, limit)
8383
: telegramClient.listDialogs(limit);
8484
}, context),
85+
'webapp.main': ({ bot }, context) => coordinator.runLive(async () => {
86+
if (!(await telegramClient.isAuthorized().catch(() => false))) {
87+
throw new Error('Not authenticated. Run `tgcli auth` first.');
88+
}
89+
return telegramClient.openMainWebApp(bot);
90+
}, context),
8591
'cli.execute': (request, context) => coordinator.runLive(async () => {
8692
const { executeOwnerCliCommand } = await loadCliModule();
8793
return executeOwnerCliCommand(request, { telegramClient, messageSyncService }, storeDir);

‎core/webapp-handoff.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { createServer } from 'node:http';
2+
import { randomBytes } from 'node:crypto';
3+
4+
export async function startWebAppHandoff(targetUrl, { ttlMs = 90000 } = {}) {
5+
const target = new URL(targetUrl);
6+
if (target.protocol !== 'https:') {
7+
throw new Error('Telegram returned a non-HTTPS Mini App URL.');
8+
}
9+
10+
let finish;
11+
const done = new Promise((resolve) => { finish = resolve; });
12+
let used = false;
13+
const path = `/${randomBytes(24).toString('base64url')}`;
14+
const server = createServer((request, response) => {
15+
if (request.method !== 'GET' || request.url !== path || used) {
16+
response.writeHead(404, { 'Cache-Control': 'no-store' });
17+
response.end();
18+
return;
19+
}
20+
used = true;
21+
response.writeHead(302, {
22+
Location: target.href,
23+
'Cache-Control': 'no-store',
24+
'Referrer-Policy': 'no-referrer',
25+
});
26+
response.end();
27+
server.close(() => finish('opened'));
28+
});
29+
30+
await new Promise((resolve, reject) => {
31+
server.once('error', reject);
32+
server.listen(0, '127.0.0.1', resolve);
33+
});
34+
const timer = setTimeout(() => server.close(() => finish('expired')), ttlMs);
35+
const address = server.address();
36+
return {
37+
url: `http://127.0.0.1:${address.port}${path}`,
38+
wait: async () => {
39+
try { return await done; } finally { clearTimeout(timer); }
40+
},
41+
close: () => server.close(),
42+
};
43+
}

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@dapi/tgcli",
3-
"version": "2.10.0",
3+
"version": "2.11.0",
44
"type": "module",
55
"description": "Telegram CLI + MCP server powered by MTProto and the official MCP SDK",
66
"main": "mcp-server.js",

‎telegram-client.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,6 +1326,20 @@ class TelegramClient {
13261326
};
13271327
}
13281328

1329+
async openMainWebApp(botRef) {
1330+
await this.ensureLogin();
1331+
const webview = await this.client.openWebview({
1332+
bot: botRef,
1333+
webview: { type: 'main' },
1334+
platform: 'macos',
1335+
});
1336+
const url = new URL(webview.url);
1337+
if (url.protocol !== 'https:') {
1338+
throw new Error('Telegram returned a non-HTTPS Mini App URL.');
1339+
}
1340+
return { url: url.href };
1341+
}
1342+
13291343
async getMessageContext(channelId, messageId, options = {}) {
13301344
await this.ensureLogin();
13311345
const safeBefore = Number.isFinite(options.before) && options.before >= 0

‎tests/webapp-handoff.test.js‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { describe, expect, it, vi } from 'vitest';
2+
3+
import TelegramClient from '../telegram-client.js';
4+
import { startWebAppHandoff } from '../core/webapp-handoff.js';
5+
6+
describe('Telegram Mini App handoff', () => {
7+
it('requests the main app from the authenticated Telegram client', async () => {
8+
const client = Object.create(TelegramClient.prototype);
9+
client.ensureLogin = vi.fn().mockResolvedValue(undefined);
10+
client.client = { openWebview: vi.fn().mockResolvedValue({
11+
url: 'https://example.org/app#tgWebAppData=signed-private-value',
12+
}) };
13+
14+
const result = await client.openMainWebApp('@BotFather');
15+
16+
expect(client.client.openWebview).toHaveBeenCalledWith({
17+
bot: '@BotFather', webview: { type: 'main' }, platform: 'macos',
18+
});
19+
expect(result.url).toContain('tgWebAppData=signed-private-value');
20+
});
21+
22+
it('rejects a non-HTTPS Mini App URL', async () => {
23+
const client = Object.create(TelegramClient.prototype);
24+
client.ensureLogin = vi.fn().mockResolvedValue(undefined);
25+
client.client = { openWebview: vi.fn().mockResolvedValue({ url: 'http://example.org/app' }) };
26+
await expect(client.openMainWebApp('@BotFather')).rejects.toThrow('non-HTTPS');
27+
});
28+
29+
it('serves the signed URL exactly once over loopback', async () => {
30+
const target = 'https://example.org/app#tgWebAppData=signed-private-value';
31+
const handoff = await startWebAppHandoff(target);
32+
expect(handoff.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_-]+$/);
33+
expect((await fetch(new URL('/', handoff.url))).status).toBe(404);
34+
35+
const response = await fetch(handoff.url, { redirect: 'manual' });
36+
expect(response.status).toBe(302);
37+
expect(response.headers.get('location')).toBe(target);
38+
expect(response.headers.get('cache-control')).toBe('no-store');
39+
expect(await handoff.wait()).toBe('opened');
40+
});
41+
});

0 commit comments

Comments
 (0)