diff --git a/README.en.md b/README.en.md index 02bbd7f..5322dea 100644 --- a/README.en.md +++ b/README.en.md @@ -104,7 +104,7 @@ pnpm dev:worker ## API Keys (for external programs) -External programs (AI assistants, scripts) can call the item management API `/api/items/*` with an API key instead of a cookie session. A key has the same permissions as the user who created it. Only `/api/items` accepts API keys for now; every other endpoint (including key management itself) still requires a login session. +External programs (AI assistants, scripts) can call the item management API `/api/items/*` and the push trigger endpoint `/api/notify` with an API key instead of a cookie session. A key has the same permissions as the user who created it. Only `/api/items` and `/api/notify` accept API keys for now; every other endpoint (including key management itself) still requires a login session. > Day-to-day management is available in the web UI under **Settings → API Keys**: create, copy, list and revoke. The curl examples below are for scripting and troubleshooting. @@ -124,9 +124,16 @@ curl -X POST https://your-worker.workers.dev/api/me/api-keys \ ```bash curl https://your-worker.workers.dev/api/items \ -H "Authorization: Bearer enk_xxxxxxxx" + +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"}' ``` -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. +`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. + +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` (including the legacy third-party token route `/api/notify/:token`) has an additional per-IP limit of 30 requests/minute, shared across both routes. **3. List and revoke** (also requires a login session) diff --git a/README.md b/README.md index 4355523..04289f6 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ pnpm dev:worker ## API Key(外部程序调用) -外部程序(如 AI 助手、脚本)可以用 API Key 调用事项管理接口 `/api/items/*`,无需 cookie 登录。API Key 的权限与创建它的用户自己的登录态一致;目前仅 `/api/items` 支持 API Key,其余接口(含 key 管理本身)仍只认登录会话。 +外部程序(如 AI 助手、脚本)可以用 API Key 调用事项管理接口 `/api/items/*` 与推送触发接口 `/api/notify`,无需 cookie 登录。API Key 的权限与创建它的用户自己的登录态一致;目前仅 `/api/items` 与 `/api/notify` 支持 API Key,其余接口(含 key 管理本身)仍只认登录会话。 > 日常管理可直接在网页的 **设置 → API 密钥** 里完成:生成、复制、查看和吊销。下面的 curl 示例适合脚本化或排查问题。 @@ -129,9 +129,16 @@ curl -X POST https://your-worker.workers.dev/api/items \ -H "Authorization: Bearer enk_xxxxxxxx" \ -H "Content-Type: application/json" \ -d '{...}' + +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"}' ``` -每个 key 限流 120 次/分钟,超出返回 `429`。key 无效、过期或已吊销时返回 `401`;对应用户被禁用后其 key 立即失效。 +`POST /api/notify` 会向该用户已启用的通知渠道发送推送;`title` 省略时默认为 `Notification`。该接口除了 API Key 也接受 cookie 登录态。 + +每个 key 限流 120 次/分钟,超出返回 `429`。key 无效、过期或已吊销时返回 `401`;对应用户被禁用后其 key 立即失效。`/api/notify`(含老的三方 token 路由 `/api/notify/:token`)另有一层按 IP 的 30 次/分钟限流,两条路由共享同一额度。 **3. 查看与吊销**(同样需要登录会话) diff --git a/worker/src/routes/notify.ts b/worker/src/routes/notify.ts index 5f620fe..669f20c 100644 --- a/worker/src/routes/notify.ts +++ b/worker/src/routes/notify.ts @@ -1,6 +1,5 @@ -import { Hono } from "hono"; -import { getTablePrefix } from "../types"; -import type { Env } from "../types"; +import { Hono, type Context } from "hono"; +import { getTablePrefix, type HonoEnv } from "../types"; import { getNotificationConfig } from "../db/queries/notifications"; import { findUserById } from "../db/queries/users"; import { @@ -8,8 +7,7 @@ import { type NotifyMessage, } from "../services/notify/index"; import { rateLimit } from "../middleware/ratelimit"; - -type HonoEnv = { Bindings: Env; Variables: Record }; +import { apiKeyOrCookieAuth } from "../middleware/apiKey"; export const notifyRoutes = new Hono(); @@ -18,6 +16,20 @@ notifyRoutes.use( rateLimit({ max: 30, window: 60, keyPrefix: "notify_trigger" }), ); +// API-key or logged-in session trigger — exact POST /api/notify (no :token). +// The enk_... bearer is validated by apiKeyOrCookieAuth (its own 120/min per-key +// limit); the 30/min notify_trigger limit below is the second layer against spam. +notifyRoutes.use("/", apiKeyOrCookieAuth); +notifyRoutes.use( + "/", + rateLimit({ max: 30, window: 60, keyPrefix: "notify_trigger" }), +); + +notifyRoutes.post("/", async (c) => { + const userId = c.get("userId"); + return notifyByUserId(c, userId); +}); + // Third-party trigger — authenticate via token in URL, header, or query param notifyRoutes.post("/:token", async (c) => { const token = c.req.param("token"); @@ -35,6 +47,16 @@ notifyRoutes.post("/:token", async (c) => { return c.json({ error: "User not found or disabled" }, 401); } + return notifyByUserId(c, userId); +}); + +/** Shared helper: resolve the user's notification config and dispatch the message. */ +async function notifyByUserId( + c: Context, + userId: string, +): Promise { + const prefix = getTablePrefix(c.env); + const notifyConfig = await getNotificationConfig(c.env.DB, prefix, userId); if (!notifyConfig) { return c.json({ error: "No notification channels configured" }, 400); @@ -54,4 +76,4 @@ notifyRoutes.post("/:token", async (c) => { const results = await sendNotifications(notifyConfig, message, c.env); return c.json({ success: true, results }); -}); +}