P9(5): restore upstream Telegram bot (settings, backup, notifications)

Per user decision 2026-10-21 (reverses the 2026-10-20 drop-Telegram
call): port the upstream 3x-ui v3.7.0-generation Telegram bot wholesale
instead of rewriting a minimal set, adapted to this fork.

- new internal/web/service/tgbot package (telego): bot lifecycle,
  commands, reports, callback router, send helpers; token validation via
  telego; custom API server URL passes the fork's SSRF sanitizer
  (loopback/private bases fall back to the default endpoint, logged)
- settings: full upstream key set (tgBotEnable/Token/Proxy/APIServer/
  ChatId, tgRunTime, tgBotBackup, tgCpu/tgMemory, tgLang,
  tgEnabledEvents) with getters/setters; settings page gains a Telegram
  tab + sidebar entry; token shown masked, clearTgBotToken honored
- wiring (web.go): stats-notify cron registered from tgRunTime when the
  bot is enabled; CheckHashStorage job; CPU/memory alarm jobs gated on
  tgEnabledEvents + thresholds; login notifications via event bus;
  POST /panel/api/setting/testTgBot and /panel/api/backuptotgbot
- lite adaptation: StatsNotifyJob no longer gates on a local Xray core
  (this panel never runs one) so the periodic report and the scheduled
  DB backup (sendDocument) can actually fire
- translations: upstream TG keys restored across all locales

End-to-end smoke (real binary + fake Telegram API over HTTPS at a
public-looking address, browser form wire format): bot starts on
settings change (getMe), testTgBot delivers, panel restart re-arms the
bot, tgRunTime='@every 1m' cron really fires sendDocument carrying the
panel SQLite DB (magic verified) plus the report sendMessage, login
notification delivered, dead-endpoint failure is logged not silent.
13/13 PASS — see P9-REPORT.md.
This commit is contained in:
Muse
2026-10-21 17:16:32 +00:00
parent 5031a70ccb
commit ceca96571d
49 changed files with 8351 additions and 50 deletions
+23
View File
@@ -41,6 +41,17 @@ export const EXAMPLES: Record<string, unknown> = {
"subTitle": "",
"subURI": "",
"subUpdates": 0,
"tgBotAPIServer": "",
"tgBotBackup": false,
"tgBotChatId": "",
"tgBotEnable": false,
"tgBotProxy": "",
"tgBotToken": "",
"tgCpu": 0,
"tgEnabledEvents": "",
"tgLang": "",
"tgMemory": 0,
"tgRunTime": "",
"timeLocation": "",
"trafficDiff": 0,
"trustedProxyCIDRs": "",
@@ -57,6 +68,7 @@ export const EXAMPLES: Record<string, unknown> = {
"expireDiff": 0,
"hasApiToken": false,
"hasNordSecret": false,
"hasTgBotToken": false,
"hasWarpSecret": false,
"ipLimitAllowlist": "",
"outboundDownThreshold": 1,
@@ -96,6 +108,17 @@ export const EXAMPLES: Record<string, unknown> = {
"subTitle": "",
"subURI": "",
"subUpdates": 0,
"tgBotAPIServer": "",
"tgBotBackup": false,
"tgBotChatId": "",
"tgBotEnable": false,
"tgBotProxy": "",
"tgBotToken": "",
"tgCpu": 0,
"tgEnabledEvents": "",
"tgLang": "",
"tgMemory": 0,
"tgRunTime": "",
"timeLocation": "",
"trafficDiff": 0,
"trustedProxyCIDRs": "",
+100
View File
@@ -134,6 +134,43 @@ export const SCHEMAS: Record<string, unknown> = {
"minimum": 0,
"type": "integer"
},
"tgBotAPIServer": {
"type": "string"
},
"tgBotBackup": {
"type": "boolean"
},
"tgBotChatId": {
"type": "string"
},
"tgBotEnable": {
"type": "boolean"
},
"tgBotProxy": {
"type": "string"
},
"tgBotToken": {
"type": "string"
},
"tgCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"tgEnabledEvents": {
"type": "string"
},
"tgLang": {
"type": "string"
},
"tgMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"tgRunTime": {
"type": "string"
},
"timeLocation": {
"type": "string"
},
@@ -211,6 +248,17 @@ export const SCHEMAS: Record<string, unknown> = {
"subTitle",
"subURI",
"subUpdates",
"tgBotAPIServer",
"tgBotBackup",
"tgBotChatId",
"tgBotEnable",
"tgBotProxy",
"tgBotToken",
"tgCpu",
"tgEnabledEvents",
"tgLang",
"tgMemory",
"tgRunTime",
"timeLocation",
"trafficDiff",
"trustedProxyCIDRs",
@@ -239,6 +287,9 @@ export const SCHEMAS: Record<string, unknown> = {
"hasNordSecret": {
"type": "boolean"
},
"hasTgBotToken": {
"type": "boolean"
},
"hasWarpSecret": {
"type": "boolean"
},
@@ -367,6 +418,43 @@ export const SCHEMAS: Record<string, unknown> = {
"minimum": 0,
"type": "integer"
},
"tgBotAPIServer": {
"type": "string"
},
"tgBotBackup": {
"type": "boolean"
},
"tgBotChatId": {
"type": "string"
},
"tgBotEnable": {
"type": "boolean"
},
"tgBotProxy": {
"type": "string"
},
"tgBotToken": {
"type": "string"
},
"tgCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"tgEnabledEvents": {
"type": "string"
},
"tgLang": {
"type": "string"
},
"tgMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"tgRunTime": {
"type": "string"
},
"timeLocation": {
"type": "string"
},
@@ -408,6 +496,7 @@ export const SCHEMAS: Record<string, unknown> = {
"expireDiff",
"hasApiToken",
"hasNordSecret",
"hasTgBotToken",
"hasWarpSecret",
"ipLimitAllowlist",
"outboundDownThreshold",
@@ -447,6 +536,17 @@ export const SCHEMAS: Record<string, unknown> = {
"subTitle",
"subURI",
"subUpdates",
"tgBotAPIServer",
"tgBotBackup",
"tgBotChatId",
"tgBotEnable",
"tgBotProxy",
"tgBotToken",
"tgCpu",
"tgEnabledEvents",
"tgLang",
"tgMemory",
"tgRunTime",
"timeLocation",
"trafficDiff",
"trustedProxyCIDRs",
+23
View File
@@ -50,6 +50,17 @@ export interface AllSetting {
subTitle: string;
subURI: string;
subUpdates: number;
tgBotAPIServer: string;
tgBotBackup: boolean;
tgBotChatId: string;
tgBotEnable: boolean;
tgBotProxy: string;
tgBotToken: string;
tgCpu: number;
tgEnabledEvents: string;
tgLang: string;
tgMemory: number;
tgRunTime: string;
timeLocation: string;
trafficDiff: number;
trustedProxyCIDRs: string;
@@ -67,6 +78,7 @@ export interface AllSettingView {
expireDiff: number;
hasApiToken: boolean;
hasNordSecret: boolean;
hasTgBotToken: boolean;
hasWarpSecret: boolean;
ipLimitAllowlist: string;
outboundDownThreshold: number;
@@ -106,6 +118,17 @@ export interface AllSettingView {
subTitle: string;
subURI: string;
subUpdates: number;
tgBotAPIServer: string;
tgBotBackup: boolean;
tgBotChatId: string;
tgBotEnable: boolean;
tgBotProxy: string;
tgBotToken: string;
tgCpu: number;
tgEnabledEvents: string;
tgLang: string;
tgMemory: number;
tgRunTime: string;
timeLocation: string;
trafficDiff: number;
trustedProxyCIDRs: string;
+23
View File
@@ -68,6 +68,17 @@ export const AllSettingSchema = z.object({
subTitle: z.string(),
subURI: z.string(),
subUpdates: z.number().int().min(0).max(525600),
tgBotAPIServer: z.string(),
tgBotBackup: z.boolean(),
tgBotChatId: z.string(),
tgBotEnable: z.boolean(),
tgBotProxy: z.string(),
tgBotToken: z.string(),
tgCpu: z.number().int().min(0).max(100),
tgEnabledEvents: z.string(),
tgLang: z.string(),
tgMemory: z.number().int().min(0).max(100),
tgRunTime: z.string(),
timeLocation: z.string(),
trafficDiff: z.number().int().min(0).max(100),
trustedProxyCIDRs: z.string(),
@@ -86,6 +97,7 @@ export const AllSettingViewSchema = z.object({
expireDiff: z.number().int().min(0),
hasApiToken: z.boolean(),
hasNordSecret: z.boolean(),
hasTgBotToken: z.boolean(),
hasWarpSecret: z.boolean(),
ipLimitAllowlist: z.string(),
outboundDownThreshold: z.number().int().min(1).max(100),
@@ -125,6 +137,17 @@ export const AllSettingViewSchema = z.object({
subTitle: z.string(),
subURI: z.string(),
subUpdates: z.number().int().min(0).max(525600),
tgBotAPIServer: z.string(),
tgBotBackup: z.boolean(),
tgBotChatId: z.string(),
tgBotEnable: z.boolean(),
tgBotProxy: z.string(),
tgBotToken: z.string(),
tgCpu: z.number().int().min(0).max(100),
tgEnabledEvents: z.string(),
tgLang: z.string(),
tgMemory: z.number().int().min(0).max(100),
tgRunTime: z.string(),
timeLocation: z.string(),
trafficDiff: z.number().int().min(0).max(100),
trustedProxyCIDRs: z.string(),
+6
View File
@@ -19,6 +19,7 @@ import {
ImportOutlined,
LogoutOutlined,
MenuOutlined,
MessageOutlined,
MoonFilled,
MoonOutlined,
PushpinFilled,
@@ -240,6 +241,11 @@ export default function AppSidebar() {
icon: <SafetyOutlined />,
label: t('pages.settings.securitySettings'),
},
{
key: '/settings#telegram',
icon: <MessageOutlined />,
label: t('pages.settings.TGBotSettings'),
},
{
key: '/settings#subscription',
icon: <CloudServerOutlined />,
@@ -0,0 +1,45 @@
import { Button, Input, Space } from 'antd';
import { useTranslation } from 'react-i18next';
interface SecretInputProps {
value: string;
configured: boolean;
clearArmed: boolean;
placeholder: string;
onChange: (value: string) => void;
onClearArmedChange: (armed: boolean) => void;
}
export default function SecretInput({
value,
configured,
clearArmed,
placeholder,
onChange,
onClearArmedChange,
}: SecretInputProps) {
const { t } = useTranslation();
return (
<Space.Compact style={{ width: '100%' }}>
<Input.Password
value={value}
placeholder={configured && !clearArmed ? placeholder : ''}
onChange={(e) => {
onChange(e.target.value);
if (clearArmed) onClearArmedChange(false);
}}
/>
{configured && (
<Button
danger={clearArmed}
onClick={() => {
onChange('');
onClearArmedChange(!clearArmed);
}}
>
{clearArmed ? t('pages.settings.secretClearUndo') : t('pages.settings.secretClear')}
</Button>
)}
</Space.Compact>
);
}
@@ -28,6 +28,7 @@ import SecurityTab from './SecurityTab';
import SubscriptionGeneralTab from './SubscriptionGeneralTab';
import SubscriptionFormatsTab from './SubscriptionFormatsTab';
import SubscriptionBalancersTab from './SubscriptionBalancersTab';
import TelegramTab from './TelegramTab';
import './SettingsPage.css';
interface ApiMsg {
@@ -37,6 +38,7 @@ interface ApiMsg {
const tabSlugs = [
'general',
'security',
'telegram',
'subscription',
'subscription-formats',
'subscription-balancers',
@@ -195,6 +197,8 @@ export default function SettingsPage() {
switch (activeSlug) {
case 'security':
return <SecurityTab />;
case 'telegram':
return <TelegramTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'subscription':
return <SubscriptionGeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'subscription-formats':
+337
View File
@@ -0,0 +1,337 @@
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Button, Input, InputNumber, Select, Space, Switch, Tabs } from 'antd';
import { BellOutlined, SendOutlined, SettingOutlined } from '@ant-design/icons';
import { LanguageManager } from '@/utils';
import { HttpUtil } from '@/utils';
import { onNumber } from '@/utils/onNumber';
import type { AllSetting } from '@/models/setting';
import { SettingListItem } from '@/components/ui';
import { TelegramNotifications } from '@/components/ui/notifications/TelegramNotifications';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel';
import SecretInput from './SecretInput';
interface TelegramTabProps {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
}
// The notification schedule is fed straight to robfig/cron's AddJob (see
// web.go startTask), which accepts @every <duration>, the @hourly/@daily/...
// macros, and full crontab expressions. This builder covers the common cases
// with dropdowns so users don't have to memorise the syntax, while "Custom"
// preserves the raw crontab escape hatch.
type Unit = 's' | 'm' | 'h';
type Macro = '@hourly' | '@daily' | '@weekly' | '@monthly';
type Mode = 'every' | Macro | 'custom';
const MACROS: Macro[] = ['@hourly', '@daily', '@weekly', '@monthly'];
const EVERY_RE = /^@every\s+(\d+)\s*([smh])$/i;
interface RunTime {
mode: Mode;
num: number;
unit: Unit;
custom: string;
}
function parseRunTime(raw: string): RunTime {
const v = (raw ?? '').trim();
const m = v.match(EVERY_RE);
if (m) {
return {
mode: 'every',
num: Math.max(1, Number(m[1]) || 1),
unit: m[2].toLowerCase() as Unit,
custom: '',
};
}
if ((MACROS as string[]).includes(v)) {
return { mode: v as Macro, num: 1, unit: 'h', custom: '' };
}
return { mode: 'custom', num: 1, unit: 'h', custom: v };
}
function composeRunTime(s: RunTime): string {
if (s.mode === 'every') return `@every ${Math.max(1, s.num || 1)}${s.unit}`;
if (s.mode === 'custom') return s.custom;
return s.mode;
}
// The panel's cron runs with seconds enabled (cron.WithSeconds() in web.go), so
// crontab expressions are 6-field: "second minute hour day month weekday". When
// the user drops into Custom we seed the box with the crontab equivalent of the
// current selection rather than a bare @macro, so they get a real expression to
// edit (and one that the 6-field parser accepts).
function toCrontab(s: RunTime): string {
switch (s.mode) {
case '@hourly':
return '0 0 * * * *';
case '@daily':
return '0 0 0 * * *';
case '@weekly':
return '0 0 0 * * 0';
case '@monthly':
return '0 0 0 1 * *';
case 'every': {
const n = Math.max(1, s.num || 1);
if (s.unit === 's') return `*/${n} * * * * *`;
if (s.unit === 'm') return `0 */${n} * * * *`;
return `0 0 */${n} * * *`;
}
default:
return s.custom;
}
}
function NotifyTimeField({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const { t } = useTranslation();
// Init once: the Settings tabs only mount after settings are fetched, so the
// incoming value is already the persisted one.
const [state, setState] = useState<RunTime>(() => parseRunTime(value));
function update(patch: Partial<RunTime>) {
const next = { ...state, ...patch };
setState(next);
onChange(composeRunTime(next));
}
function onModeChange(mode: Mode) {
// Seed Custom with the crontab equivalent of the current selection so the
// box starts from a real expression (e.g. "0 0 0 * * *", not "@daily").
if (mode === 'custom' && !state.custom.trim()) {
update({ mode, custom: toCrontab(state) });
} else {
update({ mode });
}
}
const modeOptions = [
{ value: 'every', label: t('pages.settings.notifyTime.every') },
{ value: '@hourly', label: t('pages.settings.notifyTime.hourly') },
{ value: '@daily', label: t('pages.settings.notifyTime.daily') },
{ value: '@weekly', label: t('pages.settings.notifyTime.weekly') },
{ value: '@monthly', label: t('pages.settings.notifyTime.monthly') },
{ value: 'custom', label: t('pages.settings.notifyTime.custom') },
];
const unitOptions = [
{ value: 's', label: t('pages.settings.notifyTime.seconds') },
{ value: 'm', label: t('pages.settings.notifyTime.minutes') },
{ value: 'h', label: t('pages.settings.notifyTime.hours') },
];
return (
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
<Select<Mode>
style={{ width: '100%' }}
value={state.mode}
options={modeOptions}
onChange={onModeChange}
aria-label={t('pages.settings.telegramNotifyTime')}
/>
{state.mode === 'every' && (
<Space.Compact style={{ width: '100%' }}>
<InputNumber
min={1}
precision={0}
style={{ width: '50%' }}
value={state.num}
onChange={onNumber((v) => update({ num: Math.max(1, v) }))}
aria-label={t('pages.settings.notifyTime.interval')}
/>
<Select<Unit>
style={{ width: '50%' }}
value={state.unit}
options={unitOptions}
onChange={(unit) => update({ unit })}
aria-label={t('pages.settings.notifyTime.unit')}
/>
</Space.Compact>
)}
{state.mode === 'custom' && (
<Input
value={state.custom}
placeholder="0 30 8 * * *"
onChange={(e) => update({ custom: e.target.value })}
aria-label={t('pages.settings.notifyTime.custom')}
/>
)}
</Space>
);
}
export default function TelegramTab({ allSetting, updateSetting }: TelegramTabProps) {
const { t } = useTranslation();
const { isMobile } = useMediaQuery();
const [testLoading, setTestLoading] = useState(false);
const [testResult, setTestResult] = useState<{ success: boolean; msg: string } | null>(null);
async function handleTestTgBot() {
setTestLoading(true);
setTestResult(null);
try {
const res = (await HttpUtil.post('/panel/api/setting/testTgBot')) as {
success?: boolean;
msg?: string;
};
setTestResult({ success: !!res.success, msg: res.msg || '' });
} catch (e: unknown) {
setTestResult({
success: false,
msg: e instanceof Error ? e.message : t('pages.settings.requestFailed'),
});
} finally {
setTestLoading(false);
}
}
const langOptions = useMemo(
() =>
LanguageManager.supportedLanguages.map(
(l: { value: string; name: string; icon: string }) => ({
value: l.value,
label: (
<>
<span role="img" aria-label={l.name}>
{l.icon}
</span>
&nbsp;&nbsp;<span>{l.name}</span>
</>
),
}),
),
[],
);
return (
<Tabs
defaultActiveKey="1"
items={[
{
key: '1',
label: catTabLabel(<SettingOutlined />, t('pages.settings.panelSettings'), isMobile),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.telegramBotEnable')}
description={t('pages.settings.telegramBotEnableDesc')}
>
<Switch
checked={allSetting.tgBotEnable}
onChange={(v) => updateSetting({ tgBotEnable: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.telegramToken')}
description={
allSetting.hasTgBotToken && !allSetting.clearTgBotToken
? t('pages.settings.telegramTokenConfigured')
: t('pages.settings.telegramTokenDesc')
}
>
<SecretInput
value={allSetting.tgBotToken}
configured={allSetting.hasTgBotToken}
clearArmed={allSetting.clearTgBotToken}
placeholder={t('pages.settings.telegramTokenPlaceholder')}
onChange={(v) => updateSetting({ tgBotToken: v })}
onClearArmedChange={(armed) => updateSetting({ clearTgBotToken: armed })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.telegramChatId')}
description={t('pages.settings.telegramChatIdDesc')}
>
<Input
value={allSetting.tgBotChatId}
onChange={(e) => updateSetting({ tgBotChatId: e.target.value })}
/>
</SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.telegramBotLanguage')}>
<Select
value={allSetting.tgLang}
onChange={(v) => updateSetting({ tgLang: v })}
style={{ width: '100%' }}
options={langOptions}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.telegramAPIServer')}
description={t('pages.settings.telegramAPIServerDesc')}
>
<Input
value={allSetting.tgBotAPIServer}
placeholder="https://api.example.com"
onChange={(e) => updateSetting({ tgBotAPIServer: e.target.value })}
/>
</SettingListItem>
<Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 16 }}>
<Button
type="primary"
icon={<SendOutlined />}
loading={testLoading}
onClick={handleTestTgBot}
>
{t('pages.settings.testTgBot')}
</Button>
{testResult && (
<Alert
type={testResult.success ? 'success' : 'error'}
title={testResult.msg}
showIcon
closable={{ onClose: () => setTestResult(null) }}
/>
)}
</Space>
</>
),
},
{
key: '2',
label: catTabLabel(<BellOutlined />, t('pages.settings.notifications'), isMobile),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.telegramNotifyTime')}
description={t('pages.settings.telegramNotifyTimeDesc')}
>
<NotifyTimeField
value={allSetting.tgRunTime}
onChange={(v) => updateSetting({ tgRunTime: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.tgNotifyBackup')}
description={t('pages.settings.tgNotifyBackupDesc')}
>
<Switch
checked={allSetting.tgBotBackup}
onChange={(v) => updateSetting({ tgBotBackup: v })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.tgEventBusNotify')}
description={t('pages.settings.tgEventBusNotifyDesc')}
>
<TelegramNotifications allSetting={allSetting} updateSetting={updateSetting} />
</SettingListItem>
</>
),
},
]}
/>
);
}