From 44f5a0fc7a1de11e0d496ddd65275181fee831e9 Mon Sep 17 00:00:00 2001 From: Todos Date: Tue, 20 Oct 2026 15:49:47 +0800 Subject: [PATCH] feat(notify): add Slack incoming webhook channel - Add sendSlack using JSON.stringify-built mrkdwn text and enforce a hooks.slack.com hostname on top of validateOutboundUrl - Register the slack sender, VALID_CHANNELS entry and slack_config type, and redact webhook_url in GET/PUT /api/me/notifications - Add slack_config to both schemas plus an idempotent ALTER TABLE migration so existing D1 databases pick up the column - Expose Slack in channel management, per-item channel selection and locales, and update the README channel count - Cover request shape, JSON escaping, URL rejection, error status and the schema migration with tests Checkpoint: VS9pA4yqaDBelmXiJbO6T --- README.en.md | 2 +- README.md | 2 +- web/src/lib/channels.ts | 1 + web/src/locales/en.json | 1 + web/src/locales/zh.json | 1 + web/src/pages/channels/ChannelPage.tsx | 12 ++ worker/src/db/queries/notifications.ts | 1 + worker/src/db/schema.sql | 1 + worker/src/lib/setup.ts | 17 +++ worker/src/routes/me.ts | 2 + worker/src/services/notify/index.ts | 2 + worker/src/services/notify/slack.ts | 49 +++++++ worker/src/types.ts | 2 + worker/test/migrations.test.ts | 174 +++++++++++++++++++++++++ worker/test/slack.test.ts | 151 +++++++++++++++++++++ 15 files changed, 416 insertions(+), 2 deletions(-) create mode 100644 worker/src/services/notify/slack.ts create mode 100644 worker/test/migrations.test.ts create mode 100644 worker/test/slack.test.ts diff --git a/README.en.md b/README.en.md index a6851b5..54e8177 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 -- **9 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX +- **10 Notification Channels** — Telegram, Webhook, WeChat Work, Email, Bark, Gotify, ServerChan, PushPlus, NotifyX, Slack - **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 4b4edbb..193bd93 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ - **自动续费** — 过期订阅自动续期并记录支付历史 - **支付历史** — 记录每笔支付,支持多币种与实时汇率转换 - **仪表盘** — 月度/年度支出统计、到期预警、分类分析 -- **9 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、Server酱、PushPlus、NotifyX +- **10 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Gotify、Server酱、PushPlus、NotifyX、Slack - **渠道管理** — 独立页面统一管理通知渠道的启用与配置 - **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道 - **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖 diff --git a/web/src/lib/channels.ts b/web/src/lib/channels.ts index d5b901d..a4a9fee 100644 --- a/web/src/lib/channels.ts +++ b/web/src/lib/channels.ts @@ -8,4 +8,5 @@ export const CHANNELS = [ { id: "serverchan", label: "ServerChan" }, { id: "pushplus", label: "PushPlus" }, { id: "notifyx", label: "NotifyX" }, + { id: "slack", label: "Slack" }, ] as const; diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 8fd0c49..1a72c70 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -348,6 +348,7 @@ "serverchan": "ServerChan", "pushplus": "PushPlus", "notifyx": "NotifyX", + "slack": "Slack", "botToken": "Bot Token", "chatId": "Chat ID", "url": "URL", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index f528d1a..eb98910 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -348,6 +348,7 @@ "serverchan": "Server酱", "pushplus": "PushPlus", "notifyx": "NotifyX", + "slack": "Slack", "botToken": "机器人令牌", "chatId": "聊天ID", "url": "URL", diff --git a/web/src/pages/channels/ChannelPage.tsx b/web/src/pages/channels/ChannelPage.tsx index dc64727..e97a62d 100644 --- a/web/src/pages/channels/ChannelPage.tsx +++ b/web/src/pages/channels/ChannelPage.tsx @@ -138,6 +138,18 @@ const CHANNELS: ChannelDef[] = [ label: "NotifyX", fields: [{ key: "api_key", label: "API Key", type: "password" }], }, + { + id: "slack", + label: "Slack", + fields: [ + { + key: "webhook_url", + label: "Webhook URL", + type: "password", + placeholder: "https://hooks.slack.com/services/...", + }, + ], + }, ]; // --------------------------------------------------------------------------- diff --git a/worker/src/db/queries/notifications.ts b/worker/src/db/queries/notifications.ts index 89e12fd..063693c 100644 --- a/worker/src/db/queries/notifications.ts +++ b/worker/src/db/queries/notifications.ts @@ -39,6 +39,7 @@ export async function upsertNotificationConfig( "serverchan_config", "pushplus_config", "notifyx_config", + "slack_config", "notification_hours", ]; diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index 0efc639..c37be7f 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -88,6 +88,7 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( serverchan_config TEXT NOT NULL DEFAULT '{}', pushplus_config TEXT NOT NULL DEFAULT '{}', notifyx_config TEXT NOT NULL DEFAULT '{}', + slack_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 be17c7e..5ef03fc 100644 --- a/worker/src/lib/setup.ts +++ b/worker/src/lib/setup.ts @@ -33,6 +33,22 @@ async function runMigrations(db: D1Database, prefix: string): Promise { // ignore } + // Migration: add slack_config column to notification_configs + try { + const notifCols = await db + .prepare(`PRAGMA table_info(${prefix}notification_configs)`) + .all<{ name: string }>(); + if (!notifCols.results.some((c) => c.name === "slack_config")) { + await db + .prepare( + `ALTER TABLE ${prefix}notification_configs ADD COLUMN slack_config TEXT NOT NULL DEFAULT '{}'`, + ) + .run(); + } + } catch (err) { + console.error("Migration failed for notification_configs table:", err); + } + // Migration: items table columns (type/use_lunar -> calendar_mode, lunar_expiry_date). // Uses ALTER TABLE instead of recreating the table: DROP TABLE would cascade-delete payment_history. try { @@ -201,6 +217,7 @@ CREATE TABLE IF NOT EXISTS {prefix}notification_configs ( serverchan_config TEXT NOT NULL DEFAULT '{}', pushplus_config TEXT NOT NULL DEFAULT '{}', notifyx_config TEXT NOT NULL DEFAULT '{}', + slack_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 0db2db1..b734fb9 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -292,6 +292,7 @@ meRoutes.get("/notifications", async (c) => { "password", "device_key", "headers", + "webhook_url", ].some((s) => k.includes(s)) ) { redacted[k] = v ? "••••••" : ""; @@ -357,6 +358,7 @@ meRoutes.put("/notifications", async (c) => { "password", "device_key", "headers", + "webhook_url", ]; for (const [k, v] of Object.entries(newConfig)) { if (secretFields.some((s) => k.includes(s)) && (!v || v === "••••••")) { diff --git a/worker/src/services/notify/index.ts b/worker/src/services/notify/index.ts index b834f20..9438b46 100644 --- a/worker/src/services/notify/index.ts +++ b/worker/src/services/notify/index.ts @@ -7,6 +7,7 @@ import { sendGotify } from "./gotify"; import { sendServerChan } from "./serverchan"; import { sendPushPlus } from "./pushplus"; import { sendNotifyX } from "./notifyx"; +import { sendSlack } from "./slack"; import { sendNotifyEmail } from "./email-notify"; import type { Env } from "../../types"; import { insertNotificationHistory } from "../../db/queries/notification-history"; @@ -48,6 +49,7 @@ const CHANNEL_SENDERS: Record< serverchan: sendServerChan, pushplus: sendPushPlus, notifyx: sendNotifyX, + slack: sendSlack, }; const SEND_TIMEOUT_MS = 15000; diff --git a/worker/src/services/notify/slack.ts b/worker/src/services/notify/slack.ts new file mode 100644 index 0000000..d54426f --- /dev/null +++ b/worker/src/services/notify/slack.ts @@ -0,0 +1,49 @@ +import type { Env } from "../../types"; +import type { NotifyMessage } from "./index"; +import { safeErrorText, validateOutboundUrl } from "./safe-fetch"; + +interface SlackConfig { + webhook_url: string; +} + +export async function sendSlack( + configJson: string, + message: NotifyMessage, + _env: Env, +): Promise<{ success: boolean; error?: string }> { + const config: SlackConfig = JSON.parse(configJson); + if (!config.webhook_url) { + return { success: false, error: "Slack webhook URL required" }; + } + + const check = validateOutboundUrl(config.webhook_url); + if (check.error || !check.url) { + return { success: false, error: `Slack: ${check.error ?? "Invalid URL"}` }; + } + if (check.url.hostname !== "hooks.slack.com") { + return { + success: false, + error: "Slack: webhook URL must be on hooks.slack.com", + }; + } + + const lines = [`_${message.title}_`, message.body]; + if (message.url) lines.push(message.url); + const text = lines.join("\n"); + + const response = await fetch(config.webhook_url, { + method: "POST", + redirect: "manual", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ text }), + }); + + if (!response.ok) { + const err = await safeErrorText(response); + return { + success: false, + error: `Slack error (${response.status}): ${err}`, + }; + } + return { success: true }; +} diff --git a/worker/src/types.ts b/worker/src/types.ts index a3df9cd..416760a 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -86,6 +86,7 @@ export interface NotificationConfig { serverchan_config: string; pushplus_config: string; notifyx_config: string; + slack_config: string; notification_hours: string; updated_at: string; } @@ -133,4 +134,5 @@ export const VALID_CHANNELS: string[] = [ "serverchan", "pushplus", "notifyx", + "slack", ]; diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts new file mode 100644 index 0000000..d6ce7e7 --- /dev/null +++ b/worker/test/migrations.test.ts @@ -0,0 +1,174 @@ +import { DatabaseSync } from "node:sqlite"; +import { describe, expect, it } from "vitest"; +import { runSetup } from "../src/lib/setup"; +import type { Env } from "../src/types"; + +/** + * Minimal D1 stand-in backed by a real in-memory SQLite database. Unlike the + * MockD1 in helpers.ts this keeps real column defaults and row data, which is + * what the slack_config migration needs to be verified against. + */ +class SqliteD1 { + readonly db = new DatabaseSync(":memory:"); + + prepare(sql: string): any { + const db = this.db; + const statement = () => db.prepare(sql); + + return { + bind: (...args: unknown[]) => ({ + first: async () => + (statement().get(...(args as any[])) ?? null) as T | null, + all: async () => ({ + results: statement().all(...(args as any[])) as T[], + }), + run: async () => { + statement().run(...(args as any[])); + return { success: true }; + }, + }), + first: async () => (statement().get() ?? null) as T | null, + all: async () => ({ results: statement().all() as T[] }), + run: async () => { + statement().run(); + return { success: true }; + }, + }; + } +} + +const PREFIX = "en_"; + +// Schema as deployed before the Slack channel existed: no slack_config column. +const OLD_SCHEMA = ` +CREATE TABLE ${PREFIX}users ( + id TEXT PRIMARY KEY, + email TEXT UNIQUE NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user', + is_active INTEGER NOT NULL DEFAULT 1, + email_verified INTEGER NOT NULL DEFAULT 0, + base_currency TEXT NOT NULL DEFAULT 'CNY', + timezone TEXT NOT NULL DEFAULT 'UTC', + language TEXT NOT NULL DEFAULT 'zh', + theme TEXT NOT NULL DEFAULT 'system', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE TABLE ${PREFIX}notification_configs ( + user_id TEXT PRIMARY KEY REFERENCES ${PREFIX}users(id) ON DELETE CASCADE, + enabled_channels TEXT NOT NULL DEFAULT '[]', + telegram_config TEXT NOT NULL DEFAULT '{}', + webhook_config TEXT NOT NULL DEFAULT '{}', + wechatbot_config TEXT NOT NULL DEFAULT '{}', + email_config TEXT NOT NULL DEFAULT '{}', + bark_config TEXT NOT NULL DEFAULT '{}', + gotify_config TEXT NOT NULL DEFAULT '{}', + serverchan_config TEXT NOT NULL DEFAULT '{}', + pushplus_config TEXT NOT NULL DEFAULT '{}', + notifyx_config TEXT NOT NULL DEFAULT '{}', + notification_hours TEXT NOT NULL DEFAULT '[]', + updated_at TEXT NOT NULL +); + +CREATE TABLE ${PREFIX}notification_history ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + item_id TEXT, + channel TEXT NOT NULL, + title TEXT NOT NULL, + body TEXT, + success INTEGER NOT NULL DEFAULT 1, + error TEXT, + created_at TEXT NOT NULL +); + +CREATE TABLE ${PREFIX}items ( + id TEXT PRIMARY KEY, + calendar_mode TEXT NOT NULL DEFAULT 'solar', + lunar_expiry_date TEXT +); + +INSERT INTO ${PREFIX}users + (id, email, password_hash, created_at, updated_at) +VALUES + ('u1', 'u1@example.com', 'hash', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'), + ('u2', 'u2@example.com', 'hash', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'); + +INSERT INTO ${PREFIX}notification_configs + (user_id, enabled_channels, telegram_config, gotify_config, notification_hours, updated_at) +VALUES + ('u1', '["telegram"]', '{"bot_token":"secret"}', '{"server_url":"https://gotify.example.com","app_token":"tok"}', '[8,9]', '2026-01-01T00:00:00.000Z'); +`; + +function makeEnv(d1: SqliteD1): Env { + return { DB: d1, TABLE_PREFIX: "en" } as unknown as Env; +} + +type ColumnInfo = { + name: string; + type: string; + notnull: number; + dflt_value: string | null; +}; + +describe("notification_configs slack_config migration", () => { + it("adds slack_config with a '{}' default and keeps existing data", async () => { + const d1 = new SqliteD1(); + d1.db.exec(OLD_SCHEMA); + + const result = await runSetup(makeEnv(d1)); + expect(result).toEqual({ success: true, alreadyInitialized: true }); + + const columns = d1.db + .prepare(`PRAGMA table_info(${PREFIX}notification_configs)`) + .all() as ColumnInfo[]; + const slackColumn = columns.find((c) => c.name === "slack_config"); + expect(slackColumn).toBeDefined(); + expect(slackColumn?.type).toBe("TEXT"); + expect(slackColumn?.notnull).toBe(1); + expect(slackColumn?.dflt_value).toBe("'{}'"); + + // The pre-existing row survives and is backfilled with the default. + 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.notification_hours).toBe("[8,9]"); + expect(row.updated_at).toBe("2026-01-01T00:00:00.000Z"); + expect(row.slack_config).toBe("{}"); + + // New rows get the same default. + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs (user_id, updated_at) VALUES (?, ?)`, + ) + .run("u2", "2026-02-01T00:00:00.000Z"); + const newRow = d1.db + .prepare( + `SELECT slack_config FROM ${PREFIX}notification_configs WHERE user_id = ?`, + ) + .get("u2") as Record; + expect(newRow.slack_config).toBe("{}"); + }); + + it("is idempotent when the column already exists", async () => { + const d1 = new SqliteD1(); + d1.db.exec(OLD_SCHEMA); + + await runSetup(makeEnv(d1)); + const second = await runSetup(makeEnv(d1)); + expect(second).toEqual({ success: true, alreadyInitialized: true }); + + const rows = d1.db + .prepare(`SELECT * FROM ${PREFIX}notification_configs`) + .all() as Record[]; + expect(rows).toHaveLength(1); + expect(rows[0].slack_config).toBe("{}"); + }); +}); diff --git a/worker/test/slack.test.ts b/worker/test/slack.test.ts new file mode 100644 index 0000000..f5cd735 --- /dev/null +++ b/worker/test/slack.test.ts @@ -0,0 +1,151 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { sendSlack } from "../src/services/notify/slack"; +import type { Env } from "../src/types"; + +const WEBHOOK_URL = "https://hooks.slack.com/services/T000/B000/XXXX"; + +function makeEnv(): Env { + return {} as Env; +} + +function okResponse(): Response { + return new Response("ok", { status: 200 }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("sendSlack", () => { + it("posts a JSON body with title, body and url to the configured webhook", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendSlack( + 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.headers).toEqual({ "Content-Type": "application/json" }); + + const payload = JSON.parse(String(init.body)); + expect(payload.text).toBe( + "_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 sendSlack( + 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)).text).toBe("_Title_\nBody"); + }); + + it("escapes quotes, backslashes and newlines so the text round-trips", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const title = 'Say "hi" \\ now'; + const body = 'line 1\nline 2 with "quotes" and \\backslash\\'; + const url = "https://enotify.example.com/items/1?a=1&b=2"; + + await sendSlack( + JSON.stringify({ webhook_url: WEBHOOK_URL }), + { title, body, url }, + makeEnv(), + ); + + const [, init] = fetchMock.mock.calls[0] as unknown as [ + string, + RequestInit, + ]; + const rawBody = String(init.body); + expect(() => JSON.parse(rawBody)).not.toThrow(); + expect(JSON.parse(rawBody).text).toBe(`_${title}_\n${body}\n${url}`); + }); + + it("fails without fetching when webhook_url is missing", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendSlack( + 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("rejects a URL that is not on hooks.slack.com without fetching", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendSlack( + JSON.stringify({ webhook_url: "https://example.com/hook" }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("hooks.slack.com"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects private/internal URLs without fetching", async () => { + const fetchMock = vi.fn(async () => okResponse()); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendSlack( + JSON.stringify({ webhook_url: "https://127.0.0.1/hook" }), + { title: "Title", body: "Body" }, + makeEnv(), + ); + + expect(result.success).toBe(false); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("reports the status code when Slack returns an error", async () => { + const fetchMock = vi.fn( + async () => new Response("invalid_payload", { status: 400 }), + ); + vi.stubGlobal("fetch", fetchMock); + + const result = await sendSlack( + 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("invalid_payload"); + }); +});