diff --git a/CLAUDE.md b/CLAUDE.md index 67b52ab..2bdaf15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,17 +52,18 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` - `dashboard.ts` — spending stats, expiry summary - `admin.ts` — user management, system settings; also manages items per user at `/api/admin/users/:uid/items` - `notify.ts` — manual notification test trigger +- `integrations.ts` — inbound third-party webhooks at `/api/integrations`; only `POST /api/integrations/vikunja/:hookToken` exists today. No session/API-key auth: the hook token locates the user's `vikunja_integrations` row and the raw body must match `X-Vikunja-Signature` (HMAC-SHA256, constant-time). Adapted events go through the default-channel `sendNotifications` path with `triggerSource: "vikunja"`. - `waker.ts` — `/_waker` mount for the waker callback receiver (SDK paths, signature and idempotency only; mounted before `app.get("*")` so a callback can never be answered with 200 HTML) - `setup.ts` — one-time DB initialization via `SETUP_SECRET` (rate-limited, 3/10min per IP); also exposes `GET /api/setup/state` (public setup-page toggle) and `POST /api/admin/setup` (admin-only, no secret). Core setup/migration logic lives in `worker/src/lib/setup.ts`. `runSetup` is a three-branch state machine after the prefix guard: ledger present → apply unrecorded migrations; no ledger but business tables present → pre-ledger in-place transition (legacy patches → shape verification → stamp `schema_v1`); neither → fresh install through the ledger. **Database** (`worker/src/db/`): - Cloudflare D1 (SQLite). `worker/src/db/schema.sql` is the readable full schema (used by tests); the runtime source of truth is the migration list below. -- **Migrations are ledger-based.** The ordered list lives in `worker/src/lib/migrations.ts` (`getMigrations(prefix)`: `schema_v1` = the whole schema at ledger introduction, `schema_v2` = notification-history `trigger_source`, `schema_v3` = `{prefix}waker_executions` + `{prefix}scheduler_tick_claims`); `worker/src/lib/migrations-runner.ts` applies the not-yet-recorded ones in order and records each name in the ledger, throwing on the first failure (a migration is recorded only after all of its statements succeeded). Append new migrations only at the END of the list as `schema_vN`; never rename, edit or reorder a merged migration; migrations must be additive (`CREATE TABLE/INDEX IF NOT EXISTS`, `ADD COLUMN`, `INSERT OR IGNORE` — no `DROP`/`RENAME`/data rewrites); migration SQL string literals must not contain `;` (the runner splits on `;` and runs the statements one by one). +- **Migrations are ledger-based.** The ordered list lives in `worker/src/lib/migrations.ts` (`getMigrations(prefix)`: `schema_v1` = the whole schema at ledger introduction, `schema_v2` = notification-history `trigger_source`, `schema_v3` = `{prefix}waker_executions` + `{prefix}scheduler_tick_claims`, `schema_v4` = `{prefix}vikunja_integrations` (one inbound Vikunja webhook integration per user, unique `hook_token`, plaintext HMAC `secret` that the management API never returns)); `worker/src/lib/migrations-runner.ts` applies the not-yet-recorded ones in order and records each name in the ledger, throwing on the first failure (a migration is recorded only after all of its statements succeeded). Append new migrations only at the END of the list as `schema_vN`; never rename, edit or reorder a merged migration; migrations must be additive (`CREATE TABLE/INDEX IF NOT EXISTS`, `ADD COLUMN`, `INSERT OR IGNORE` — no `DROP`/`RENAME`/data rewrites); migration SQL string literals must not contain `;` (the runner splits on `;` and runs the statements one by one). - The ledger table name is built only by `migrationsTable()`: `_` + prefix core (trailing `_` stripped, case preserved) + `_schema_migrations`, i.e. `_enotify_schema_migrations` for the default prefix and `_schema_migrations` with no prefix. Ledger tables are not part of the eNotify table family and are ignored by `detectTablePrefixes()` (other projects' ledgers coexist in a shared D1). - Transitioning a pre-ledger database, production cutover and rollback: `docs/migration-ledger-cutover-runbook.md`. - All table names use a `{prefix}` placeholder at definition time, resolved at runtime via `TABLE_PREFIX` env var and the `getTablePrefix()` helper in `types.ts` (the ONLY resolution point). Three states: unset/null → default `enotify` (`enotify_`); custom non-empty value → verbatim with trailing `_`; explicit `""` → no prefix. `runSetup` in `worker/src/lib/setup.ts` detects existing initialized schemas under other prefixes via `detectTablePrefixes()` and aborts with 409 `PREFIX_CONFLICT` instead of silently re-initializing; CI maps unset/empty vars to `enotify` and the reserved word `none` to `""`. -- Query functions are organized by entity in `worker/src/db/queries/`. Key entities: `items`, `payments`, `users`, `notifications` (channel config), `settings`. +- Query functions are organized by entity in `worker/src/db/queries/`. Key entities: `items`, `payments`, `users`, `notifications` (channel config), `settings`, `vikunja-integrations` (per-user hook token + HMAC secret). **Core utilities** (`worker/src/core/`): @@ -73,6 +74,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS` **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. +**Vikunja integration** (`worker/src/services/vikunja-webhook.ts` + `worker/src/routes/integrations.ts`): pure helpers — `verifyVikunjaSignature` (WebCrypto HMAC-SHA256 over the raw body, constant-time `crypto.subtle.verify`, never `===`), `buildVikunjaMessage` (three User webhook events → `NotifyMessage`, due dates formatted in the receiving user's timezone, unknown events/incomplete payloads → `null`) and `normalizeVikunjaBaseUrl`; token/secret generation reuses `generateRandomToken` from `core/apiKey.ts`. Management lives at `/api/me/integrations/vikunja` (create 201 returns the secret once, GET never returns it, PUT toggles `enabled`/`base_url`, `POST …/regenerate-secret`, DELETE 404 when absent). Inbound status codes are fixed: 404 unknown token, 403 disabled, 401 bad signature, 400 bad JSON/missing `event_name` or no default channel, 200 `{ignored:true}` for unknown events/incomplete data, 200 `{success:true,results}` once a send was attempted (60/min per hook token). **Scheduler** (`worker/src/services/scheduler.ts`): Runs hourly. For each active user it: 1. Checks their allowed notification hours (per-timezone). diff --git a/README.en.md b/README.en.md index 15287f7..7b012ad 100644 --- a/README.en.md +++ b/README.en.md @@ -26,6 +26,7 @@ A smart notification management system that helps you track expiry dates and exp - **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 +- **Vikunja Integration** — Vikunja task reminders and overdue events are pushed through the eNotify default channel and logged in the history - **Two-Factor Auth** — TOTP (authenticator app), Email OTP, Passkey - **Password Reset** — Reset password via email verification code - **Admin Panel** — User management, system settings, user impersonation @@ -175,6 +176,51 @@ curl https://your-worker.workers.dev/api/me/api-keys -H "Cookie: access_token=.. curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/ -H "Cookie: access_token=..." ``` +## Vikunja Integration (inbound webhook) + +A self-hosted [Vikunja](https://vikunja.io) instance can push task reminders and overdue events to eNotify, which fans them out through the user's default channel (the same default-channel semantics as `POST /api/notify`). Every delivery is recorded in the notification history with the source `vikunja`. + +**Apply the migration after upgrading.** The feature depends on the `{prefix}vikunja_integrations` table created by `schema_v4`: after deploying, an admin runs "Check and upgrade database" once (or `POST /api/setup` / `POST /api/admin/setup`) so the migration reaches `schema_v4`. A legacy database that the in-place transition only stamped with `schema_v1` needs one more run to apply `schema_v2`–`schema_v4`. + +**Prerequisite: enable webhooks on the Vikunja server.** The feature is controlled by the `webhooks.enabled` config option (enabled by default); if it was turned off, set `webhooks.enabled: true` in `config.yml` (or `VIKUNJA_WEBHOOKS_ENABLED=true`) and restart, then Vikunja shows the Webhooks section under the account settings. Each user creates one webhook there with the URL and secret generated below. + +**1. Create the integration** (requires a login session) + +```bash +curl -X POST https://your-worker.workers.dev/api/me/integrations/vikunja \ + -H "Content-Type: application/json" \ + -H "Cookie: access_token=" \ + -d '{"base_url": "https://vikunja.example.com"}' +``` + +`base_url` is optional and is used to build the task link `{base_url}/tasks/{task.id}` in the push (empty means no link). The `secret` in the response is shown **only once** — paste it into the Vikunja webhook's Secret field; a lost secret can only be rotated. The `hook_token` is safe to display and forms the inbound URL: + +`https://your-worker.workers.dev/api/integrations/vikunja/` + +Each user has at most one integration (a second create returns 409). Management endpoints (same session-only auth as `/api/me/api-keys`): + +| Method and path | Description | +| --- | --- | +| `POST /api/me/integrations/vikunja` | Create; 201 returns `hook_token` and the one-time `secret`; 409 if it already exists | +| `GET /api/me/integrations/vikunja` | Read; `{configured:false}` when absent, **never returns the secret** (only `secret_configured:true`) | +| `PUT /api/me/integrations/vikunja` | Update `enabled` (boolean) and `base_url` (must be `http://` or `https://`, trailing slashes trimmed, empty string clears it) | +| `POST /api/me/integrations/vikunja/regenerate-secret` | Rotate the secret, returning the new plaintext once; 404 if absent | +| `DELETE /api/me/integrations/vikunja` | Delete the integration (inbound requests then return 404); 404 if absent | + +**2. Create the webhook in Vikunja** + +- Target URL: the inbound URL above; +- Secret: the secret returned on create/rotation; +- Events: select only `task.reminder.fired` (reminder fired) and `tasks.overdue` (overdue summary). `task.overdue` overlaps with `tasks.overdue`; selecting both delivers two messages, so keep only the summary. + +**3. Inbound contract** + +- Endpoint: `POST /api/integrations/vikunja/:hookToken`. It accepts neither a session nor an API key — only the HMAC signature. +- Signature: Vikunja sends HMAC-SHA256 of the raw request body in `X-Vikunja-Signature` (lowercase hex); eNotify compares it in constant time with that integration's secret. A missing, malformed or mismatching signature always yields `401 {"error":"Invalid signature"}`. +- Events: the three adapted User webhooks events are `task.reminder.fired`, `task.overdue` and `tasks.overdue`; any other `event_name` returns 200 `{ignored:true}` without sending. +- Delivery semantics match `/api/notify`: only the default channel, 400 without a default channel and no send, no notification-hours gate, no eNotify items created, no dedupe, and the response waits for delivery (`200 {success:true, results}`). +- Status codes: unknown hookToken 404, integration disabled 403, bad signature 401, body not JSON or missing `event_name` 400, known event with incomplete data 200 `{ignored:true}` (logged only), unknown event 200 `{ignored:true}`. Rate limit: 60 requests/minute per hookToken. + ## Environment Variables ### Worker Environment Variables diff --git a/README.md b/README.md index cc97a79..123eceb 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ - **按项选择渠道** — 每个通知项可单独多选使用哪些渠道,未指定则只使用默认渠道 - **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖 - **通知历史** — 查看所有已发送通知的记录与状态 +- **Vikunja 集成** — Vikunja 的任务提醒与逾期事件经 eNotify 默认渠道推送,历史可查 - **两步验证** — TOTP(验证器应用)、邮箱验证码、Passkey - **密码重置** — 通过邮箱验证码重置密码 - **管理员后台** — 用户管理、系统设置、模拟登录 @@ -180,6 +181,51 @@ curl https://your-worker.workers.dev/api/me/api-keys -H "Cookie: access_token=.. curl -X DELETE https://your-worker.workers.dev/api/me/api-keys/ -H "Cookie: access_token=..." ``` +## Vikunja 集成(入站 webhook) + +用户自托管的 [Vikunja](https://vikunja.io) 可以把任务提醒与逾期事件推给 eNotify,由 eNotify 的默认渠道(与 `POST /api/notify` 相同的默认渠道语义)扇出;每次推送都会以来源 `vikunja` 记入通知历史。 + +**升级后先应用迁移。** 本功能依赖 `schema_v4` 新建的 `{prefix}vikunja_integrations` 表:部署新版本后,管理员需在后台执行一次「检查并升级数据库」(或调用 `POST /api/setup` / `POST /api/admin/setup`)把迁移补到 `schema_v4`。就地过渡的存量库第一次只打戳 `schema_v1`,需要再点一次补齐 `schema_v2`–`schema_v4`。 + +**前置:在 Vikunja 服务端开启 webhooks。** 该功能由配置项 `webhooks.enabled` 控制(默认开启);若实例已关闭,需在 `config.yml` 里设置 `webhooks.enabled: true`(或环境变量 `VIKUNJA_WEBHOOKS_ENABLED=true`)并重启服务,账户设置里才会出现 Webhooks 入口。每个用户在自己的 Vikunja「设置 → Webhooks」中新建 webhook,填入下面生成的地址与 secret。 + +**1. 创建集成**(需登录,cookie 会话) + +```bash +curl -X POST https://your-worker.workers.dev/api/me/integrations/vikunja \ + -H "Content-Type: application/json" \ + -H "Cookie: access_token=<登录后的 access_token>" \ + -d '{"base_url": "https://vikunja.example.com"}' +``` + +`base_url` 可选,用于拼推送里的任务链接 `{base_url}/tasks/{task.id}`(留空则不带链接)。响应中的 `secret` **只出现这一次**,请填入 Vikunja webhook 的 Secret 字段,丢失只能轮换。`hook_token` 可以回显,用来拼入站地址: + +`https://your-worker.workers.dev/api/integrations/vikunja/` + +每个用户只有一个集成(重复创建返回 409)。管理接口(鉴权与 `/api/me/api-keys` 一致,仅认登录会话): + +| 方法与路径 | 说明 | +| --- | --- | +| `POST /api/me/integrations/vikunja` | 创建;201 返回 `hook_token` 与一次性 `secret`;已存在 409 | +| `GET /api/me/integrations/vikunja` | 查询;未创建返回 `{configured:false}`,**永不返回 secret 明文**(只有 `secret_configured:true`) | +| `PUT /api/me/integrations/vikunja` | 修改 `enabled`(布尔)与 `base_url`(须 `http://` 或 `https://`,自动去尾斜杠,空串表示清空) | +| `POST /api/me/integrations/vikunja/regenerate-secret` | 轮换 secret,仅此一次返回新明文;未创建 404 | +| `DELETE /api/me/integrations/vikunja` | 删除集成;删除后入站请求返回 404;未创建 404 | + +**2. 在 Vikunja 里建 webhook** + +- Target URL:上面的入站地址; +- Secret:创建或轮换时拿到的 secret; +- 事件:只勾 `task.reminder.fired`(提醒到点)与 `tasks.overdue`(逾期汇总)。`task.overdue` 与 `tasks.overdue` 内容重叠,同时勾选会收到两条,建议只留汇总。 + +**3. 入站约定** + +- 端点:`POST /api/integrations/vikunja/:hookToken`,不使用会话或 API Key,只认 HMAC 验签。 +- 验签:Vikunja 对未解析的请求 body 计算 HMAC-SHA256,放在 `X-Vikunja-Signature` 头(hex 小写);eNotify 用该集成对应的 secret 做常量时间比对。签名头缺失、格式不合或比对失败一律 `401 {"error":"Invalid signature"}`。 +- 事件:已适配 `task.reminder.fired`、`task.overdue`、`tasks.overdue` 三个 User webhooks 事件;其他 `event_name` 返回 200 `{ignored:true}` 且不发送。 +- 发送语义与 `/api/notify` 一致:只发默认渠道;未设默认渠道返回 400 且不发送;不做通知时段门控;不创建 eNotify 事项;不去重;等发送完成才回响应(`200 {success:true, results}`)。 +- 状态码:hookToken 不存在 404、集成已停用 403、验签失败 401、body 非 JSON 或缺 `event_name` 400、已知事件但 data 缺关键字段 200 `{ignored:true}`(仅记日志)、未知事件 200 `{ignored:true}`。按 hookToken 限流 60 次/分钟。 + ## 环境变量 ### Worker 环境变量 diff --git a/docs/migration-ledger-cutover-runbook.md b/docs/migration-ledger-cutover-runbook.md index 5716454..9ed86b9 100644 --- a/docs/migration-ledger-cutover-runbook.md +++ b/docs/migration-ledger-cutover-runbook.md @@ -7,18 +7,18 @@ ## 两条路径的关系(先读这一段) - **合并即自动部署**(`main` 推送触发 deploy)。部署完成、用户执行下文切换之前,生产库处于「旧代码已下线、新代码待过渡」状态:新代码对存量库走的是**就地过渡分支**(旧补丁集最后跑一遍 → 验形 → 打戳 `schema_v1`),所以即使有人先点了「检查并升级数据库」,也只会安全打戳完成过渡,不会损坏数据。 -- 本文的 §8 完整关口(导出 → 改名 → 新装 → 恢复导入 → 验收 → 重签 Key)是当初定下的**从严路径**:它给出的是一份「干净的新 schema_v1 结构 + 官方恢复通道」的库,代价是需要重导入与重签 API Key。 +- 本文的 §8 完整关口(导出 → 改名 → 新装 → 恢复导入 → 验收 → 重签 Key)是当初定下的**从严路径**:它给出的是一份「干净的新版全量结构(`schema_v1`–`schema_v4`)+ 官方恢复通道」的库,代价是需要重导入与重签 API Key。 - **二选一由用户在关口决定**: - - 选「就地过渡」:部署后点一次「检查并升级数据库」,核对账本出现 `schema_v1` 即可收工,不动数据、不重签 Key; + - 选「就地过渡」:部署后点一次「检查并升级数据库」,核对账本出现 `schema_v1`;再点一次把 `schema_v2`–`schema_v4` 补齐(建出 waker 表与 Vikunja 集成表)即可收工,不动数据、不重签 Key; - 选「§8 完整切换」:按下面 0–7 步执行。 - 两条路径最终都是「7 张业务表 + `_enotify_schema_migrations` 账本含一条 `schema_v1`」,结构一致;区别只在于数据是怎么进新表的(就地 vs 导出再导入)。 + 两条路径最终都是「同一套业务表(含 `schema_v4` 新建的 `vikunja_integrations`)+ `_enotify_schema_migrations` 账本含 `schema_v1` 起的全部迁移」,结构一致;区别只在于数据是怎么进新表的(就地 vs 导出再导入)。 --- ## 0. 前置检查(不改动任何东西) -1. 确认已部署的版本包含本次改动:管理面板「检查并升级数据库」的返回里应带 `migrations` 字段(就地过渡会是 `[{"name":"schema_v1","status":"stamped"}]`,新装是 `applied`,之后是 `skipped`)。 +1. 确认已部署的版本包含本次改动:管理面板「检查并升级数据库」的返回里应带 `migrations` 字段(就地过渡会是 `[{"name":"schema_v1","status":"stamped"}]`,新装是 `schema_v1`–`schema_v4` 全部 `applied`,之后是 `skipped`)。 2. 记录切换前的基线数字(第 5 步要逐项对照): ```bash @@ -35,9 +35,9 @@ **核对**:文件能打开、`format`/`version` 字段存在、`users`/`items`/`notification_configs` 等条目数与第 0 步的数字对得上。 **回滚**:无(只读,不改库)。这份 JSON 是后续所有步骤的兜底。 -## 2. 把 7 张业务表逐张 RENAME 到备份命名(不直删) +## 2. 把业务表逐张 RENAME 到备份命名,并释放具名索引(不直删) -> ⚠️ **命名方式与规格 §2 的字面写法不同,原因写在这里**:`runSetup` 的前缀冲突守卫用 `detectTablePrefixes()` 识别「另一套 eNotify 表族」——只要库里存在 ≥4 张 `<前缀>_users` / `<前缀>_items` 这类命名的表且含 `users`,就会被判为另一个前缀并返回 409 `PREFIX_CONFLICT`。若把 7 张表改名成 `bak_users`、`bak_items` 这类**前缀形式**,第 3 步的新装会被守卫拦下。因此备份命名统一采用**后缀形式**:`enotify__bak_`,语义仍是「改名而不是删除」、随时可改回,但不会命中守卫的识别规则。 +> ⚠️ **命名方式与规格 §2 的字面写法不同,原因写在这里**:`runSetup` 的前缀冲突守卫用 `detectTablePrefixes()` 识别「另一套 eNotify 表族」——只要库里存在 ≥4 张 `<前缀>_users` / `<前缀>_items` 这类命名的表且含 `users`,就会被判为另一个前缀并返回 409 `PREFIX_CONFLICT`。若把业务表改名成 `bak_users`、`bak_items` 这类**前缀形式**,第 3 步的新装会被守卫拦下。因此备份命名统一采用**后缀形式**:`enotify_
_bak_`,语义仍是「改名而不是删除」、随时可改回,但不会命中守卫的识别规则。 1. 先看账本表是否存在(部署后有人点过「检查并升级数据库」就会有): @@ -53,7 +53,7 @@ "ALTER TABLE _enotify_schema_migrations RENAME TO _enotify_schema_migrations_bak_" ``` -2. 逐张改名(7 条,`` 由执行时确定并记入交付评论): +2. 逐张改名(7 张核心业务表 + 部署后可能已建的 `vikunja_integrations`,`` 由执行时确定并记入交付评论): ```bash npx wrangler d1 execute --remote --command "ALTER TABLE enotify_users RENAME TO enotify_users_bak_" @@ -65,6 +65,35 @@ npx wrangler d1 execute --remote --command "ALTER TABLE enotify_notification_history RENAME TO enotify_notification_history_bak_" ``` + 这 7 张表各自带具名二级索引,`RENAME TO` 会把索引连同**原名字**一起留在备份表上。第 3 步新装的 `CREATE INDEX IF NOT EXISTS` 见到名字已存在会静默跳过,活表就会永久缺少这些索引(`items.user_id`、`payment_history.item_id/user_id`、`notification_history.user_id/filter` 的查询都会退化为全表扫描)。所以改名后要立刻释放这 5 个规范索引名(备份表不再保留这些二级索引,行数据本身完整): + + ```bash + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_items_user_id" + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_payment_history_item_id" + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_payment_history_user_id" + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_notification_history_user_id" + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_notification_history_filter" + ``` + + 另有一张表必须单独确认:`enotify_vikunja_integrations`(本版 `schema_v4` 新建,带指向 `enotify_users` 的外键)。部署后点过「检查并升级数据库」的库才会有它;存在时必须一起改名(并按下面三条命令处理索引),否则第 3 步会因为「表已存在」跳过建表,而它的外键已经被 `RENAME TO` 改写指向备份用户表,之后新建用户的集成记录会报 `FOREIGN KEY constraint failed`。先查它是否存在: + + ```bash + npx wrangler d1 execute --remote --command \ + "SELECT name FROM sqlite_master WHERE type='table' AND name='enotify_vikunja_integrations'" + ``` + + 有返回就按顺序执行下面三条(无返回则全部跳过,第 3 步会新建): + + ```bash + npx wrangler d1 execute --remote --command "ALTER TABLE enotify_vikunja_integrations RENAME TO enotify_vikunja_integrations_bak_" + npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_vikunja_integrations_hook_token" + npx wrangler d1 execute --remote --command "CREATE UNIQUE INDEX IF NOT EXISTS idx_enotify_vikunja_integrations_bak_hook_token ON enotify_vikunja_integrations_bak_(hook_token)" + ``` + + **为什么不能只改名**:SQLite 的 `ALTER TABLE ... RENAME TO` 会把带显式名字的索引跟着表保留在原名字下,`idx_enotify_vikunja_integrations_hook_token` 会留在备份表上;第 3 步新装的 `CREATE UNIQUE INDEX IF NOT EXISTS` 见到名字已存在会**静默跳过**,活表就没有 `hook_token` 唯一约束(重复 token 能插入,入站按 token 查用户会变成不确定)。因此必须先释放规范索引名,再给备份快照另建一个改名后的唯一索引;三条命令的顺序不能调换。 + + 该表由 `schema_v4` 新建,切换前没有需要迁移的历史数据(全站档导出也不含它);如果你在切换前已经建过集成,切换完成后重新创建一次即可(新 secret 只显示一次)。 + 注意:SQLite 的 `RENAME TO` 会把其他表里指向它的外键定义一并改写到新名字,所以备份表族内部仍然自洽(改回时同样自动还原)。 **核对**: @@ -74,11 +103,25 @@ npx wrangler d1 execute --remote --command \ "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" ``` -应看到 7 张 `enotify_*_bak_`,且**没有**任何以 `users`/`user_2fa`/`items`/`payment_history`/`notification_configs`/`system_settings`/`notification_history` 结尾或等值的表名(这是第 3 步能顺利新装的关键)。 +应看到 7 张核心业务表的 `enotify_*_bak_`(若第 2 步检测到集成表,还会多一张 `enotify_vikunja_integrations_bak_`),且**没有**任何以 `users`/`user_2fa`/`items`/`payment_history`/`notification_configs`/`system_settings`/`notification_history`/`vikunja_integrations` 结尾或等值的表名(这是第 3 步能顺利新装的关键)。7 张核心业务表的备份表只保留表与行数据:它们的具名二级索引已在第 2 步被释放、不再复制;集成表的备份表则保留一个改名后的唯一索引 `idx_enotify_vikunja_integrations_bak_hook_token`。这样第 3 步才能把规范索引建到活表上,不是数据损坏。 -**回滚**:把这 7 条改回去(`ALTER TABLE enotify_users_bak_ RENAME TO enotify_users`,其余同理),并把第 1 小步挪开的账本表改回原名;然后重跑一次 setup 让它按当前真实结构决定打戳或跳过。 +**回滚**:把这批改名改回去(`ALTER TABLE enotify_users_bak_ RENAME TO enotify_users`,其余同理;若曾改过集成表,同样改回 `enotify_vikunja_integrations`)。第 2 步已把规范索引名从备份表上释放,所以改回后必须把 5 个核心二级索引和集成表的唯一索引重新建回: + +```bash +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_items_user_id ON enotify_items(user_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_payment_history_item_id ON enotify_payment_history(item_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_payment_history_user_id ON enotify_payment_history(user_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_notification_history_user_id ON enotify_notification_history(user_id, created_at)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_notification_history_filter ON enotify_notification_history(user_id, channel, success, created_at)" +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_vikunja_integrations_bak_hook_token" +npx wrangler d1 execute --remote --command "CREATE UNIQUE INDEX IF NOT EXISTS idx_enotify_vikunja_integrations_hook_token ON enotify_vikunja_integrations(hook_token)" +``` -## 3. 触发 setup,走新装路径生成 schema_v1 全量结构 + 账本 +(最后两条只适用于第 2 步检测到集成表、执行过那三条命令的库;切换前没有该表时跳过这两条,否则会报 `no such table: main.enotify_vikunja_integrations`。) + +最后把第 1 小步挪开的账本表改回原名;然后重跑一次 setup 让它按当前真实结构决定打戳或跳过。 + +## 3. 触发 setup,走新装路径生成全量结构(schema_v1–schema_v4)+ 账本 管理面板「检查并升级数据库」,或: @@ -86,16 +129,72 @@ npx wrangler d1 execute --remote --command \ curl -X POST https://<你的域名>/api/setup -H "X-Setup-Secret: " ``` -**核对**:返回 `{"success":true,"effectivePrefix":"enotify_","migrations":[{"name":"schema_v1","status":"applied"}]}`(此路径**不应**出现 `alreadyInitialized`); +**核对**:返回 `{"success":true,"effectivePrefix":"enotify_","migrations":[{"name":"schema_v1","status":"applied"},{"name":"schema_v2","status":"applied"},{"name":"schema_v3","status":"applied"},{"name":"schema_v4","status":"applied"}]}`(此路径**不应**出现 `alreadyInitialized`); ```bash npx wrangler d1 execute --remote --command \ "SELECT name FROM _enotify_schema_migrations" ``` -应只有一行 `schema_v1`;`SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'enotify_%'` 应是 7 张业务表。 +应有 `schema_v1`、`schema_v2`、`schema_v3`、`schema_v4` 四行。同一条查询里的 `SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'enotify_%'` 会同时列出第 2 步改名留下的 `enotify_*_bak_`;排除这些备份表后应正好是 10 张:7 张核心业务表 + `waker_executions` + `scheduler_tick_claims` + `vikunja_integrations`。 + +再确认活表带回了全部具名索引。5 个核心二级索引: + +```bash +npx wrangler d1 execute --remote --command \ + "SELECT name, tbl_name FROM sqlite_master WHERE type='index' AND name IN ('idx_enotify_items_user_id','idx_enotify_payment_history_item_id','idx_enotify_payment_history_user_id','idx_enotify_notification_history_user_id','idx_enotify_notification_history_filter')" +``` + +应返回 5 行,且 `tbl_name` 分别是 `enotify_items`、`enotify_payment_history`(两条)、`enotify_notification_history`(两条),不能是 `*_bak_`。 + +集成表的唯一索引(`sqlite_master` 看不出唯一性,用 `PRAGMA index_list`): + +```bash +npx wrangler d1 execute --remote --command \ + "PRAGMA index_list(enotify_vikunja_integrations)" +``` + +结果里必须有 `name = idx_enotify_vikunja_integrations_hook_token` 且 `unique = 1` 的一行。 + +**如果索引缺失**(例如第 2 步漏做了释放):重跑 setup 不会补救——`schema_v1`–`schema_v4` 已记入账本,返回全是 `skipped`,DDL 不会再执行。请在**活表**上直接重建;SQLite 的索引名是全库唯一的,若规范名仍被备份表占用,必须先释放,建完再把备份表的索引补回: + +```bash +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_vikunja_integrations_hook_token" +npx wrangler d1 execute --remote --command "CREATE UNIQUE INDEX IF NOT EXISTS idx_enotify_vikunja_integrations_hook_token ON enotify_vikunja_integrations(hook_token)" +npx wrangler d1 execute --remote --command "CREATE UNIQUE INDEX IF NOT EXISTS idx_enotify_vikunja_integrations_bak_hook_token ON enotify_vikunja_integrations_bak_(hook_token)" +``` + +5 个核心索引同理,必须**先释放名字、再建**。`CREATE INDEX IF NOT EXISTS` 的名字检查是全库的:规范名此刻还挂在备份表上,直接建会被静默跳过;带 `IF NOT EXISTS` 时不会报错,去掉它时 SQLite 的报错原文是 `index <名字> already exists`(不是「already an index with that name」)。按下面的顺序执行: + +```bash +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_items_user_id" +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_payment_history_item_id" +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_payment_history_user_id" +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_notification_history_user_id" +npx wrangler d1 execute --remote --command "DROP INDEX IF EXISTS idx_enotify_notification_history_filter" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_items_user_id ON enotify_items(user_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_payment_history_item_id ON enotify_payment_history(item_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_payment_history_user_id ON enotify_payment_history(user_id)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_notification_history_user_id ON enotify_notification_history(user_id, created_at)" +npx wrangler d1 execute --remote --command "CREATE INDEX IF NOT EXISTS idx_enotify_notification_history_filter ON enotify_notification_history(user_id, channel, success, created_at)" +``` + +若在索引缺失期间已经写入重复的 `hook_token`,先清掉重复行(`SELECT hook_token, COUNT(*) AS n FROM enotify_vikunja_integrations GROUP BY hook_token HAVING n > 1`,保留一行再删其余)再建唯一索引,否则建索引会失败。 + +**回滚**:按下面的顺序删除第 3 步新建的表(先子表、后父表,每一张都要删,否则改回备份时会重名): + +```bash +npx wrangler d1 execute --remote --command "DROP TABLE enotify_vikunja_integrations" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_user_2fa" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_notification_configs" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_payment_history" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_items" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_notification_history" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_system_settings" +npx wrangler d1 execute --remote --command "DROP TABLE enotify_users" +``` -**回滚**:把这一步新生成的 7 张空表改名或删除(`DROP TABLE enotify_users` …),把 `_enotify_schema_migrations` 改名为 `_enotify_schema_migrations_discard_`,再把第 2 步的备份表族改回原名。库即回到切换前状态(数据仍在备份表里)。 +`enotify_waker_*` 不参与本流程:切换前已有的保留原样;切换前没有的(第 3 步新建)一并 `DROP TABLE enotify_waker_executions` 与 `DROP TABLE enotify_scheduler_tick_claims`。把 `_enotify_schema_migrations` 改名为 `_enotify_schema_migrations_discard_`,再把第 2 步的备份表族改回原名(含集成表),并按第 2 步回滚的全部索引语句把 5 个核心二级索引和集成表的规范唯一索引建回。库即回到切换前状态(数据仍在备份表里)。 ## 4. 用全站档「恢复模式」导入第 1 步的 JSON @@ -117,8 +216,8 @@ npx wrangler d1 execute --remote --command \ "SELECT name, applied_at FROM _enotify_schema_migrations" ``` - 应有且仅有 `schema_v1`。 -5. 再次点「检查并升级数据库」应返回 `migrations:[{"name":"schema_v1","status":"skipped"}]`(幂等、无副作用)。 + 应有且仅有 `schema_v1`、`schema_v2`、`schema_v3`、`schema_v4` 四行。 +5. 再次点「检查并升级数据库」应返回四条 `skipped`(`schema_v1`–`schema_v4`,幂等、无副作用)。 **任一项不过**:立即执行第 3 步的回滚,把备份表族改回原名,回到切换前状态,并把失败项记入交付评论。 @@ -131,7 +230,7 @@ npx wrangler d1 execute --remote --command \ ## 7. 备份表族的去留 -`enotify_*_bak_` 与 `_enotify_schema_migrations_bak_` 在验收通过后**保留不删**,去留由用户另行决定(删掉即失去手动回退能力;如需删除,先用 `SELECT COUNT(*)` 确认新表数据完整)。 +`enotify_*_bak_` 与 `_enotify_schema_migrations_bak_` 在验收通过后**保留不删**,去留由用户另行决定(删掉即失去手动回退能力;如需删除,先用 `SELECT COUNT(*)` 确认新表数据完整)。其中 `enotify_vikunja_integrations_bak_`(仅当第 2 步检测到该表时存在)只是切换前的集成配置快照,新库的集成表已由 `schema_v4` 建出、旧 secret 不会被复用。注意它仍挂着指向 `enotify_users_bak_` 的 `ON DELETE CASCADE` 外键:一旦删除 bak 用户表,快照行会被级联清空(表还在、数据没了),所以它本就不承载需要保留的数据;需要集成时在设置页重新创建一次即可。 --- @@ -142,6 +241,6 @@ npx wrangler d1 execute --remote --command \ - 返回 `migrations:[{"name":"schema_v1","status":"stamped"}]`; - 旧补丁集最后跑一遍(补齐历史增量、清理退役渠道 ID),验形通过后写入账本一条 `schema_v1`; - 数据原地不动,无需重签 API Key; -- 之后每次升级再点一次,返回 `skipped` 或新迁移的 `applied`。 +- 打戳只记录 `schema_v1`;再点一次会把 `schema_v2`–`schema_v4` 补上(建出 waker 表与 Vikunja 集成表),返回里是它们的 `applied`,之后再点返回全部 `skipped`。 若验形失败,setup 返回 `SCHEMA_VERIFY_FAILED` 并列出缺失的表/列,**账本不会被打戳**;按错误提示修复后重试即可,旧补丁产生的增量都是幂等的、无害的。 diff --git a/worker/src/core/apiKey.ts b/worker/src/core/apiKey.ts index c8b9d4a..05a2c34 100644 --- a/worker/src/core/apiKey.ts +++ b/worker/src/core/apiKey.ts @@ -42,11 +42,20 @@ export async function sha256Hex(input: string): Promise { ).join(""); } -export function generateApiKey(): string { +/** + * High-entropy URL-safe token: 32 random bytes (256 bits) from WebCrypto, + * base64url-encoded without padding. `prefix` makes the token recognisable + * (e.g. `enk_`, `vhk_`); the randomness never comes from Math.random. + */ +export function generateRandomToken(prefix = ""): string { const bytes = crypto.getRandomValues(new Uint8Array(32)); const b64 = btoa(String.fromCharCode(...bytes)) .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); - return `${API_KEY_PREFIX}${b64}`; + return `${prefix}${b64}`; +} + +export function generateApiKey(): string { + return generateRandomToken(API_KEY_PREFIX); } diff --git a/worker/src/db/queries/vikunja-integrations.ts b/worker/src/db/queries/vikunja-integrations.ts new file mode 100644 index 0000000..d7f2ff6 --- /dev/null +++ b/worker/src/db/queries/vikunja-integrations.ts @@ -0,0 +1,105 @@ +import type { VikunjaIntegration } from "../../types"; + +/** + * Data access for `{prefix}vikunja_integrations` (schema_v4): one inbound + * Vikunja webhook integration per user, keyed by `user_id` (the `hook_token` + * is unique so a delivery can locate its owner). + * + * The plaintext `secret` deliberately lives in this table (HMAC verification + * needs the raw key); callers that build API responses must never echo it. + */ + +export type VikunjaIntegrationUpdates = Partial< + Pick +>; + +export async function getVikunjaIntegrationByToken( + db: D1Database, + prefix: string, + hookToken: string, +): Promise { + const table = `${prefix}vikunja_integrations`; + return db + .prepare(`SELECT * FROM ${table} WHERE hook_token = ?`) + .bind(hookToken) + .first(); +} + +export async function getVikunjaIntegrationByUser( + db: D1Database, + prefix: string, + userId: string, +): Promise { + const table = `${prefix}vikunja_integrations`; + return db + .prepare(`SELECT * FROM ${table} WHERE user_id = ?`) + .bind(userId) + .first(); +} + +export async function createVikunjaIntegration( + db: D1Database, + prefix: string, + data: { + user_id: string; + hook_token: string; + secret: string; + base_url?: string; + enabled?: boolean; + }, +): Promise { + const table = `${prefix}vikunja_integrations`; + const now = new Date().toISOString(); + await db + .prepare( + `INSERT INTO ${table} (user_id, hook_token, secret, base_url, enabled, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .bind( + data.user_id, + data.hook_token, + data.secret, + data.base_url ?? "", + data.enabled === false ? 0 : 1, + now, + now, + ) + .run(); +} + +export async function updateVikunjaIntegration( + db: D1Database, + prefix: string, + userId: string, + data: VikunjaIntegrationUpdates, +): Promise { + const table = `${prefix}vikunja_integrations`; + const allowedCols = new Set(["hook_token", "secret", "base_url", "enabled"]); + const entries = (Object.entries(data) as [string, unknown][]).filter( + ([col]) => allowedCols.has(col), + ); + if (entries.length === 0) return; + + const setClauses = entries.map(([col]) => `${col} = ?`).join(", "); + const values = entries.map(([, val]) => val); + + await db + .prepare( + `UPDATE ${table} SET ${setClauses}, updated_at = ? WHERE user_id = ?`, + ) + .bind(...values, new Date().toISOString(), userId) + .run(); +} + +export async function deleteVikunjaIntegration( + db: D1Database, + prefix: string, + userId: string, +): Promise { + const table = `${prefix}vikunja_integrations`; + const result = await db + .prepare(`DELETE FROM ${table} WHERE user_id = ?`) + .bind(userId) + .run(); + return result.meta.changes > 0; +} diff --git a/worker/src/db/schema.sql b/worker/src/db/schema.sql index 49f5636..9bc21cb 100644 --- a/worker/src/db/schema.sql +++ b/worker/src/db/schema.sql @@ -138,3 +138,20 @@ CREATE TABLE IF NOT EXISTS {prefix}scheduler_tick_claims ( CREATE INDEX IF NOT EXISTS idx_{prefix}scheduler_tick_claims_claimed_at ON {prefix}scheduler_tick_claims(claimed_at); + +-- Vikunja inbound webhook integration: one row per user (schema_v4). +-- The hook token only locates the user, every delivery must pass the HMAC +-- check with the secret. The secret is intentionally stored in plaintext +-- (HMAC needs the raw key), so the management API never returns it. +CREATE TABLE IF NOT EXISTS {prefix}vikunja_integrations ( + user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, + hook_token TEXT NOT NULL, + secret TEXT NOT NULL, + base_url TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_{prefix}vikunja_integrations_hook_token + ON {prefix}vikunja_integrations(hook_token); diff --git a/worker/src/index.ts b/worker/src/index.ts index d0ec057..062573d 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -13,6 +13,7 @@ import { adminRoutes } from "./routes/admin"; import { adminBackupRoutes, meBackupRoutes } from "./routes/backup"; import { notifyRoutes } from "./routes/notify"; import { setupRoutes } from "./routes/setup"; +import { integrationRoutes } from "./routes/integrations"; import { wakerRoutes } from "./routes/waker"; import { CALLBACK_MOUNT_PATH } from "./waker"; import { runSchedulerTick } from "./services/scheduler-tick"; @@ -22,7 +23,10 @@ import { isEmailConfigured } from "./services/email"; const app = new Hono(); const redactSecrets = (line: string) => - line.replace(/(\/api\/(?:setup|notify)\/)[^\s/?]+/g, "$1[redacted]"); + line.replace( + /(\/api\/(?:setup|notify|integrations\/vikunja)\/)[^\s/?]+/g, + "$1[redacted]", + ); app.use( "*", logger((line, ...rest) => console.log(redactSecrets(line), ...rest)), @@ -75,6 +79,7 @@ app.route("/api/dashboard", dashboardRoutes); app.route("/api/admin", adminRoutes); app.route("/api/notify", notifyRoutes); app.route("/api/setup", setupRoutes); +app.route("/api/integrations", integrationRoutes); app.get("/api/health", (c) => c.json({ status: "ok", timestamp: new Date().toISOString() }), diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts index 860bb8e..b44f97f 100644 --- a/worker/src/lib/migrations.ts +++ b/worker/src/lib/migrations.ts @@ -175,6 +175,24 @@ CREATE TABLE IF NOT EXISTS {prefix}scheduler_tick_claims ( CREATE INDEX IF NOT EXISTS idx_{prefix}scheduler_tick_claims_claimed_at ON {prefix}scheduler_tick_claims(claimed_at)`; +/** + * schema_v4 — Vikunja inbound webhook integration: one row per user. The hook + * token only locates the user; the per-user HMAC secret authenticates every + * delivery, so the secret is stored in plaintext (HMAC needs the raw key) and + * the management API never returns it after creation/rotation. + */ +const SCHEMA_V4 = `CREATE TABLE IF NOT EXISTS {prefix}vikunja_integrations ( + user_id TEXT PRIMARY KEY REFERENCES {prefix}users(id) ON DELETE CASCADE, + hook_token TEXT NOT NULL, + secret TEXT NOT NULL, + base_url TEXT NOT NULL DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_{prefix}vikunja_integrations_hook_token + ON {prefix}vikunja_integrations(hook_token)`; + export function getMigrations(prefix: string): Migration[] { return [ { @@ -189,5 +207,9 @@ export function getMigrations(prefix: string): Migration[] { name: "schema_v3", sql: SCHEMA_V3.replace(/\{prefix\}/g, prefix), }, + { + name: "schema_v4", + sql: SCHEMA_V4.replace(/\{prefix\}/g, prefix), + }, ]; } diff --git a/worker/src/routes/integrations.ts b/worker/src/routes/integrations.ts new file mode 100644 index 0000000..3fc0191 --- /dev/null +++ b/worker/src/routes/integrations.ts @@ -0,0 +1,125 @@ +import { Hono } from "hono"; +import { getTablePrefix } from "../types"; +import type { HonoEnv } from "../types"; +import { getVikunjaIntegrationByToken } from "../db/queries/vikunja-integrations"; +import { findUserById } from "../db/queries/users"; +import { getNotificationConfig } from "../db/queries/notifications"; +import { sendNotifications } from "../services/notify/index"; +import { + VIKUNJA_SIGNATURE_HEADER, + buildVikunjaMessage, + isVikunjaEventName, + verifyVikunjaSignature, +} from "../services/vikunja-webhook"; +import { rateLimit } from "../middleware/ratelimit"; + +/** + * Inbound integration endpoints. Deliberately NOT behind session auth or + * `apiKeyOrCookieAuth`: Vikunja can only send its own HMAC-signed payload. + * + * `POST /api/integrations/vikunja/:hookToken` + * limit → look up the token → enabled → read the raw body once → verify the + * HMAC → parse JSON → map the event → user/config → `sendNotifications` + * (no channels: the #154 default-channel semantics apply, no + * notification_hours gate, no items, no dedupe) → respond after sending. + */ +export const integrationRoutes = new Hono(); + +const VIKUNJA_WEBHOOK_PATH = "/vikunja/:hookToken"; + +integrationRoutes.use( + VIKUNJA_WEBHOOK_PATH, + rateLimit({ + max: 60, + window: 60, + keyPrefix: "vikunja_webhook", + keyFn: (c) => c.req.param("hookToken") || "unknown", + }), +); + +integrationRoutes.post(VIKUNJA_WEBHOOK_PATH, async (c) => { + const prefix = getTablePrefix(c.env); + const hookToken = c.req.param("hookToken"); + + const integration = await getVikunjaIntegrationByToken( + c.env.DB, + prefix, + hookToken, + ); + if (!integration) return c.json({ error: "Not found" }, 404); + if (!integration.enabled) { + return c.json({ error: "Integration disabled" }, 403); + } + + // The signature covers the exact bytes Vikunja sent, so the body is read + // once as text and that same string is both verified and parsed. + const rawBody = await c.req.text(); + const signature = c.req.header(VIKUNJA_SIGNATURE_HEADER); + if (!(await verifyVikunjaSignature(integration.secret, signature, rawBody))) { + return c.json({ error: "Invalid signature" }, 401); + } + + let payload: Record; + try { + const parsed: unknown = JSON.parse(rawBody); + if ( + parsed === null || + typeof parsed !== "object" || + Array.isArray(parsed) + ) { + return c.json({ error: "Invalid payload" }, 400); + } + payload = parsed as Record; + } catch { + return c.json({ error: "Invalid JSON" }, 400); + } + + const eventName = payload.event_name; + if (typeof eventName !== "string" || eventName === "") { + return c.json({ error: "Missing event_name" }, 400); + } + // Unknown events are ignored (forward compatible), not an error. + if (!isVikunjaEventName(eventName)) return c.json({ ignored: true }); + + const user = await findUserById(c.env.DB, prefix, integration.user_id); + // A deleted/disabled owner is answered like an unknown token, so the + // endpoint never reveals which half of the lookup failed. + if (!user?.is_active) return c.json({ error: "Not found" }, 404); + + const message = buildVikunjaMessage( + eventName, + payload.data, + integration.base_url, + user.timezone || "UTC", + ); + if (message === null) { + // Vikunja never retries, so a malformed known event is only logged. + console.error( + `[vikunja] ignored ${eventName} for user ${user.id}: incomplete payload data`, + ); + return c.json({ ignored: true }); + } + + const config = await getNotificationConfig(c.env.DB, prefix, user.id); + if (!config) { + return c.json({ error: "No notification channels configured" }, 400); + } + + try { + const results = await sendNotifications(config, message, c.env, { + db: c.env.DB, + prefix, + userId: user.id, + itemId: null, + triggerSource: "vikunja", + }); + return c.json({ success: true, results }); + } catch (err) { + // Config-class failures (no default channel, default not enabled, …) are + // reported verbatim, same as POST /api/notify. + return c.json( + { error: err instanceof Error ? err.message : String(err) }, + 400, + ); + } +}); diff --git a/worker/src/routes/me.ts b/worker/src/routes/me.ts index 9c216f3..5775b52 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; +import type { Context } from "hono"; import { getTablePrefix, VALID_CHANNELS } from "../types"; -import type { HonoEnv, JWTPayload } from "../types"; +import type { HonoEnv, JWTPayload, VikunjaIntegration } from "../types"; import { authMiddleware, getEffectiveUserId } from "../middleware/auth"; import { rateLimit } from "../middleware/ratelimit"; import { findUserById, updateUser } from "../db/queries/users"; @@ -42,6 +43,17 @@ import { sha256Hex, } from "../core/apiKey"; import { sendToChannel, type NotifyMessage } from "../services/notify/index"; +import { + generateVikunjaHookToken, + generateVikunjaSecret, + normalizeVikunjaBaseUrl, +} from "../services/vikunja-webhook"; +import { + createVikunjaIntegration, + deleteVikunjaIntegration, + getVikunjaIntegrationByUser, + updateVikunjaIntegration, +} from "../db/queries/vikunja-integrations"; import { getCookie, setCookie } from "hono/cookie"; export const meRoutes = new Hono(); @@ -607,6 +619,155 @@ meRoutes.delete("/api-keys/:id", async (c) => { return c.json({ success: true }); }); +// ── Vikunja integration ─────────────────────────────────────────────────── + +const VIKUNJA_PATH = "/integrations/vikunja"; + +/** Read a JSON object body; an empty body is `{}`, malformed JSON is null. */ +async function readOptionalJsonObject( + c: Context, +): Promise | null> { + const raw = await c.req.text(); + if (raw.trim() === "") return {}; + try { + const parsed: unknown = JSON.parse(raw); + if ( + parsed === null || + typeof parsed !== "object" || + Array.isArray(parsed) + ) { + return null; + } + return parsed as Record; + } catch { + return null; + } +} + +/** Public view of the integration: the secret is never included. */ +function vikunjaIntegrationJson(row: VikunjaIntegration) { + return { + configured: true, + hook_token: row.hook_token, + base_url: row.base_url ?? "", + enabled: !!row.enabled, + secret_configured: true, + created_at: row.created_at, + updated_at: row.updated_at, + }; +} + +meRoutes.get(VIKUNJA_PATH, async (c) => { + const userId = getEffectiveUserId(c); + const prefix = getTablePrefix(c.env); + const row = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (!row) return c.json({ configured: false }); + return c.json(vikunjaIntegrationJson(row)); +}); + +meRoutes.post(VIKUNJA_PATH, async (c) => { + const userId = getEffectiveUserId(c); + const prefix = getTablePrefix(c.env); + const body = await readOptionalJsonObject(c); + if (body === null) return c.json({ error: "Invalid JSON" }, 400); + + let baseUrl = ""; + if (body.base_url !== undefined) { + const normalized = normalizeVikunjaBaseUrl(body.base_url); + if (normalized === null) return c.json({ error: "Invalid base_url" }, 400); + baseUrl = normalized; + } + + const existing = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (existing) { + return c.json({ error: "Integration already exists" }, 409); + } + + const hookToken = generateVikunjaHookToken(); + const secret = generateVikunjaSecret(); + try { + await createVikunjaIntegration(c.env.DB, prefix, { + user_id: userId, + hook_token: hookToken, + secret, + base_url: baseUrl, + }); + } catch (err) { + // Two concurrent creates: the primary key decides, the loser sees 409. + const raced = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (raced) return c.json({ error: "Integration already exists" }, 409); + throw err; + } + + // The plaintext secret is only ever returned here (and on rotation). The + // rest of the body is the same view GET returns, so a client can treat the + // create result as a cached read. + const created = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (created) { + return c.json({ ...vikunjaIntegrationJson(created), secret }, 201); + } + return c.json( + { hook_token: hookToken, secret, base_url: baseUrl, enabled: true }, + 201, + ); +}); + +meRoutes.put(VIKUNJA_PATH, async (c) => { + const userId = getEffectiveUserId(c); + const prefix = getTablePrefix(c.env); + const existing = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (!existing) return c.json({ error: "Not found" }, 404); + + const body = await readOptionalJsonObject(c); + if (body === null) return c.json({ error: "Invalid JSON" }, 400); + + const updates: { enabled?: number; base_url?: string } = {}; + if (body.enabled !== undefined) { + if (typeof body.enabled !== "boolean") { + return c.json({ error: "enabled must be a boolean" }, 400); + } + updates.enabled = body.enabled ? 1 : 0; + } + if (body.base_url !== undefined) { + const normalized = normalizeVikunjaBaseUrl(body.base_url); + if (normalized === null) return c.json({ error: "Invalid base_url" }, 400); + updates.base_url = normalized; + } + if (Object.keys(updates).length === 0) { + return c.json({ error: "No valid fields to update" }, 400); + } + + await updateVikunjaIntegration(c.env.DB, prefix, userId, updates); + return c.json({ + success: true, + enabled: + updates.enabled === undefined + ? !!existing.enabled + : updates.enabled === 1, + base_url: updates.base_url ?? existing.base_url ?? "", + }); +}); + +meRoutes.post(`${VIKUNJA_PATH}/regenerate-secret`, async (c) => { + const userId = getEffectiveUserId(c); + const prefix = getTablePrefix(c.env); + const existing = await getVikunjaIntegrationByUser(c.env.DB, prefix, userId); + if (!existing) return c.json({ error: "Not found" }, 404); + + const secret = generateVikunjaSecret(); + await updateVikunjaIntegration(c.env.DB, prefix, userId, { secret }); + // Rotation is the only other time the plaintext secret leaves the server. + return c.json({ secret }); +}); + +meRoutes.delete(VIKUNJA_PATH, async (c) => { + const userId = getEffectiveUserId(c); + const prefix = getTablePrefix(c.env); + const deleted = await deleteVikunjaIntegration(c.env.DB, prefix, userId); + if (!deleted) return c.json({ error: "Not found" }, 404); + return c.json({ success: true }); +}); + // ── Sessions ────────────────────────────────────────────────────────────── meRoutes.get("/sessions", async (c) => { diff --git a/worker/src/services/vikunja-webhook.ts b/worker/src/services/vikunja-webhook.ts new file mode 100644 index 0000000..a085471 --- /dev/null +++ b/worker/src/services/vikunja-webhook.ts @@ -0,0 +1,274 @@ +import { generateRandomToken } from "../core/apiKey"; +import type { NotifyMessage } from "./notify/index"; + +/** + * Vikunja inbound webhook adaptation (pure logic, unit tested on its own). + * + * Vikunja delivers `POST {event_name, time, data}` with an + * `X-Vikunja-Signature` header: the lowercase hex HMAC-SHA256 of the raw + * request body, keyed with the webhook secret the user configured in Vikunja. + * The route only reads the raw body once and verifies that exact string, so + * re-serialising the JSON can never break the signature. + */ + +export const VIKUNJA_HOOK_TOKEN_PREFIX = "vhk_"; +export const VIKUNJA_SIGNATURE_HEADER = "X-Vikunja-Signature"; + +/** User webhooks events eNotify adapts; everything else is ignored (200). */ +export const VIKUNJA_EVENT_NAMES = [ + "task.reminder.fired", + "task.overdue", + "tasks.overdue", +] as const; + +export type VikunjaEventName = (typeof VIKUNJA_EVENT_NAMES)[number]; + +/** `tasks.overdue` renders one line per task, at most 10 lines in total. */ +export const VIKUNJA_SUMMARY_MAX_LINES = 10; + +export function isVikunjaEventName(value: string): value is VikunjaEventName { + return (VIKUNJA_EVENT_NAMES as readonly string[]).includes(value); +} + +/** Hook token: high-entropy locator, safe to display and paste into Vikunja. */ +export function generateVikunjaHookToken(): string { + return generateRandomToken(VIKUNJA_HOOK_TOKEN_PREFIX); +} + +/** Webhook secret: raw HMAC key material, shown to the user only once. */ +export function generateVikunjaSecret(): string { + return generateRandomToken(); +} + +const encoder = new TextEncoder(); + +function hexToBytes(hex: string): Uint8Array | null { + if (hex.length === 0 || hex.length % 2 !== 0) return null; + const bytes = new Uint8Array(hex.length / 2); + for (let index = 0; index < bytes.length; index += 1) { + const byte = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16); + if (Number.isNaN(byte)) return null; + bytes[index] = byte; + } + return bytes; +} + +/** + * Constant-time HMAC-SHA256 check of `X-Vikunja-Signature` against the raw + * request body. Uses WebCrypto's `verify` (never `===` on signature strings), + * and rejects anything that is not exactly 64 hex characters (32 bytes). + */ +export async function verifyVikunjaSignature( + secret: string, + signatureHeader: string | null | undefined, + rawBody: string, +): Promise { + if (!secret || !signatureHeader) return false; + + const provided = signatureHeader.trim(); + if (!/^[0-9a-fA-F]{64}$/.test(provided)) return false; + const signature = hexToBytes(provided); + if (signature === null || signature.length !== 32) return false; + + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["verify"], + ); + return crypto.subtle.verify("HMAC", key, signature, encoder.encode(rawBody)); +} + +/** + * Normalise a user-supplied Vikunja base URL: `http(s)` only, no trailing + * slash, `""` means "no link". Returns null when the value is unusable. + */ +export function normalizeVikunjaBaseUrl(value: unknown): string | null { + if (typeof value !== "string") return null; + const trimmed = value.trim().replace(/\/+$/, ""); + if (trimmed === "") return ""; + if (!/^https?:\/\//i.test(trimmed)) return null; + try { + const url = new URL(trimmed); + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + } catch { + return null; + } + return trimmed; +} + +function asRecord(value: unknown): Record | null { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + return null; + } + return value as Record; +} + +function trimmedString(value: unknown): string { + return typeof value === "string" ? value.trim() : ""; +} + +/** Vikunja uses numbers for ids; accept a non-empty numeric string too. */ +function idString(value: unknown): string | null { + if (typeof value === "number" && Number.isFinite(value)) return String(value); + if (typeof value === "string" && value.trim() !== "") return value.trim(); + return null; +} + +function parseDueDate(dueDate: unknown): Date | null { + if (typeof dueDate !== "string") return null; + const raw = dueDate.trim(); + // Go's zero time is what Vikunja sends for "no due date". + if (raw === "" || raw.startsWith("0001-01-01")) return null; + const date = new Date(raw); + if (Number.isNaN(date.getTime())) return null; + if (date.getUTCFullYear() <= 1) return null; + return date; +} + +/** + * `due_date` in the receiving user's timezone as `YYYY-MM-DD HH:mm`; null for + * the zero value / invalid input so the 截止 line is simply omitted. + */ +export function formatVikunjaDue( + dueDate: unknown, + timeZone: string, +): string | null { + const date = parseDueDate(dueDate); + if (date === null) return null; + + const options: Intl.DateTimeFormatOptions = { + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }; + const zone = + typeof timeZone === "string" && timeZone.trim() !== "" + ? timeZone.trim() + : "UTC"; + + let parts: Intl.DateTimeFormatPart[]; + try { + parts = new Intl.DateTimeFormat("en-CA", { + ...options, + timeZone: zone, + }).formatToParts(date); + } catch { + // A stored timezone can only be invalid if it predates validation; never + // fail a delivery over it, fall back to UTC. + parts = new Intl.DateTimeFormat("en-CA", { + ...options, + timeZone: "UTC", + }).formatToParts(date); + } + + const get = (type: string): string => + parts.find((part) => part.type === type)?.value ?? ""; + const year = get("year"); + const month = get("month"); + const day = get("day"); + const hour = get("hour"); + const minute = get("minute"); + if (!year || !month || !day || !hour || !minute) return null; + return `${year}-${month}-${day} ${hour}:${minute}`; +} + +function projectTitle( + projects: Record, + projectId: unknown, +): string { + const key = idString(projectId); + if (key === null) return ""; + return trimmedString(asRecord(projects[key])?.title); +} + +function buildSingleTaskMessage( + eventName: "task.reminder.fired" | "task.overdue", + data: Record, + baseUrl: string, + timeZone: string, +): NotifyMessage | null { + const task = asRecord(data.task); + if (task === null) return null; + const taskId = idString(task.id); + const title = trimmedString(task.title); + if (taskId === null || title === "") return null; + + const bodyLines = [`项目:${trimmedString(asRecord(data.project)?.title)}`]; + const due = formatVikunjaDue(task.due_date, timeZone); + if (due !== null) bodyLines.push(`截止:${due}`); + + return { + title: + eventName === "task.reminder.fired" + ? `⏰ ${title}` + : `⚠️ 已逾期:${title}`, + body: bodyLines.join("\n"), + url: baseUrl === "" ? undefined : `${baseUrl}/tasks/${taskId}`, + }; +} + +function buildOverdueSummary( + data: Record, + baseUrl: string, +): NotifyMessage | null { + const rawTasks = data.tasks; + if (!Array.isArray(rawTasks) || rawTasks.length === 0) return null; + + const projects = asRecord(data.projects) ?? {}; + const total = rawTasks.length; + const truncated = total > VIKUNJA_SUMMARY_MAX_LINES; + const visible = truncated + ? VIKUNJA_SUMMARY_MAX_LINES - 1 + : VIKUNJA_SUMMARY_MAX_LINES; + + const lines: string[] = []; + for (const rawTask of rawTasks.slice(0, visible)) { + const task = asRecord(rawTask); + const title = trimmedString(task?.title); + if (title === "") continue; + const project = projectTitle(projects, task?.project_id); + lines.push(project === "" ? `· ${title}` : `· ${title}(${project})`); + } + // A summary whose task entries are all malformed has nothing to show. + if (lines.length === 0 && !truncated) return null; + if (truncated) lines.push(`… 等共 ${total} 个`); + + return { + title: `⚠️ ${total} 个任务已逾期`, + body: lines.join("\n"), + url: baseUrl === "" ? undefined : baseUrl, + }; +} + +/** + * Translate a Vikunja User webhook event into the eNotify message shape. + * Returns null for unknown events and for known events whose payload is too + * incomplete to describe (the route answers 200 `{ignored: true}` then). + */ +export function buildVikunjaMessage( + eventName: string, + data: unknown, + baseUrl: string | null | undefined, + timeZone: string, +): NotifyMessage | null { + if (!isVikunjaEventName(eventName)) return null; + const payload = asRecord(data); + if (payload === null) return null; + + const normalizedBaseUrl = normalizeVikunjaBaseUrl(baseUrl) ?? ""; + + if (eventName === "tasks.overdue") { + return buildOverdueSummary(payload, normalizedBaseUrl); + } + return buildSingleTaskMessage( + eventName, + payload, + normalizedBaseUrl, + timeZone, + ); +} diff --git a/worker/src/types.ts b/worker/src/types.ts index 3684480..6f2f9a7 100644 --- a/worker/src/types.ts +++ b/worker/src/types.ts @@ -105,6 +105,23 @@ export interface NotificationConfig { updated_at: string; } +/** + * One inbound Vikunja webhook integration per user (table + * `{prefix}vikunja_integrations`). `hook_token` only locates the user; every + * delivery must still pass the HMAC check with `secret`. The secret is stored + * in plaintext because HMAC needs the raw key material — the management API + * therefore never returns it after creation/rotation. + */ +export interface VikunjaIntegration { + user_id: string; + hook_token: string; + secret: string; + base_url: string; + enabled: number; + created_at: string; + updated_at: string; +} + export interface SystemSetting { key: string; value: string; diff --git a/worker/test/admin.test.ts b/worker/test/admin.test.ts index 0ceefb5..da82c7e 100644 --- a/worker/test/admin.test.ts +++ b/worker/test/admin.test.ts @@ -31,6 +31,7 @@ describe("POST /api/admin/setup", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -120,6 +121,7 @@ describe("POST /api/admin/setup", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); }); diff --git a/worker/test/ledger.test.ts b/worker/test/ledger.test.ts index ce779de..dad295d 100644 --- a/worker/test/ledger.test.ts +++ b/worker/test/ledger.test.ts @@ -280,12 +280,13 @@ describe("migrationsTable name formula", () => { }); describe("migration list", () => { - it("keeps schema_v1 as the base and appends schema_v2 / schema_v3", () => { + it("keeps schema_v1 as the base and appends schema_v2 / schema_v3 / schema_v4", () => { const migrations = getMigrations("enotify_"); expect(migrations.map((m) => m.name)).toEqual([ "schema_v1", "schema_v2", "schema_v3", + "schema_v4", ]); // `{prefix}` is resolved for the caller, the DDL itself carries no placeholder. expect(migrations[0].sql).toContain( @@ -306,6 +307,13 @@ describe("migration list", () => { "CREATE INDEX IF NOT EXISTS idx_enotify_scheduler_tick_claims_claimed_at", ); expect(migrations[2].sql).not.toContain("{prefix}"); + expect(migrations[3].sql).toContain( + "CREATE TABLE IF NOT EXISTS enotify_vikunja_integrations", + ); + expect(migrations[3].sql).toContain( + "CREATE UNIQUE INDEX IF NOT EXISTS idx_enotify_vikunja_integrations_hook_token", + ); + expect(migrations[3].sql).not.toContain("{prefix}"); }); it("migration SQL contains no ';' inside string literals", () => { @@ -323,7 +331,7 @@ describe("migration list", () => { // ─── fresh install ──────────────────────────────────────────────────────────── describe("fresh install through the ledger", () => { - it("creates the 7 business tables, the 2 waker tables, the ledger and the default settings", async () => { + it("creates the 7 business tables, the waker and Vikunja tables, the ledger and the default settings", async () => { const d1 = new SqliteD1(); const result = await runSetup(makeEnv(d1, "enotify")); @@ -335,6 +343,7 @@ describe("fresh install through the ledger", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -349,6 +358,7 @@ describe("fresh install through the ledger", () => { "notification_history", "waker_executions", "scheduler_tick_claims", + "vikunja_integrations", ]) { expect(tables).toContain(`enotify_${table}`); } @@ -357,6 +367,7 @@ describe("fresh install through the ledger", () => { { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); expect( indexesOf(d1, "enotify_scheduler_tick_claims").map((i) => i.name), @@ -379,6 +390,9 @@ describe("fresh install through the ledger", () => { expect( indexesOf(d1, "enotify_notification_history").map((i) => i.name), ).toContain("idx_enotify_notification_history_filter"); + expect( + indexesOf(d1, "enotify_vikunja_integrations").map((i) => i.name), + ).toContain("idx_enotify_vikunja_integrations_hook_token"); const settings = rowsOf(d1, "enotify_system_settings", "key").map( (r) => r.key, @@ -409,6 +423,7 @@ describe("fresh install through the ledger", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, ], }); expect(snapshot(d1)).toEqual(before); @@ -590,6 +605,7 @@ describe("legacy database transition", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -603,6 +619,7 @@ describe("legacy database transition", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, ], }); expect(snapshot(d1)).toEqual(afterSecond); @@ -736,12 +753,14 @@ describe("ledger consistency check", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); expect(ledgerRows(d1, "_schema_migrations")).toEqual([ { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); expect(exists(d1, "users")).toBe(true); }); @@ -760,6 +779,7 @@ describe("prefix variants", () => { { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); expect(exists(d1, "enotify_users")).toBe(true); expect(exists(d1, "enotify_waker_executions")).toBe(true); @@ -775,6 +795,7 @@ describe("prefix variants", () => { { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); expect(exists(d1, "users")).toBe(true); expect(exists(d1, "waker_executions")).toBe(true); @@ -790,6 +811,7 @@ describe("prefix variants", () => { { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); expect(exists(d1, "X_users")).toBe(true); expect(exists(d1, "X_waker_executions")).toBe(true); @@ -862,6 +884,7 @@ describe("prefix conflict guard with the ledger", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); // The foreign ledger is neither read nor written. @@ -870,6 +893,7 @@ describe("prefix conflict guard with the ledger", () => { { name: "schema_v1" }, { name: "schema_v2" }, { name: "schema_v3" }, + { name: "schema_v4" }, ]); }); diff --git a/worker/test/migrations.test.ts b/worker/test/migrations.test.ts index 89f16e8..d54d676 100644 --- a/worker/test/migrations.test.ts +++ b/worker/test/migrations.test.ts @@ -1,4 +1,10 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { getMigrations } from "../src/lib/migrations"; +import { + ensureLedgerTable, + recordMigration, + splitStatements, +} from "../src/lib/migrations-runner"; import { runSetup } from "../src/lib/setup"; import { sendNotifications } from "../src/services/notify/index"; import type { Env, NotificationConfig } from "../src/types"; @@ -235,6 +241,7 @@ describe("notification_configs slack_config migration", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -243,6 +250,7 @@ describe("notification_configs slack_config migration", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, ]); const rows = d1.db @@ -419,6 +427,7 @@ describe("retired channel cleanup migration", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -427,6 +436,7 @@ describe("retired channel cleanup migration", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, ]); expect(enabledChannelsOf(d1, "u1")).toBe('["telegram"]'); @@ -487,6 +497,7 @@ describe("fresh install schema", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -504,3 +515,198 @@ describe("fresh install schema", () => { expect(names).toContain("discord_config"); }); }); + +// ─── Vikunja integration (schema_v4) ───────────────────────────────────────── + +const VIKUNJA_TABLE = `${PREFIX}vikunja_integrations`; +const VIKUNJA_INDEX = `idx_${PREFIX}vikunja_integrations_hook_token`; + +function hasTable(d1: SqliteD1, name: string): boolean { + return ( + d1.db + .prepare( + `SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, + ) + .get(name) !== undefined + ); +} + +function indexInfo( + d1: SqliteD1, + table: string, +): { name: string; unique: number }[] { + return d1.db.prepare(`PRAGMA index_list(${table})`).all() as { + name: string; + unique: number; + }[]; +} + +/** + * Apply only the named migrations — real DDL plus real ledger rows — which is + * exactly the state a database left behind by an older release is in. + */ +async function applyMigrationsOnly( + d1: SqliteD1, + names: string[], +): Promise { + const db = d1 as unknown as D1Database; + await ensureLedgerTable(db, PREFIX); + const wanted = getMigrations(PREFIX).filter((m) => names.includes(m.name)); + for (const migration of wanted) { + for (const statement of splitStatements(migration.sql)) { + d1.db.exec(statement); + } + await recordMigration(db, PREFIX, migration.name); + } +} + +function seedVikunjaUserRow(d1: SqliteD1, id: string): void { + d1.db + .prepare( + `INSERT INTO ${PREFIX}users (id, email, password_hash, created_at, updated_at) + VALUES (?, ?, 'hash', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`, + ) + .run(id, `${id}@example.com`); +} + +function seedVikunjaRow(d1: SqliteD1, userId: string, hookToken: string): void { + d1.db + .prepare( + `INSERT INTO ${VIKUNJA_TABLE} + (user_id, hook_token, secret, base_url, enabled, created_at, updated_at) + VALUES (?, ?, 'secret-value', 'https://vikunja.example.com', 1, ?, ?)`, + ) + .run( + userId, + hookToken, + "2026-01-01T00:00:00.000Z", + "2026-01-01T00:00:00.000Z", + ); +} + +describe("vikunja_integrations migration (schema_v4)", () => { + it("creates the table and the unique hook_token index on a fresh install", async () => { + const d1 = new SqliteD1(); + + const result = await runSetup(makeEnv(d1)); + expect(result).toEqual({ + success: true, + effectivePrefix: "en_", + migrations: [ + { name: "schema_v1", status: "applied" }, + { name: "schema_v2", status: "applied" }, + { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, + ], + }); + + expect(hasTable(d1, VIKUNJA_TABLE)).toBe(true); + const columns = d1.db + .prepare(`PRAGMA table_info(${VIKUNJA_TABLE})`) + .all() as ColumnInfo[]; + expect(columns.map((c) => c.name)).toEqual([ + "user_id", + "hook_token", + "secret", + "base_url", + "enabled", + "created_at", + "updated_at", + ]); + const hookTokenIndex = indexInfo(d1, VIKUNJA_TABLE).find( + (index) => index.name === VIKUNJA_INDEX, + ); + expect(hookTokenIndex).toMatchObject({ unique: 1 }); + }); + + it("enforces the unique hook token", async () => { + const d1 = new SqliteD1(); + await runSetup(makeEnv(d1)); + seedVikunjaUserRow(d1, "u1"); + seedVikunjaUserRow(d1, "u2"); + seedVikunjaRow(d1, "u1", "vhk_one"); + + expect(() => seedVikunjaRow(d1, "u2", "vhk_one")).toThrow(/UNIQUE/); + expect( + d1.db.prepare(`SELECT COUNT(*) AS count FROM ${VIKUNJA_TABLE}`).get(), + ).toEqual({ count: 1 }); + }); + + it("upgrades a v3 database in place, keeps its data and is idempotent", async () => { + const d1 = new SqliteD1(); + await applyMigrationsOnly(d1, ["schema_v1", "schema_v2", "schema_v3"]); + seedVikunjaUserRow(d1, "u1"); + d1.db + .prepare( + `INSERT INTO ${PREFIX}notification_configs + (user_id, enabled_channels, default_channel, updated_at) + VALUES ('u1', '["telegram"]', 'telegram', '2026-01-01T00:00:00.000Z')`, + ) + .run(); + expect(hasTable(d1, VIKUNJA_TABLE)).toBe(false); + + const upgraded = await runSetup(makeEnv(d1)); + expect(upgraded).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "en_", + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "applied" }, + ], + }); + expect(hasTable(d1, VIKUNJA_TABLE)).toBe(true); + expect( + indexInfo(d1, VIKUNJA_TABLE).some( + (index) => index.name === VIKUNJA_INDEX && index.unique === 1, + ), + ).toBe(true); + // Pre-existing rows survive the upgrade untouched. + expect( + d1.db + .prepare(`SELECT id, email FROM ${PREFIX}users WHERE id = 'u1'`) + .get(), + ).toEqual({ id: "u1", email: "u1@example.com" }); + expect( + d1.db + .prepare( + `SELECT enabled_channels, default_channel FROM ${PREFIX}notification_configs WHERE user_id = 'u1'`, + ) + .get(), + ).toEqual({ + enabled_channels: '["telegram"]', + default_channel: "telegram", + }); + + seedVikunjaRow(d1, "u1", "vhk_upgrade"); + + const second = await runSetup(makeEnv(d1)); + expect(second).toEqual({ + success: true, + alreadyInitialized: true, + effectivePrefix: "en_", + migrations: [ + { name: "schema_v1", status: "skipped" }, + { name: "schema_v2", status: "skipped" }, + { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, + ], + }); + expect( + d1.db + .prepare( + `SELECT user_id, hook_token, base_url, enabled FROM ${VIKUNJA_TABLE}`, + ) + .all(), + ).toEqual([ + { + user_id: "u1", + hook_token: "vhk_upgrade", + base_url: "https://vikunja.example.com", + enabled: 1, + }, + ]); + }); +}); diff --git a/worker/test/prefix.test.ts b/worker/test/prefix.test.ts index 0ffebbc..7efd582 100644 --- a/worker/test/prefix.test.ts +++ b/worker/test/prefix.test.ts @@ -239,6 +239,7 @@ describe("runSetup anti-silent-switch guard", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -267,6 +268,7 @@ describe("runSetup anti-silent-switch guard", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -315,6 +317,7 @@ describe("admin setup route surfaces prefix conflicts", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); }); diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts index 511cda4..bdfe73d 100644 --- a/worker/test/setup.test.ts +++ b/worker/test/setup.test.ts @@ -167,6 +167,7 @@ describe("POST /api/setup (regression)", () => { { name: "schema_v1", status: "applied" }, { name: "schema_v2", status: "applied" }, { name: "schema_v3", status: "applied" }, + { name: "schema_v4", status: "applied" }, ], }); @@ -176,6 +177,7 @@ describe("POST /api/setup (regression)", () => { "schema_v1", "schema_v2", "schema_v3", + "schema_v4", ]); }); @@ -200,6 +202,7 @@ describe("POST /api/setup (regression)", () => { { name: "schema_v1", status: "skipped" }, { name: "schema_v2", status: "skipped" }, { name: "schema_v3", status: "skipped" }, + { name: "schema_v4", status: "skipped" }, ], }); }); diff --git a/worker/test/support/vikunja.ts b/worker/test/support/vikunja.ts new file mode 100644 index 0000000..5633470 --- /dev/null +++ b/worker/test/support/vikunja.ts @@ -0,0 +1,155 @@ +import { runSetup } from "../../src/lib/setup"; +import type { Env } from "../../src/types"; +import { MockKV, TEST_JWT_SECRET, TEST_SETUP_SECRET } from "../helpers"; +import { SqliteD1 } from "./sqlite-d1"; + +/** Prefix used by every Vikunja integration test ("en" → tables `en_*`). */ +export const VIKUNJA_PREFIX = "en_"; +export const VIKUNJA_USER_ID = "u-1"; + +const encoder = new TextEncoder(); + +export function makeVikunjaEnv(d1: SqliteD1): Env { + return { + DB: d1, + KV: new MockKV(), + JWT_SECRET: TEST_JWT_SECRET, + SETUP_SECRET: TEST_SETUP_SECRET, + TABLE_PREFIX: "en", + ASSETS: {}, + } as unknown as Env; +} + +/** Fresh database through the real migration runner. */ +export async function setupVikunjaDb(): Promise<{ + d1: SqliteD1; + env: Env; +}> { + const d1 = new SqliteD1(); + const env = makeVikunjaEnv(d1); + const result = await runSetup(env); + if (!result.success) throw new Error("setup failed"); + return { d1, env }; +} + +export function seedVikunjaUser( + d1: SqliteD1, + opts: { userId?: string; timezone?: string; isActive?: boolean } = {}, +): string { + const userId = opts.userId ?? VIKUNJA_USER_ID; + const now = "2026-01-01T00:00:00.000Z"; + d1.db + .prepare( + `INSERT INTO ${VIKUNJA_PREFIX}users + (id, email, password_hash, is_active, timezone, created_at, updated_at) + VALUES (?, ?, 'hash', ?, ?, ?, ?)`, + ) + .run( + userId, + `${userId}@example.com`, + opts.isActive === false ? 0 : 1, + opts.timezone ?? "Asia/Shanghai", + now, + now, + ); + return userId; +} + +export function seedVikunjaConfig( + d1: SqliteD1, + opts: { + userId?: string; + defaultChannel?: string; + notificationHours?: string; + } = {}, +): void { + d1.db + .prepare( + `INSERT INTO ${VIKUNJA_PREFIX}notification_configs + (user_id, enabled_channels, default_channel, telegram_config, + bark_config, notification_hours, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + opts.userId ?? VIKUNJA_USER_ID, + '["telegram","bark"]', + opts.defaultChannel ?? "telegram", + '{"bot_token":"bot-token","chat_id":"42"}', + '{"device_key":"device-key"}', + opts.notificationHours ?? "[]", + "2026-01-01T00:00:00.000Z", + ); +} + +export function seedVikunjaIntegration( + d1: SqliteD1, + opts: { + userId?: string; + hookToken?: string; + secret?: string; + baseUrl?: string; + enabled?: boolean; + } = {}, +): { hookToken: string; secret: string } { + const hookToken = opts.hookToken ?? "vhk_seeded_token"; + const secret = opts.secret ?? "seeded-secret-value"; + const now = "2026-01-01T00:00:00.000Z"; + d1.db + .prepare( + `INSERT INTO ${VIKUNJA_PREFIX}vikunja_integrations + (user_id, hook_token, secret, base_url, enabled, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + opts.userId ?? VIKUNJA_USER_ID, + hookToken, + secret, + opts.baseUrl ?? "https://vikunja.example.com", + opts.enabled === false ? 0 : 1, + now, + now, + ); + return { hookToken, secret }; +} + +export function setVikunjaIntegration( + d1: SqliteD1, + fields: { enabled?: number; base_url?: string; secret?: string }, + userId = VIKUNJA_USER_ID, +): void { + const sets: string[] = []; + const values: unknown[] = []; + for (const [column, value] of Object.entries(fields)) { + if (value === undefined) continue; + sets.push(`${column} = ?`); + values.push(value); + } + if (sets.length === 0) return; + d1.db + .prepare( + `UPDATE ${VIKUNJA_PREFIX}vikunja_integrations SET ${sets.join(", ")} WHERE user_id = ?`, + ) + .run(...values, userId); +} + +/** Hex HMAC-SHA256 of the raw body, exactly what Vikunja sends. */ +export async function signVikunjaBody( + secret: string, + rawBody: string, +): Promise { + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = await crypto.subtle.sign( + "HMAC", + key, + encoder.encode(rawBody), + ); + return Array.from(new Uint8Array(signature), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} diff --git a/worker/test/vikunja-inbound.test.ts b/worker/test/vikunja-inbound.test.ts new file mode 100644 index 0000000..17f83c5 --- /dev/null +++ b/worker/test/vikunja-inbound.test.ts @@ -0,0 +1,355 @@ +import { Hono } from "hono"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { integrationRoutes } from "../src/routes/integrations"; +import type { Env } from "../src/types"; +import { request } from "./helpers"; +import type { SqliteD1 } from "./support/sqlite-d1"; +import { + VIKUNJA_PREFIX, + VIKUNJA_USER_ID, + seedVikunjaConfig, + seedVikunjaIntegration, + seedVikunjaUser, + setVikunjaIntegration, + setupVikunjaDb, + signVikunjaBody, +} from "./support/vikunja"; + +const app = new Hono(); +app.route("/api/integrations", integrationRoutes); + +let d1: SqliteD1; +let env: Env; +let fetchMock: ReturnType; + +beforeEach(async () => { + ({ d1, env } = await setupVikunjaDb()); + fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +function webhookBody(event: string, data: unknown): string { + return JSON.stringify({ + event_name: event, + time: "2026-11-05T01:30:00Z", + data, + }); +} + +function taskPayload() { + return { + task: { + id: 42, + title: "买牛奶", + due_date: "2026-11-05T01:30:00Z", + project_id: 7, + }, + user: { id: 1 }, + project: { id: 7, title: "家务" }, + reminder: { reminder: "2026-11-05T00:00:00Z" }, + }; +} + +function post( + hookToken: string, + rawBody: string, + signature: string | null, +): Promise<{ status: number; body: any }> { + const headers: Record = { + "Content-Type": "application/json", + }; + if (signature !== null) headers["X-Vikunja-Signature"] = signature; + return request(app, env, `/api/integrations/vikunja/${hookToken}`, { + method: "POST", + headers, + body: rawBody, + }); +} + +async function deliver( + hookToken: string, + rawBody: string, + secret: string, +): Promise<{ status: number; body: any }> { + return post(hookToken, rawBody, await signVikunjaBody(secret, rawBody)); +} + +/** User + notification config + enabled integration, i.e. the happy path. */ +function seedReady(opts: { defaultChannel?: string } = {}) { + seedVikunjaUser(d1); + seedVikunjaConfig(d1, { defaultChannel: opts.defaultChannel }); + return seedVikunjaIntegration(d1); +} + +function historyRows(): Record[] { + return d1.db + .prepare(`SELECT * FROM ${VIKUNJA_PREFIX}notification_history`) + .all() as Record[]; +} + +describe("POST /api/integrations/vikunja/:hookToken", () => { + it("answers an unknown hook token with 404", async () => { + const res = await deliver( + "vhk_does_not_exist", + webhookBody("task.reminder.fired", taskPayload()), + "any-secret", + ); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: "Not found" }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("answers a disabled integration with 403 and sends nothing", async () => { + seedVikunjaUser(d1); + seedVikunjaConfig(d1); + const { hookToken, secret } = seedVikunjaIntegration(d1, { + enabled: false, + }); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(403); + expect(res.body).toEqual({ error: "Integration disabled" }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(historyRows()).toHaveLength(0); + }); + + it("rejects a wrong, tampered or missing signature with 401", async () => { + const { hookToken, secret } = seedReady(); + const rawBody = webhookBody("task.reminder.fired", taskPayload()); + + const wrongSecret = await deliver(hookToken, rawBody, "not-the-secret"); + const tampered = await post( + hookToken, + rawBody, + await signVikunjaBody(secret, `${rawBody} `), + ); + const missing = await post(hookToken, rawBody, null); + const malformed = await post(hookToken, rawBody, "deadbeef"); + + for (const res of [wrongSecret, tampered, missing, malformed]) { + expect(res.status).toBe(401); + expect(res.body).toEqual({ error: "Invalid signature" }); + } + expect(fetchMock).not.toHaveBeenCalled(); + expect(historyRows()).toHaveLength(0); + }); + + it("sends a reminder through the default channel and records trigger_source=vikunja", async () => { + const { hookToken, secret } = seedReady(); + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ + success: true, + results: [{ channel: "telegram", success: true }], + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(String(fetchMock.mock.calls[0][0])).toContain( + "api.telegram.org/botbot-token/sendMessage", + ); + + const history = historyRows(); + expect(history).toHaveLength(1); + expect(history[0]).toMatchObject({ + user_id: VIKUNJA_USER_ID, + item_id: null, + channel: "telegram", + title: "⏰ 买牛奶", + success: 1, + error: null, + trigger_source: "vikunja", + }); + // Due date rendered in the receiving user's timezone (Asia/Shanghai). + expect(history[0].body).toBe("项目:家务\n截止:2026-11-05 09:30"); + + // The integration only sends: no eNotify items are created. + const itemCount = d1.db + .prepare(`SELECT COUNT(*) AS count FROM ${VIKUNJA_PREFIX}items`) + .get() as { count: number }; + expect(itemCount.count).toBe(0); + }); + + it("returns 400 and sends nothing when no default channel is configured", async () => { + const { hookToken, secret } = seedReady({ defaultChannel: "" }); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(400); + expect(res.body).toEqual({ error: "No default channel configured" }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(historyRows()).toHaveLength(0); + }); + + it("returns 400 and sends nothing when the user has no channel config", async () => { + seedVikunjaUser(d1); + const { hookToken, secret } = seedVikunjaIntegration(d1); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(400); + expect(res.body).toEqual({ + error: "No notification channels configured", + }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("answers an unknown event with 200 {ignored:true} and sends nothing", async () => { + const { hookToken, secret } = seedReady(); + + const res = await deliver( + hookToken, + webhookBody("task.created", { task: { id: 1, title: "x" } }), + secret, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ ignored: true }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(historyRows()).toHaveLength(0); + }); + + it("answers an incomplete known event with 200 {ignored:true}, logs and sends nothing", async () => { + const { hookToken, secret } = seedReady(); + const errorMock = vi.spyOn(console, "error").mockImplementation(() => {}); + + const res = await deliver( + hookToken, + webhookBody("task.overdue", { task: { id: 42 } }), + secret, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ ignored: true }); + expect(errorMock).toHaveBeenCalledTimes(1); + expect(String(errorMock.mock.calls[0][0])).toContain("task.overdue"); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("answers 404 when the owning user is disabled", async () => { + seedVikunjaUser(d1, { isActive: false }); + seedVikunjaConfig(d1); + const { hookToken, secret } = seedVikunjaIntegration(d1); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: "Not found" }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("rejects a signed body that is not JSON or has no event_name", async () => { + const { hookToken, secret } = seedReady(); + + const notJson = await deliver(hookToken, "definitely not json", secret); + expect(notJson.status).toBe(400); + + const noEventName = await deliver( + hookToken, + JSON.stringify({ data: taskPayload() }), + secret, + ); + expect(noEventName.status).toBe(400); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("does not apply notification_hours gating", async () => { + const currentHour = Number( + new Intl.DateTimeFormat("en-US", { + timeZone: "Asia/Shanghai", + hour: "2-digit", + hourCycle: "h23", + }) + .formatToParts(new Date()) + .find((part) => part.type === "hour")?.value ?? "0", + ); + const otherHour = (currentHour + 1) % 24; + + seedVikunjaUser(d1); + seedVikunjaConfig(d1, { + notificationHours: JSON.stringify([otherHour]), + }); + const { hookToken, secret } = seedVikunjaIntegration(d1); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(200); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("rate limits per hook token at 60 requests per minute", async () => { + seedVikunjaUser(d1); + seedVikunjaConfig(d1); + const { hookToken, secret } = seedVikunjaIntegration(d1); + const rawBody = webhookBody("task.reminder.fired", taskPayload()); + const signature = await signVikunjaBody(secret, rawBody); + + for (let index = 0; index < 60; index += 1) { + const res = await post(hookToken, rawBody, signature); + expect(res.status).toBe(200); + } + const limited = await post(hookToken, rawBody, signature); + expect(limited.status).toBe(429); + }); + + it("stops delivering once the integration is deleted", async () => { + const { hookToken, secret } = seedReady(); + d1.db + .prepare( + `DELETE FROM ${VIKUNJA_PREFIX}vikunja_integrations WHERE hook_token = ?`, + ) + .run(hookToken); + + const res = await deliver( + hookToken, + webhookBody("task.reminder.fired", taskPayload()), + secret, + ); + expect(res.status).toBe(404); + }); +}); + +describe("inbound route respects base_url changes", () => { + it("uses the stored base_url in the task link after an update", async () => { + seedVikunjaUser(d1); + seedVikunjaConfig(d1, { defaultChannel: "bark" }); + const { hookToken, secret } = seedVikunjaIntegration(d1, { + baseUrl: "https://vikunja.old", + }); + setVikunjaIntegration(d1, { base_url: "https://vikunja.internal" }); + + const res = await deliver( + hookToken, + webhookBody("task.overdue", taskPayload()), + secret, + ); + expect(res.status).toBe(200); + const sent = JSON.parse(String(fetchMock.mock.calls[0][1].body)) as { + url?: string; + }; + expect(sent.url).toBe("https://vikunja.internal/tasks/42"); + }); +}); diff --git a/worker/test/vikunja-integration-admin.test.ts b/worker/test/vikunja-integration-admin.test.ts new file mode 100644 index 0000000..9ee597d --- /dev/null +++ b/worker/test/vikunja-integration-admin.test.ts @@ -0,0 +1,302 @@ +import { Hono } from "hono"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { integrationRoutes } from "../src/routes/integrations"; +import { meRoutes } from "../src/routes/me"; +import type { Env } from "../src/types"; +import { cookieHeader, makeToken, request, seedSession } from "./helpers"; +import type { SqliteD1 } from "./support/sqlite-d1"; +import { + VIKUNJA_PREFIX, + VIKUNJA_USER_ID, + seedVikunjaConfig, + seedVikunjaUser, + setupVikunjaDb, + signVikunjaBody, +} from "./support/vikunja"; + +const app = new Hono(); +app.route("/api/me", meRoutes); +app.route("/api/integrations", integrationRoutes); + +const INTEGRATION_PATH = "/api/me/integrations/vikunja"; + +let d1: SqliteD1; +let env: Env; +let headers: Record; +let fetchMock: ReturnType; + +beforeEach(async () => { + ({ d1, env } = await setupVikunjaDb()); + seedVikunjaUser(d1); + seedVikunjaConfig(d1); + await seedSession( + env as unknown as Record, + VIKUNJA_USER_ID, + "s-1", + ); + headers = cookieHeader( + await makeToken("user", { sub: VIKUNJA_USER_ID, sid: "s-1" }), + ); + fetchMock = vi.fn(async () => new Response("ok", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +function getIntegration(): Promise<{ status: number; body: any }> { + return request(app, env, INTEGRATION_PATH, { headers }); +} + +function createIntegration( + body?: unknown, +): Promise<{ status: number; body: any }> { + return request(app, env, INTEGRATION_PATH, { + method: "POST", + headers: { ...headers, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + +function updateIntegration( + body: unknown, +): Promise<{ status: number; body: any }> { + return request(app, env, INTEGRATION_PATH, { + method: "PUT", + headers: { ...headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); +} + +function deleteIntegration(): Promise<{ status: number; body: any }> { + return request(app, env, INTEGRATION_PATH, { method: "DELETE", headers }); +} + +function regenerateSecret(): Promise<{ status: number; body: any }> { + return request(app, env, `${INTEGRATION_PATH}/regenerate-secret`, { + method: "POST", + headers, + }); +} + +async function deliver( + hookToken: string, + rawBody: string, + secret: string, +): Promise<{ status: number; body: any }> { + return request(app, env, `/api/integrations/vikunja/${hookToken}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Vikunja-Signature": await signVikunjaBody(secret, rawBody), + }, + body: rawBody, + }); +} + +function reminderBody(): string { + return JSON.stringify({ + event_name: "task.reminder.fired", + time: "2026-11-05T01:30:00Z", + data: { + task: { + id: 42, + title: "买牛奶", + due_date: "2026-11-05T01:30:00Z", + project_id: 7, + }, + user: { id: 1 }, + project: { id: 7, title: "家务" }, + reminder: { reminder: "2026-11-05T00:00:00Z" }, + }, + }); +} + +describe("GET /api/me/integrations/vikunja", () => { + it("reports configured:false before anything is created", async () => { + const res = await getIntegration(); + expect(res.status).toBe(200); + expect(res.body).toEqual({ configured: false }); + }); + + it("requires a login session", async () => { + const res = await request(app, env, INTEGRATION_PATH, {}); + expect(res.status).toBe(401); + }); +}); + +describe("POST /api/me/integrations/vikunja", () => { + it("returns the hook token and the plaintext secret exactly once", async () => { + const created = await createIntegration(); + expect(created.status).toBe(201); + expect(created.body.hook_token).toMatch(/^vhk_[A-Za-z0-9_-]{43}$/); + expect(created.body.secret).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(created.body).toMatchObject({ base_url: "", enabled: true }); + + const view = await getIntegration(); + expect(view.status).toBe(200); + expect(view.body).toMatchObject({ + configured: true, + hook_token: created.body.hook_token, + base_url: "", + enabled: true, + secret_configured: true, + }); + expect(view.body).not.toHaveProperty("secret"); + expect(JSON.stringify(view.body)).not.toContain(created.body.secret); + expect(view.body.created_at).toBeTypeOf("string"); + expect(view.body.updated_at).toBeTypeOf("string"); + + // The create body is the GET view plus the one-time secret. + const { secret: _secret, ...createdView } = created.body; + expect(createdView).toEqual(view.body); + }); + + it("accepts base_url, trims trailing slashes and rejects non-http(s)", async () => { + const invalid = await createIntegration({ + base_url: "ftp://vikunja.local", + }); + expect(invalid.status).toBe(400); + expect(invalid.body).toEqual({ error: "Invalid base_url" }); + expect((await getIntegration()).body).toEqual({ configured: false }); + + const created = await createIntegration({ + base_url: "https://vikunja.example.com/", + }); + expect(created.status).toBe(201); + expect(created.body.base_url).toBe("https://vikunja.example.com"); + expect((await getIntegration()).body.base_url).toBe( + "https://vikunja.example.com", + ); + }); + + it("rejects a second creation with 409", async () => { + expect((await createIntegration()).status).toBe(201); + const duplicate = await createIntegration(); + expect(duplicate.status).toBe(409); + expect(duplicate.body).toEqual({ error: "Integration already exists" }); + }); + + it("rejects malformed JSON with 400", async () => { + const res = await request(app, env, INTEGRATION_PATH, { + method: "POST", + headers: { ...headers, "Content-Type": "application/json" }, + body: "{not-json", + }); + expect(res.status).toBe(400); + }); +}); + +describe("PUT /api/me/integrations/vikunja", () => { + it("updates base_url and enabled with validation", async () => { + await createIntegration(); + + const invalidUrl = await updateIntegration({ + base_url: "mailto:me@example.com", + }); + expect(invalidUrl.status).toBe(400); + expect(invalidUrl.body).toEqual({ error: "Invalid base_url" }); + + const savedUrl = await updateIntegration({ + base_url: "http://vikunja.internal:3456/", + }); + expect(savedUrl.status).toBe(200); + expect(savedUrl.body.base_url).toBe("http://vikunja.internal:3456"); + + const disabled = await updateIntegration({ enabled: false }); + expect(disabled.status).toBe(200); + expect(disabled.body.enabled).toBe(false); + expect((await getIntegration()).body.enabled).toBe(false); + + const enabled = await updateIntegration({ enabled: true }); + expect(enabled.status).toBe(200); + expect(enabled.body.enabled).toBe(true); + expect((await getIntegration()).body.base_url).toBe( + "http://vikunja.internal:3456", + ); + + const badEnabled = await updateIntegration({ enabled: "yes" }); + expect(badEnabled.status).toBe(400); + + const empty = await updateIntegration({}); + expect(empty.status).toBe(400); + }); + + it("returns 404 before the integration exists", async () => { + const res = await updateIntegration({ enabled: false }); + expect(res.status).toBe(404); + }); +}); + +describe("POST /api/me/integrations/vikunja/regenerate-secret", () => { + it("rotates the secret: the old signature fails, the new one passes", async () => { + const created = await createIntegration(); + const { hook_token: hookToken } = created.body; + const oldSecret = created.body.secret as string; + const rawBody = reminderBody(); + + const before = await deliver(hookToken, rawBody, oldSecret); + expect(before.status).toBe(200); + + const rotated = await regenerateSecret(); + expect(rotated.status).toBe(200); + const newSecret = rotated.body.secret as string; + expect(newSecret).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(newSecret).not.toBe(oldSecret); + expect(JSON.stringify(rotated.body)).not.toContain(oldSecret); + + const withOld = await deliver(hookToken, rawBody, oldSecret); + expect(withOld.status).toBe(401); + expect(withOld.body).toEqual({ error: "Invalid signature" }); + + const withNew = await deliver(hookToken, rawBody, newSecret); + expect(withNew.status).toBe(200); + expect(withNew.body).toEqual({ + success: true, + results: [{ channel: "telegram", success: true }], + }); + + const history = d1.db + .prepare( + `SELECT trigger_source FROM ${VIKUNJA_PREFIX}notification_history`, + ) + .all() as { trigger_source: string }[]; + expect(history).toHaveLength(2); + expect(history.every((row) => row.trigger_source === "vikunja")).toBe(true); + }); + + it("returns 404 before the integration exists", async () => { + const res = await regenerateSecret(); + expect(res.status).toBe(404); + }); +}); + +describe("DELETE /api/me/integrations/vikunja", () => { + it("deletes the integration and the inbound endpoint stops accepting it", async () => { + const created = await createIntegration(); + const { hook_token: hookToken } = created.body; + const rawBody = reminderBody(); + expect( + (await deliver(hookToken, rawBody, created.body.secret)).status, + ).toBe(200); + + const deleted = await deleteIntegration(); + expect(deleted.status).toBe(200); + expect(deleted.body).toEqual({ success: true }); + expect((await getIntegration()).body).toEqual({ configured: false }); + + const inbound = await deliver(hookToken, rawBody, created.body.secret); + expect(inbound.status).toBe(404); + expect(inbound.body).toEqual({ error: "Not found" }); + + const again = await deleteIntegration(); + expect(again.status).toBe(404); + }); + + it("returns 404 before the integration exists", async () => { + const res = await deleteIntegration(); + expect(res.status).toBe(404); + }); +}); diff --git a/worker/test/vikunja-webhook.test.ts b/worker/test/vikunja-webhook.test.ts new file mode 100644 index 0000000..854fa21 --- /dev/null +++ b/worker/test/vikunja-webhook.test.ts @@ -0,0 +1,290 @@ +import { describe, expect, it } from "vitest"; +import { + buildVikunjaMessage, + formatVikunjaDue, + verifyVikunjaSignature, +} from "../src/services/vikunja-webhook"; + +const encoder = new TextEncoder(); + +async function sign( + secret: string, + body: string, + hexCase: "lower" | "upper" = "lower", +): Promise { + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(body)); + const hex = Array.from(new Uint8Array(signature), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); + return hexCase === "upper" ? hex.toUpperCase() : hex; +} + +const SECRET = "vikunja-test-secret"; +const BODY = '{"event_name":"task.overdue","data":{}}'; + +describe("verifyVikunjaSignature", () => { + it("accepts the HMAC-SHA256 hex of the raw body", async () => { + await expect( + verifyVikunjaSignature(SECRET, await sign(SECRET, BODY), BODY), + ).resolves.toBe(true); + // Hex case is not part of the signature material. + await expect( + verifyVikunjaSignature(SECRET, await sign(SECRET, BODY, "upper"), BODY), + ).resolves.toBe(true); + }); + + it("rejects a signature made with another secret", async () => { + await expect( + verifyVikunjaSignature(SECRET, await sign("other-secret", BODY), BODY), + ).resolves.toBe(false); + }); + + it("rejects any body change after signing", async () => { + const signature = await sign(SECRET, BODY); + await expect( + verifyVikunjaSignature(SECRET, signature, `${BODY} `), + ).resolves.toBe(false); + await expect( + verifyVikunjaSignature(SECRET, signature, BODY.replace("overdue", "due")), + ).resolves.toBe(false); + }); + + it("rejects a missing signature header", async () => { + await expect(verifyVikunjaSignature(SECRET, null, BODY)).resolves.toBe( + false, + ); + await expect(verifyVikunjaSignature(SECRET, undefined, BODY)).resolves.toBe( + false, + ); + await expect(verifyVikunjaSignature(SECRET, "", BODY)).resolves.toBe(false); + }); + + it("rejects anything that is not 64 hex characters", async () => { + const valid = await sign(SECRET, BODY); + for (const header of [ + "abc", + valid.slice(0, 63), + `${valid}0`, + "z".repeat(64), + `v2=${valid}`, + ]) { + await expect(verifyVikunjaSignature(SECRET, header, BODY)).resolves.toBe( + false, + ); + } + // 64 hex chars, but not the right digest. + await expect( + verifyVikunjaSignature(SECRET, "a".repeat(64), BODY), + ).resolves.toBe(false); + }); + + it("rejects when no secret is configured", async () => { + await expect( + verifyVikunjaSignature("", await sign(SECRET, BODY), BODY), + ).resolves.toBe(false); + }); +}); + +describe("formatVikunjaDue", () => { + it("formats in the receiving user's timezone as YYYY-MM-DD HH:mm", () => { + expect(formatVikunjaDue("2026-11-05T01:30:00Z", "Asia/Shanghai")).toBe( + "2026-11-05 09:30", + ); + expect(formatVikunjaDue("2026-11-05T01:30:00Z", "UTC")).toBe( + "2026-11-05 01:30", + ); + expect(formatVikunjaDue("2026-11-05T23:30:00Z", "UTC")).toBe( + "2026-11-05 23:30", + ); + }); + + it("omits the zero value and invalid dates", () => { + expect(formatVikunjaDue("0001-01-01T00:00:00Z", "UTC")).toBeNull(); + expect(formatVikunjaDue("not-a-date", "UTC")).toBeNull(); + expect(formatVikunjaDue(null, "UTC")).toBeNull(); + expect(formatVikunjaDue("", "UTC")).toBeNull(); + }); +}); + +const BASE_URL = "https://vikunja.example.com"; + +function reminderData() { + return { + task: { + id: 42, + title: "买牛奶", + due_date: "2026-11-05T01:30:00Z", + project_id: 7, + }, + user: { id: 1 }, + project: { id: 7, title: "家务" }, + reminder: { reminder: "2026-11-05T00:00:00Z" }, + }; +} + +describe("buildVikunjaMessage: single task events", () => { + it("maps task.reminder.fired with due date, project and task link", () => { + expect( + buildVikunjaMessage( + "task.reminder.fired", + reminderData(), + BASE_URL, + "Asia/Shanghai", + ), + ).toEqual({ + title: "⏰ 买牛奶", + body: "项目:家务\n截止:2026-11-05 09:30", + url: "https://vikunja.example.com/tasks/42", + }); + }); + + it("maps task.overdue with the overdue title", () => { + const data = reminderData(); + expect( + buildVikunjaMessage("task.overdue", data, BASE_URL, "Asia/Shanghai"), + ).toEqual({ + title: "⚠️ 已逾期:买牛奶", + body: "项目:家务\n截止:2026-11-05 09:30", + url: "https://vikunja.example.com/tasks/42", + }); + }); + + it("drops the due line for the zero due date", () => { + const data = reminderData(); + data.task.due_date = "0001-01-01T00:00:00Z"; + expect( + buildVikunjaMessage("task.reminder.fired", data, BASE_URL, "UTC"), + ).toEqual({ + title: "⏰ 买牛奶", + body: "项目:家务", + url: "https://vikunja.example.com/tasks/42", + }); + }); + + it("carries no url when base_url is empty", () => { + expect( + buildVikunjaMessage("task.reminder.fired", reminderData(), "", "UTC"), + ).toEqual({ + title: "⏰ 买牛奶", + body: "项目:家务\n截止:2026-11-05 01:30", + url: undefined, + }); + expect( + buildVikunjaMessage("task.overdue", reminderData(), null, "UTC")?.url, + ).toBeUndefined(); + }); + + it("tolerates a missing project by keeping the line empty", () => { + const data = reminderData(); + delete (data as Record).project; + expect( + buildVikunjaMessage("task.overdue", data, BASE_URL, "UTC")?.body, + ).toBe("项目:\n截止:2026-11-05 01:30"); + }); +}); + +describe("buildVikunjaMessage: tasks.overdue summary", () => { + function summaryData(count: number) { + const projects: Record = { + "7": { id: 7, title: "家务" }, + "8": { id: 8, title: "工作" }, + }; + return { + tasks: Array.from({ length: count }, (_, index) => ({ + id: index + 1, + title: `任务${index + 1}`, + project_id: index === 1 ? 8 : index === 0 ? 7 : 99, + })), + user: { id: 1 }, + projects, + }; + } + + it("renders one aggregate message with project names and the base url", () => { + expect( + buildVikunjaMessage("tasks.overdue", summaryData(3), BASE_URL, "UTC"), + ).toEqual({ + title: "⚠️ 3 个任务已逾期", + body: "· 任务1(家务)\n· 任务2(工作)\n· 任务3", + url: "https://vikunja.example.com", + }); + }); + + it("keeps 10 lines and replaces the last task with a total when longer", () => { + const message = buildVikunjaMessage( + "tasks.overdue", + summaryData(12), + BASE_URL, + "UTC", + ); + expect(message?.title).toBe("⚠️ 12 个任务已逾期"); + const lines = (message?.body ?? "").split("\n"); + expect(lines).toHaveLength(10); + expect(lines[8]).toBe("· 任务9"); + expect(lines[9]).toBe("… 等共 12 个"); + }); + + it("does not add the total line for exactly 10 tasks", () => { + const message = buildVikunjaMessage( + "tasks.overdue", + summaryData(10), + BASE_URL, + "UTC", + ); + const lines = (message?.body ?? "").split("\n"); + expect(lines).toHaveLength(10); + expect(lines[9]).toBe("· 任务10"); + }); + + it("uses no url when base_url is empty", () => { + expect( + buildVikunjaMessage("tasks.overdue", summaryData(2), "", "UTC")?.url, + ).toBeUndefined(); + }); +}); + +describe("buildVikunjaMessage: ignored input", () => { + it("returns null for unknown events", () => { + expect( + buildVikunjaMessage( + "task.created", + { task: { id: 1, title: "x" } }, + BASE_URL, + "UTC", + ), + ).toBeNull(); + }); + + it("returns null for incomplete known events", () => { + expect( + buildVikunjaMessage("task.reminder.fired", null, "", "UTC"), + ).toBeNull(); + expect( + buildVikunjaMessage("task.reminder.fired", {}, "", "UTC"), + ).toBeNull(); + expect( + buildVikunjaMessage( + "task.reminder.fired", + { task: { id: 1 } }, + "", + "UTC", + ), + ).toBeNull(); + expect( + buildVikunjaMessage("task.overdue", { task: { title: "x" } }, "", "UTC"), + ).toBeNull(); + expect( + buildVikunjaMessage("tasks.overdue", { tasks: [] }, "", "UTC"), + ).toBeNull(); + expect( + buildVikunjaMessage("tasks.overdue", { tasks: "nope" }, "", "UTC"), + ).toBeNull(); + }); +});