This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
# Install dependencies (run from root)
pnpm install
# Start both frontend and backend in development
pnpm dev
# Start individually
pnpm dev:web # Vite dev server (React)
pnpm dev:worker # Wrangler dev server (Cloudflare Workers)
# Build
pnpm build # Build both web and worker
pnpm build:web
pnpm build:worker
# Type checking
pnpm typecheck # Check both packages
# Run worker tests (Vitest)
pnpm test
# Deploy (builds web, then deploys worker with assets)
pnpm deployThis is a pnpm monorepo with two packages:
web/— React 19 SPA (Vite + Tailwind CSS v4 + shadcn/ui)worker/— Cloudflare Workers backend (Hono.js)
The worker serves the frontend's static assets from web/dist/ via the ASSETS binding. There is no separate API server; the single Cloudflare Worker handles both the API (/api/*) and SPA fallback.
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/):
auth.ts— registration, login, logout, email verificationauth2fa.ts— TOTP, Passkey (WebAuthn), email OTPme.ts— user profile, notification settingsitems.ts— CRUD for items (notifications) and payment history; routes at/api/itemsdashboard.ts— spending stats, expiry summaryadmin.ts— user management, system settings; also manages items per user at/api/admin/users/:uid/itemsnotify.ts— manual notification test triggerintegrations.ts— inbound third-party webhooks at/api/integrations; onlyPOST /api/integrations/vikunja/:hookTokenexists today. No session/API-key auth: the hook token locates the user'svikunja_integrationsrow and the raw body must matchX-Vikunja-Signature(HMAC-SHA256, constant-time). Adapted events go through the default-channelsendNotificationspath withtriggerSource: "vikunja".waker.ts—/_wakermount for the waker callback receiver (SDK paths, signature and idempotency only; mounted beforeapp.get("*")so a callback can never be answered with 200 HTML)setup.ts— one-time DB initialization viaSETUP_SECRET(rate-limited, 3/10min per IP); also exposesGET /api/setup/state(public setup-page toggle) andPOST /api/admin/setup(admin-only, no secret). Core setup/migration logic lives inworker/src/lib/setup.ts.runSetupis 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 → stampschema_v1); neither → fresh install through the ledger.
Database (worker/src/db/):
- Cloudflare D1 (SQLite).
worker/src/db/schema.sqlis 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-historytrigger_source,schema_v3={prefix}waker_executions+{prefix}scheduler_tick_claims,schema_v4={prefix}vikunja_integrations(one inbound Vikunja webhook integration per user, uniquehook_token, plaintext HMACsecretthat the management API never returns));worker/src/lib/migrations-runner.tsapplies 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 asschema_vN; never rename, edit or reorder a merged migration; migrations must be additive (CREATE TABLE/INDEX IF NOT EXISTS,ADD COLUMN,INSERT OR IGNORE— noDROP/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_migrationsfor the default prefix and_schema_migrationswith no prefix. Ledger tables are not part of the eNotify table family and are ignored bydetectTablePrefixes()(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 viaTABLE_PREFIXenv var and thegetTablePrefix()helper intypes.ts(the ONLY resolution point). Three states: unset/null → defaultenotify(enotify_); custom non-empty value → verbatim with trailing_; explicit""→ no prefix.runSetupinworker/src/lib/setup.tsdetects existing initialized schemas under other prefixes viadetectTablePrefixes()and aborts with 409PREFIX_CONFLICTinstead of silently re-initializing; CI maps unset/empty vars toenotifyand the reserved wordnoneto"". - 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/):
auth.ts— JWT signing/verification, password hashing, ID generationtime.ts— timezone-aware date arithmetic, period calculationslunar.ts— Chinese lunar calendar support (1900–2100)currency.ts— multi-currency / exchange rate conversion
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:
- Checks their allowed notification hours (per-timezone).
- Auto-renews expired items (with KV deduplication).
- Sends reminders for items expiring within the user's configured threshold (with per-hour KV deduplication). If an item has specific channels configured (
channelscolumn), 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()inindex.ts,source: "cron",scheduledFor: event.scheduledTime(awaited, notwaitUntil). Not scheduled in production any more —worker/wrangler.tomlshipscrons = []; it stays in code for the rollback path; - waker entry:
services/waker-callback.ts, jobhourly-reminder-sweep,source: "waker",scheduledFor: ctx.scheduledFor; mounted at/_wakerbyroutes/waker.tsusing the verbatim SDK copy inworker/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.
The hourly sweep is driven by the waker job alone. worker/wrangler.toml keeps [triggers] with crons = [] — an explicit empty array, because per Cloudflare docs removing or commenting out the crons key does not disable an existing Cron Trigger (wrangler only PUTs /schedules when crons is defined), so deleting the section would leave the old cron running. The only setting is WAKER_SIGNING_KEY (GitHub Secret → wrangler deploy --secrets-file): unset/blank/*_PLACEHOLDER means unconfigured, and deploy.yml then fails the deploy because no non-empty crons exists either. 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 databaseKV— KV namespace (used for scheduler deduplication and status)ASSETS— static file serving- Secrets:
JWT_SECRET,SETUP_SECRET, andWAKER_SIGNING_KEY(required in production — the hourly sweep's only entry point; empty ⇒deploy.ymlfails unlesscronsis non-empty) - Env var:
TABLE_PREFIX(three states: unset → defaultenotify, tables likeenotify_users; custom value → verbatim with trailing_; explicit""/CInone→ no prefix; allows shared DB with prefix isolation)
Entry point: web/src/main.tsx
Routing (React Router v7): Auth pages, dashboard, item list/detail/new (/items/*), channels (/channels), settings, admin pages.
API communication: web/src/lib/api.ts — thin wrapper over fetch for the backend API.
i18n: react-i18next with zh.json / en.json locale files in web/src/locales/. Language auto-detected from browser. The items namespace covers notification management UI strings; nav.items is the nav label. The channels namespace covers channel management UI strings.
Auth state: web/src/hooks/useAuth.tsx — provides user context and JWT-based auth throughout the app.
- Code/DB/API: uses
item/Item/items(table:${prefix}items, routes:/api/items) - UI (zh): shows "通知" / "通知管理"
- UI (en): shows "Notification" / "Notifications"
notification_config/NotificationConfigrefers to push channel configuration, not items — these are separate concepts.- Code/UI for channels:
channels/Channelin code and nav. DB columnchannelson items stores a JSON array of channel IDs (e.g.["telegram","email"]). Empty array[]means "use the default channel". - UI (zh): shows "渠道" / "渠道管理"
- UI (en): shows "Channel" / "Channel Management"
- Uses
@theme inlineinweb/src/index.cssto map shadcn/ui CSS variables (--primaryetc.) to Tailwind color tokens (--color-primary). - Toggle thumb vertical centering: use
top-[calc(50%-8px)]instead oftop-1/2 -translate-y-1/2to avoid conflict with horizontaltranslate-x-*(Tailwind v4 uses CSStranslateshorthand — two translate classes on the same element override each other).