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
37 changes: 33 additions & 4 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,44 @@ jobs:
env:
JWT_SECRET: ${{ secrets.JWT_SECRET }}
SETUP_SECRET: ${{ secrets.SETUP_SECRET }}
WAKER_SIGNING_KEY: ${{ secrets.WAKER_SIGNING_KEY }}
run: |
node -e '
const fs = require("fs");
const secrets = {
JWT_SECRET: process.env.JWT_SECRET,
SETUP_SECRET: process.env.SETUP_SECRET,
};

// Optional waker callback signing key — the only waker-related
// setting this project has. Only its presence is logged, never its
// value; the trimmed value is what the receiver verifies with.
// Same rule as the runtime gate (wakerSigningKey()): a trimmed value
// ending in _PLACEHOLDER is still a placeholder, i.e. unconfigured.
const wakerKey = (process.env.WAKER_SIGNING_KEY || "").trim();
const wakerConfigured =
wakerKey.length > 0 && !wakerKey.endsWith("_PLACEHOLDER");
if (wakerConfigured) {
secrets.WAKER_SIGNING_KEY = wakerKey;
console.log("WAKER_SIGNING_KEY: configured");
} else {
console.log("WAKER_SIGNING_KEY: not configured (native cron only)");
}

// Interlock: once wrangler.toml has no [triggers], the waker task is
// the only schedule source. Losing the key as well would silently
// stop every hourly sweep, so fail the deploy instead.
const wranglerToml = fs.readFileSync("wrangler.toml", "utf8");
if (!wakerConfigured && !/^\[triggers\]/m.test(wranglerToml)) {
console.error(
"neither [triggers] nor WAKER_SIGNING_KEY is configured: nothing would run",
);
process.exit(1);
}

fs.writeFileSync(
process.env.RUNNER_TEMP + "/secrets.json",
JSON.stringify({
JWT_SECRET: process.env.JWT_SECRET,
SETUP_SECRET: process.env.SETUP_SECRET,
}),
JSON.stringify(secrets),
{ mode: 0o600 },
);
'
Expand Down
20 changes: 16 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ The worker serves the frontend's static assets from `web/dist/` via the `ASSETS`

### Backend (`worker/`)

**Entry point**: `worker/src/index.ts` — registers all Hono routes and the scheduled handler.
**Entry point**: `worker/src/index.ts` — registers all Hono routes, the `/_waker` callback mount (before the SPA fallback) and the native scheduled handler.

**Route structure** (`worker/src/routes/`):

Expand All @@ -52,12 +52,13 @@ 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
- `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)`, currently a single collapsed `schema_v1` = the whole schema); `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`); `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 `""`.
Expand All @@ -72,18 +73,29 @@ 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.

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

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

`services/scheduler.ts` is the single business implementation. Both schedule entries go through `services/scheduler-tick.ts` `runSchedulerTick(env, { source, scheduledFor })`:

- **native entry**: `scheduled()` in `index.ts`, `source: "cron"`, `scheduledFor: event.scheduledTime` (awaited, not `waitUntil`);
- **waker entry**: `services/waker-callback.ts`, job `hourly-reminder-sweep`, `source: "waker"`, `scheduledFor: ctx.scheduledFor`; mounted at `/_waker` by `routes/waker.ts` using the verbatim SDK copy in `worker/src/waker/` (waker-client 2.0.0 — never hand-edit that directory).

The guard in front of the business pass is one atomic D1 claim per UTC hour (`{prefix}scheduler_tick_claims`, `INSERT … ON CONFLICT(tick_key) DO NOTHING` + `meta.changes`), so cron and waker can never sweep the same hour twice; the SDK's own `{prefix}waker_executions` ledger dedupes executionId retries. Failure semantics: cron keeps the claim on failure (no re-run that could double-send), waker releases it and rethrows so the platform retry (same executionId) completes the hour. Claims are pruned after 7 days.

Two cases go beyond the plain table: manual triggers and dead-letter replays arrive with `trigger: "manual"` and `scheduledFor` = the dispatch time, so they run the sweep **without taking the hourly slot** (the executionId ledger and KV dedupe keep them idempotent) — otherwise the console's "run now" would be swallowed by the cron claim of that hour. And when the platform aborts an execution (timeout / evicted isolate) the claim is never released, so a waker retry may take over its own orphaned claim after `WAKER_STALE_CLAIM_SECONDS` (20s, smaller than `backoffSeconds` 30) and finish the hour; a cron claim is never taken over.

Waker is optional and the **only** setting is `WAKER_SIGNING_KEY` (GitHub Secret → `wrangler deploy --secrets-file`): unset/blank/`*_PLACEHOLDER` means native cron only. The gate is `wakerSigningKey()` in `services/scheduler-tick.ts`; the receiver stays mounted and fails closed with 500 JSON `signing_key_missing`. Do not reintroduce `WAKER_MODE`/`WAKER_URL`/project tokens — the SDK's `mountWakerReceiver`, `createWakerClient*`, `syncManifest` and `resolveWakerMode` must stay uncalled.

**Cloudflare bindings**:

- `DB` — D1 database
- `KV` — KV namespace (used for scheduler deduplication and status)
- `ASSETS` — static file serving
- Secrets: `JWT_SECRET`, `SETUP_SECRET`
- Secrets: `JWT_SECRET`, `SETUP_SECRET`, and optional `WAKER_SIGNING_KEY` (empty ⇒ native cron only)
- Env var: `TABLE_PREFIX` (three states: unset → default `enotify`, tables like `enotify_users`; custom value → verbatim with trailing `_`; explicit `""`/CI `none` → no prefix; allows shared DB with prefix isolation)

### Frontend (`web/`)
Expand Down
48 changes: 48 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ In your repository Settings → Secrets and variables → Actions, add:
| `CLOUDFLARE_API_TOKEN` | Cloudflare API Token (needs Workers and D1 permissions) |
| `JWT_SECRET` | Any random 64-char string — e.g. `openssl rand -hex 32` |
| `SETUP_SECRET` | Any random string — e.g. `openssl rand -hex 16` |
| `WAKER_SIGNING_KEY` | **Optional** waker callback signing key; leave unset to stay on native cron (see "Waker Scheduling") |

In Settings → Secrets and variables → Actions → Variables, add:

Expand Down Expand Up @@ -185,6 +186,53 @@ CI deployment convention (`.github/workflows/deploy.yml`): a GitHub Variables `T
| `JWT_SECRET` | JWT signing secret, any random 64-char string |
| `SETUP_SECRET` | Database initialization route secret, any random string |
| `TABLE_PREFIX` | Table prefix, three states: unset → default `enotify` (tables like `enotify_users`); explicit empty string / CI `none` → no prefix; custom value → verbatim with trailing `_` |
| `WAKER_SIGNING_KEY` | Optional. Waker callback signing key; missing / blank / `*_PLACEHOLDER` means unconfigured → native cron only |

## Waker Scheduling (optional)

By default the hourly reminder sweep runs on the native Cloudflare Cron Trigger (`[triggers]` in `worker/wrangler.toml`, `0 * * * *` UTC). It can also be driven by the [waker](https://github.com/WorkerHub/waker) platform: **the only setting is `WAKER_SIGNING_KEY`** — leave it unset and the default cron keeps running; set it and both entries coexist, arbitrated by an hourly claim, so nothing is sent twice.

> Signature verification, the timestamp window and executionId idempotency come from the official SDK source copy (`worker/src/waker/`, `@workerhub/waker-client` 2.0.0). That directory must not be edited by hand.

### 1. Configure the signing key (optional)

Add the GitHub Secret `WAKER_SIGNING_KEY` (value = the signing key the waker console shows **once** when the project is created; keep a copy in your password manager first). At deploy time it is only written to `$RUNNER_TEMP/secrets.json` (0600) and uploaded via `wrangler deploy --secrets-file`; CI logs only `configured` / `not configured`, **never the value**.

Empty, whitespace-only, `undefined` and `*_PLACEHOLDER` values are all treated as "not configured". In that state the receiver is still mounted but fails closed: a real callback gets **500 JSON `signing_key_missing`**, a request without signature headers gets 400, and `GET /_waker/execute` gets 404 — it **never falls through to the SPA's 200 HTML**, never queries the DB, writes the ledger or runs business code. Deploying without the key always succeeds.

### 2. Create the job in the waker console

Create a project `eNotify` (callback URL = your production domain; the platform appends `/_waker/execute`), then one declarative job:

| Field | Value |
| --- | --- |
| Job name | `hourly-reminder-sweep` (must match `WAKER_JOB_NAME` in the code verbatim, otherwise the callback gets 404 `unknown_job`) |
| Kind | cron |
| Cron | `0 * * * *` |
| Timezone | `UTC` |
| Payload | `{}` |
| Misfire | `fire_once` |
| Concurrency | `forbid` |
| maxRetries | `2` |
| backoffSeconds | `30` |
| timeoutSeconds | `300` |
| jitterSeconds | `0` |
| enabled | `true` |

There is no registration client, project token, dynamic registration/cancellation or self-renewal in this repo: the job is maintained in the console only. The handler **awaits the business pass** before answering 2xx; failures are retried by the platform and the same executionId never runs twice.

### 3. Database migration

`schema_v3` adds two tables under the configured table prefix (default `enotify_waker_executions`, `enotify_scheduler_tick_claims`): the SDK's executionId idempotency ledger and the hourly claim table. After upgrading, call `POST /api/setup` once (or use "check and upgrade database" in the admin UI); migrations are additive and re-runnable. If the key is configured while the claim table does not exist yet, **both** entries stop safely (no double-send wins), so migrate before configuring the key.

### 4. Dual run, cutover and disabling

- **Dual run**: while `[triggers]` stays, both entries exist. Each UTC hour exactly one of them wins the D1 claim and runs the sweep; the other one skips (the waker side answers `duplicate_tick`), so no notification or renewal happens twice. Claim rows are kept for 7 days for troubleshooting.
- **Cut over to waker only**: first confirm exactly one claim row per hour (`SELECT tick_key, source, claimed_at FROM enotify_scheduler_tick_claims ORDER BY claimed_at DESC LIMIT 6`), then delete `[triggers]` from `worker/wrangler.toml` and deploy. CI interlocks: deploying with no `[triggers]` and no `WAKER_SIGNING_KEY` fails outright (otherwise nothing would run at the top of the hour).
- **Disable callbacks**: `wrangler deploy --secrets-file` is additive (omitting a key does not delete the old value). Restore `[triggers]`, deploy, and explicitly run `npx wrangler secret delete WAKER_SIGNING_KEY`. Even if you forget, the hourly claim still prevents duplicate runs.
- **Rotate the key**: rotate in the waker console → the old key stops working immediately → update the GitHub Secret `WAKER_SIGNING_KEY` → redeploy. Callbacks during the window are rejected (401) and retried by the platform.
- **Manual trigger / dead-letter replay**: the platform sends the **dispatch time** for these runs, not a nominal slot (waker `manualTrigger` / `replayDeadLetter`), so they run the sweep **without taking the hourly claim**; the executionId ledger and the sweep's own KV dedupe keep them from sending anything twice. The console's "run now" therefore really runs (response `trigger: "manual"`, `executed: true` in the execution log) instead of being swallowed by the cron claim of that hour.
- **Timeout / crash**: when the platform aborts a request after `timeoutSeconds` there is no chance to release the claim. A retry (same executionId) takes over the SDK ledger row and the `source=waker` hourly claim after 20 seconds and finishes the hour; a cron claim is **never** taken over (cron has no retry, and re-running would send twice).

## License

Expand Down
Loading
Loading