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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`):

Expand All @@ -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).
Expand Down
46 changes: 46 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/<id> -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=<access_token after login>" \
-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/<hook_token>`

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
Expand Down
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
- **按项选择渠道** — 每个通知项可单独多选使用哪些渠道,未指定则只使用默认渠道
- **定时提醒** — 每小时自动检查并发送到期提醒,支持全局时段配置和每项独立覆盖
- **通知历史** — 查看所有已发送通知的记录与状态
- **Vikunja 集成** — Vikunja 的任务提醒与逾期事件经 eNotify 默认渠道推送,历史可查
- **两步验证** — TOTP(验证器应用)、邮箱验证码、Passkey
- **密码重置** — 通过邮箱验证码重置密码
- **管理员后台** — 用户管理、系统设置、模拟登录
Expand Down Expand Up @@ -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/<id> -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/<hook_token>`

每个用户只有一个集成(重复创建返回 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 环境变量
Expand Down
Loading
Loading