From e2c80869e968c4df0fe31cbfdeed4755e863d3fa Mon Sep 17 00:00:00 2001 From: Todos Date: Tue, 20 Oct 2026 17:49:45 +0800 Subject: [PATCH 1/2] chore: checkpoint VhWxu4F-DfsE_sVjXnVTN --- CLAUDE.md | 2 +- README.en.md | 2 +- README.md | 2 +- web/src/lib/channels.ts | 4 +- web/src/locales/en.json | 4 +- web/src/locales/zh.json | 4 +- web/src/pages/channels/ChannelPage.tsx | 37 ++-- worker/src/db/queries/notifications.ts | 4 +- worker/src/db/schema.sql | 4 +- worker/src/lib/setup.ts | 39 ++++- worker/src/routes/me.ts | 2 + worker/src/services/notify/discord.ts | 66 +++++++ worker/src/services/notify/feishu.ts | 114 ++++++++++++ worker/src/services/notify/gotify.ts | 47 ----- worker/src/services/notify/index.ts | 8 +- worker/src/services/notify/notifyx.ts | 37 ---- worker/src/types.ts | 8 +- worker/test/discord.test.ts | 188 ++++++++++++++++++++ worker/test/feishu.test.ts | 230 +++++++++++++++++++++++++ worker/test/migrations.test.ts | 71 +++++++- 20 files changed, 744 insertions(+), 129 deletions(-) create mode 100644 worker/src/services/notify/discord.ts create mode 100644 worker/src/services/notify/feishu.ts delete mode 100644 worker/src/services/notify/gotify.ts delete mode 100644 worker/src/services/notify/notifyx.ts create mode 100644 worker/test/discord.test.ts create mode 100644 worker/test/feishu.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9148f49..b85d26b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -67,7 +67,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `lunar.ts` — Chinese lunar calendar support (1900–2100) - `currency.ts` — multi-currency / exchange rate conversion -**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Gotify, NotifyX, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter. +**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` fans out to all enabled channels, with optional per-item channel filtering via the `channels` parameter. **Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it: diff --git a/README.en.md b/README.en.md index 44d29b8..972c63d 100644 --- a/README.en.md +++ b/README.en.md @@ -11,7 +11,7 @@ A smart notification management system that helps you track expiry dates and exp - **Auto-renewal** — Expired subscriptions are automatically renewed with payment history recorded - **Payment History** — Record every payment, multi-currency with real-time exchange rates - **Dashboard** — Monthly/yearly expense stats, expiry alerts, category analysis -- **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, NotifyX, Slack +- **8 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Slack, Feishu, Discord - **Channel Management** — Dedicated page to enable and configure notification channels - **Per-Item Channel Selection** — Each notification item can specify which channels to use; defaults to all enabled channels if unset - **Scheduled Reminders** — Hourly auto-check with global notification hours and per-item override diff --git a/README.md b/README.md index 102b368..19c02bd 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ - **自动续费** — 过期订阅自动续期并记录支付历史 - **支付历史** — 记录每笔支付,支持多币种与实时汇率转换 - **仪表盘** — 月度/年度支出统计、到期预警、分类分析 -- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、NotifyX、Slack +- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Slack、飞书、Discord - **渠道管理** — 独立页面统一管理通知渠道的启用与配置 - **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道 - **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖 diff --git a/web/src/lib/channels.ts b/web/src/lib/channels.ts index 6ff3087..7843f41 100644 --- a/web/src/lib/channels.ts +++ b/web/src/lib/channels.ts @@ -4,7 +4,7 @@ export const CHANNELS = [ { id: "wechatbot", label: "WeCom Bot" }, { id: "email", label: "Email" }, { id: "bark", label: "Bark" }, - { id: "gotify", label: "Gotify" }, - { id: "notifyx", label: "NotifyX" }, { id: "slack", label: "Slack" }, + { id: "feishu", label: "Feishu" }, + { id: "discord", label: "Discord" }, ] as const; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index aed88bf..959c75c 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -344,9 +344,9 @@ "wechatbot": "WeCom Bot", "email": "Email", "bark": "Bark", - "gotify": "Gotify", - "notifyx": "NotifyX", "slack": "Slack", + "feishu": "Feishu Bot", + "discord": "Discord", "botToken": "Bot Token", "chatId": "Chat ID", "url": "URL", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index f0bda25..4f43858 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -344,9 +344,9 @@ "wechatbot": "企业微信机器人", "email": "邮件", "bark": "Bark", - "gotify": "Gotify", - "notifyx": "NotifyX", "slack": "Slack", + "feishu": "飞书群机器人", + "discord": "Discord", "botToken": "机器人令牌", "chatId": "聊天ID", "url": "URL", diff --git a/web/src/pages/channels/ChannelPage.tsx b/web/src/pages/channels/ChannelPage.tsx index 577989a..45ef214 100644 --- a/web/src/pages/channels/ChannelPage.tsx +++ b/web/src/pages/channels/ChannelPage.tsx @@ -107,32 +107,43 @@ const CHANNELS: ChannelDef[] = [ ], }, { - id: "gotify", - label: "Gotify", + id: "slack", + label: "Slack", fields: [ { - key: "server_url", - label: "Server URL", - type: "text", - placeholder: "https://", + key: "webhook_url", + label: "Webhook URL", + type: "password", + placeholder: "https://hooks.slack.com/services/...", }, - { key: "app_token", label: "App Token", type: "password" }, ], }, { - id: "notifyx", - label: "NotifyX", - fields: [{ key: "api_key", label: "API Key", type: "password" }], + id: "feishu", + label: "Feishu", + fields: [ + { + key: "webhook_url", + label: "Webhook URL", + type: "password", + placeholder: "https://open.feishu.cn/open-apis/bot/v2/hook/...", + }, + { + key: "secret", + label: "Sign Secret (optional)", + type: "password", + }, + ], }, { - id: "slack", - label: "Slack", + id: "discord", + label: "Discord", fields: [ { key: "webhook_url", label: "Webhook URL", type: "password", - placeholder: "https://hooks.slack.com/services/...", + placeholder: "https://discord.com/api/webhooks/...", }, ], }, diff --git a/worker/src/db/queries/notifications.ts b/worker/src/db/queries/notifications.ts index 4d2ced7..3cc2cea 100644 --- a/worker/src/db/queries/notifications.ts +++ b/worker/src/db/queries/notifications.ts @@ -35,9 +35,9 @@ export async function upsertNotificationConfig( "wechatbot_config", "email_config", "bark_config", - "gotify_config", - "notifyx_config", "slack_config", + "feishu_config", + "discord_config", "notification_hours", ]; diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index da03079..08956f8 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -84,9 +84,9 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( wechatbot_config TEXT NOT NULL DEFAULT '{}', email_config TEXT NOT NULL DEFAULT '{}', bark_config TEXT NOT NULL DEFAULT '{}', - gotify_config TEXT NOT NULL DEFAULT '{}', - notifyx_config TEXT NOT NULL DEFAULT '{}', slack_config TEXT NOT NULL DEFAULT '{}', + feishu_config TEXT NOT NULL DEFAULT '{}', + discord_config TEXT NOT NULL DEFAULT '{}', notification_hours TEXT NOT NULL DEFAULT '[]', updated_at TEXT NOT NULL ); diff --git a/worker/src/lib/setup.ts b/worker/src/lib/setup.ts index e25cace..f16e127 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -16,6 +16,11 @@ const DEFAULT_SETTINGS: Record = { app_name: "eNotify", }; +// Channel IDs whose sender code has been removed. Their DB columns are kept +// (dropping them would require rebuilding the table) but any stale ID left in +// enabled_channels is stripped so it cannot fail every push. +const RETIRED_CHANNELS = ["serverchan", "pushplus", "gotify", "notifyx"]; + async function runMigrations(db: D1Database, prefix: string): Promise { // Migration: add body column to notification_history try { @@ -49,10 +54,28 @@ async function runMigrations(db: D1Database, prefix: string): Promise { console.error("Migration failed for notification_configs table:", err); } - // Migration: drop retired channels (serverchan/pushplus) from enabled_channels. - // Their sender code is gone, so a stale ID would make every push fail with - // "Unknown channel" and write a notification_history row. Idempotent: the - // second run finds nothing to strip and performs no UPDATE. + // Migration: add feishu_config / discord_config columns to notification_configs + try { + const notifCols = await db + .prepare(`PRAGMA table_info(${prefix}notification_configs)`) + .all<{ name: string }>(); + for (const column of ["feishu_config", "discord_config"]) { + if (!notifCols.results.some((c) => c.name === column)) { + await db + .prepare( + `ALTER TABLE ${prefix}notification_configs ADD COLUMN ${column} TEXT NOT NULL DEFAULT '{}'`, + ) + .run(); + } + } + } catch (err) { + console.error("Migration failed for notification_configs table:", err); + } + + // Migration: drop retired channels (serverchan/pushplus/gotify/notifyx) from + // enabled_channels. Their sender code is gone, so a stale ID would make every + // push fail with "Unknown channel" and write a notification_history row. + // Idempotent: the second run finds nothing to strip and performs no UPDATE. try { const rows = await db .prepare( @@ -67,9 +90,7 @@ async function runMigrations(db: D1Database, prefix: string): Promise { continue; } if (!Array.isArray(channels)) continue; - const filtered = channels.filter( - (ch) => ch !== "serverchan" && ch !== "pushplus", - ); + const filtered = channels.filter((ch) => !RETIRED_CHANNELS.includes(ch)); if (filtered.length === channels.length) continue; await db .prepare( @@ -246,9 +267,9 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( wechatbot_config TEXT NOT NULL DEFAULT '{}', email_config TEXT NOT NULL DEFAULT '{}', bark_config TEXT NOT NULL DEFAULT '{}', - gotify_config TEXT NOT NULL DEFAULT '{}', - notifyx_config TEXT NOT NULL DEFAULT '{}', slack_config TEXT NOT NULL DEFAULT '{}', + feishu_config TEXT NOT NULL DEFAULT '{}', + discord_config TEXT NOT NULL DEFAULT '{}', notification_hours TEXT NOT NULL DEFAULT '[]', updated_at TEXT NOT NULL ); diff --git a/worker/src/routes/me.ts b/worker/src/routes/me.ts index b734fb9..ca42bae 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -293,6 +293,7 @@ meRoutes.get("/notifications", async (c) => { "device_key", "headers", "webhook_url", + "secret", ].some((s) => k.includes(s)) ) { redacted[k] = v ? "••••••" : ""; @@ -359,6 +360,7 @@ meRoutes.put("/notifications", async (c) => { "device_key", "headers", "webhook_url", + "secret", ]; for (const [k, v] of Object.entries(newConfig)) { if (secretFields.some((s) => k.includes(s)) && (!v || v === "••••••")) { diff --git a/worker/src/services/notify/discord.ts b/worker/src/services/notify/discord.ts new file mode 100644 index 0000000..323fcf0 --- /dev/null +++ b/worker/src/services/notify/discord.ts @@ -0,0 +1,66 @@ +import type { Env } from "../../types"; +import type { NotifyMessage } from "./index"; +import { safeErrorText, validateOutboundUrl } from "./safe-fetch"; + +interface DiscordConfig { + webhook_url: string; +} + +const DISCORD_HOSTS = new Set(["discord.com", "discordapp.com"]); +const DISCORD_WEBHOOK_PATH = "/api/webhooks/"; +const DISCORD_CONTENT_LIMIT = 2000; + +export async function sendDiscord( + configJson: string, + message: NotifyMessage, + _env: Env, +): Promise<{ success: boolean; error?: string }> { + const config: DiscordConfig = JSON.parse(configJson); + if (!config.webhook_url) { + return { success: false, error: "Discord webhook URL required" }; + } + + const check = validateOutboundUrl(config.webhook_url); + if (check.error || !check.url) { + return { + success: false, + error: `Discord: ${check.error ?? "Invalid URL"}`, + }; + } + if (!DISCORD_HOSTS.has(check.url.hostname)) { + return { + success: false, + error: "Discord: webhook URL must be on discord.com or discordapp.com", + }; + } + if (!check.url.pathname.startsWith(DISCORD_WEBHOOK_PATH)) { + return { + success: false, + error: `Discord: webhook URL path must start with ${DISCORD_WEBHOOK_PATH}`, + }; + } + + const lines = [`**${message.title}**`, message.body]; + if (message.url) lines.push(message.url); + // Discord caps `content` at 2000 characters. Slice by code point so + // multi-byte characters and surrogate pairs are never split in half. + const content = Array.from(lines.join("\n")) + .slice(0, DISCORD_CONTENT_LIMIT) + .join(""); + + const response = await fetch(config.webhook_url, { + method: "POST", + redirect: "manual", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ content }), + }); + + if (response.status !== 200 && response.status !== 204) { + const err = await safeErrorText(response); + return { + success: false, + error: `Discord error (${response.status}): ${err}`, + }; + } + return { success: true }; +} diff --git a/worker/src/services/notify/feishu.ts b/worker/src/services/notify/feishu.ts new file mode 100644 index 0000000..7bb5027 --- /dev/null +++ b/worker/src/services/notify/feishu.ts @@ -0,0 +1,114 @@ +import type { Env } from "../../types"; +import type { NotifyMessage } from "./index"; +import { safeErrorText, validateOutboundUrl } from "./safe-fetch"; + +interface FeishuConfig { + webhook_url: string; + secret?: string; +} + +const FEISHU_HOSTS = new Set(["open.feishu.cn", "open.larksuite.com"]); +const FEISHU_HOOK_PATH = "/open-apis/bot/v2/hook/"; + +function toBase64(buffer: ArrayBuffer): string { + const bytes = new Uint8Array(buffer); + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary); +} + +/** + * Feishu/Lark custom bot signature: HMAC-SHA256 whose *key* is + * `${timestamp}\n${secret}` and whose message is the empty string, Base64 + * encoded. (See the official "custom bot security settings" docs.) + */ +export async function signFeishu( + timestamp: number | string, + secret: string, +): Promise { + const encoder = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(`${timestamp}\n${secret}`), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = await crypto.subtle.sign("HMAC", key, encoder.encode("")); + return toBase64(signature); +} + +export async function sendFeishu( + configJson: string, + message: NotifyMessage, + _env: Env, +): Promise<{ success: boolean; error?: string }> { + const config: FeishuConfig = JSON.parse(configJson); + if (!config.webhook_url) { + return { success: false, error: "Feishu webhook URL required" }; + } + + const check = validateOutboundUrl(config.webhook_url); + if (check.error || !check.url) { + return { success: false, error: `Feishu: ${check.error ?? "Invalid URL"}` }; + } + if (!FEISHU_HOSTS.has(check.url.hostname)) { + return { + success: false, + error: + "Feishu: webhook URL must be on open.feishu.cn or open.larksuite.com", + }; + } + if (!check.url.pathname.startsWith(FEISHU_HOOK_PATH)) { + return { + success: false, + error: `Feishu: webhook URL path must start with ${FEISHU_HOOK_PATH}`, + }; + } + + const lines = [message.title, message.body]; + if (message.url) lines.push(message.url); + const text = lines.join("\n"); + + const payload: Record = { + msg_type: "text", + content: { text }, + }; + if (config.secret) { + const timestamp = Math.floor(Date.now() / 1000); + payload.timestamp = String(timestamp); + payload.sign = await signFeishu(timestamp, config.secret); + } + + const response = await fetch(config.webhook_url, { + method: "POST", + redirect: "manual", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + + if (!response.ok) { + const err = await safeErrorText(response); + return { + success: false, + error: `Feishu error (${response.status}): ${err}`, + }; + } + + // The bot API answers HTTP 200 even when the business call fails; `code` + // distinguishes the two, so the body has to be inspected. + let data: { code?: number; msg?: string }; + try { + data = await response.json(); + } catch { + return { success: false, error: "Feishu error: invalid response body" }; + } + if (data.code !== undefined && data.code !== 0) { + const msg = String(data.msg ?? "").slice(0, 200); + return { + success: false, + error: `Feishu error (code ${data.code}): ${msg}`, + }; + } + return { success: true }; +} diff --git a/worker/src/services/notify/gotify.ts b/worker/src/services/notify/gotify.ts deleted file mode 100644 index a280520..0000000 --- a/worker/src/services/notify/gotify.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { NotifyMessage } from "./index"; -import type { Env } from "../../types"; -import { validateOutboundUrl, safeErrorText } from "./safe-fetch"; - -interface GotifyConfig { - server_url: string; - app_token: string; -} - -export async function sendGotify( - configJson: string, - message: NotifyMessage, - _env: Env, -): Promise<{ success: boolean; error?: string }> { - const config: GotifyConfig = JSON.parse(configJson); - if (!config.server_url || !config.app_token) { - return { - success: false, - error: "Gotify server URL and app token required", - }; - } - - const check = validateOutboundUrl(config.server_url, { allowPrivate: true }); - if (check.error) { - return { success: false, error: `Gotify: ${check.error}` }; - } - - const url = `${config.server_url.replace(/\/$/, "")}/message?token=${config.app_token}`; - - const response = await fetch(url, { - redirect: "manual", - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - title: message.title, - message: message.body, - extras: { "client::notification": { click: { url: message.url } } }, - }), - }); - - if (!response.ok) { - const err = await safeErrorText(response); - return { success: false, error: `Gotify error: ${err}` }; - } - - return { success: true }; -} diff --git a/worker/src/services/notify/index.ts b/worker/src/services/notify/index.ts index 3faac89..8061665 100644 --- a/worker/src/services/notify/index.ts +++ b/worker/src/services/notify/index.ts @@ -3,9 +3,9 @@ import { sendTelegram } from "./telegram"; import { sendWebhook } from "./webhook"; import { sendWechatBot } from "./wechatbot"; import { sendBark } from "./bark"; -import { sendGotify } from "./gotify"; -import { sendNotifyX } from "./notifyx"; import { sendSlack } from "./slack"; +import { sendFeishu } from "./feishu"; +import { sendDiscord } from "./discord"; import { sendNotifyEmail } from "./email-notify"; import type { Env } from "../../types"; import { insertNotificationHistory } from "../../db/queries/notification-history"; @@ -43,9 +43,9 @@ const CHANNEL_SENDERS: Record< wechatbot: sendWechatBot, email: sendNotifyEmail, bark: sendBark, - gotify: sendGotify, - notifyx: sendNotifyX, slack: sendSlack, + feishu: sendFeishu, + discord: sendDiscord, }; const SEND_TIMEOUT_MS = 15000; diff --git a/worker/src/services/notify/notifyx.ts b/worker/src/services/notify/notifyx.ts deleted file mode 100644 index 186b569..0000000 --- a/worker/src/services/notify/notifyx.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { NotifyMessage } from "./index"; -import type { Env } from "../../types"; - -interface NotifyXConfig { - api_key: string; -} - -export async function sendNotifyX( - configJson: string, - message: NotifyMessage, - _env: Env, -): Promise<{ success: boolean; error?: string }> { - const config: NotifyXConfig = JSON.parse(configJson); - if (!config.api_key) { - return { success: false, error: "NotifyX API key required" }; - } - - const response = await fetch("https://notifyx.imshan.com/api/notification", { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-API-Key": config.api_key, - }, - body: JSON.stringify({ - title: message.title, - body: message.body, - url: message.url, - }), - }); - - if (!response.ok) { - const err = await response.text(); - return { success: false, error: `NotifyX error: ${err}` }; - } - - return { success: true }; -} diff --git a/worker/src/types.ts b/worker/src/types.ts index b199e16..cd08e50 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -82,9 +82,9 @@ export interface NotificationConfig { wechatbot_config: string; email_config: string; bark_config: string; - gotify_config: string; - notifyx_config: string; slack_config: string; + feishu_config: string; + discord_config: string; notification_hours: string; updated_at: string; } @@ -128,7 +128,7 @@ export const VALID_CHANNELS: string[] = [ "wechatbot", "email", "bark", - "gotify", - "notifyx", "slack", + "feishu", + "discord", ]; diff --git a/worker/test/discord.test.ts b/worker/test/discord.test.ts new file mode 100644 index 0000000..c909d71 --- /dev/null +++ b/worker/test/discord.test.ts @@ -0,0 +1,188 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { sendDiscord } from "../src/services/notify/discord"; +import type { Env } from "../src/types"; + +const WEBHOOK_URL = + "https://discord.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"; +const LEGACY_WEBHOOK_URL = + "https://discordapp.com/api/webhooks/1234567890/abcdefghijklmnopqrstuvwxyz"; + +function makeEnv(): Env { + return {} as Env; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("sendDiscord", () => { + it("posts a bold title, body and url and succeeds on HTTP 204", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { + title: "Renewal due", + body: "Your plan expires soon.", + url: "https://enotify.example.com/items/1", + }, + makeEnv(), + ); + + expect(result).toEqual({ success: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const [url, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + expect(url).toBe(WEBHOOK_URL); + expect(init.method).toBe("POST"); + expect(init.redirect).toBe("manual"); + expect(init.headers).toEqual({ "Content-Type": "application/json" }); + expect(JSON.parse(String(init.body))).toEqual({ + content: + "**Renewal due**\nYour plan expires soon.\nhttps://enotify.example.com/items/1", + }); + }); + + it("omits the url line when message.url is empty and accepts HTTP 200", async () => { + const fetchMock = vi.fn(async () => new Response("", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result).toEqual({ success: true }); + const [, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + expect(JSON.parse(String(init.body)).content).toBe("**Title**\nBody"); + }); + + it("accepts the legacy discordapp.com domain", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: LEGACY_WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result).toEqual({ success: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("rejects other hosts without fetching", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ + webhook_url: "https://example.com/api/webhooks/1/abc", + }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("discord.com"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a Discord URL with the wrong path without fetching", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: "https://discord.com/channels/1/2" }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("/api/webhooks/"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("fails without fetching when webhook_url is missing", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: "" }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("webhook URL required"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("truncates content to 2000 characters without splitting multi-byte characters", async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal("fetch", fetchMock); + + const body = "😀中文".repeat(1000); + await sendDiscord( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body }, + makeEnv(), + ); + + const [, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + const content = JSON.parse(String(init.body)).content as string; + expect(Array.from(content)).toHaveLength(2000); + // encodeURIComponent throws on a lone surrogate, so this proves the cut + // never landed in the middle of an emoji's surrogate pair. + expect(() => encodeURIComponent(content)).not.toThrow(); + expect(content).toBe( + Array.from(`**Title**\n${body}`).slice(0, 2000).join(""), + ); + }); + + it("fails on HTTP 500 and reports the status and body", async () => { + const fetchMock = vi.fn( + async () => new Response("server error", { status: 500 }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("500"); + expect(result.error).toContain("server error"); + }); + + it("fails on HTTP 429 without retrying", async () => { + const fetchMock = vi.fn( + async () => new Response("rate limited", { status: 429 }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendDiscord( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("429"); + expect(result.error).toContain("rate limited"); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/worker/test/feishu.test.ts b/worker/test/feishu.test.ts new file mode 100644 index 0000000..00ad8fd --- /dev/null +++ b/worker/test/feishu.test.ts @@ -0,0 +1,230 @@ +import { createHmac } from "node:crypto"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { sendFeishu, signFeishu } from "../src/services/notify/feishu"; +import type { Env } from "../src/types"; + +const WEBHOOK_URL = + "https://open.feishu.cn/open-apis/bot/v2/hook/00000000-0000-0000-0000-000000000000"; +const LARK_WEBHOOK_URL = + "https://open.larksuite.com/open-apis/bot/v2/hook/00000000-0000-0000-0000-000000000000"; + +function makeEnv(): Env { + return {} as Env; +} + +function okResponse(body: unknown = { code: 0, msg: "success" }): Response { + return new Response(JSON.stringify(body), { status: 200 }); +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); +}); + +describe("signFeishu", () => { + it("matches the official HMAC-SHA256(timestamp\\nsecret, empty message) algorithm", async () => { + const timestamp = 1700000000; + const secret = "feishu-secret"; + + const expected = createHmac("sha256", `${timestamp}\n${secret}`) + .update("") + .digest("base64"); + + await expect(signFeishu(timestamp, secret)).resolves.toBe(expected); + }); +}); + +describe("sendFeishu", () => { + it("posts a text message with title, body and url and omits the signature without a secret", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { + title: "Renewal due", + body: "Your plan expires soon.", + url: "https://enotify.example.com/items/1", + }, + makeEnv(), + ); + + expect(result).toEqual({ success: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + + const [url, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + expect(url).toBe(WEBHOOK_URL); + expect(init.method).toBe("POST"); + expect(init.redirect).toBe("manual"); + expect(init.headers).toEqual({ "Content-Type": "application/json" }); + + const payload = JSON.parse(String(init.body)); + expect(payload).toEqual({ + msg_type: "text", + content: { + text: "Renewal due\nYour plan expires soon.\nhttps://enotify.example.com/items/1", + }, + }); + }); + + it("omits the url line when message.url is empty", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + const [, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + expect(JSON.parse(String(init.body)).content.text).toBe("Title\nBody"); + }); + + it("signs the request with the configured secret and the current timestamp", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(1700000000 * 1000)); + + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const secret = "feishu-secret"; + await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL, secret }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + const [, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + const payload = JSON.parse(String(init.body)); + expect(payload.timestamp).toBe("1700000000"); + expect(payload.sign).toBe( + createHmac("sha256", `1700000000\n${secret}`).update("").digest("base64"), + ); + }); + + it("accepts the international Lark domain", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: LARK_WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result).toEqual({ success: true }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("rejects other hosts without fetching", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ + webhook_url: "https://example.com/open-apis/bot/v2/hook/abc", + }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("open.feishu.cn"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a Feishu URL with the wrong path without fetching", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ + webhook_url: "https://open.feishu.cn/open-apis/bot/v2", + }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("/open-apis/bot/v2/hook/"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("fails without fetching when webhook_url is missing", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: "" }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("webhook URL required"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("fails when the API answers 200 with a non-zero code", async () => { + const fetchMock = vi.fn( + async () => + new Response(JSON.stringify({ code: 19002, msg: "sign match fail" }), { + status: 200, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("19002"); + expect(result.error).toContain("sign match fail"); + }); + + it("fails when the response body is not JSON", async () => { + const fetchMock = vi.fn( + async () => new Response("not json", { status: 200 }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("invalid response body"); + }); + + it("reports the status code when the API returns an error", async () => { + const fetchMock = vi.fn( + async () => new Response("bad request", { status: 400 }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendFeishu( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("400"); + expect(result.error).toContain("bad request"); + }); +}); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index 6af02b3..cc49e05 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -174,6 +174,43 @@ describe("notification_configs slack_config migration", () => { }); }); +describe("notification_configs feishu/discord migration", () => { + it("adds feishu_config and discord_config with a '{}' default and keeps existing data", async () => { + const d1 = new SqliteD1(); + d1.db.exec(OLD_SCHEMA); + + await runSetup(makeEnv(d1)); + + const columns = d1.db + .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) + .all() as ColumnInfo[]; + for (const name of ["feishu_config", "discord_config"]) { + const column = columns.find((c) => c.name === name); + expect(column).toBeDefined(); + expect(column?.type).toBe("TEXT"); + expect(column?.notnull).toBe(1); + expect(column?.dflt_value).toBe("'{}'"); + } + + // Retired channel columns stay in place for existing databases; only the + // type declarations and read/write code for them were removed. + const names = columns.map((c) => c.name); + expect(names).toContain("gotify_config"); + expect(names).toContain("notifyx_config"); + + const row = d1.db + .prepare(`SELECT * FROM ${PREFIX}notification_configs WHERE user_id = ?`) + .get("u1") as Record; + expect(row.enabled_channels).toBe('["telegram"]'); + expect(row.telegram_config).toBe('{"bot_token":"secret"}'); + expect(row.gotify_config).toBe( + '{"server_url":"https://gotify.example.com","app_token":"tok"}', + ); + expect(row.feishu_config).toBe("{}"); + expect(row.discord_config).toBe("{}"); + }); +}); + /** Seed a legacy database whose enabled_channels still lists retired channels. */ function seedLegacyChannels(d1: SqliteD1): void { d1.db.exec(OLD_SCHEMA); @@ -184,7 +221,7 @@ function seedLegacyChannels(d1: SqliteD1): void { WHERE user_id = ?`, ) .run( - '["telegram","serverchan","pushplus"]', + '["telegram","serverchan","pushplus","gotify","notifyx"]', '{"bot_token":"secret","chat_id":"42"}', "u1", ); @@ -233,6 +270,29 @@ function seedLegacyChannels(d1: SqliteD1): void { VALUES (?, ?, ?)`, ) .run("u4", '["telegram","serverchan"]', "2026-01-01T00:00:00.000Z"); + // Mixed row: only the retired IDs go, the remaining channels keep their order. + d1.db + .prepare( + `INSERT INTO ${PREFIX}users (id, email, password_hash, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`, + ) + .run( + "u5", + "u5@example.com", + "hash", + "2026-01-01T00:00:00.000Z", + "2026-01-01T00:00:00.000Z", + ); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, enabled_channels, updated_at) + VALUES (?, ?, ?)`, + ) + .run( + "u5", + '["bark","gotify","email","notifyx"]', + "2026-01-01T00:00:00.000Z", + ); } function enabledChannelsOf(d1: SqliteD1, userId: string): unknown { @@ -249,7 +309,7 @@ afterEach(() => { }); describe("retired channel cleanup migration", () => { - it("strips serverchan and pushplus from enabled_channels", async () => { + it("strips serverchan, pushplus, gotify and notifyx from enabled_channels", async () => { const d1 = new SqliteD1(); seedLegacyChannels(d1); @@ -258,6 +318,8 @@ describe("retired channel cleanup migration", () => { expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); // Rows without retired channels are left untouched. expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); + // Only the retired IDs are removed; the remaining order is preserved. + expect(enabledChannelsOf(d1, "u5")).toBe('["bark","email"]'); // A malformed value is skipped without aborting the migration: u4 comes // after the bad row, so it is only stripped if processing continued. expect(enabledChannelsOf(d1, "u3")).toBe("not-json"); @@ -276,6 +338,7 @@ describe("retired channel cleanup migration", () => { expect(enabledChannelsOf(d1, "u2")).toBe('["bark"]'); expect(enabledChannelsOf(d1, "u3")).toBe("not-json"); expect(enabledChannelsOf(d1, "u4")).toBe('["telegram"]'); + expect(enabledChannelsOf(d1, "u5")).toBe('["bark","email"]'); }); it("no longer reports unknown channels after the migration", async () => { @@ -326,6 +389,10 @@ describe("fresh install schema", () => { const names = columns.map((c) => c.name); expect(names).not.toContain("serverchan_config"); expect(names).not.toContain("pushplus_config"); + expect(names).not.toContain("gotify_config"); + expect(names).not.toContain("notifyx_config"); expect(names).toContain("slack_config"); + expect(names).toContain("feishu_config"); + expect(names).toContain("discord_config"); }); }); From 30831f393edf1109784cb66dfceef8c347d0e3a6 Mon Sep 17 00:00:00 2001 From: Todos Date: Tue, 20 Oct 2026 17:57:00 +0800 Subject: [PATCH 2/2] chore: checkpoint UjODNDJIM1eqy72WtX-bm --- web/src/components/ChannelSelector.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/web/src/components/ChannelSelector.tsx b/web/src/components/ChannelSelector.tsx index 07f784e..89628b2 100644 --- a/web/src/components/ChannelSelector.tsx +++ b/web/src/components/ChannelSelector.tsx @@ -186,13 +186,17 @@ export function ChannelSelector({
{selected.map((channelId) => { const channel = CHANNELS.find((ch) => ch.id === channelId); - if (!channel) return null; + // Unknown IDs are retired channels still stored on old items. They + // are not offered in the dropdown, but must stay removable here: + // otherwise the item could never be saved again (the API rejects + // retired IDs) and it would silently stop notifying. return ( - {channel.label} + {channel?.label ?? channelId}