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
11 changes: 9 additions & 2 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)

Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 示例适合脚本化或排查问题。

Expand All @@ -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. 查看与吊销**(同样需要登录会话)

Expand Down
34 changes: 28 additions & 6 deletions worker/src/routes/notify.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
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 {
sendNotifications,
type NotifyMessage,
} from "../services/notify/index";
import { rateLimit } from "../middleware/ratelimit";

type HonoEnv = { Bindings: Env; Variables: Record<string, any> };
import { apiKeyOrCookieAuth } from "../middleware/apiKey";

export const notifyRoutes = new Hono<HonoEnv>();

Expand All @@ -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");
Expand All @@ -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<HonoEnv>,
userId: string,
): Promise<Response> {
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);
Expand All @@ -54,4 +76,4 @@ notifyRoutes.post("/:token", async (c) => {

const results = await sendNotifications(notifyConfig, message, c.env);
return c.json({ success: true, results });
});
}
Loading