5.5 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
WeChat iLink Bot protocol HTTP gateway. Wraps QR-code login, long-poll message receiving, and message/media/typing APIs into REST endpoints. Built with Bun + Hono + Zod.
Commands
bun install # Install dependencies
bun run dev # Dev mode with auto-reload (--watch), port 3456
bun run start # Production mode, port 3456
bun run check # Type-check only (tsc --noEmit)
bun lint # Biome lint check
bun lint:fix # Biome lint auto-fix
bun format # Biome format
bun test test/ # Run tests (requires running server + API_KEY env var)
Tests are Bun-native (describe/test/expect). They run against a live server on localhost:3456 and require interactive QR scan with 120s timeout. There is no way to run a single test file differently — it's one test file at test/api.test.ts. Tests are sequential with phases: pre-login checks → QR login → post-login API tests → logout.
Architecture
Two layers: SDK (protocol client) and Gateway (HTTP API).
SDK (src/sdk/)
Low-level WeChat iLink protocol wrapper (mirrors @tencent-weixin/openclaw-weixin@2.1.8):
auth.ts— QR code login state machine (idle → waiting → scanned → confirmed/failed). Handlesscaned_but_redirectby switching base URL.api.ts— HTTP calls to iLink API (getUpdates, sendMessage, getConfig, sendTyping, getUploadUrl) with timeout via AbortController. Usesjson-bigintfor number preservation.cdn.ts— Media upload (AES-128-ECB encrypt → CDN POST) and download (fetch → AES decrypt)crypto.ts— AES-128-ECB encrypt/decrypt helpers using Node.js cryptotypes.ts— Protocol enums and request/response types
Gateway (src/gateway/)
Hono HTTP server with two nested apps: outer app handles public routes + auth middleware, inner authedApp adds login guard and injects Credentials into Hono context via c.set('credentials', creds).
app.ts— Middleware chain: HTTP logger → bearer token auth (skips/webhook) → public routes (/auth,/status,/webhook) → login guard → authed routes (/messages,/media,/typing,/config)state.ts— Persistent state manager. Credentials, sync cursor, context tokens persisted toDATA_DIRas JSON. In-memory ring buffer for messages, async-flushed to disk every 500ms with graceful shutdown flush (SIGINT/SIGTERM).poller.ts— Background long-poll loop. Filters own messages (MessageType.BOT), caches context_token per sender, pushes to buffer, delivers webhooks (fire-and-forget with 2x retry).routes/— One file per route group. Each route file creates its ownHono<Env>withEnv = { Variables: { credentials: Credentials } }.
Key Data Flows
Incoming messages: Poller long-polls → filters BOT messages → caches context_token → ring buffer → webhook delivery (background)
Outgoing messages: POST /messages/send → Zod validation → resolve "self" to user_id → for URL-based media: download → encrypt → upload to CDN → send via API
Login: POST /auth/login → QR code URL returned → background poll for scan → on confirm: save credentials, start poller
State Persistence (DATA_DIR, default ./data)
credentials.json— botToken, accountId, baseUrl, userId (cleared on logout)sync.json— getUpdates cursor (survives restarts)context-token.json— userId → context_token map (needed for replies)messages/*.json— Per-session message files (ring buffer overflow)
Code Conventions
- Runtime: Bun v1.0+, no build step — Bun runs TypeScript directly
- Formatting: Biome — single quotes, semicolons as-needed, 2-space indent, 120 char line width
- Validation: Zod schemas in
src/gateway/lib/schemas.tsfor all request bodies. Routes use@hono/zod-validatorviazValidator('json', schema). - Logging: Custom structured logger (
src/lib/logger.ts) —logger.info(tag, msg, extra?)with tags like'poller','api','cdn','auth','send','http' - HTTP status codes: Constants in
src/gateway/lib/http.ts(HttpStatus.OK,HttpStatus.BAD_REQUEST, etc.) - "self" resolution: Routes accept
to="self"which resolves to logged-in user_id viaresolve-to.ts - Context tokens: Required for sending replies. Auto-cached from incoming messages by poller. Can be overridden per-request.
- BigInt: Uses
json-bigintfor protocol number preservation - Exhaustive switches: Message item type switches use
const _exhaustive: never = itempattern
Non-Obvious Details
- Poller pauses for 1 hour on session expiry (errcode -14) to avoid API hammering
- Media AES keys are hex internally but base64 in API responses — conversion happens in
messages.ts:uploadFromUrl - Webhook route (
POST /webhook/:token) uses token-in-URL auth with timing-safe compare, bypasses bearer auth - If credentials exist on startup, polling auto-starts without login
CLIENT_ID_PREFIXinconstants.tsprefixes all outgoing message IDs- Docker container runs on port 3000 internally, mapped to 29527 in docker-compose; dev mode uses port 3456
API_KEYmust be longer than 12 characters (strict>, not>=)- Send items support two mutually exclusive patterns:
{ url: string }(gateway downloads + re-uploads) or{ cdn: { encrypt_query_param, aes_key } }(pre-uploaded reference)