Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@ 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, 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.
**Notification services** (`worker/src/services/notify/`): Each channel (Telegram, Webhook, Email, Bark, Slack, Feishu, Discord, WeChatBot) is a separate file. `index.ts` sends to selected enabled channels via the `channels` parameter, or only to the user's default channel when no channels are selected.

**Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly via Cloudflare Cron Trigger (`0 * * * *`). For each active user it:

1. Checks their allowed notification hours (per-timezone).
2. Auto-renews expired items (with KV deduplication).
3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise all enabled channels receive the notification.
3. Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (`channels` column), only those channels are used; otherwise only the user's default channel receives the notification.

**Cloudflare bindings**:

Expand Down Expand Up @@ -101,7 +101,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS`
- **UI (zh)**: shows "通知" / "通知管理"
- **UI (en)**: shows "Notification" / "Notifications"
- **`notification_config`** / `NotificationConfig` refers to push channel configuration, not items — these are separate concepts.
- **Code/UI for channels**: `channels` / `Channel` in code and nav. DB column `channels` on items stores a JSON array of channel IDs (e.g. `["telegram","email"]`). Empty array `[]` means "use all enabled channels".
- **Code/UI for channels**: `channels` / `Channel` in code and nav. DB column `channels` on items stores a JSON array of channel IDs (e.g. `["telegram","email"]`). Empty array `[]` means "use the default channel".
- **UI (zh)**: shows "渠道" / "渠道管理"
- **UI (en)**: shows "Channel" / "Channel Management"

Expand Down
10 changes: 8 additions & 2 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ A smart notification management system that helps you track expiry dates and exp
- **Dashboard** — Monthly/yearly expense stats, expiry alerts, category analysis
- **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
- **Per-Item Channel Selection** — Each notification item can select multiple channels; if unset, only the default channel is used
- **Scheduled Reminders** — Hourly auto-check with global notification hours and per-item override
- **Notification History** — View all sent notifications with delivery status
- **Two-Factor Auth** — TOTP (authenticator app), Email OTP, Passkey
Expand Down Expand Up @@ -140,9 +140,15 @@ curl -X POST https://your-worker.workers.dev/api/notify \
-H "Authorization: Bearer enk_xxxxxxxx" \
-H "Content-Type: application/json" \
-d '{"title": "Reminder", "body": "Content", "url": "https://example.com"}'

# Send only to Telegram and Bark
curl -X POST https://your-worker.workers.dev/api/notify \
-H "Authorization: Bearer enk_xxxxxxxx" \
-H "Content-Type: application/json" \
-d '{"title": "Reminder", "body": "Content", "channels": ["telegram", "bark"]}'
```

`POST /api/notify` sends a push to the user's enabled notification channels; `title` defaults to `Notification` when omitted. Besides the API key, it also accepts a cookie login session.
`POST /api/notify` accepts an optional `channels` array to select multiple channels. If omitted or empty, only the user's default channel is used. Unknown or disabled channels, and requests without channels when no default is configured, return 400 without sending. `title` defaults to `Notification` when omitted. Besides the API key, it also accepts a cookie login session.

Each key is limited to 120 requests/minute (`429` beyond that). Invalid, expired or revoked keys get `401`; keys stop working as soon as their user is disabled. `/api/notify` has an additional per-IP limit of 30 requests/minute.

Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
- **仪表盘** — 月度/年度支出统计、到期预警、分类分析
- **8 个通知渠道** — Telegram、Webhook、企业微信、邮件、Bark、Slack、飞书、Discord
- **渠道管理** — 独立页面统一管理通知渠道的启用与配置
- **按项选择渠道** — 每个通知项可单独指定使用哪些渠道,未指定则默认使用所有已启用渠道
- **按项选择渠道** — 每个通知项可单独多选使用哪些渠道,未指定则只使用默认渠道
- **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖
- **通知历史** — 查看所有已发送通知的记录与状态
- **两步验证** — TOTP(验证器应用)、邮箱验证码、Passkey
Expand Down Expand Up @@ -145,9 +145,15 @@ curl -X POST https://your-worker.workers.dev/api/notify \
-H "Authorization: Bearer enk_xxxxxxxx" \
-H "Content-Type: application/json" \
-d '{"title": "提醒", "body": "内容", "url": "https://example.com"}'

# 多选 Telegram 和 Bark,其他渠道不发送
curl -X POST https://your-worker.workers.dev/api/notify \
-H "Authorization: Bearer enk_xxxxxxxx" \
-H "Content-Type: application/json" \
-d '{"title": "提醒", "body": "内容", "channels": ["telegram", "bark"]}'
```

`POST /api/notify` 会向该用户已启用的通知渠道发送推送;`title` 省略时默认为 `Notification`。该接口除了 API Key 也接受 cookie 登录态。
`POST /api/notify` 请求体可带可选 `channels` 数组多选渠道;不带或为空数组时只发该用户的默认渠道。`channels` 含未知或未启用渠道、或未设默认渠道时返回 400 且不发送。`title` 省略时默认为 `Notification`。该接口除了 API Key 也接受 cookie 登录态。

每个 key 限流 120 次/分钟,超出返回 `429`。key 无效、过期或已吊销时返回 `401`;对应用户被禁用后其 key 立即失效。`/api/notify` 另有一层按 IP 的 30 次/分钟限流。

Expand Down
1 change: 1 addition & 0 deletions worker/src/db/queries/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export async function upsertNotificationConfig(

const fields: (keyof Omit<NotificationConfig, "user_id" | "updated_at">)[] = [
"enabled_channels",
"default_channel",
"telegram_config",
"webhook_config",
"wechatbot_config",
Expand Down
1 change: 1 addition & 0 deletions worker/src/db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id
CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE,
enabled_channels TEXT NOT NULL DEFAULT '[]',
default_channel TEXT NOT NULL DEFAULT '',
telegram_config TEXT NOT NULL DEFAULT '{}',
webhook_config TEXT NOT NULL DEFAULT '{}',
wechatbot_config TEXT NOT NULL DEFAULT '{}',
Expand Down
44 changes: 37 additions & 7 deletions worker/src/lib/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,37 @@ async function runMigrations(db: D1Database, prefix: string): Promise<void> {
console.error("Migration failed for notification_configs table:", err);
}

// Migration: add default_channel column to notification_configs. This must
// run before the retired-channel cleanup, which reads the new column.
try {
const notifCols = await db
.prepare(`PRAGMA table_info(${prefix}notification_configs)`)
.all<{ name: string }>();
if (!notifCols.results.some((c) => c.name === "default_channel")) {
await db
.prepare(
`ALTER TABLE ${prefix}notification_configs ADD COLUMN default_channel 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.
// enabled_channels and default_channel. Their sender code is gone, so stale
// enabled IDs would fail and a retired default would make routing fail too.
// Idempotent: the second run finds nothing to strip and performs no UPDATE.
try {
const rows = await db
.prepare(
`SELECT user_id, enabled_channels FROM ${prefix}notification_configs`,
`SELECT user_id, enabled_channels, default_channel FROM ${prefix}notification_configs`,
)
.all<{ user_id: string; enabled_channels: string }>();
.all<{
user_id: string;
enabled_channels: string;
default_channel: string;
}>();
for (const row of rows.results) {
let channels: unknown;
try {
Expand All @@ -91,12 +112,20 @@ async function runMigrations(db: D1Database, prefix: string): Promise<void> {
}
if (!Array.isArray(channels)) continue;
const filtered = channels.filter((ch) => !RETIRED_CHANNELS.includes(ch));
if (filtered.length === channels.length) continue;
const defaultChannel = RETIRED_CHANNELS.includes(row.default_channel)
? ""
: row.default_channel;
if (
filtered.length === channels.length &&
defaultChannel === row.default_channel
) {
continue;
}
await db
.prepare(
`UPDATE ${prefix}notification_configs SET enabled_channels = ? WHERE user_id = ?`,
`UPDATE ${prefix}notification_configs SET enabled_channels = ?, default_channel = ? WHERE user_id = ?`,
)
.bind(JSON.stringify(filtered), row.user_id)
.bind(JSON.stringify(filtered), defaultChannel, row.user_id)
.run();
}
} catch (err) {
Expand Down Expand Up @@ -262,6 +291,7 @@ CREATE INDEX IF NOT EXISTS idx_{prefix}payment_history_user_id
CREATE TABLE IF NOT EXISTS {prefix}notification_configs (
user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE,
enabled_channels TEXT NOT NULL DEFAULT '[]',
default_channel TEXT NOT NULL DEFAULT '',
telegram_config TEXT NOT NULL DEFAULT '{}',
webhook_config TEXT NOT NULL DEFAULT '{}',
wechatbot_config TEXT NOT NULL DEFAULT '{}',
Expand Down
33 changes: 20 additions & 13 deletions worker/src/routes/items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -702,19 +702,26 @@ itemRoutes.post("/:id/test-notify", async (c) => {
itemChannels = [];
}

const results = await sendNotifications(
notifyConfig,
message,
c.env,
{
db: c.env.DB,
prefix,
userId,
itemId: id,
},
itemChannels?.length ? itemChannels : undefined,
);
return c.json({ results });
try {
const results = await sendNotifications(
notifyConfig,
message,
c.env,
{
db: c.env.DB,
prefix,
userId,
itemId: id,
},
itemChannels?.length ? itemChannels : undefined,
);
return c.json({ results });
} catch (err) {
return c.json(
{ error: err instanceof Error ? err.message : String(err) },
400,
);
}
});

// Payment history
Expand Down
30 changes: 29 additions & 1 deletion worker/src/routes/me.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,11 +240,16 @@ meRoutes.get("/notifications", async (c) => {

const config = await getNotificationConfig(c.env.DB, prefix, userId);
if (!config) {
return c.json({ enabled_channels: [], notification_hours: [] });
return c.json({
enabled_channels: [],
default_channel: "",
notification_hours: [],
});
}

// Redact sensitive fields - return configured flags instead
const safeConfig: Record<string, any> = {
default_channel: config.default_channel || "",
enabled_channels: (() => {
try {
return JSON.parse(config.enabled_channels);
Expand Down Expand Up @@ -334,6 +339,16 @@ meRoutes.put("/notifications", async (c) => {
}
updates.enabled_channels = JSON.stringify(body.enabled_channels);
}
if (body.default_channel !== undefined) {
if (
typeof body.default_channel !== "string" ||
(body.default_channel !== "" &&
!VALID_CHANNELS.includes(body.default_channel))
) {
return c.json({ error: "Invalid channel name" }, 400);
}
updates.default_channel = body.default_channel;
}
if (body.notification_hours !== undefined) {
if (!Array.isArray(body.notification_hours))
return c.json({ error: "notification_hours must be an array" }, 400);
Expand All @@ -352,6 +367,19 @@ meRoutes.put("/notifications", async (c) => {

const channels = VALID_CHANNELS;
const existing = await getNotificationConfig(c.env.DB, prefix, userId);

let finalEnabled: string[] = [];
try {
finalEnabled =
body.enabled_channels ?? JSON.parse(existing?.enabled_channels || "[]");
} catch {
finalEnabled = [];
}
const finalDefault = body.default_channel ?? existing?.default_channel ?? "";
if (finalDefault !== "" && !finalEnabled.includes(finalDefault)) {
return c.json({ error: "Default channel must be an enabled channel" }, 400);
}

for (const ch of channels) {
if (body[`${ch}_config`]) {
const existingConfig = existing
Expand Down
44 changes: 41 additions & 3 deletions worker/src/routes/notify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Hono } from "hono";
import { getTablePrefix, type HonoEnv } from "../types";
import { getTablePrefix, VALID_CHANNELS, type HonoEnv } from "../types";
import { getNotificationConfig } from "../db/queries/notifications";
import {
sendNotifications,
Expand Down Expand Up @@ -35,16 +35,54 @@ notifyRoutes.post("/", async (c) => {
title?: string;
body?: string;
url?: string;
channels?: unknown;
}>();

let channels: string[] | undefined;
if (body.channels !== undefined) {
if (!Array.isArray(body.channels)) {
return c.json({ error: "channels must be an array" }, 400);
}
channels = body.channels;
const invalidChannel = channels.find((ch) => !VALID_CHANNELS.includes(ch));
if (invalidChannel !== undefined) {
return c.json({ error: `Invalid channel name: ${invalidChannel}` }, 400);
}
let enabledChannels: string[];
try {
enabledChannels = JSON.parse(notifyConfig.enabled_channels || "[]");
} catch {
enabledChannels = [];
}
const disabledChannel = channels.find(
(ch) => !enabledChannels.includes(ch),
);
if (disabledChannel) {
return c.json({ error: `Channel not enabled: ${disabledChannel}` }, 400);
}
}

const message: NotifyMessage = {
title: body.title || "Notification",
body: body.body || "",
url: body.url,
};

const results = await sendNotifications(notifyConfig, message, c.env);
return c.json({ success: true, results });
try {
const results = await sendNotifications(
notifyConfig,
message,
c.env,
undefined,
channels,
);
return c.json({ success: true, results });
} catch (err) {
return c.json(
{ error: err instanceof Error ? err.message : String(err) },
400,
);
}
});

// Third-party token trigger — deprecated in favour of API keys. Return 410
Expand Down
17 changes: 15 additions & 2 deletions worker/src/services/notify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,27 @@ export async function sendNotifications(
enabledChannels = [];
}

let targetChannels: string[];
// If specific channels are requested, intersect with enabled channels
if (channels && channels.length > 0) {
enabledChannels = enabledChannels.filter((ch) => channels.includes(ch));
targetChannels = enabledChannels.filter((ch) => channels.includes(ch));
if (targetChannels.length === 0) {
throw new Error("None of the requested channels are enabled");
}
} else {
const defaultChannel = config.default_channel || "";
if (defaultChannel === "") {
throw new Error("No default channel configured");
}
if (!enabledChannels.includes(defaultChannel)) {
throw new Error(`Default channel is not enabled: ${defaultChannel}`);
}
targetChannels = [defaultChannel];
}

const results: NotifyResult[] = [];

for (const channel of enabledChannels) {
for (const channel of targetChannels) {
const sender = CHANNEL_SENDERS[channel];
if (!sender) {
results.push({ channel, success: false, error: "Unknown channel" });
Expand Down
32 changes: 20 additions & 12 deletions worker/src/services/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,18 +330,26 @@ async function processSubscription(
};
}

await sendNotifications(
notifyConfig,
message,
env,
{
db: env.DB,
prefix,
userId,
itemId: sub.id,
},
channels,
);
try {
await sendNotifications(
notifyConfig,
message,
env,
{
db: env.DB,
prefix,
userId,
itemId: sub.id,
},
channels,
);
} catch (err) {
console.error(
`Failed to resolve notification channels for item ${sub.id}:`,
err instanceof Error ? err.message : String(err),
);
continue;
}
await kv.put(dedupeKey, "1", { expirationTtl: 172800 });
}
}
Loading
Loading