diff --git a/docs/content/docs/en/operations/meta.json b/docs/content/docs/en/operations/meta.json index a69d9d2ca..c3b7c348a 100644 --- a/docs/content/docs/en/operations/meta.json +++ b/docs/content/docs/en/operations/meta.json @@ -8,6 +8,7 @@ "backup-restore", "telegram-bot", "discord-bot", + "wechat-notifications", "security" ] } diff --git a/docs/content/docs/en/operations/wechat-notifications.mdx b/docs/content/docs/en/operations/wechat-notifications.mdx new file mode 100644 index 000000000..248aeef8c --- /dev/null +++ b/docs/content/docs/en/operations/wechat-notifications.mdx @@ -0,0 +1,62 @@ +--- +title: WeChat Notifications +description: Receive event alerts and scheduled reports through a WeCom group robot or a compatible WeChat webhook gateway. +icon: MessageCircle +--- + +WeChat is an independent, optional text-notification channel. It supports event alerts and scheduled status reports, with its own language, event selection, and CPU/memory thresholds. Existing notification channels retain their settings. WeChat notifications are disabled by default. + +WeCom mode sends to an enterprise group robot. Personal WeChat requires a separately deployed bridge that implements the custom gateway protocol and has its own working WeChat connection. The panel does not include that bridge or provide a direct personal WeChat bot login. + +## Setup + +1. Open **Panel Settings → WeChat** and enable notifications. +2. Choose a delivery mode: + - **WeCom group robot**: add a message-push robot to your enterprise WeChat group and paste its HTTPS webhook URL. See the [official configuration guide](https://developer.work.weixin.qq.com/document/path/99110). + - **Custom webhook gateway**: enter your HTTPS receiver URL and, optionally, a Bearer token that the receiver verifies. A compatible gateway delivers messages to personal WeChat. This uses the protocol below; an arbitrary third-party push URL or a WeChat contact name is not a receiver. +3. Select the notification language. It is independent of the Telegram bot language. +4. Under **Notifications**, choose events and thresholds. A metric threshold of `0` disables that metric's alerts. +5. Optionally enable scheduled reports and choose a cron schedule. `@daily` uses the panel scheduler's time zone. +6. **Save**, then click **Send test notification**. The test uses saved settings and is disabled while the channel is off or any settings have unsaved changes. + +URLs can contain robot credentials, so both the URL and token are redacted when settings are loaded. Leaving a secret blank retains its saved value; **Clear** followed by **Save** removes it. Disable the channel before clearing a required destination. Saving also updates report schedules and metric sampling without restarting the panel. + +![WeChat notification settings with a saved custom gateway and redacted credentials](/images/wechat-settings.png) + +## Alerts and reports + +Event keys are `login.attempt`, `cpu.high`, `memory.high`, `xray.crash`, `node.down`, `node.up`, `outbound.down`, and `outbound.up`. The initial selection is login attempts and high CPU usage. Login notifications include the attempted username, client IP, outcome, and available failure reason, but not the password. + +Repeated alerts for one event and source are limited to one successful send per minute. Failed and successful login outcomes have separate limits. A failed delivery does not consume the successful-send cooldown. + +Reports summarize the host, panel and Xray versions, CPU, memory, disk, uptime, and inbound/client counts, including disabled, expired, and depleted entries. Reports also run when Xray is stopped. This channel has no remote commands or file-backup feature, and does not include subscription links or client configuration files in reports. + +Traffic totals cover client statistics managed by this panel, deduplicated by client email. Used traffic is upload plus download. Remaining traffic sums each client's non-negative quota balance; when a runtime quota is unset, the client's configured quota is used. If there are no client statistics or any client has no configured quota, the remaining total reads **Quota not configured**. These values do not represent a VPS provider's billing allowance or traffic outside 3x-ui. + +## Custom gateway protocol, version 1 + +The panel sends an HTTPS `POST` with `Content-Type: application/json` and, when configured, `Authorization: Bearer `: + +```json +{ + "version": 1, + "id": "8f793626-a0e0-4a28-bddf-84c077a1bd21", + "type": "event", + "event": "cpu.high", + "hostname": "my-server", + "occurred_at": "2026-11-04T12:00:00Z", + "text": "3x-ui · my-server\nHigh CPU usage: 92.00%; threshold: 80%" +} +``` + +`type` is `event`, `report`, or `test`. For events, `event` is a selected event key; reports and tests use `report` and `test`. `occurred_at` preserves the event's occurrence time, falling back to send time only when no event time is available. `text` is plain UTF-8 text, at most 20,480 bytes. + +The receiver should verify authentication and version, durably enqueue with a uniqueness constraint on `id`, and return `2xx` after accepting responsibility for delivery. This acknowledges the gateway's receipt, not necessarily delivery to the final WeChat user. The receiver handles final delivery and further retries. + +Connection failures and `5xx` receive at most one retry with the **same ID and body**. Other rejected responses are not retried. Deduplicate by ID to handle lost acknowledgements. Each request has a 10-second timeout, responses are limited to 4 KiB, and redirects are refused. This contract has no dependency on a particular gateway service. + +## WeCom and network requirements + +WeCom mode requires the official `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...` endpoint and a successful `errcode: 0` response. Long text is split at UTF-8 boundaries into at most ten messages of 2,048 bytes, spaced at least 3.1 seconds apart. Requests are not automatically retried because the robot API has no ID-based deduplication for this channel. + +Both modes use direct outbound HTTPS with certificate verification, independent of the panel outbound proxy. Custom receivers must resolve to public addresses. Private, loopback, link-local, and metadata-service addresses are blocked again at connection time. Provide a public HTTPS receiver when the final WeChat adapter runs on a private network. diff --git a/docs/content/docs/en/reference/api/settings.mdx b/docs/content/docs/en/reference/api/settings.mdx index 525d19711..9a0c6f100 100644 --- a/docs/content/docs/en/reference/api/settings.mdx +++ b/docs/content/docs/en/reference/api/settings.mdx @@ -56,6 +56,11 @@ _openapi: title: Test Discord bot connection by sending a test embed to the configured channel. url: '#test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel' + - depth: 2 + title: Send a text test notification using the saved WeChat destination. + Supports WeCom group robots and compatible personal WeChat webhook + gateways. Requires WeChat notifications to be enabled. + url: '#send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled' - depth: 2 title: Return the built-in default Xray JSON config template that ships with this panel version. @@ -100,6 +105,10 @@ _openapi: - content: Test Discord bot connection by sending a test embed to the configured channel. id: test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel + - content: Send a text test notification using the saved WeChat destination. + Supports WeCom group robots and compatible personal WeChat webhook + gateways. Requires WeChat notifications to be enabled. + id: send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled - content: Return the built-in default Xray JSON config template that ships with this panel version. id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version @@ -113,7 +122,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/content/docs/zh/operations/meta.json b/docs/content/docs/zh/operations/meta.json index 56a2eb6f5..77c58b749 100644 --- a/docs/content/docs/zh/operations/meta.json +++ b/docs/content/docs/zh/operations/meta.json @@ -8,6 +8,7 @@ "backup-restore", "telegram-bot", "discord-bot", + "wechat-notifications", "security" ] } diff --git a/docs/content/docs/zh/operations/wechat-notifications.mdx b/docs/content/docs/zh/operations/wechat-notifications.mdx new file mode 100644 index 000000000..4e648c2e8 --- /dev/null +++ b/docs/content/docs/zh/operations/wechat-notifications.mdx @@ -0,0 +1,60 @@ +--- +title: 微信通知 +description: 通过企业微信群机器人或兼容的个人微信网关接收面板告警和定时状态报告。 +icon: MessageCircle +--- + +微信是独立、默认关闭的文字通知通道,可与 Telegram、Discord、邮件同时使用。它有自己的语言、事件选择、CPU 和内存阈值,以及独立的定时报告计划。 + +企业微信模式向企业微信群机器人发送消息。个人微信需要另外部署兼容下文协议的桥接服务,并由该服务维护可用的微信连接。面板不包含这个桥接服务,也不提供直接登录个人微信机器人的入口。 + +## 配置 + +1. 打开 **面板设置 → 微信**,启用通知。 +2. 选择发送方式。 + - **企业微信群机器人**:在企业微信群中添加消息推送机器人,填写其 HTTPS Webhook 地址。见[企业微信官方说明](https://developer.work.weixin.qq.com/document/path/99110)。 + - **自定义 Webhook 网关**:填写自己实现的兼容 HTTPS 接口,按需配置接收端校验的 Bearer Token,再由该服务向个人微信投递。接口必须实现下文协议,微信联系人或任意第三方推送 URL 不能直接作为接收端。 +3. 选择通知语言,该设置独立于 Telegram 机器人语言。 +4. 在 **通知** 中选择事件和指标阈值。阈值为 `0` 时关闭对应指标告警。 +5. 按需启用定时报告并设置计划。`@daily` 使用面板调度器的时区。 +6. 先 **保存**,再 **发送测试通知**。测试使用已保存的配置;通道关闭或存在未保存的设置修改时,测试按钮不可用。 + +地址可能包含机器人密钥,因此地址和 Token 均在返回浏览器时隐藏。留空保留原值,点击 **清空** 后保存才会删除。清除必填地址前应先关闭通知。保存后会更新报告计划和指标采样任务,无需重启面板。 + +![已保存自定义网关、隐藏凭据的微信通知设置页面](/images/wechat-settings.png) + +## 内容和频率 + +可选事件包括登录尝试、CPU 和内存超阈值、Xray 崩溃、节点离线与恢复、出站不可达与恢复。默认选择登录尝试和 CPU 告警。登录通知包含尝试的用户名、来源 IP、结果和可用的失败原因,不包含密码。 + +同类事件和来源每分钟最多成功发送一次;同一来源的登录失败和成功分别限频。发送失败不占用成功发送的冷却时间。 + +报告汇总主机、面板和 Xray 版本、CPU、内存、磁盘、运行时间,以及入站和客户端的总数、禁用、过期、流量耗尽数量。Xray 停止时仍能报告状态。此通道不提供远程命令或文件备份,报告不包含订阅链接和客户端配置文件。 + +流量只汇总本面板管理的客户端统计,按客户端邮箱去重。已用流量为上传与下载之和;剩余流量为每个客户端额度扣除已用量后的非负余额之和,运行统计中未设置额度时回退到客户端配置的额度。没有客户端统计,或任意客户端未配置额度时,剩余流量显示 **未配置额度**。这不是 VPS 服务商的计费额度,也不包含绕过 3x-ui 的流量。 + +## 自定义网关协议 + +HTTPS `POST`,`Content-Type: application/json`。配置 Token 时发送 `Authorization: Bearer `。 + +```json +{ + "version": 1, + "id": "8f793626-a0e0-4a28-bddf-84c077a1bd21", + "type": "event", + "event": "cpu.high", + "hostname": "my-server", + "occurred_at": "2026-11-04T12:00:00Z", + "text": "3x-ui · my-server\nCPU 使用率:92.00%;阈值:80%" +} +``` + +`type` 为 `event`、`report` 或 `test`。事件键为 `login.attempt`、`cpu.high`、`memory.high`、`xray.crash`、`node.down`、`node.up`、`outbound.down`、`outbound.up`;报告和测试分别使用 `report`、`test`。`occurred_at` 保留事件发生的 UTC 时间,缺失时才使用发送时间。正文最多 20,480 个 UTF-8 字节。 + +接收端应校验认证和版本,以 `id` 为唯一键可靠入队,再返回 `2xx`。这代表网关接受投递责任,最终微信消息的发送及重试由网关负责。 + +连接失败或 `5xx` 时,面板最多重试一次,沿用相同 ID 和正文;其他失败响应不重试。接收端应按 ID 去重,避免响应丢失造成重复消息。每次请求超时 10 秒,响应最多 4 KiB,不跟随重定向。协议不依赖特定的网关服务。 + +企业微信模式只接受官方机器人 HTTPS 地址,并要求响应 `errcode: 0`。长消息按 UTF-8 字节边界拆分,每段最多 2,048 字节、最多十段,发送间隔至少 3.1 秒。该接口不能按本通道的 ID 去重,因此不自动重试。 + +两种方式均直接通过 HTTPS 连接、校验证书,不继承面板出站代理。自定义地址必须指向公网,实际连接时再次阻止回环、私网、链路本地和元数据服务地址。微信适配器位于内网时,应提供公开的 HTTPS 接收网关。 diff --git a/docs/public/images/wechat-settings.png b/docs/public/images/wechat-settings.png new file mode 100644 index 000000000..dfdbb0878 Binary files /dev/null and b/docs/public/images/wechat-settings.png differ diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4fc2cdbf9..7218bb091 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -646,6 +646,40 @@ "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -837,7 +871,17 @@ "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, @@ -920,6 +964,12 @@ "hasWarpSecret": { "type": "boolean" }, + "hasWechatToken": { + "type": "boolean" + }, + "hasWechatWebhookURL": { + "type": "boolean" + }, "ipLimitAllowlist": { "type": "string" }, @@ -1485,6 +1535,40 @@ "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -1512,6 +1596,8 @@ "hasTgBotToken", "hasTwoFactorToken", "hasWarpSecret", + "hasWechatToken", + "hasWechatWebhookURL", "ipLimitAllowlist", "ldapAutoCreate", "ldapAutoDelete", @@ -1684,7 +1770,17 @@ "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, @@ -14414,6 +14510,36 @@ } } }, + "/panel/api/setting/testWechat": { + "post": { + "tags": [ + "Settings" + ], + "summary": "Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.", + "operationId": "post_panel_api_setting_testWechat", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/setting/getDefaultJsonConfig": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4fc2cdbf9..7218bb091 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -646,6 +646,40 @@ "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -837,7 +871,17 @@ "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, @@ -920,6 +964,12 @@ "hasWarpSecret": { "type": "boolean" }, + "hasWechatToken": { + "type": "boolean" + }, + "hasWechatWebhookURL": { + "type": "boolean" + }, "ipLimitAllowlist": { "type": "string" }, @@ -1485,6 +1535,40 @@ "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -1512,6 +1596,8 @@ "hasTgBotToken", "hasTwoFactorToken", "hasWarpSecret", + "hasWechatToken", + "hasWechatWebhookURL", "ipLimitAllowlist", "ldapAutoCreate", "ldapAutoDelete", @@ -1684,7 +1770,17 @@ "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, @@ -14414,6 +14510,36 @@ } } }, + "/panel/api/setting/testWechat": { + "post": { + "tags": [ + "Settings" + ], + "summary": "Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.", + "operationId": "post_panel_api_setting_testWechat", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": {} + } + } + } + } + } + } + } + }, "/panel/api/setting/getDefaultJsonConfig": { "get": { "tags": [ diff --git a/frontend/src/components/ui/notifications/WechatNotifications.stories.tsx b/frontend/src/components/ui/notifications/WechatNotifications.stories.tsx new file mode 100644 index 000000000..6fbb96352 --- /dev/null +++ b/frontend/src/components/ui/notifications/WechatNotifications.stories.tsx @@ -0,0 +1,96 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AllSetting } from '@/models/setting'; +import { WechatNotifications } from './WechatNotifications'; + +const meta = { + title: 'UI/Notifications/WechatNotifications', + component: WechatNotifications, + tags: ['autodocs'], + parameters: { + layout: 'padded', + docs: { + description: { + component: + 'Grid of grouped event checkboxes on the settings page that picks which panel events (outbound/node health, Xray crashes, CPU/RAM thresholds, login attempts) trigger a WeChat notification, stored as a comma-separated list in wechatEnabledEvents.', + }, + }, + }, + argTypes: { + allSetting: { + description: + 'Panel settings snapshot; wechatEnabledEvents holds the selected event keys and wechatCpu/wechatMemory the alert threshold percentages.', + }, + updateSetting: { + description: + 'Receives a partial settings patch when an event is toggled or a threshold input changes.', + }, + }, +} satisfies Meta; + +export default meta; + +type Story = StoryObj; + +function StatefulDemo({ initial }: { initial: AllSetting }) { + const [settings, setSettings] = useState(initial); + return ( + setSettings((prev) => new AllSetting({ ...prev, ...patch }))} + /> + ); +} + +const placeholderArgs = { + allSetting: new AllSetting(), + updateSetting: () => undefined, +}; + +export const NothingSelected: Story = { + args: placeholderArgs, + render: () => , +}; + +export const SystemThresholdAlerts: Story = { + args: placeholderArgs, + render: () => ( + + ), +}; + +export const InfrastructureOnly: Story = { + args: placeholderArgs, + render: () => ( + + ), +}; + +export const AllEventsEnabled: Story = { + args: placeholderArgs, + render: () => ( + + ), +}; diff --git a/frontend/src/components/ui/notifications/WechatNotifications.tsx b/frontend/src/components/ui/notifications/WechatNotifications.tsx new file mode 100644 index 000000000..b56dd957e --- /dev/null +++ b/frontend/src/components/ui/notifications/WechatNotifications.tsx @@ -0,0 +1,160 @@ +import { InputNumber } from 'antd'; +import { + CloudServerOutlined, + ThunderboltOutlined, + DesktopOutlined, + DashboardOutlined, + SafetyOutlined, +} from '@ant-design/icons'; +import type { AllSetting } from '@/models/setting'; +import { onNumber } from '@/utils/onNumber'; +import { NotificationLayout } from './NotificationLayout'; +import { NotificationGroup } from './NotificationGroup'; +import type { NotificationGroupConfig } from './types'; + +const GROUPS: NotificationGroupConfig[] = [ + { + icon: , + title: 'eventGroupOutbound', + events: [ + { + key: 'outbound.down', + label: 'eventOutboundDown', + settingKey: 'outboundDownThreshold', + hint: 'eventDownThresholdHint', + extra: ({ value, onChange, ariaLabel }) => ( + onChange(Math.round(next)))} + aria-label={ariaLabel} + style={{ width: 80 }} + /> + ), + }, + { key: 'outbound.up', label: 'eventOutboundUp', settingKey: '' }, + ], + }, + { + icon: , + title: 'eventGroupXray', + events: [{ key: 'xray.crash', label: 'eventXrayCrash', settingKey: '' }], + }, + { + icon: , + title: 'eventGroupNode', + events: [ + { + key: 'node.down', + label: 'eventNodeDown', + settingKey: 'nodeDownThreshold', + hint: 'eventDownThresholdHint', + extra: ({ value, onChange, ariaLabel }) => ( + onChange(Math.round(next)))} + aria-label={ariaLabel} + style={{ width: 80 }} + /> + ), + }, + { key: 'node.up', label: 'eventNodeUp', settingKey: '' }, + ], + }, + { + icon: , + title: 'eventGroupSystem', + events: [ + { + key: 'cpu.high', + label: 'eventCPUHigh', + settingKey: 'wechatCpu', + extra: ({ value, onChange, ariaLabel }) => ( + onChange(Math.round(next)))} + aria-label={ariaLabel} + style={{ width: 80 }} + /> + ), + }, + { + key: 'memory.high', + label: 'eventMemoryHigh', + settingKey: 'wechatMemory', + extra: ({ value, onChange, ariaLabel }) => ( + onChange(Math.round(next)))} + aria-label={ariaLabel} + style={{ width: 80 }} + /> + ), + }, + ], + }, + { + icon: , + title: 'eventGroupSecurity', + events: [{ key: 'login.attempt', label: 'eventLoginAttempt', settingKey: '' }], + }, +]; + +interface Props { + allSetting: AllSetting; + updateSetting: (patch: Partial) => void; +} + +export function WechatNotifications({ allSetting, updateSetting }: Props) { + const events = allSetting.wechatEnabledEvents || ''; + const selected = events + ? events + .split(',') + .map((s) => s.trim()) + .filter(Boolean) + : []; + + function toggle(key: string) { + const next = selected.includes(key) ? selected.filter((e) => e !== key) : [...selected, key]; + updateSetting({ wechatEnabledEvents: next.join(',') }); + } + + function toggleAll(keys: string[]) { + const allSelected = keys.every((v) => selected.includes(v)); + const next = allSelected + ? selected.filter((v) => !keys.includes(v)) + : [...new Set([...selected, ...keys])]; + updateSetting({ wechatEnabledEvents: next.join(',') }); + } + + return ( + + {GROUPS.map((group, i) => ( + + ))} + + ); +} diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index d166f94f8..39a5cca61 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -189,7 +189,17 @@ export const EXAMPLES: Record = { "webDomain": "", "webKeyFile": "", "webListen": "", - "webPort": 1 + "webPort": 1, + "wechatCpu": 0, + "wechatEnable": false, + "wechatEnabledEvents": "", + "wechatLang": "", + "wechatMemory": 0, + "wechatMode": "", + "wechatReportEnable": false, + "wechatRunTime": "", + "wechatToken": "", + "wechatWebhookURL": "" }, "AllSettingView": { "datepicker": "", @@ -216,6 +226,8 @@ export const EXAMPLES: Record = { "hasTgBotToken": false, "hasTwoFactorToken": false, "hasWarpSecret": false, + "hasWechatToken": false, + "hasWechatWebhookURL": false, "ipLimitAllowlist": "", "ldapAutoCreate": false, "ldapAutoDelete": false, @@ -388,7 +400,17 @@ export const EXAMPLES: Record = { "webDomain": "", "webKeyFile": "", "webListen": "", - "webPort": 1 + "webPort": 1, + "wechatCpu": 0, + "wechatEnable": false, + "wechatEnabledEvents": "", + "wechatLang": "", + "wechatMemory": 0, + "wechatMode": "", + "wechatReportEnable": false, + "wechatRunTime": "", + "wechatToken": "", + "wechatWebhookURL": "" }, "AmneziaWGLogs": { "events": [ diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 02c719ffa..9212e25f3 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -620,6 +620,40 @@ export const SCHEMAS: Record = { "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -811,7 +845,17 @@ export const SCHEMAS: Record = { "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, @@ -894,6 +938,12 @@ export const SCHEMAS: Record = { "hasWarpSecret": { "type": "boolean" }, + "hasWechatToken": { + "type": "boolean" + }, + "hasWechatWebhookURL": { + "type": "boolean" + }, "ipLimitAllowlist": { "type": "string" }, @@ -1459,6 +1509,40 @@ export const SCHEMAS: Record = { "maximum": 65535, "minimum": 1, "type": "integer" + }, + "wechatCpu": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatEnable": { + "type": "boolean" + }, + "wechatEnabledEvents": { + "type": "string" + }, + "wechatLang": { + "type": "string" + }, + "wechatMemory": { + "maximum": 100, + "minimum": 0, + "type": "integer" + }, + "wechatMode": { + "type": "string" + }, + "wechatReportEnable": { + "type": "boolean" + }, + "wechatRunTime": { + "type": "string" + }, + "wechatToken": { + "type": "string" + }, + "wechatWebhookURL": { + "type": "string" } }, "required": [ @@ -1486,6 +1570,8 @@ export const SCHEMAS: Record = { "hasTgBotToken", "hasTwoFactorToken", "hasWarpSecret", + "hasWechatToken", + "hasWechatWebhookURL", "ipLimitAllowlist", "ldapAutoCreate", "ldapAutoDelete", @@ -1658,7 +1744,17 @@ export const SCHEMAS: Record = { "webDomain", "webKeyFile", "webListen", - "webPort" + "webPort", + "wechatCpu", + "wechatEnable", + "wechatEnabledEvents", + "wechatLang", + "wechatMemory", + "wechatMode", + "wechatReportEnable", + "wechatRunTime", + "wechatToken", + "wechatWebhookURL" ], "type": "object" }, diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 2bcdae760..558c1dcb7 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -195,6 +195,16 @@ export interface AllSetting { webKeyFile: string; webListen: string; webPort: number; + wechatCpu: number; + wechatEnable: boolean; + wechatEnabledEvents: string; + wechatLang: string; + wechatMemory: number; + wechatMode: string; + wechatReportEnable: boolean; + wechatRunTime: string; + wechatToken: string; + wechatWebhookURL: string; } export interface AllSettingView { @@ -222,6 +232,8 @@ export interface AllSettingView { hasTgBotToken: boolean; hasTwoFactorToken: boolean; hasWarpSecret: boolean; + hasWechatToken: boolean; + hasWechatWebhookURL: boolean; ipLimitAllowlist: string; ldapAutoCreate: boolean; ldapAutoDelete: boolean; @@ -395,6 +407,16 @@ export interface AllSettingView { webKeyFile: string; webListen: string; webPort: number; + wechatCpu: number; + wechatEnable: boolean; + wechatEnabledEvents: string; + wechatLang: string; + wechatMemory: number; + wechatMode: string; + wechatReportEnable: boolean; + wechatRunTime: string; + wechatToken: string; + wechatWebhookURL: string; } export interface AmneziaWGLogs { diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 1d3f3bc3a..6b65791f1 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -205,6 +205,16 @@ export const AllSettingSchema = z.object({ webKeyFile: z.string(), webListen: z.string(), webPort: z.number().int().min(1).max(65535), + wechatCpu: z.number().int().min(0).max(100), + wechatEnable: z.boolean(), + wechatEnabledEvents: z.string(), + wechatLang: z.string(), + wechatMemory: z.number().int().min(0).max(100), + wechatMode: z.string(), + wechatReportEnable: z.boolean(), + wechatRunTime: z.string(), + wechatToken: z.string(), + wechatWebhookURL: z.string(), }); export type AllSetting = z.infer; @@ -233,6 +243,8 @@ export const AllSettingViewSchema = z.object({ hasTgBotToken: z.boolean(), hasTwoFactorToken: z.boolean(), hasWarpSecret: z.boolean(), + hasWechatToken: z.boolean(), + hasWechatWebhookURL: z.boolean(), ipLimitAllowlist: z.string(), ldapAutoCreate: z.boolean(), ldapAutoDelete: z.boolean(), @@ -406,6 +418,16 @@ export const AllSettingViewSchema = z.object({ webKeyFile: z.string(), webListen: z.string(), webPort: z.number().int().min(1).max(65535), + wechatCpu: z.number().int().min(0).max(100), + wechatEnable: z.boolean(), + wechatEnabledEvents: z.string(), + wechatLang: z.string(), + wechatMemory: z.number().int().min(0).max(100), + wechatMode: z.string(), + wechatReportEnable: z.boolean(), + wechatRunTime: z.string(), + wechatToken: z.string(), + wechatWebhookURL: z.string(), }); export type AllSettingView = z.infer; diff --git a/frontend/src/layouts/AppSidebar.tsx b/frontend/src/layouts/AppSidebar.tsx index d440cc30e..52aa347b9 100644 --- a/frontend/src/layouts/AppSidebar.tsx +++ b/frontend/src/layouts/AppSidebar.tsx @@ -28,6 +28,7 @@ import { SettingOutlined, SunOutlined, TelegramFilled, + WechatOutlined, } from '@ant-design/icons'; import { HttpUtil } from '@/utils'; @@ -237,6 +238,11 @@ export default function AppSidebar() { icon: , label: t('pages.settings.discordSettings'), }, + { + key: '/settings#wechat', + icon: , + label: t('pages.settings.wechatSettings'), + }, { key: '/settings#subscription', icon: , diff --git a/frontend/src/models/setting.ts b/frontend/src/models/setting.ts index 5098e3ed0..2dbaa4611 100644 --- a/frontend/src/models/setting.ts +++ b/frontend/src/models/setting.ts @@ -1,5 +1,10 @@ import { ObjectUtil } from '@/utils'; -import type { SubProfileMode, SubHostSortMode, NetworkTrafficMode } from '@/schemas/setting'; +import type { + SubProfileMode, + SubHostSortMode, + NetworkTrafficMode, + WechatMode, +} from '@/schemas/setting'; export class AllSetting { webListen = ''; @@ -207,6 +212,20 @@ export class AllSetting { discordEnabledEvents = 'login.attempt,cpu.high'; hasDiscordBotToken = false; clearDiscordBotToken = false; + wechatEnable = false; + wechatMode: WechatMode = 'wecom'; + wechatWebhookURL = ''; + hasWechatWebhookURL = false; + clearWechatWebhookURL = false; + wechatToken = ''; + hasWechatToken = false; + clearWechatToken = false; + wechatLang = 'en-US'; + wechatReportEnable = false; + wechatRunTime = '@daily'; + wechatEnabledEvents = 'login.attempt,cpu.high'; + wechatCpu = 80; + wechatMemory = 80; constructor(data?: unknown) { if (data != null) { diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8079c537b..ce092af6b 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -2161,6 +2161,12 @@ export const sections: readonly Section[] = [ summary: 'Test Discord bot connection by sending a test embed to the configured channel.', response: '{\n "success": true,\n "msg": "Test notification sent successfully"\n}', }, + { + method: 'POST', + path: '/panel/api/setting/testWechat', + summary: + 'Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.', + }, { method: 'GET', path: '/panel/api/setting/getDefaultJsonConfig', diff --git a/frontend/src/pages/settings/SettingsPage.tsx b/frontend/src/pages/settings/SettingsPage.tsx index bba170c3a..7f42169c0 100644 --- a/frontend/src/pages/settings/SettingsPage.tsx +++ b/frontend/src/pages/settings/SettingsPage.tsx @@ -28,6 +28,7 @@ import SecurityTab from './SecurityTab'; import TelegramTab from './TelegramTab'; import EmailTab from './EmailTab'; import DiscordTab from './DiscordTab'; +import WechatTab from './WechatTab'; import SubscriptionGeneralTab from './SubscriptionGeneralTab'; import SubscriptionFormatsTab from './SubscriptionFormatsTab'; import SubscriptionBalancersTab from './SubscriptionBalancersTab'; @@ -43,6 +44,7 @@ const tabSlugs = [ 'telegram', 'email', 'discord', + 'wechat', 'subscription', 'subscription-formats', 'subscription-balancers', @@ -221,6 +223,14 @@ export default function SettingsPage() { return ; case 'discord': return ; + case 'wechat': + return ( + + ); case 'subscription': return ; case 'subscription-formats': @@ -230,7 +240,7 @@ export default function SettingsPage() { default: return ; } - }, [activeSlug, allSetting, updateSetting, savePayload]); + }, [activeSlug, allSetting, updateSetting, savePayload, saveDisabled]); return ( diff --git a/frontend/src/pages/settings/WechatTab.stories.tsx b/frontend/src/pages/settings/WechatTab.stories.tsx new file mode 100644 index 000000000..14d08ed96 --- /dev/null +++ b/frontend/src/pages/settings/WechatTab.stories.tsx @@ -0,0 +1,62 @@ +import { useState } from 'react'; +import type { Meta, StoryObj } from '@storybook/react-vite'; + +import { AllSetting } from '@/models/setting'; +import WechatTab from './WechatTab'; + +const meta = { + title: 'Pages/Settings/WechatTab', + component: WechatTab, + tags: ['autodocs'], + parameters: { layout: 'padded' }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +function SettingsPreview({ initial }: { initial: AllSetting }) { + const [setting, setSetting] = useState(initial); + return ( + setSetting((current) => new AllSetting({ ...current, ...patch }))} + /> + ); +} + +const placeholderArgs = { allSetting: new AllSetting(), updateSetting: () => undefined }; + +export const WecomRobot: Story = { + args: placeholderArgs, + render: () => , +}; + +export const SavedCustomGateway: Story = { + args: placeholderArgs, + render: () => ( + + ), +}; + +export const UnsavedChanges: Story = { + args: { + allSetting: new AllSetting({ + wechatEnable: true, + wechatMode: 'webhook', + wechatWebhookURL: 'https://receiver.example/notify', + }), + updateSetting: () => undefined, + hasPendingChanges: true, + }, +}; diff --git a/frontend/src/pages/settings/WechatTab.tsx b/frontend/src/pages/settings/WechatTab.tsx new file mode 100644 index 000000000..e1a52db48 --- /dev/null +++ b/frontend/src/pages/settings/WechatTab.tsx @@ -0,0 +1,235 @@ +import { useMemo, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + Alert, + Button, + ConfigProvider, + Select, + Space, + Switch, + Tabs, + Typography, + theme, +} from 'antd'; +import { BellOutlined, SendOutlined, SettingOutlined } from '@ant-design/icons'; +import { HttpUtil, LanguageManager } from '@/utils'; +import type { AllSetting } from '@/models/setting'; +import type { WechatMode } from '@/schemas/setting'; +import { SettingListItem } from '@/components/ui'; +import { WechatNotifications } from '@/components/ui/notifications/WechatNotifications'; +import { useMediaQuery } from '@/hooks/useMediaQuery'; +import { catTabLabel } from './catTabLabel'; +import { NotifyTimeField } from './NotifyTimeField'; +import SecretInput from './SecretInput'; + +interface WechatTabProps { + allSetting: AllSetting; + updateSetting: (patch: Partial) => void; + hasPendingChanges?: boolean; +} + +export default function WechatTab({ + allSetting, + updateSetting, + hasPendingChanges = false, +}: WechatTabProps) { + const { t } = useTranslation(); + const { token } = theme.useToken(); + const { isMobile } = useMediaQuery(); + const [testing, setTesting] = useState(false); + const [testResult, setTestResult] = useState<{ success: boolean; msg: string } | null>(null); + const languageOptions = useMemo( + () => + LanguageManager.supportedLanguages.map((lang) => ({ + value: lang.value, + label: `${lang.icon} ${lang.name}`, + })), + [], + ); + + async function testWechat() { + setTesting(true); + setTestResult(null); + try { + const result = await HttpUtil.post('/panel/api/setting/testWechat', undefined, { + silent: true, + }); + setTestResult({ + success: !!result.success, + msg: + result.msg || + t(result.success ? 'pages.settings.wechatTestSuccess' : 'pages.settings.requestFailed'), + }); + } catch (error: unknown) { + setTestResult({ + success: false, + msg: error instanceof Error ? error.message : t('pages.settings.requestFailed'), + }); + } finally { + setTesting(false); + } + } + + return ( + + , + t('pages.settings.panelSettings'), + isMobile, + ), + children: ( + <> + + updateSetting({ wechatEnable: value })} + /> + + + + value={allSetting.wechatMode} + onChange={(value) => updateSetting({ wechatMode: value })} + style={{ width: '100%' }} + options={[ + { value: 'wecom', label: t('pages.settings.wechatModeWecom') }, + { value: 'webhook', label: t('pages.settings.wechatModeWebhook') }, + ]} + /> + + + + updateSetting({ wechatWebhookURL: value })} + onClearArmedChange={(value) => updateSetting({ clearWechatWebhookURL: value })} + /> + + {allSetting.wechatMode === 'webhook' && ( + + updateSetting({ wechatToken: value })} + onClearArmedChange={(value) => updateSetting({ clearWechatToken: value })} + /> + + )} + +