include weixin-ilink-gateway source

This commit is contained in:
mayunfei committed 2026-12-04 10:12:20 +08:00
1 parent 5f8428a318
commit 43a6f7b72b
51 files changed
+5351 -1

No files matched your search

Submodule weixin-ilink-gateway deleted from ad6097361b.
+8
View File
@@ -0,0 +1,8 @@
node_modules
data
.git
.github
*.md
test
biome.json
docker-compose.yaml
+26
View File
@@ -0,0 +1,26 @@
# Gateway authentication key (required)
# You can generate with `openssl rand -hex 16`
API_KEY=
# Server port
PORT=3456
# Data directory for persistence
DATA_DIR=./data
# Webhook URLs for message delivery (comma-separated, optional)
# WEBHOOK_URLS=https://your-server.com/webhook,https://backup.com/webhook
WEBHOOK_URLS=
# Incoming webhook token (optional, enables POST /webhook/:token)
# You can generate with `openssl rand -hex 16`
WEBHOOK_TOKEN=
# Max download size for media uploads (MB)
MAX_DOWNLOAD_SIZE_MB=128
# Download timeout for fetching media URLs (ms)
DOWNLOAD_TIMEOUT_MS=30000
# Max messages kept in memory buffer
MAX_BUFFER_SIZE=1000
+25
View File
@@ -0,0 +1,25 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- run: bun install --frozen-lockfile
- name: Lint
run: bun lint
- name: Typecheck
run: bun check
+40
View File
@@ -0,0 +1,40 @@
name: Release
on:
push:
tags: ["v*"]
permissions:
contents: read
packages: write
jobs:
docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v6
id: meta
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
- uses: docker/build-push-action@v7
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+37
View File
@@ -0,0 +1,37 @@
# dependencies (bun install)
node_modules
# output
out
dist
*.tgz
# code coverage
coverage
*.lcov
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# caches
.eslintcache
.cache
*.tsbuildinfo
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
# runtime data
data/
+13
View File
@@ -0,0 +1,13 @@
{
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports.biome": "explicit"
},
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome"
}
}
+83
View File
@@ -0,0 +1,83 @@
# 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
```bash
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). Handles `scaned_but_redirect` by switching base URL.
- `api.ts` — HTTP calls to iLink API (getUpdates, sendMessage, getConfig, sendTyping, getUploadUrl) with timeout via AbortController. Uses `json-bigint` for 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 crypto
- `types.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 to `DATA_DIR` as 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 own `Hono<Env>` with `Env = { 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.ts` for all request bodies. Routes use `@hono/zod-validator` via `zValidator('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 via `resolve-to.ts`
- **Context tokens**: Required for sending replies. Auto-cached from incoming messages by poller. Can be overridden per-request.
- **BigInt**: Uses `json-bigint` for protocol number preservation
- **Exhaustive switches**: Message item type switches use `const _exhaustive: never = item` pattern
## 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_PREFIX` in `constants.ts` prefixes all outgoing message IDs
- Docker container runs on port 3000 internally, mapped to 29527 in docker-compose; dev mode uses port 3456
- `API_KEY` must 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)
+26
View File
@@ -0,0 +1,26 @@
FROM oven/bun:1-alpine AS build
WORKDIR /app
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production
COPY src/ ./src/
COPY tsconfig.json ./
RUN bun build --compile --minify src/index.ts --outfile server
FROM alpine:3.21
WORKDIR /app
RUN apk add --no-cache libstdc++ libgcc
COPY --from=build /app/server ./server
RUN adduser -D app && mkdir -p /app/data && chown -R app:app /app/data
USER app
ENV PORT=3000
EXPOSE 3000
VOLUME /app/data
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -qO- http://localhost:3000/status || exit 1
CMD ["./server"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Kadxy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+169
View File
@@ -0,0 +1,169 @@
# weixin-ilink-gateway
**[简体中文](README_zh.md)**
A lightweight HTTP gateway built on top of [`@tencent-weixin/openclaw-weixin`](https://www.npmjs.com/package/@tencent-weixin/openclaw-weixin) that wraps the WeChat iLink Bot protocol into a clean REST API — QR code login, messaging, media upload/download, webhook push & receive, all as simple HTTP endpoints.
Built with [Bun](https://bun.sh) + [Hono](https://hono.dev) + [Zod](https://zod.dev).
## Features
- **QR Code Login** — Simple login flow with real-time scan status polling
- **Message Receiving** — Background long-poll with in-memory ring buffer and optional webhook push
- **Message Sending** — Text, image, video, and file support; URL-based media is automatically downloaded and uploaded to CDN
- **Media Handling** — Upload, presign, and download with transparent AES encryption/decryption
- **State Persistence** — Credentials, sync cursors, and context tokens survive restarts
- **Webhook Delivery** — Fire-and-forget delivery with automatic retry; also supports inbound webhooks
## Quick Start
```bash
git clone https://github.com/kadxy/weixin-ilink-gateway.git
cd weixin-ilink-gateway
cp .env.example .env # Edit to set at least API_KEY
docker compose up -d
```
The service will be available at `http://localhost:29527`.
### Running from Source
> Requires [Bun](https://bun.sh) v1.0+
```bash
bun install
bun run dev # Starts with auto-reload on file changes
```
Default port is **3456** (override with `PORT` env var).
## Configuration
| Variable | Required | Default | Description |
| --- | --- | --- | --- |
| `API_KEY` | **Yes** | — | Bearer token for authenticating API requests (min 12 chars) |
| `PORT` | No | `3456` | Server listen port |
| `DATA_DIR` | No | `./data` | Directory for persisted state files |
| `WEBHOOK_URLS` | No | — | Comma-separated URLs for push-delivering incoming messages |
| `WEBHOOK_TOKEN` | No | — | Enables the `POST /webhook/:token` inbound endpoint |
| `MAX_DOWNLOAD_SIZE_MB` | No | `128` | Max file size (MB) for URL-based media downloads |
| `DOWNLOAD_TIMEOUT_MS` | No | `30000` | Timeout (ms) for downloading media from external URLs |
| `MAX_BUFFER_SIZE` | No | `1000` | Max messages kept in the in-memory ring buffer |
## API Reference
All endpoints require `Authorization: Bearer <API_KEY>` unless noted otherwise.
### Auth
```text
POST /auth/login Start QR code login, returns { qr_url }
POST /auth/logout Logout and stop message polling
```
### Status
```text
GET /status Login state, polling status, webhook config
```
### Messages (requires login)
```text
POST /messages/send Send one or more message items
GET /messages/updates?after=<seq> Get buffered incoming messages
```
<details>
<summary>Send body example</summary>
```json
{
"to": "<user_id or \"self\">",
"items": [
{ "type": "text", "text": "Hello!" },
{ "type": "image", "url": "https://example.com/photo.jpg" },
{ "type": "video", "cdn": { "encrypt_query_param": "...", "aes_key": "..." } },
{ "type": "file", "file_name": "doc.pdf", "url": "https://example.com/doc.pdf" }
],
"context_token": "(optional, auto-resolved from cache)"
}
```
Each item supports either `url` (the gateway downloads and re-uploads to CDN) or `cdn` (a pre-uploaded reference). The `file` type additionally requires `file_name`.
> **Note:** Sending messages requires a `context_token` for the target user. The gateway auto-caches this token when an incoming message is received from that user via the poller. Until then, sends to that user will fail. To bootstrap, send a message _to_ the bot from the target user first.
</details>
### Media (requires login)
```text
POST /media/upload Upload a file via multipart form (fields: file, to)
POST /media/presign Get a presigned URL for direct CDN upload
POST /media/download Download and decrypt a file from CDN
```
<details>
<summary>Upload response</summary>
```json
{
"ok": true,
"media_type": "image",
"file_name": "photo.png",
"filekey": "...",
"encrypt_query_param": "...",
"aes_key": "...",
"file_size": 12345,
"file_size_ciphertext": 12352
}
```
The returned `encrypt_query_param` and `aes_key` can be passed as a `cdn` reference in `/messages/send`.
</details>
### Typing (requires login)
```text
POST /typing/start Send typing indicator { "to": "<user_id>" }
POST /typing/stop Cancel typing indicator { "to": "<user_id>" }
```
### Config (requires login)
```text
POST /config Get bot config (e.g. typing ticket) for a user
```
### Webhook (no auth required)
```text
POST /webhook/:token Send a text message to self via inbound webhook
```
Accepts `application/json` (`{ "text": "..." }`) or `text/plain` body.
Requires the `WEBHOOK_TOKEN` env var to be set; the `:token` path parameter must match.
### Console (no auth required)
```text
GET /console Browser-based debug console
```
A built-in single-page UI for testing the API. Enter your API key in the browser, then login via QR code, send test messages, and more. Supports English and Chinese (auto-detected from browser language).
## Project Structure
```text
src/
├── sdk/ WeChat iLink protocol client (auth, API, CDN, crypto)
└── gateway/ HTTP gateway layer (routes, poller, state management)
```
## License
[MIT](LICENSE)
+169
View File
@@ -0,0 +1,169 @@
# weixin-ilink-gateway
**[English](README.md)**
基于微信官方插件 [`@tencent-weixin/openclaw-weixin`](https://www.npmjs.com/package/@tencent-weixin/openclaw-weixin) 封装的轻量 HTTP 网关,将 iLink Bot 协议的扫码登录、消息收发、媒体上传下载、Webhook 推送与接收等能力封装为 REST API,方便任何语言和平台接入微信 ClawBot。
基于 [Bun](https://bun.sh) + [Hono](https://hono.dev) + [Zod](https://zod.dev) 构建。
## 功能特性
- **扫码登录** — 简单的二维码登录流程,支持实时轮询扫码状态
- **消息接收** — 后台长轮询,内存环形缓冲区 + 可选 Webhook 推送
- **消息发送** — 支持文本、图片、视频、文件;URL 媒体自动下载并上传至 CDN
- **媒体处理** — 上传、预签名、下载,自动处理 AES 加解密
- **状态持久化** — 登录凭证、同步游标、上下文令牌重启后自动恢复
- **Webhook 推送** — 收到消息后自动推送至配置的 URL,失败自动重试;同时支持入站 Webhook
## 快速开始
```bash
git clone https://github.com/kadxy/weixin-ilink-gateway.git
cd weixin-ilink-gateway
cp .env.example .env # 编辑 .env,至少设置 API_KEY
docker compose up -d
```
服务默认运行在 `http://localhost:29527`。
### 从源码运行
> 需要 [Bun](https://bun.sh) v1.0+
```bash
bun install
bun run dev # 文件变更时自动重载
```
默认端口 **3456**(可通过 `PORT` 环境变量覆盖)。
## 配置项
| 变量 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `API_KEY` | **是** | — | API 请求的 Bearer Token(至少 12 位) |
| `PORT` | 否 | `3456` | 服务监听端口 |
| `DATA_DIR` | 否 | `./data` | 持久化状态文件目录 |
| `WEBHOOK_URLS` | 否 | — | 消息推送目标 URL,多个用逗号分隔 |
| `WEBHOOK_TOKEN` | 否 | — | 启用 `POST /webhook/:token` 入站端点 |
| `MAX_DOWNLOAD_SIZE_MB` | 否 | `128` | URL 媒体下载的最大文件大小(MB) |
| `DOWNLOAD_TIMEOUT_MS` | 否 | `30000` | 下载外部媒体 URL 的超时时间(毫秒) |
| `MAX_BUFFER_SIZE` | 否 | `1000` | 内存环形缓冲区最大消息数 |
## API 参考
除特别说明外,所有接口均需要 `Authorization: Bearer <API_KEY>` 认证。
### 登录认证
```text
POST /auth/login 发起扫码登录,返回 { qr_url }
POST /auth/logout 登出并停止消息轮询
```
### 状态
```text
GET /status 登录状态、轮询状态、Webhook 配置
```
### 消息(需登录)
```text
POST /messages/send 发送一条或多条消息
GET /messages/updates?after=<seq> 获取缓冲区中的新消息
```
<details>
<summary>发送请求体示例</summary>
```json
{
"to": "<user_id 或 \"self\">",
"items": [
{ "type": "text", "text": "你好!" },
{ "type": "image", "url": "https://example.com/photo.jpg" },
{ "type": "video", "cdn": { "encrypt_query_param": "...", "aes_key": "..." } },
{ "type": "file", "file_name": "doc.pdf", "url": "https://example.com/doc.pdf" }
],
"context_token": "(可选,自动从缓存中解析)"
}
```
每种消息类型支持 `url`(网关自动下载并上传至 CDN)或 `cdn`(已上传的 CDN 引用)两种方式。`file` 类型还需要提供 `file_name`。
> **注意:** 发送消息需要目标用户的 `context_token`。该令牌会在轮询器收到该用户的消息时自动缓存。在此之前,向该用户发送消息会失败。要初始化令牌,需要先让目标用户向 Bot 发送一条消息。
</details>
### 媒体(需登录)
```text
POST /media/upload 通过 multipart 表单上传文件(字段:file, to)
POST /media/presign 获取预签名 URL,用于直接上传至 CDN
POST /media/download 从 CDN 下载并解密文件
```
<details>
<summary>上传响应示例</summary>
```json
{
"ok": true,
"media_type": "image",
"file_name": "photo.png",
"filekey": "...",
"encrypt_query_param": "...",
"aes_key": "...",
"file_size": 12345,
"file_size_ciphertext": 12352
}
```
返回的 `encrypt_query_param` 和 `aes_key` 可作为 `cdn` 引用传入 `/messages/send`。
</details>
### 输入状态(需登录)
```text
POST /typing/start 发送输入状态指示器 { "to": "<user_id>" }
POST /typing/stop 取消输入状态指示器 { "to": "<user_id>" }
```
### 配置(需登录)
```text
POST /config 获取指定用户的 Bot 配置(如 typing ticket)
```
### Webhook(无需认证)
```text
POST /webhook/:token 通过入站 Webhook 向自己发送文本消息
```
支持 `application/json`(`{ "text": "..." }`)或 `text/plain` 请求体。
需要设置 `WEBHOOK_TOKEN` 环境变量,URL 中的 `:token` 必须与之匹配。
### 调试控制台(无需认证)
```text
GET /console 浏览器调试控制台
```
内置的单页调试界面,在浏览器中输入 API Key 即可扫码登录、发送测试消息等。支持中英文自动切换。
## 项目结构
```text
src/
├── sdk/ 微信 iLink 协议客户端(登录、API、CDN、加解密)
└── gateway/ HTTP 网关层(路由、轮询、状态管理)
```
## 协议
[MIT](LICENSE)
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",
"formatter": {
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 120
},
"linter": {
"enabled": true
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "asNeeded"
}
}
}
+64
View File
@@ -0,0 +1,64 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "weixin-ilink-gateway",
"dependencies": {
"@hono/zod-validator": "^0.7.6",
"hono": "^4.12.13",
"json-bigint": "^1.0.0",
"zod": "^4.3.6",
},
"devDependencies": {
"@biomejs/biome": "^2.4.12",
"@types/bun": "latest",
"@types/json-bigint": "^1.0.4",
},
"peerDependencies": {
"typescript": "^5",
},
},
},
"packages": {
"@biomejs/biome": ["@biomejs/biome@2.4.12", "https://registry.npmmirror.com/@biomejs/biome/-/biome-2.4.12.tgz", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],
"@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.4.12.tgz", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],
"@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.4.12.tgz", { "os": "darwin", "cpu": "x64" }, "sha512-x9uJ0bI1rJsWICp3VH8w/5PnAVD3A7SqzDpbrfoUQX1QyWrK5jSU4fRLo/wSgGeplCivbxBRKmt5Xq4/nWvq8A=="],
"@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.4.12.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-tOwuCuZZtKi1jVzbk/5nXmIsziOB6yqN8c9r9QM0EJYPU6DpQWf11uBOSCfFKKM4H3d9ZoarvlgMfbcuD051Pw=="],
"@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.4.12.tgz", { "os": "linux", "cpu": "arm64" }, "sha512-FhfpkAAlKL6kwvcVap0Hgp4AhZmtd3YImg0kK1jd7C/aSoh4SfsB2f++yG1rU0lr8Y5MCFJrcSkmssiL9Xnnig=="],
"@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-linux-x64/-/cli-linux-x64-2.4.12.tgz", { "os": "linux", "cpu": "x64" }, "sha512-8pFeAnLU9QdW9jCIslB/v82bI0lhBmz2ZAKc8pVMFPO0t0wAHsoEkrUQUbMkIorTRIjbqyNZHA3lEXavsPWYSw=="],
"@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.4.12.tgz", { "os": "linux", "cpu": "x64" }, "sha512-dwTIgZrGutzhkQCuvHynCkyW6hJxUuyZqKKO0YNfaS2GUoRO+tOvxXZqZB6SkWAOdfZTzwaw8IEdUnIkHKHoew=="],
"@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.4.12.tgz", { "os": "win32", "cpu": "arm64" }, "sha512-B0DLnx0vA9ya/3v7XyCaP+/lCpnbWbMOfUFFve+xb5OxyYvdHaS55YsSddr228Y+JAFk58agCuZTsqNiw2a6ig=="],
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.12", "https://registry.npmmirror.com/@biomejs/cli-win32-x64/-/cli-win32-x64-2.4.12.tgz", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],
"@hono/zod-validator": ["@hono/zod-validator@0.7.6", "https://registry.npmmirror.com/@hono/zod-validator/-/zod-validator-0.7.6.tgz", { "peerDependencies": { "hono": ">=3.9.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Io1B6d011Gj1KknV4rXYz4le5+5EubcWEU/speUjuw9XMMIaP3n78yXLhjd2A3PXaXaUwEAluOiAyLqhBEJgsw=="],
"@types/bun": ["@types/bun@1.3.12", "https://registry.npmmirror.com/@types/bun/-/bun-1.3.12.tgz", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
"@types/json-bigint": ["@types/json-bigint@1.0.4", "https://registry.npmmirror.com/@types/json-bigint/-/json-bigint-1.0.4.tgz", {}, "sha512-ydHooXLbOmxBbubnA7Eh+RpBzuaIiQjh8WGJYQB50JFGFrdxW7JzVlyEV7fAXw0T2sqJ1ysTneJbiyNLqZRAag=="],
"@types/node": ["@types/node@25.6.0", "https://registry.npmmirror.com/@types/node/-/node-25.6.0.tgz", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
"bignumber.js": ["bignumber.js@9.3.1", "https://registry.npmmirror.com/bignumber.js/-/bignumber.js-9.3.1.tgz", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
"bun-types": ["bun-types@1.3.12", "https://registry.npmmirror.com/bun-types/-/bun-types-1.3.12.tgz", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
"hono": ["hono@4.12.13", "https://registry.npmmirror.com/hono/-/hono-4.12.13.tgz", {}, "sha512-cURhqIxgqO41Ae6/UthPZlsLxMRhRnkF1bY3no8b7YI4nP3klwag/fTfWT+YZAdq8UyusypunAVwl4AkTe++QQ=="],
"json-bigint": ["json-bigint@1.0.0", "https://registry.npmmirror.com/json-bigint/-/json-bigint-1.0.0.tgz", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],
"typescript": ["typescript@5.9.3", "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.19.2", "https://registry.npmmirror.com/undici-types/-/undici-types-7.19.2.tgz", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="],
"zod": ["zod@4.3.6", "https://registry.npmmirror.com/zod/-/zod-4.3.6.tgz", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
}
}
+15
View File
@@ -0,0 +1,15 @@
services:
gateway:
image: ghcr.io/kadxy/weixin-ilink-gateway:latest
container_name: weixin-ilink-gateway
restart: unless-stopped
ports:
- "29527:3000"
volumes:
- gateway-data:/app/data
env_file: .env
environment:
- DATA_DIR=/app/data
volumes:
gateway-data:
+850
View File
@@ -0,0 +1,850 @@
openapi: 3.1.0
info:
title: WeChat iLink Gateway
description: Universal HTTP gateway for Tencent WeChat iLink Bot API.
version: 0.1.0
servers:
- url: http://localhost:3456
description: Local development
security:
- bearerAuth: []
webhooks:
newMessage:
post:
summary: Outgoing webhook — new message notification
description: |
When `WEBHOOK_URLS` is configured, the gateway POSTs each incoming user message
to every URL. The payload is the raw WeChat message object (unmodified).
Retries up to 2 times with 1s delay on failure.
tags: [Webhook]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/WeixinMessage"
responses:
"200":
description: Webhook received successfully
paths:
# ---------------------------------------------------------------------------
# Incoming Webhook
# ---------------------------------------------------------------------------
/webhook/{token}:
post:
summary: Incoming webhook (send text to self)
description: |
Receives text from external services and sends it to the bot's own WeChat as a text message.
Authenticates via token in URL path (set via `WEBHOOK_TOKEN` env var).
Does NOT require Bearer auth. Supports `text/plain` body or JSON `{"text": "..."}`.
tags: [Webhook]
security: []
parameters:
- name: token
in: path
required: true
schema:
type: string
description: Must match `WEBHOOK_TOKEN` environment variable
requestBody:
required: true
content:
text/plain:
schema:
type: string
example: Hello from external service
application/json:
schema:
type: object
required: [text]
properties:
text:
type: string
example: Hello from external service
responses:
"200":
description: Message sent
content:
application/json:
schema:
type: object
required: [ok, client_id]
properties:
ok:
type: boolean
example: true
client_id:
type: string
"400":
$ref: "#/components/responses/BadRequest"
"401":
$ref: "#/components/responses/Unauthorized"
"500":
description: Send failed
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: false
message:
type: string
# ---------------------------------------------------------------------------
# Auth
# ---------------------------------------------------------------------------
/auth/login:
post:
summary: Start QR code login
description: |
Initiates a WeChat QR code login flow. Returns a QR code URL immediately.
The server polls for scan confirmation in the background.
Rejects with 409 if already logged in.
tags: [Auth]
responses:
"200":
description: QR code generated
content:
application/json:
schema:
type: object
required: [ok, qr_url]
properties:
ok:
type: boolean
example: true
qr_url:
type: string
description: Base64-encoded QR code image content
"409":
$ref: "#/components/responses/Conflict"
/auth/logout:
post:
summary: Logout and stop polling
description: Clears credentials, context tokens, stops message polling, and resets login state.
tags: [Auth]
responses:
"200":
description: Logged out
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: true
message:
type: string
example: Logged out
"400":
$ref: "#/components/responses/BadRequest"
# ---------------------------------------------------------------------------
# Status
# ---------------------------------------------------------------------------
/status:
get:
summary: Get gateway status
description: Returns current login state, polling status, and webhook configuration. Does not require login.
tags: [Status]
responses:
"200":
description: Current status
content:
application/json:
schema:
type: object
required: [ok, logged_in, user_id, login_status, login_error, qr_url, polling, webhook_urls]
properties:
ok:
type: boolean
example: true
logged_in:
type: boolean
user_id:
type: string
nullable: true
login_status:
type: string
enum: [idle, waiting, scanned, confirmed, failed]
login_error:
type: string
nullable: true
qr_url:
type: string
nullable: true
polling:
type: boolean
webhook_urls:
type: array
items:
type: string
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
/messages/send:
post:
summary: Send messages
description: |
Sends one or more message items to a user. Supports text, image, video, and file.
Media can be provided as a URL (auto-uploaded) or a pre-uploaded CDN reference.
The `to` field accepts a user ID or `"self"` to message yourself.
A `context_token` is auto-injected from cache if not provided.
tags: [Messages]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/SendMessageRequest"
responses:
"200":
description: Send results (per item)
content:
application/json:
schema:
type: object
required: [ok, results]
properties:
ok:
type: boolean
description: true if all items sent successfully
results:
type: array
items:
$ref: "#/components/schemas/SendResult"
warnings:
type: array
items:
type: string
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
/messages/updates:
get:
summary: Get buffered messages
description: |
Returns messages from the in-memory buffer. Optionally filter by sequence number.
Messages are received via background long-polling and buffered (max 1000).
tags: [Messages]
parameters:
- name: after
in: query
required: false
schema:
type: integer
description: Only return messages with seq > this value
responses:
"200":
description: Buffered messages
content:
application/json:
schema:
type: object
required: [ok, count, messages]
properties:
ok:
type: boolean
example: true
count:
type: integer
messages:
type: array
items:
$ref: "#/components/schemas/WeixinMessage"
"401":
$ref: "#/components/responses/Unauthorized"
# ---------------------------------------------------------------------------
# Media
# ---------------------------------------------------------------------------
/media/upload:
post:
summary: Upload media file
description: |
Uploads a file to WeChat CDN. Automatically detects media type from MIME type or file extension.
Returns CDN reference fields that can be used in `/messages/send` with the `cdn` format.
tags: [Media]
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file, to]
properties:
file:
type: string
format: binary
to:
type: string
description: Target user ID or `"self"`
responses:
"200":
description: Upload successful
content:
application/json:
schema:
type: object
required: [ok, media_type, file_name, filekey, encrypt_query_param, aes_key, file_size, file_size_ciphertext]
properties:
ok:
type: boolean
example: true
media_type:
type: string
enum: [image, video, file]
file_name:
type: string
filekey:
type: string
encrypt_query_param:
type: string
description: CDN encrypted query parameter for download
aes_key:
type: string
description: Base64-encoded AES key for decryption
file_size:
type: integer
description: Original file size in bytes
file_size_ciphertext:
type: integer
description: Encrypted file size in bytes
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
/media/presign:
post:
summary: Get presigned upload URL
description: |
Returns a presigned CDN upload URL for client-side upload.
Use this when you want to encrypt and upload the file yourself.
tags: [Media]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/MediaPresignRequest"
responses:
"200":
description: Presigned URL
content:
application/json:
schema:
type: object
required: [ok]
properties:
ok:
type: boolean
example: true
upload_param:
type: string
thumb_upload_param:
type: string
upload_full_url:
type: string
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
/media/download:
post:
summary: Download and decrypt media
description: Downloads an encrypted file from WeChat CDN, decrypts it, and returns the raw binary.
tags: [Media]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/MediaDownloadRequest"
responses:
"200":
description: Decrypted file binary
content:
application/octet-stream:
schema:
type: string
format: binary
headers:
Content-Disposition:
schema:
type: string
example: attachment; filename="photo.jpg"
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
# ---------------------------------------------------------------------------
# Typing
# ---------------------------------------------------------------------------
/typing/start:
post:
summary: Send typing indicator
description: Shows a "typing..." indicator to the target user. Automatically fetches and caches the typing ticket.
tags: [Typing]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ToRequest"
responses:
"200":
$ref: "#/components/responses/Ok"
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
/typing/stop:
post:
summary: Cancel typing indicator
description: Cancels the "typing..." indicator for the target user.
tags: [Typing]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ToRequest"
responses:
"200":
$ref: "#/components/responses/Ok"
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
/config:
post:
summary: Get bot configuration
description: |
Retrieves bot configuration for a target user, including typing ticket.
Auto-injects context_token from cache if not provided.
tags: [Config]
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/ConfigRequest"
responses:
"200":
description: Bot configuration
content:
application/json:
schema:
type: object
required: [ok]
properties:
ok:
type: boolean
example: true
typing_ticket:
type: string
"400":
$ref: "#/components/responses/ValidationError"
"401":
$ref: "#/components/responses/Unauthorized"
# =============================================================================
# Components
# =============================================================================
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: API key set via `API_KEY` environment variable
# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------
schemas:
ToRequest:
type: object
required: [to]
properties:
to:
type: string
description: Target user ID or `"self"`
ConfigRequest:
type: object
required: [to]
properties:
to:
type: string
description: Target user ID or `"self"`
context_token:
type: string
description: Optional override; auto-injected from cache if omitted
CdnRef:
type: object
required: [encrypt_query_param, aes_key]
properties:
encrypt_query_param:
type: string
aes_key:
type: string
file_size_ciphertext:
type: integer
SendItemText:
type: object
required: [type, text]
properties:
type:
type: string
enum: [text]
text:
type: string
SendItemImageUrl:
type: object
required: [type, url]
properties:
type:
type: string
enum: [image]
url:
type: string
description: Image URL (will be auto-downloaded and uploaded to CDN)
SendItemImageCdn:
type: object
required: [type, cdn]
properties:
type:
type: string
enum: [image]
cdn:
$ref: "#/components/schemas/CdnRef"
SendItemVideoUrl:
type: object
required: [type, url]
properties:
type:
type: string
enum: [video]
url:
type: string
SendItemVideoCdn:
type: object
required: [type, cdn]
properties:
type:
type: string
enum: [video]
cdn:
$ref: "#/components/schemas/CdnRef"
SendItemFileUrl:
type: object
required: [type, url, file_name]
properties:
type:
type: string
enum: [file]
url:
type: string
file_name:
type: string
SendItemFileCdn:
type: object
required: [type, cdn, file_name]
properties:
type:
type: string
enum: [file]
cdn:
$ref: "#/components/schemas/CdnRef"
file_name:
type: string
SendItem:
oneOf:
- $ref: "#/components/schemas/SendItemText"
- $ref: "#/components/schemas/SendItemImageUrl"
- $ref: "#/components/schemas/SendItemImageCdn"
- $ref: "#/components/schemas/SendItemVideoUrl"
- $ref: "#/components/schemas/SendItemVideoCdn"
- $ref: "#/components/schemas/SendItemFileUrl"
- $ref: "#/components/schemas/SendItemFileCdn"
discriminator:
propertyName: type
SendMessageRequest:
type: object
required: [to, items]
properties:
to:
type: string
description: Target user ID or `"self"`
items:
type: array
minItems: 1
items:
$ref: "#/components/schemas/SendItem"
context_token:
type: string
description: Optional override; auto-injected from cache if omitted
SendResult:
type: object
required: [type, ok]
properties:
type:
type: string
enum: [text, image, video, file]
ok:
type: boolean
client_id:
type: string
error:
type: string
MediaPresignRequest:
type: object
required: [to, filekey, media_type, rawsize, rawfilemd5, filesize, aeskey]
properties:
to:
type: string
filekey:
type: string
media_type:
type: integer
description: "1=image, 2=video, 3=file, 4=voice"
rawsize:
type: integer
rawfilemd5:
type: string
filesize:
type: integer
description: AES-ECB padded size
aeskey:
type: string
description: Hex-encoded AES key
thumb_rawsize:
type: integer
thumb_rawfilemd5:
type: string
thumb_filesize:
type: integer
no_need_thumb:
type: boolean
MediaDownloadRequest:
type: object
required: [full_url, aes_key, file_name]
properties:
full_url:
type: string
format: uri
aes_key:
type: string
description: Base64-encoded AES key
file_name:
type: string
CDNMedia:
type: object
properties:
encrypt_query_param:
type: string
aes_key:
type: string
encrypt_type:
type: integer
full_url:
type: string
MessageItem:
type: object
properties:
type:
type: integer
description: "0=NONE, 1=TEXT, 2=IMAGE, 3=VOICE, 4=FILE, 5=VIDEO"
create_time_ms:
type: integer
update_time_ms:
type: integer
is_completed:
type: boolean
msg_id:
type: string
text_item:
type: object
properties:
text:
type: string
image_item:
type: object
properties:
media:
$ref: "#/components/schemas/CDNMedia"
mid_size:
type: integer
voice_item:
type: object
properties:
media:
$ref: "#/components/schemas/CDNMedia"
playtime:
type: integer
text:
type: string
file_item:
type: object
properties:
media:
$ref: "#/components/schemas/CDNMedia"
file_name:
type: string
md5:
type: string
len:
type: string
video_item:
type: object
properties:
media:
$ref: "#/components/schemas/CDNMedia"
video_size:
type: integer
play_length:
type: integer
WeixinMessage:
type: object
description: Original WeChat message format (unmodified)
properties:
seq:
type: integer
message_id:
type: string
description: String to avoid JS precision loss on large integers
from_user_id:
type: string
to_user_id:
type: string
client_id:
type: string
create_time_ms:
type: integer
update_time_ms:
type: integer
session_id:
type: string
group_id:
type: string
message_type:
type: integer
description: "0=NONE, 1=USER, 2=BOT"
message_state:
type: integer
description: "0=NEW, 1=GENERATING, 2=FINISH"
item_list:
type: array
items:
$ref: "#/components/schemas/MessageItem"
context_token:
type: string
# ---------------------------------------------------------------------------
# Reusable responses
# ---------------------------------------------------------------------------
responses:
Ok:
description: Success
content:
application/json:
schema:
type: object
required: [ok]
properties:
ok:
type: boolean
example: true
BadRequest:
description: Bad request
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: false
message:
type: string
Unauthorized:
description: Missing/invalid Bearer token or not logged in
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: false
message:
type: string
Conflict:
description: Already logged in
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: false
message:
type: string
ValidationError:
description: Request validation failed
content:
application/json:
schema:
type: object
required: [ok, message]
properties:
ok:
type: boolean
example: false
message:
type: string
+314
View File
@@ -0,0 +1,314 @@
{
"name": "weixin-ilink-gateway",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "weixin-ilink-gateway",
"version": "0.1.0",
"license": "MIT",
"dependencies": {
"@hono/zod-validator": "^0.7.6",
"hono": "^4.12.13",
"json-bigint": "^1.0.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@biomejs/biome": "^2.4.12",
"@types/bun": "latest",
"@types/json-bigint": "^1.0.4"
},
"peerDependencies": {
"typescript": "^5"
}
},
"node_modules/@biomejs/biome": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.5.15.tgz",
"integrity": "sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ==",
"dev": true,
"license": "MIT OR Apache-2.0",
"bin": {
"biome": "bin/biome"
},
"engines": {
"node": ">=14.21.3"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/biome"
},
"optionalDependencies": {
"@biomejs/cli-darwin-arm64": "2.5.15",
"@biomejs/cli-darwin-x64": "2.5.15",
"@biomejs/cli-linux-arm64": "2.5.15",
"@biomejs/cli-linux-arm64-musl": "2.5.15",
"@biomejs/cli-linux-x64": "2.5.15",
"@biomejs/cli-linux-x64-musl": "2.5.15",
"@biomejs/cli-win32-arm64": "2.5.15",
"@biomejs/cli-win32-x64": "2.5.15"
}
},
"node_modules/@biomejs/cli-darwin-arm64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.5.15.tgz",
"integrity": "sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-darwin-x64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.5.15.tgz",
"integrity": "sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.5.15.tgz",
"integrity": "sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64-musl": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.5.15.tgz",
"integrity": "sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.5.15.tgz",
"integrity": "sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64-musl": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.5.15.tgz",
"integrity": "sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-arm64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.5.15.tgz",
"integrity": "sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-x64": {
"version": "2.5.15",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.5.15.tgz",
"integrity": "sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@hono/zod-validator": {
"version": "0.7.6",
"resolved": "https://registry.npmjs.org/@hono/zod-validator/-/zod-validator-0.7.6.tgz",
"integrity": "sha512-Io1B6d011Gj1KknV4rXYz4le5+5EubcWEU/speUjuw9XMMIaP3n78yXLhjd2A3PXaXaUwEAluOiAyLqhBEJgsw==",
"license": "MIT",
"peerDependencies": {
"hono": ">=3.9.0",
"zod": "^3.25.0 || ^4.0.0"
}
},
"node_modules/@types/bun": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.4.3.tgz",
"integrity": "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw==",
"dev": true,
"license": "MIT",
"dependencies": {
"bun-types": "1.4.3"
}
},
"node_modules/@types/json-bigint": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@types/json-bigint/-/json-bigint-1.0.4.tgz",
"integrity": "sha512-ydHooXLbOmxBbubnA7Eh+RpBzuaIiQjh8WGJYQB50JFGFrdxW7JzVlyEV7fAXw0T2sqJ1ysTneJbiyNLqZRAag==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/node/node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/bignumber.js": {
"version": "9.3.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
"integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/bun-types": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.4.3.tgz",
"integrity": "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"undici-types": "*"
}
},
"node_modules/hono": {
"version": "4.13.13",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",
"integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
}
},
"node_modules/json-bigint": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
"license": "MIT",
"dependencies": {
"bignumber.js": "^9.0.0"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "8.11.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.11.2.tgz",
"integrity": "sha512-iMVNmWZ0leK/goS6eXMizSzmm9CDWtyphwbaCms3DNLqRxDL+mMoNVcZMTyyVgXP0N+Z8neAMzDoUOUJL8veKg==",
"dev": true,
"license": "MIT"
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "weixin-ilink-gateway",
"version": "0.1.0",
"module": "src/index.ts",
"type": "module",
"private": false,
"scripts": {
"dev": "bun run --watch src/index.ts",
"start": "bun run src/index.ts",
"check": "tsc --noEmit",
"format": "biome format --write ./src ./test",
"lint": "biome check ./src ./test",
"lint:fix": "biome check --write ./src ./test",
"test": "bun test test/"
},
"devDependencies": {
"@biomejs/biome": "^2.4.12",
"@types/bun": "latest",
"@types/json-bigint": "^1.0.4"
},
"peerDependencies": {
"typescript": "^5"
},
"dependencies": {
"@hono/zod-validator": "^0.7.6",
"hono": "^4.12.13",
"json-bigint": "^1.0.0",
"zod": "^4.3.6"
},
"license": "MIT"
}
+43
View File
@@ -0,0 +1,43 @@
const env = (key: string, fallback?: string): string => {
const v = process.env[key]
if (v !== undefined && v !== '') return v
if (fallback !== undefined) return fallback
throw new Error(`Missing required environment variable: ${key}`)
}
const intEnv = (key: string, fallback: number): number => {
const raw = process.env[key]
if (raw === undefined || raw === '') return fallback
const n = parseInt(raw, 10)
if (Number.isNaN(n)) throw new Error(`Invalid integer for ${key}: ${raw}`)
return n
}
export const config = {
/** Gateway API authentication key (required, min 12 chars). */
apiKey: env('API_KEY'),
/** Server listen port. */
port: intEnv('PORT', 3456),
/** Directory for persisted state files. */
dataDir: env('DATA_DIR', './data'),
/** Comma-separated webhook URLs for push delivery. */
webhookUrls: env('WEBHOOK_URLS', '')
.split(',')
.map((u) => u.trim())
.filter(Boolean),
/** Token that authorises incoming POST /webhook/:token requests. */
webhookToken: env('WEBHOOK_TOKEN', ''),
/** Max file size (bytes) when downloading a URL for upload. */
maxDownloadSize: intEnv('MAX_DOWNLOAD_SIZE_MB', 128) * 1024 * 1024,
/** Timeout (ms) when downloading a media URL. */
downloadTimeoutMs: intEnv('DOWNLOAD_TIMEOUT_MS', 30_000),
/** Max messages kept in the in-memory ring buffer (upper limit 1 GB worth ≈ 1,073,741,824). */
maxBufferSize: Math.min(intEnv('MAX_BUFFER_SIZE', 1000), 1_073_741_824),
} as const
+87
View File
@@ -0,0 +1,87 @@
import { Hono } from 'hono'
import { logger as honoLogger } from 'hono/logger'
import { logger } from '../lib/logger.js'
import { HttpStatus } from './lib/http.js'
import authRoutes from './routes/auth.js'
import configRoutes from './routes/config.js'
import consoleRoutes from './routes/console.js'
import mediaRoutes from './routes/media.js'
import messagesRoutes from './routes/messages.js'
import statusRoutes from './routes/status.js'
import typingRoutes from './routes/typing.js'
import webhookRoutes from './routes/webhook.js'
import type { Credentials } from './state.js'
import { getCredentials } from './state.js'
type Env = {
Variables: {
credentials: Credentials
}
}
export const createApp = (apiKey: string): Hono => {
const app = new Hono()
// HTTP request/response logging
const logFn = (msg: string) => logger.info('http', msg)
app.use('/*', honoLogger(logFn))
// Bearer token auth (skip for /webhook — uses token-in-URL auth)
app.use('/*', async (c, next) => {
if (c.req.path.startsWith('/webhook') || c.req.path.startsWith('/console')) {
await next()
return
}
const header = c.req.header('Authorization')
if (!header) {
logger.warn('http', `${c.req.method} ${c.req.path} → 401 Missing Authorization header`)
return c.json({ ok: false, message: 'Missing Authorization header' }, HttpStatus.UNAUTHORIZED)
}
const match = header.match(/^Bearer\s+(.+)$/i)
if (!match || match[1] !== apiKey) {
logger.warn('http', `${c.req.method} ${c.req.path} → 401 Invalid token`)
return c.json({ ok: false, message: 'Invalid token' }, HttpStatus.UNAUTHORIZED)
}
await next()
})
// Public routes (no login required)
app.route('/auth', authRoutes)
app.route('/status', statusRoutes)
app.route('/webhook', webhookRoutes)
app.route('/console', consoleRoutes)
// Login guard: check credentials and inject into context
const authedApp = new Hono<Env>()
authedApp.use('/*', async (c, next) => {
const creds = getCredentials()
if (!creds) {
return c.json({ ok: false, message: 'Not logged in' }, HttpStatus.UNAUTHORIZED)
}
c.set('credentials', creds)
await next()
})
authedApp.route('/messages', messagesRoutes)
authedApp.route('/media', mediaRoutes)
authedApp.route('/typing', typingRoutes)
authedApp.route('/config', configRoutes)
app.route('/', authedApp)
// Global error handler
app.onError((err, c) => {
logger.error('http', `${c.req.method} ${c.req.path} → 500`, {
error: err.message,
})
return c.json({ ok: false, message: err.message }, HttpStatus.INTERNAL_SERVER_ERROR)
})
// 404
app.notFound((c) => {
return c.json({ ok: false, message: `Cannot ${c.req.method} ${c.req.path}` }, HttpStatus.NOT_FOUND)
})
return app
}
@@ -0,0 +1,2 @@
/** Prefix used when generating client IDs for outgoing messages. */
export const CLIENT_ID_PREFIX = 'weixin-ilink-gateway'
@@ -0,0 +1,8 @@
export const HttpStatus = {
OK: 200,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
NOT_FOUND: 404,
CONFLICT: 409,
INTERNAL_SERVER_ERROR: 500,
} as const
@@ -0,0 +1,54 @@
export const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'ico', 'heic'])
export const VIDEO_EXTS = new Set(['mp4', 'mov', 'avi', 'mkv', 'webm', 'flv', 'wmv'])
export const MIME_MAP: Record<string, string> = {
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
gif: 'image/gif',
webp: 'image/webp',
bmp: 'image/bmp',
svg: 'image/svg+xml',
ico: 'image/x-icon',
heic: 'image/heic',
mp4: 'video/mp4',
mov: 'video/quicktime',
avi: 'video/x-msvideo',
mkv: 'video/x-matroska',
webm: 'video/webm',
flv: 'video/x-flv',
wmv: 'video/x-ms-wmv',
pdf: 'application/pdf',
txt: 'text/plain',
json: 'application/json',
html: 'text/html',
css: 'text/css',
js: 'application/javascript',
zip: 'application/zip',
gz: 'application/gzip',
doc: 'application/msword',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
xls: 'application/vnd.ms-excel',
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
mp3: 'audio/mpeg',
wav: 'audio/wav',
ogg: 'audio/ogg',
}
export const inferMediaType = (mime: string, filename: string): 'image' | 'video' | 'file' => {
if (mime && mime !== 'application/octet-stream') {
if (mime.startsWith('image/')) return 'image'
if (mime.startsWith('video/')) return 'video'
return 'file'
}
const ext = filename.split('.').pop()?.toLowerCase() ?? ''
if (IMAGE_EXTS.has(ext)) return 'image'
if (VIDEO_EXTS.has(ext)) return 'video'
return 'file'
}
export const inferMimeFromFilename = (filename: string): string => {
const ext = filename.split('.').pop()?.toLowerCase() ?? ''
return MIME_MAP[ext] ?? 'application/octet-stream'
}
@@ -0,0 +1 @@
export const resolveToUserId = (to: string, loggedInUserId: string): string => (to === 'self' ? loggedInUserId : to)
@@ -0,0 +1,67 @@
import { z } from 'zod'
// ---------------------------------------------------------------------------
// Common
// ---------------------------------------------------------------------------
const cdnRef = z.object({
encrypt_query_param: z.string(),
aes_key: z.string(),
file_size_ciphertext: z.number().optional(),
})
export const toSchema = z.object({
to: z.string(),
})
// ---------------------------------------------------------------------------
// Messages
// ---------------------------------------------------------------------------
const urlOrCdn = z.union([z.object({ url: z.string() }), z.object({ cdn: cdnRef })])
const sendItem = z.union([
z.object({ type: z.literal('text'), text: z.string() }),
z.object({ type: z.literal('image') }).and(urlOrCdn),
z.object({ type: z.literal('video') }).and(urlOrCdn),
z.object({ type: z.literal('file'), file_name: z.string() }).and(urlOrCdn),
])
export const sendMessageSchema = z.object({
to: z.string(),
items: z.array(sendItem).min(1),
context_token: z.string().optional(),
})
export const configSchema = z.object({
to: z.string(),
context_token: z.string().optional(),
})
export const mediaDownloadSchema = z.object({
full_url: z.string().url(),
aes_key: z.string(),
file_name: z.string(),
})
export const mediaPresignSchema = z.object({
to: z.string(),
filekey: z.string(),
media_type: z.number(),
rawsize: z.number(),
rawfilemd5: z.string(),
filesize: z.number(),
aeskey: z.string(),
thumb_rawsize: z.number().optional(),
thumb_rawfilemd5: z.string().optional(),
thumb_filesize: z.number().optional(),
no_need_thumb: z.boolean().optional(),
})
export const mediaUploadSchema = z.object({
file: z.instanceof(File),
to: z.string(),
})
export type SendItem = z.infer<typeof sendItem>
export type SendMessageBody = z.infer<typeof sendMessageSchema>
+163
View File
@@ -0,0 +1,163 @@
import { config } from '../config.js'
import { logger } from '../lib/logger.js'
import { getUpdates } from '../sdk/api.js'
import type { WeixinMessage } from '../sdk/types.js'
import { MessageType } from '../sdk/types.js'
import { getCredentials, getSyncBuf, pushMessage, saveSyncBuf, setContextToken } from './state.js'
// ---------------------------------------------------------------------------
// Constants (matches official monitor.ts)
// ---------------------------------------------------------------------------
const SESSION_EXPIRED_ERRCODE = -14
const SESSION_PAUSE_DURATION_MS = 60 * 60 * 1000 // 1 hour
const MAX_CONSECUTIVE_FAILURES = 3
const BACKOFF_DELAY_MS = 30_000
const RETRY_DELAY_MS = 2_000
// ---------------------------------------------------------------------------
// Poller state
// ---------------------------------------------------------------------------
let polling = false
let pauseUntil = 0
export const getWebhookUrls = (): readonly string[] => config.webhookUrls
export const isPolling = (): boolean => polling
// ---------------------------------------------------------------------------
// Webhook delivery
// ---------------------------------------------------------------------------
const WEBHOOK_MAX_RETRIES = 2
const WEBHOOK_RETRY_DELAY_MS = 1_000
const deliverToWebhook = async (url: string, body: string): Promise<void> => {
for (let attempt = 1; attempt <= WEBHOOK_MAX_RETRIES; attempt++) {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
})
if (res.ok) return
logger.warn('webhook', `${url} responded ${res.status} (attempt ${attempt}/${WEBHOOK_MAX_RETRIES})`)
} catch (err) {
logger.warn(
'webhook',
`${url} failed (attempt ${attempt}/${WEBHOOK_MAX_RETRIES}): ${err instanceof Error ? err.message : err}`,
)
}
if (attempt < WEBHOOK_MAX_RETRIES) await sleep(WEBHOOK_RETRY_DELAY_MS)
}
}
const deliverWebhooks = async (msg: WeixinMessage): Promise<void> => {
if (!config.webhookUrls.length) return
const body = JSON.stringify(msg)
await Promise.allSettled(config.webhookUrls.map((url) => deliverToWebhook(url, body)))
}
// ---------------------------------------------------------------------------
// Main polling loop
// ---------------------------------------------------------------------------
export const startPolling = (): void => {
if (polling) return
const creds = getCredentials()
if (!creds) {
throw new Error('Cannot start polling: no credentials')
}
polling = true
pollLoop(creds.baseUrl, creds.botToken).catch((err) => {
polling = false
logger.error('poller', `Poll loop crashed: ${err instanceof Error ? err.message : err}`)
})
}
export const stopPolling = (): void => {
polling = false
}
const pollLoop = async (baseUrl: string, token: string): Promise<void> => {
let consecutiveFailures = 0
while (polling) {
// Session pause check
if (Date.now() < pauseUntil) {
const remaining = pauseUntil - Date.now()
await sleep(Math.min(remaining, 60_000))
continue
}
try {
const syncBuf = getSyncBuf()
const resp = await getUpdates({
baseUrl,
token,
get_updates_buf: syncBuf,
})
// Session expired
if (resp.errcode === SESSION_EXPIRED_ERRCODE) {
logger.error('poller', `Session expired (errcode=${SESSION_EXPIRED_ERRCODE}), pausing for 1 hour`)
pauseUntil = Date.now() + SESSION_PAUSE_DURATION_MS
continue
}
// Other error
if (resp.ret !== 0 && resp.ret !== undefined) {
throw new Error(`getUpdates ret=${resp.ret} errcode=${resp.errcode} errmsg=${resp.errmsg}`)
}
// Save new sync cursor
if (resp.get_updates_buf) {
saveSyncBuf(resp.get_updates_buf)
}
// Process messages
if (resp.msgs?.length) {
const incoming = resp.msgs.filter((m) => m.message_type !== MessageType.BOT)
if (incoming.length) {
logger.info('poller', `Received ${incoming.length} message(s)`)
}
for (const msg of resp.msgs) {
// Skip BOT's own messages
if (msg.message_type === MessageType.BOT) continue
logger.info('poller', `Message from=${msg.from_user_id} type=${msg.message_type} seq=${msg.seq}`)
// Cache context token for replies
if (msg.from_user_id && msg.context_token) {
setContextToken(msg.from_user_id, msg.context_token)
}
// Deliver: webhook + queue
pushMessage(msg)
await deliverWebhooks(msg)
}
}
consecutiveFailures = 0
} catch (err) {
consecutiveFailures++
logger.error(
'poller',
`Error (${consecutiveFailures}/${MAX_CONSECUTIVE_FAILURES}): ${err instanceof Error ? err.message : err}`,
)
if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
logger.error('poller', `${MAX_CONSECUTIVE_FAILURES} consecutive failures, backing off ${BACKOFF_DELAY_MS}ms`)
await sleep(BACKOFF_DELAY_MS)
consecutiveFailures = 0
} else {
await sleep(RETRY_DELAY_MS)
}
}
}
}
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
@@ -0,0 +1,38 @@
import { Hono } from 'hono'
import { logger } from '../../lib/logger.js'
import { resetLoginStatus, startLogin } from '../../sdk/auth.js'
import { HttpStatus } from '../lib/http.js'
import { isPolling, startPolling, stopPolling } from '../poller.js'
import { clearContextTokens, clearCredentials, getCredentials, saveCredentials } from '../state.js'
const auth = new Hono()
auth.post('/login', async (c) => {
if (getCredentials()) {
return c.json({ ok: false, message: 'Already logged in' }, HttpStatus.CONFLICT)
}
const { qrcodeUrl } = await startLogin((result) => {
clearContextTokens()
saveCredentials(result)
if (!isPolling()) startPolling()
logger.info('auth', `Login confirmed, user=${result.userId}`)
})
return c.json({ ok: true, qr_url: qrcodeUrl })
})
auth.post('/logout', (c) => {
if (!getCredentials()) {
return c.json({ ok: false, message: 'Not logged in' }, HttpStatus.BAD_REQUEST)
}
const userId = getCredentials()?.userId
stopPolling()
clearCredentials()
clearContextTokens()
resetLoginStatus()
logger.info('auth', `Logout user=${userId}`)
return c.json({ ok: true, message: 'Logged out' })
})
export default auth
@@ -0,0 +1,31 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { getConfig } from '../../sdk/api.js'
import { resolveToUserId } from '../lib/resolve-to.js'
import { configSchema } from '../lib/schemas.js'
import type { Credentials } from '../state.js'
import { getContextToken } from '../state.js'
type Env = { Variables: { credentials: Credentials } }
const config = new Hono<Env>()
config.post('/', zValidator('json', configSchema), async (c) => {
const creds = c.get('credentials')
const body = c.req.valid('json')
const toUserId = resolveToUserId(body.to, creds.userId)
const contextToken = body.context_token ?? getContextToken(toUserId)
const response = await getConfig({
baseUrl: creds.baseUrl,
token: creds.botToken,
ilinkUserId: toUserId,
contextToken,
})
return c.json({ ok: true, ...response })
})
export default config
@@ -0,0 +1,443 @@
import { Hono } from 'hono'
const consoleApp = new Hono()
consoleApp.get('/', (c) => {
return c.html(HTML)
})
export default consoleApp
const HTML = /* html */ `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Console — weixin-ilink-gateway</title>
<script src="https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js"></script>
<style>
:root {
--bg: #f7f7f8; --surface: #fff; --surface2: #f0f0f2; --border: #e2e2e5;
--text: #1a1a1a; --text2: #6b6b76; --accent: #2563eb; --accent-hover: #1d4ed8;
--danger: #dc2626; --danger-hover: #b91c1c; --success: #16a34a; --warn: #ca8a04;
--radius: 12px; --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
}
* { box-sizing: border-box; margin: 0; padding: 0 }
body { font-family: var(--font); background: var(--bg); color: var(--text); min-height: 100vh; display: flex; justify-content: center }
button { font-family: var(--font) }
.container { width: 100%; max-width: 560px; padding: 48px 24px 40px }
.header { text-align: center; margin-bottom: 40px }
.header h1 { font-size: 16px; font-weight: 600; color: var(--text2); letter-spacing: 1.5px; text-transform: uppercase }
.screen { display: none }
.screen.active { display: block }
/* Center the auth & login screens vertically */
.screen-center { display: none }
.screen-center.active { display: flex; flex-direction: column; justify-content: center; min-height: 50vh }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 28px; margin-bottom: 16px }
.card-title { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .8px; color: var(--text2); margin-bottom: 16px }
input, textarea {
width: 100%; padding: 10px 12px; background: var(--surface2); border: 1px solid var(--border);
border-radius: 8px; color: var(--text); font-size: 14px; font-family: var(--font);
outline: none; transition: border-color .15s;
}
input:focus, textarea:focus { border-color: var(--accent) }
input::placeholder { color: #999 }
.input-group { position: relative }
.input-group input { padding-right: 44px }
.input-group .toggle {
position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
background: none; border: none; color: var(--text2); cursor: pointer; font-size: 16px; padding: 4px;
}
.input-group .toggle:hover { color: var(--text) }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
padding: 10px 20px; border: none; border-radius: 8px; font-size: 13px; font-weight: 500;
cursor: pointer; transition: all .15s; width: 100%;
}
.btn:active { transform: scale(.98) }
.btn-accent { background: var(--accent); color: #fff }
.btn-accent:hover { background: var(--accent-hover) }
.btn-accent:disabled { background: #93b4f0; color: #fff; cursor: not-allowed; transform: none }
.btn-danger { background: var(--danger); color: #fff }
.btn-danger:hover { background: var(--danger-hover) }
.btn-ghost { background: transparent; border: 1px solid var(--border); color: var(--text2) }
.btn-ghost:hover { border-color: #bbb; color: var(--text) }
.btn-sm { padding: 8px 14px; font-size: 12px; width: auto }
.badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 500 }
.badge-success { background: rgba(22,163,74,.08); color: var(--success) }
.badge-warn { background: rgba(202,138,4,.08); color: var(--warn) }
.badge::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: currentColor }
.qr-wrap { display: flex; flex-direction: column; align-items: center; gap: 16px; padding: 20px 0 }
.qr-status { font-size: 13px; color: var(--text2) }
.send-result { font-size: 12px; margin-top: 8px; padding: 8px; border-radius: 6px; display: none }
.send-result.ok { display: block; background: rgba(22,163,74,.06); color: var(--success) }
.send-result.err { display: block; background: rgba(220,38,38,.06); color: var(--danger) }
.error-text { color: var(--danger); font-size: 13px; margin-top: 8px; display: none }
.error-text.visible { display: block }
.info-row { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; font-size: 13px }
.info-row + .info-row { border-top: 1px solid var(--border) }
.info-label { color: var(--text2) }
.info-value { color: var(--text); font-family: "SF Mono", Monaco, Consolas, monospace; font-size: 12px }
.footer { text-align: center; margin-top: 32px }
.footer a { color: var(--text2); font-size: 12px; text-decoration: none }
.footer a:hover { color: var(--text) }
.lang-switch { color: var(--text2); font-size: 12px; cursor: pointer; background: none; border: none; font-family: var(--font) }
.lang-switch:hover { color: var(--text) }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>WEIXIN-ILINK-GATEWAY</h1>
</div>
<!-- Screen: API Key -->
<div id="screen-auth" class="screen-center active">
<div class="card">
<div class="card-title" data-i18n="apikey_title">API KEY</div>
<div class="input-group">
<input id="apikey" type="password" placeholder="Enter your API key" data-i18n-ph="apikey_placeholder">
<button class="toggle" onclick="toggleKey()">&#128065;</button>
</div>
<div id="auth-error" class="error-text"></div>
<div style="margin-top:16px">
<button id="btn-connect" class="btn btn-accent" onclick="doConnect()" data-i18n="connect">Connect</button>
</div>
</div>
</div>
<!-- Screen: Login (not logged in) -->
<div id="screen-login" class="screen-center">
<div class="card">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
<span class="badge badge-warn" data-i18n="not_logged_in">Not logged in</span>
<button class="btn btn-ghost btn-sm" onclick="doDisconnect()" data-i18n="disconnect">Disconnect</button>
</div>
<div id="qr-area" class="qr-wrap" style="display:none">
<div id="qr-canvas"></div>
<div id="qr-status" class="qr-status" data-i18n="waiting_scan">Waiting for scan...</div>
</div>
<button id="btn-login" class="btn btn-accent" onclick="doLogin()" data-i18n="scan_login">Scan to Login</button>
</div>
</div>
<!-- Screen: Dashboard (logged in) -->
<div id="screen-dash" class="screen">
<div class="card">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
<span class="badge badge-success" data-i18n="logged_in">Logged in</span>
<div style="display:flex;gap:8px">
<button class="btn btn-ghost btn-sm" onclick="doDisconnect()" data-i18n="disconnect">Disconnect</button>
<button class="btn btn-danger btn-sm" onclick="doLogout()" data-i18n="logout">Logout</button>
</div>
</div>
<div id="dash-info"></div>
</div>
<div class="card">
<div class="card-title" data-i18n="send_test">Send Test</div>
<div style="font-size:12px;color:var(--text2);margin-bottom:12px" data-i18n="context_tip"></div>
<div style="display:flex;gap:8px">
<button class="btn btn-accent" onclick="doSendText()" data-i18n="send_text">Text</button>
<button class="btn btn-accent" onclick="doSendImage()" data-i18n="send_image">Image</button>
</div>
<div id="send-result" class="send-result"></div>
</div>
</div>
<div class="footer">
<button class="lang-switch" onclick="switchLang()"></button>
&nbsp;&middot;&nbsp;
<a href="https://github.com/kadxy/weixin-ilink-gateway" target="_blank">GitHub</a>
</div>
</div>
<script>
/* ── i18n ── */
var LANGS = {
en: {
apikey_title: 'API KEY',
apikey_placeholder: 'Enter your API key',
connect: 'Connect',
disconnect: 'Disconnect',
not_logged_in: 'Not logged in',
logged_in: 'Logged in',
scan_login: 'Scan to Login',
waiting_scan: 'Waiting for scan...',
scanned: 'Scanned — confirm on phone',
login_success: 'Login successful',
login_failed: 'Login failed',
logout: 'Logout',
send_test: 'Send Test',
send_text: 'Text',
send_image: 'Image',
sent_ok: 'Sent',
send_fail: 'Failed',
context_tip: 'Note: context_token is required to send messages. It is auto-cached when a message is received from the target user.',
user_id: 'User ID',
polling: 'Polling',
active: 'Active',
inactive: 'Inactive',
connecting: 'Connecting...',
invalid_key: 'Invalid API key',
conn_error: 'Connection failed',
switch_lang: '中文',
},
zh: {
apikey_title: 'API 密钥',
apikey_placeholder: '输入 API Key',
connect: '连接',
disconnect: '断开',
not_logged_in: '未登录',
logged_in: '已登录',
scan_login: '扫码登录',
waiting_scan: '等待扫码...',
scanned: '已扫码,请在手机上确认',
login_success: '登录成功',
login_failed: '登录失败',
logout: '登出',
send_test: '发送测试',
send_text: '文本',
send_image: '图片',
sent_ok: '发送成功',
send_fail: '发送失败',
context_tip: '注意:发送消息需要 context_token。当收到目标用户的消息后会自动缓存。',
user_id: '用户 ID',
polling: '轮询',
active: '运行中',
inactive: '未运行',
connecting: '连接中...',
invalid_key: 'API Key 无效',
conn_error: '连接失败',
switch_lang: 'English',
},
}
var lang = /^zh/i.test(navigator.language) ? 'zh' : 'en'
function t(key) { return LANGS[lang][key] || key }
function applyLang() {
document.querySelectorAll('[data-i18n]').forEach(function(el) {
el.textContent = t(el.dataset.i18n)
})
document.querySelectorAll('[data-i18n-ph]').forEach(function(el) {
el.placeholder = t(el.dataset.i18nPh)
})
document.querySelector('.lang-switch').textContent = t('switch_lang')
}
function switchLang() {
lang = lang === 'en' ? 'zh' : 'en'
localStorage.setItem('gw_lang', lang)
applyLang()
}
/* ── helpers ── */
function $(id) { return document.getElementById(id) }
var apiKey = localStorage.getItem('gw_apikey') || ''
$('apikey').value = apiKey
function showScreen(id) {
document.querySelectorAll('.screen, .screen-center').forEach(function(s) { s.classList.remove('active') })
$(id).classList.add('active')
}
function getHeaders() {
return { Authorization: 'Bearer ' + apiKey, 'Content-Type': 'application/json' }
}
function api(method, path, body) {
var opts = { method: method, headers: getHeaders() }
if (body) opts.body = JSON.stringify(body)
return fetch(path, opts).then(function(res) { return res.json() })
}
function toggleKey() {
var el = $('apikey')
el.type = el.type === 'password' ? 'text' : 'password'
}
function setDashInfo(status) {
var info = $('dash-info')
while (info.firstChild) info.removeChild(info.firstChild)
var rows = [
[t('user_id'), status.user_id || '-'],
[t('polling'), status.polling ? t('active') : t('inactive')],
]
rows.forEach(function(r) {
var row = document.createElement('div')
row.className = 'info-row'
var label = document.createElement('span')
label.className = 'info-label'
label.textContent = r[0]
var value = document.createElement('span')
value.className = 'info-value'
value.textContent = r[1]
row.appendChild(label)
row.appendChild(value)
info.appendChild(row)
})
}
/* ── connect (validate API key via /status) ── */
function doConnect() {
var btn = $('btn-connect')
var errEl = $('auth-error')
var inputKey = $('apikey').value.trim()
if (!inputKey) return
btn.disabled = true
btn.textContent = t('connecting')
errEl.classList.remove('visible')
var prevKey = apiKey
apiKey = inputKey
api('GET', '/status').then(function(data) {
if (!data.ok) {
apiKey = prevKey
errEl.textContent = t('invalid_key')
errEl.classList.add('visible')
btn.disabled = false
btn.textContent = t('connect')
return
}
localStorage.setItem('gw_apikey', apiKey)
btn.disabled = false
btn.textContent = t('connect')
enterApp(data)
}).catch(function() {
apiKey = prevKey
errEl.textContent = t('conn_error')
errEl.classList.add('visible')
btn.disabled = false
btn.textContent = t('connect')
})
}
$('apikey').addEventListener('keydown', function(e) { if (e.key === 'Enter') doConnect() })
function doDisconnect() {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
showScreen('screen-auth')
}
function enterApp(status) {
if (status.logged_in) {
showDashboard(status)
} else {
showScreen('screen-login')
}
}
/* ── login flow ── */
var pollTimer = null
function doLogin() {
var btn = $('btn-login')
var area = $('qr-area')
var canvas = $('qr-canvas')
var statusEl = $('qr-status')
btn.disabled = true
api('POST', '/auth/login').then(function(data) {
if (!data.qr_url) { btn.disabled = false; return }
while (canvas.firstChild) canvas.removeChild(canvas.firstChild)
var qr = qrcode(0, 'M')
qr.addData(data.qr_url)
qr.make()
var img = document.createElement('img')
img.src = qr.createDataURL(4, 4)
img.width = 200
img.height = 200
img.style.borderRadius = '8px'
canvas.appendChild(img)
area.style.display = 'flex'
statusEl.textContent = t('waiting_scan')
if (pollTimer) clearInterval(pollTimer)
pollTimer = setInterval(function() {
api('GET', '/status').then(function(s) {
if (s.logged_in) {
statusEl.textContent = t('login_success')
clearInterval(pollTimer); pollTimer = null
setTimeout(function() { showDashboard(s) }, 800)
return
}
var st = s.login_status
if (st === 'scanned') statusEl.textContent = t('scanned')
else if (st === 'failed') {
statusEl.textContent = t('login_failed')
clearInterval(pollTimer); pollTimer = null
btn.disabled = false
}
})
}, 2000)
}).catch(function() {
btn.disabled = false
})
}
/* ── dashboard ── */
function showDashboard(status) {
showScreen('screen-dash')
setDashInfo(status)
}
function doLogout() {
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
api('POST', '/auth/logout').then(function() {
showScreen('screen-login')
})
}
/* ── send test ── */
function sendItems(items) {
var el = $('send-result')
api('POST', '/messages/send', { to: 'self', items: items }).then(function(data) {
if (data.ok) {
el.className = 'send-result ok'
el.textContent = t('sent_ok')
} else {
el.className = 'send-result err'
el.textContent = (data.message || t('send_fail'))
}
setTimeout(function() { el.className = 'send-result' }, 3000)
}).catch(function(e) {
el.className = 'send-result err'
el.textContent = e.message
setTimeout(function() { el.className = 'send-result' }, 3000)
})
}
function doSendText() {
var text = lang === 'zh' ? 'Console 测试消息 — ' + new Date().toLocaleTimeString() : 'Console test message — ' + new Date().toLocaleTimeString()
sendItems([{ type: 'text', text: text }])
}
function doSendImage() {
sendItems([{ type: 'image', url: 'https://wechat.design/uploads/740a6c40367a4d2db0bc8c80ccc8018e.jpg' }])
}
/* ── init ── */
var savedLang = localStorage.getItem('gw_lang')
if (savedLang) lang = savedLang
applyLang()
</script>
</body>
</html>`
@@ -0,0 +1,101 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { logger } from '../../lib/logger.js'
import { getUploadUrl } from '../../sdk/api.js'
import { downloadAndDecrypt, uploadFile, uploadImage, uploadVideo } from '../../sdk/cdn.js'
import { inferMediaType, inferMimeFromFilename } from '../lib/mime.js'
import { resolveToUserId } from '../lib/resolve-to.js'
import { mediaDownloadSchema, mediaPresignSchema, mediaUploadSchema } from '../lib/schemas.js'
import type { Credentials } from '../state.js'
type Env = { Variables: { credentials: Credentials } }
const media = new Hono<Env>()
// ---------------------------------------------------------------------------
// POST /upload
// ---------------------------------------------------------------------------
media.post('/upload', zValidator('form', mediaUploadSchema), async (c) => {
const creds = c.get('credentials')
const { file, to } = c.req.valid('form')
const resolvedTo = resolveToUserId(to, creds.userId)
const buf = Buffer.from(await file.arrayBuffer())
const opts = { baseUrl: creds.baseUrl, token: creds.botToken }
const mediaType = inferMediaType(file.type, file.name)
logger.info('media', `Upload ${mediaType} to=${resolvedTo} file=${file.name} size=${buf.length}`)
const uploader = mediaType === 'image' ? uploadImage : mediaType === 'video' ? uploadVideo : uploadFile
const uploaded = await uploader({ buf, toUserId: resolvedTo, opts })
logger.info('media', `Upload ${mediaType} ok filekey=${uploaded.filekey}`)
return c.json({
ok: true,
media_type: mediaType,
file_name: file.name,
filekey: uploaded.filekey,
encrypt_query_param: uploaded.downloadEncryptedQueryParam,
// aeskey is hex internally; protocol expects base64(hex_string), not base64(hex_to_bytes)
aes_key: Buffer.from(uploaded.aeskey).toString('base64'),
file_size: uploaded.fileSize,
file_size_ciphertext: uploaded.fileSizeCiphertext,
})
})
// ---------------------------------------------------------------------------
// POST /presign
// ---------------------------------------------------------------------------
media.post('/presign', zValidator('json', mediaPresignSchema), async (c) => {
const creds = c.get('credentials')
const body = c.req.valid('json')
const toUserId = resolveToUserId(body.to, creds.userId)
logger.info('media', `Presign media_type=${body.media_type} to=${toUserId}`)
const resp = await getUploadUrl({
baseUrl: creds.baseUrl,
token: creds.botToken,
filekey: body.filekey,
media_type: body.media_type,
to_user_id: toUserId,
rawsize: body.rawsize,
rawfilemd5: body.rawfilemd5,
filesize: body.filesize,
aeskey: body.aeskey,
thumb_rawsize: body.thumb_rawsize,
thumb_rawfilemd5: body.thumb_rawfilemd5,
thumb_filesize: body.thumb_filesize,
no_need_thumb: body.no_need_thumb,
})
return c.json({
ok: true,
upload_param: resp.upload_param,
thumb_upload_param: resp.thumb_upload_param,
upload_full_url: resp.upload_full_url,
})
})
// ---------------------------------------------------------------------------
// POST /download
// ---------------------------------------------------------------------------
media.post('/download', zValidator('json', mediaDownloadSchema), async (c) => {
const body = c.req.valid('json')
logger.info('media', `Download file=${body.file_name}`)
const buf = await downloadAndDecrypt('', body.aes_key, undefined, 'mediaDownload', body.full_url)
const mime = inferMimeFromFilename(body.file_name)
return new Response(buf, {
headers: {
'Content-Type': mime,
'Content-Disposition': `attachment; filename="${encodeURIComponent(body.file_name)}"`,
},
})
})
export default media
@@ -0,0 +1,215 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { config } from '../../config.js'
import { logger } from '../../lib/logger.js'
import { generateId, sendMessage } from '../../sdk/api.js'
import { uploadFile, uploadImage, uploadVideo } from '../../sdk/cdn.js'
import type { MessageItem, SendMessageReq } from '../../sdk/types.js'
import { MessageItemType, MessageState, MessageType } from '../../sdk/types.js'
import { CLIENT_ID_PREFIX } from '../lib/constants.js'
import { HttpStatus } from '../lib/http.js'
import { resolveToUserId } from '../lib/resolve-to.js'
import { type SendItem, sendMessageSchema } from '../lib/schemas.js'
import type { Credentials } from '../state.js'
import { getContextToken, getMessagesAfter } from '../state.js'
type Env = { Variables: { credentials: Credentials } }
const messages = new Hono<Env>()
// ---------------------------------------------------------------------------
// POST /send
// ---------------------------------------------------------------------------
messages.post('/send', zValidator('json', sendMessageSchema), async (c) => {
const creds = c.get('credentials')
const body = c.req.valid('json')
const toUserId = resolveToUserId(body.to, creds.userId)
const contextToken = body.context_token ?? getContextToken(toUserId)
logger.info('send', `Sending ${body.items.length} item(s) to=${toUserId}`)
if (!contextToken) {
logger.warn('send', `No context_token for to=${toUserId}`)
return c.json(
{
ok: false,
message:
'No context_token available for this user. The target user must send a message to the bot first so the token gets cached, or provide context_token explicitly.',
},
HttpStatus.BAD_REQUEST,
)
}
const opts = { baseUrl: creds.baseUrl, token: creds.botToken }
const results: {
type: string
ok: boolean
client_id?: string
error?: string
}[] = []
for (const item of body.items) {
const clientId = generateId(CLIENT_ID_PREFIX)
try {
const msgItem = await buildMessageItem(item, toUserId, opts)
const req: SendMessageReq = {
msg: {
from_user_id: '',
to_user_id: toUserId,
client_id: clientId,
message_type: MessageType.BOT,
message_state: MessageState.FINISH,
item_list: [msgItem],
context_token: contextToken,
},
}
await sendMessage({ ...opts, body: req })
logger.info('send', `${item.type} ok client_id=${clientId}`)
results.push({ type: item.type, ok: true, client_id: clientId })
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
logger.error('send', `${item.type} failed: ${errMsg}`, {
client_id: clientId,
})
results.push({
type: item.type,
ok: false,
client_id: clientId,
error: errMsg,
})
}
}
const response: Record<string, unknown> = {
ok: results.every((r) => r.ok),
results,
}
return c.json(response)
})
// ---------------------------------------------------------------------------
// GET /updates
// ---------------------------------------------------------------------------
messages.get('/updates', (c) => {
const afterParam = c.req.query('after')
const afterSeq = afterParam != null ? parseInt(afterParam, 10) : undefined
const msgs = getMessagesAfter(Number.isNaN(afterSeq) ? undefined : afterSeq)
return c.json({ ok: true, count: msgs.length, messages: msgs })
})
export default messages
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
type ApiOpts = { baseUrl: string; token: string }
const buildMessageItem = async (item: SendItem, toUserId: string, opts: ApiOpts): Promise<MessageItem> => {
switch (item.type) {
case 'text':
return { type: MessageItemType.TEXT, text_item: { text: item.text } }
case 'image': {
const { eqp, aesKey, size } =
'cdn' in item
? {
eqp: item.cdn.encrypt_query_param,
aesKey: item.cdn.aes_key,
size: item.cdn.file_size_ciphertext,
}
: await uploadFromUrl(item.url, 'image', toUserId, opts)
return {
type: MessageItemType.IMAGE,
image_item: {
media: { encrypt_query_param: eqp, aes_key: aesKey, encrypt_type: 1 },
mid_size: size,
},
}
}
case 'video': {
const { eqp, aesKey, size } =
'cdn' in item
? {
eqp: item.cdn.encrypt_query_param,
aesKey: item.cdn.aes_key,
size: item.cdn.file_size_ciphertext,
}
: await uploadFromUrl(item.url, 'video', toUserId, opts)
return {
type: MessageItemType.VIDEO,
video_item: {
media: { encrypt_query_param: eqp, aes_key: aesKey, encrypt_type: 1 },
video_size: size,
},
}
}
case 'file': {
const { eqp, aesKey, size } =
'cdn' in item
? {
eqp: item.cdn.encrypt_query_param,
aesKey: item.cdn.aes_key,
size: item.cdn.file_size_ciphertext,
}
: await uploadFromUrl(item.url, 'file', toUserId, opts)
return {
type: MessageItemType.FILE,
file_item: {
media: { encrypt_query_param: eqp, aes_key: aesKey, encrypt_type: 1 },
file_name: item.file_name,
len: size != null ? String(size) : undefined,
},
}
}
default: {
const _exhaustive: never = item
throw new Error(`Unknown item type: ${(_exhaustive as SendItem).type}`)
}
}
}
const uploadFromUrl = async (
url: string,
mediaType: 'image' | 'video' | 'file',
toUserId: string,
opts: ApiOpts,
): Promise<{ eqp: string; aesKey: string; size: number }> => {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), config.downloadTimeoutMs)
try {
const resp = await fetch(url, { signal: controller.signal })
if (!resp.ok) throw new Error(`Failed to download ${mediaType}: ${resp.status}`)
const contentLength = resp.headers.get('content-length')
if (contentLength && parseInt(contentLength, 10) > config.maxDownloadSize) {
throw new Error(`File too large: ${contentLength} bytes (max ${config.maxDownloadSize})`)
}
const buf = Buffer.from(await resp.arrayBuffer())
if (buf.length > config.maxDownloadSize) {
throw new Error(`File too large: ${buf.length} bytes (max ${config.maxDownloadSize})`)
}
const uploader = mediaType === 'image' ? uploadImage : mediaType === 'video' ? uploadVideo : uploadFile
const uploaded = await uploader({ buf, toUserId, opts })
return {
eqp: uploaded.downloadEncryptedQueryParam,
// aeskey is hex internally; the protocol expects the hex *string* base64-encoded,
// NOT the raw bytes. i.e. base64(hex_string), not base64(hex_to_bytes).
aesKey: Buffer.from(uploaded.aeskey).toString('base64'),
size: uploaded.fileSizeCiphertext,
}
} finally {
clearTimeout(timeout)
}
}
@@ -0,0 +1,25 @@
import { Hono } from 'hono'
import { config } from '../../config.js'
import { getLoginStatus } from '../../sdk/auth.js'
import { getWebhookUrls, isPolling } from '../poller.js'
import { getCredentials } from '../state.js'
const status = new Hono()
status.get('/', (c) => {
const creds = getCredentials()
const login = getLoginStatus()
return c.json({
ok: true,
logged_in: !!creds,
user_id: creds?.userId ?? null,
login_status: login.status,
login_error: login.error,
qr_url: login.qr_url,
polling: isPolling(),
webhook_urls: getWebhookUrls(),
incoming_webhook_enabled: !!config.webhookToken,
})
})
export default status
@@ -0,0 +1,85 @@
import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { logger } from '../../lib/logger.js'
import { getConfig, sendTyping } from '../../sdk/api.js'
import { TypingStatus } from '../../sdk/types.js'
import { resolveToUserId } from '../lib/resolve-to.js'
import { toSchema } from '../lib/schemas.js'
import type { Credentials } from '../state.js'
import { getContextToken } from '../state.js'
type Env = { Variables: { credentials: Credentials } }
const typing = new Hono<Env>()
// NOTE: Currently the bot only chats 1-on-1 with the owner, so this cache won't grow unbounded.
// If multi-user support is added later, consider adding TTL-based eviction.
const ticketCache = new Map<string, { ticket: string; expiresAt: number }>()
const TICKET_TTL_MS = 24 * 60 * 60 * 1000
const getTicket = async (baseUrl: string, token: string, userId: string): Promise<string> => {
const cached = ticketCache.get(userId)
if (cached && Date.now() < cached.expiresAt) {
return cached.ticket
}
const contextToken = getContextToken(userId)
const resp = await getConfig({
baseUrl,
token,
ilinkUserId: userId,
contextToken,
})
if (!resp.typing_ticket) {
throw new Error('Failed to get typing_ticket from getConfig')
}
ticketCache.set(userId, {
ticket: resp.typing_ticket,
expiresAt: Date.now() + TICKET_TTL_MS,
})
return resp.typing_ticket
}
typing.post('/start', zValidator('json', toSchema), async (c) => {
const creds = c.get('credentials')
const { to } = c.req.valid('json')
const toUserId = resolveToUserId(to, creds.userId)
logger.info('typing', `start to=${toUserId}`)
const ticket = await getTicket(creds.baseUrl, creds.botToken, toUserId)
await sendTyping({
baseUrl: creds.baseUrl,
token: creds.botToken,
body: {
ilink_user_id: toUserId,
typing_ticket: ticket,
status: TypingStatus.TYPING,
},
})
return c.json({ ok: true })
})
typing.post('/stop', zValidator('json', toSchema), async (c) => {
const creds = c.get('credentials')
const { to } = c.req.valid('json')
const toUserId = resolveToUserId(to, creds.userId)
logger.info('typing', `stop to=${toUserId}`)
const ticket = await getTicket(creds.baseUrl, creds.botToken, toUserId)
await sendTyping({
baseUrl: creds.baseUrl,
token: creds.botToken,
body: {
ilink_user_id: toUserId,
typing_ticket: ticket,
status: TypingStatus.CANCEL,
},
})
return c.json({ ok: true })
})
export default typing
@@ -0,0 +1,89 @@
import { timingSafeEqual } from 'node:crypto'
import { Hono } from 'hono'
import { config } from '../../config.js'
import { logger } from '../../lib/logger.js'
import { generateId, sendMessage } from '../../sdk/api.js'
import type { SendMessageReq } from '../../sdk/types.js'
import { MessageItemType, MessageState, MessageType } from '../../sdk/types.js'
import { CLIENT_ID_PREFIX } from '../lib/constants.js'
import { HttpStatus } from '../lib/http.js'
import { getContextToken, getCredentials } from '../state.js'
const webhook = new Hono()
function safeEqual(a: string, b: string): boolean {
const bufA = Buffer.from(a)
const bufB = Buffer.from(b)
if (bufA.length !== bufB.length) return false
return timingSafeEqual(bufA, bufB)
}
// ---------------------------------------------------------------------------
// POST /:token
// ---------------------------------------------------------------------------
webhook.post('/:token', async (c) => {
// Token auth
if (!config.webhookToken || !safeEqual(c.req.param('token'), config.webhookToken)) {
return c.json({ ok: false, message: 'Invalid token' }, HttpStatus.UNAUTHORIZED)
}
// Login guard
const creds = getCredentials()
if (!creds) {
return c.json({ ok: false, message: 'Not logged in' }, HttpStatus.UNAUTHORIZED)
}
// Extract text from body
const contentType = c.req.header('Content-Type') ?? ''
let text: string
if (contentType.includes('text/plain')) {
text = await c.req.text()
} else {
// Default: JSON — extract "text" field (Slack-compatible)
const body = await c.req.json<{ text?: string }>()
text = body?.text ?? ''
}
text = text.trim()
if (!text) {
return c.json({ ok: false, message: 'Empty message' }, HttpStatus.BAD_REQUEST)
}
// Send to self
const toUserId = creds.userId
const contextToken = getContextToken(toUserId)
const clientId = generateId(CLIENT_ID_PREFIX)
logger.info('webhook', `Sending text to self, length=${text.length}`)
if (!contextToken) {
logger.warn('webhook', 'No context_token for self, message may not be delivered')
}
const opts = { baseUrl: creds.baseUrl, token: creds.botToken }
const req: SendMessageReq = {
msg: {
from_user_id: '',
to_user_id: toUserId,
client_id: clientId,
message_type: MessageType.BOT,
message_state: MessageState.FINISH,
item_list: [{ type: MessageItemType.TEXT, text_item: { text } }],
context_token: contextToken,
},
}
try {
await sendMessage({ ...opts, body: req })
logger.info('webhook', `ok client_id=${clientId}`)
return c.json({ ok: true, client_id: clientId })
} catch (err) {
const errMsg = err instanceof Error ? err.message : String(err)
logger.error('webhook', `failed: ${errMsg}`, { client_id: clientId })
return c.json({ ok: false, message: errMsg }, HttpStatus.INTERNAL_SERVER_ERROR)
}
})
export default webhook
+202
View File
@@ -0,0 +1,202 @@
import fs from 'node:fs'
import path from 'node:path'
import { config } from '../config.js'
import { logger } from '../lib/logger.js'
import type { WeixinMessage } from '../sdk/types.js'
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
const DATA_DIR = config.dataDir
const ensureDataDir = (): void => {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true })
}
}
const readJson = <T>(filename: string, fallback: T): T => {
try {
const filePath = path.join(DATA_DIR, filename)
return JSON.parse(fs.readFileSync(filePath, 'utf-8')) as T
} catch {
return fallback
}
}
const writeJsonAsync = (filePath: string, data: unknown): void => {
Bun.write(filePath, JSON.stringify(data, null, 2)).catch((err) => {
logger.error('state', `Failed to write ${filePath}: ${err instanceof Error ? err.message : err}`)
})
}
const writeJsonSync = (filePath: string, data: unknown): void => {
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8')
}
const writeJson = (filename: string, data: unknown): void => {
ensureDataDir()
writeJsonAsync(path.join(DATA_DIR, filename), data)
}
// ---------------------------------------------------------------------------
// Credentials
// ---------------------------------------------------------------------------
export interface Credentials {
botToken: string
accountId: string
baseUrl: string
userId: string
}
let credentials: Credentials | null = null
export const loadCredentials = (): Credentials | null => {
if (credentials) return credentials
const saved = readJson<Partial<Credentials>>('credentials.json', {})
if (saved.botToken && saved.accountId && saved.baseUrl && saved.userId) {
credentials = saved as Credentials
return credentials
}
return null
}
export const saveCredentials = (creds: Credentials): void => {
credentials = creds
writeJson('credentials.json', creds)
}
export const getCredentials = (): Credentials | null => credentials
export const clearCredentials = (): void => {
credentials = null
const filePath = path.join(DATA_DIR, 'credentials.json')
try {
fs.unlinkSync(filePath)
} catch (err) {
logger.warn('state', `Failed to delete ${filePath}: ${err instanceof Error ? err.message : err}`)
}
}
// ---------------------------------------------------------------------------
// Sync buffer (getUpdates cursor)
// ---------------------------------------------------------------------------
let syncBuf = ''
export const loadSyncBuf = (): string => {
if (syncBuf) return syncBuf
const saved = readJson<{ get_updates_buf?: string }>('sync.json', {})
syncBuf = saved.get_updates_buf ?? ''
return syncBuf
}
export const saveSyncBuf = (buf: string): void => {
syncBuf = buf
writeJson('sync.json', { get_updates_buf: buf })
}
export const getSyncBuf = (): string => syncBuf
// ---------------------------------------------------------------------------
// Context token (per user_id, required for replies)
// ---------------------------------------------------------------------------
const CONTEXT_TOKEN_FILE = 'context-token.json'
const contextTokens = new Map<string, string>()
export const loadContextTokens = (): void => {
const saved = readJson<Record<string, string>>(CONTEXT_TOKEN_FILE, {})
for (const [userId, token] of Object.entries(saved)) {
contextTokens.set(userId, token)
}
}
export const setContextToken = (userId: string, token: string): void => {
contextTokens.set(userId, token)
writeJson(CONTEXT_TOKEN_FILE, Object.fromEntries(contextTokens))
}
export const getContextToken = (userId: string): string | undefined => contextTokens.get(userId)
export const clearContextTokens = (): void => {
contextTokens.clear()
writeJson(CONTEXT_TOKEN_FILE, {})
}
// ---------------------------------------------------------------------------
// Message buffer (per-session file, original format preserved)
// ---------------------------------------------------------------------------
const messageBuffer: WeixinMessage[] = []
const MAX_BUFFER_SIZE = config.maxBufferSize
let sessionMessageFile = ''
let flushTimer: ReturnType<typeof setTimeout> | null = null
const FLUSH_DELAY_MS = 500
const flushMessages = (): void => {
flushTimer = null
if (sessionMessageFile) {
writeJsonAsync(sessionMessageFile, messageBuffer)
}
}
const flushMessagesSync = (): void => {
if (flushTimer) {
clearTimeout(flushTimer)
flushTimer = null
}
if (sessionMessageFile) {
writeJsonSync(sessionMessageFile, messageBuffer)
}
}
const scheduleFlush = (): void => {
if (flushTimer) return
flushTimer = setTimeout(flushMessages, FLUSH_DELAY_MS)
}
const initMessageSession = (): void => {
const messagesDir = path.join(DATA_DIR, 'messages')
if (!fs.existsSync(messagesDir)) {
fs.mkdirSync(messagesDir, { recursive: true })
}
const sessionId = new Date().toISOString().replace(/[:.]/g, '-')
sessionMessageFile = path.join(messagesDir, `${sessionId}.json`)
}
export const pushMessage = (msg: WeixinMessage): void => {
messageBuffer.push(msg)
if (messageBuffer.length > MAX_BUFFER_SIZE) {
messageBuffer.splice(0, messageBuffer.length - MAX_BUFFER_SIZE)
}
scheduleFlush()
}
export const getMessagesAfter = (afterSeq?: number): WeixinMessage[] => {
if (afterSeq == null) return [...messageBuffer]
return messageBuffer.filter((m) => (m.seq ?? 0) > afterSeq)
}
// ---------------------------------------------------------------------------
// Init
// ---------------------------------------------------------------------------
export const initState = (): void => {
ensureDataDir()
loadCredentials()
loadSyncBuf()
loadContextTokens()
initMessageSession()
process.on('beforeExit', flushMessagesSync)
process.on('SIGINT', () => {
flushMessagesSync()
process.exit(0)
})
process.on('SIGTERM', () => {
flushMessagesSync()
process.exit(0)
})
}
+34
View File
@@ -0,0 +1,34 @@
import { config } from './config.js'
import { createApp } from './gateway/app.js'
import { startPolling } from './gateway/poller.js'
import { getCredentials, initState } from './gateway/state.js'
import { logger } from './lib/logger.js'
// ---------------------------------------------------------------------------
// Bootstrap
// ---------------------------------------------------------------------------
if (config.apiKey.length <= 12) {
logger.error('init', 'API_KEY must be at least 12 characters long')
process.exit(1)
}
// Load persisted state
initState()
// Create Hono app
const app = createApp(config.apiKey)
// Start server
logger.info('init', `Gateway running on port ${config.port}`)
// Auto-start polling if credentials exist
const creds = getCredentials()
if (creds) {
logger.info('init', `Credentials found for ${creds.userId}, starting poller`)
startPolling()
} else {
logger.info('init', 'No credentials found, login via POST /auth/login')
}
export default { port: config.port, fetch: app.fetch }
+51
View File
@@ -0,0 +1,51 @@
// ---------------------------------------------------------------------------
// Minimal structured logger — zero dependencies, with ANSI colors
// ---------------------------------------------------------------------------
// Output: 10:30:00.123 INFO [poller] Received 3 messages
// Swap this file out for pino/winston later without touching call sites.
// ---------------------------------------------------------------------------
type Level = 'info' | 'warn' | 'error'
// ANSI color codes
const RESET = '\x1b[0m'
const DIM = '\x1b[2m'
const BOLD = '\x1b[1m'
const LEVEL_STYLE: Record<Level, { label: string; color: string }> = {
info: { label: 'INFO ', color: '\x1b[36m' }, // cyan
warn: { label: 'WARN ', color: '\x1b[33m' }, // yellow
error: { label: 'ERROR', color: '\x1b[31m' }, // red
}
const TAG_COLOR = '\x1b[35m' // magenta
const formatTime = (): string => {
const d = new Date()
const h = String(d.getHours()).padStart(2, '0')
const m = String(d.getMinutes()).padStart(2, '0')
const s = String(d.getSeconds()).padStart(2, '0')
const ms = String(d.getMilliseconds()).padStart(3, '0')
return `${h}:${m}:${s}.${ms}`
}
const emit = (level: Level, tag: string, msg: string, extra?: Record<string, unknown>): void => {
const { label, color } = LEVEL_STYLE[level]
const ts = `${DIM}${formatTime()}${RESET}`
const lvl = `${color}${BOLD}${label}${RESET}`
const t = `${TAG_COLOR}[${tag}]${RESET}`
const line = `${ts} ${lvl} ${t} ${msg}`
const fn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log
if (extra && Object.keys(extra).length) {
fn(line, extra)
} else {
fn(line)
}
}
export const logger = {
info: (tag: string, msg: string, extra?: Record<string, unknown>) => emit('info', tag, msg, extra),
warn: (tag: string, msg: string, extra?: Record<string, unknown>) => emit('warn', tag, msg, extra),
error: (tag: string, msg: string, extra?: Record<string, unknown>) => emit('error', tag, msg, extra),
}
+266
View File
@@ -0,0 +1,266 @@
import crypto from 'node:crypto'
import JSONBig from 'json-bigint'
const JSONSafe = JSONBig({ storeAsString: true })
import { logger } from '../lib/logger.js'
import type {
BaseInfo,
GetConfigResp,
GetUpdatesReq,
GetUpdatesResp,
GetUploadUrlReq,
GetUploadUrlResp,
SendMessageReq,
SendTypingReq,
} from './types.js'
// ---------------------------------------------------------------------------
// Configuration — mirrors official package.json fields
// ---------------------------------------------------------------------------
const CHANNEL_VERSION = '2.1.8'
const ILINK_APP_ID = 'bot'
const buildClientVersion = (version: string): number => {
const parts = version.split('.').map((p) => parseInt(p, 10))
const major = parts[0] ?? 0
const minor = parts[1] ?? 0
const patch = parts[2] ?? 0
return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff)
}
const ILINK_APP_CLIENT_VERSION = buildClientVersion(CHANNEL_VERSION)
export const buildBaseInfo = (): BaseInfo => ({
channel_version: CHANNEL_VERSION,
})
// ---------------------------------------------------------------------------
// Timeouts
// ---------------------------------------------------------------------------
const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000
const DEFAULT_API_TIMEOUT_MS = 15_000
const DEFAULT_CONFIG_TIMEOUT_MS = 10_000
// ---------------------------------------------------------------------------
// Header construction
// ---------------------------------------------------------------------------
const ensureTrailingSlash = (url: string): string => (url.endsWith('/') ? url : `${url}/`)
const randomWechatUin = (): string => {
const uint32 = crypto.randomBytes(4).readUInt32BE(0)
return Buffer.from(String(uint32), 'utf-8').toString('base64')
}
const buildCommonHeaders = (): Record<string, string> => ({
'iLink-App-Id': ILINK_APP_ID,
'iLink-App-ClientVersion': String(ILINK_APP_CLIENT_VERSION),
})
const buildHeaders = (opts: { token?: string; body: string }): Record<string, string> => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
AuthorizationType: 'ilink_bot_token',
'Content-Length': String(Buffer.byteLength(opts.body, 'utf-8')),
'X-WECHAT-UIN': randomWechatUin(),
...buildCommonHeaders(),
}
if (opts.token?.trim()) {
headers.Authorization = `Bearer ${opts.token.trim()}`
}
return headers
}
// ---------------------------------------------------------------------------
// Fetch wrappers
// ---------------------------------------------------------------------------
export type WeixinApiOptions = {
baseUrl: string
token?: string
timeoutMs?: number
}
export const apiGetFetch = async (params: {
baseUrl: string
endpoint: string
timeoutMs?: number
label: string
}): Promise<string> => {
const base = ensureTrailingSlash(params.baseUrl)
const url = new URL(params.endpoint, base)
const hdrs = buildCommonHeaders()
const timeoutMs = params.timeoutMs
const controller = timeoutMs != null && timeoutMs > 0 ? new AbortController() : undefined
const t = controller != null && timeoutMs != null ? setTimeout(() => controller.abort(), timeoutMs) : undefined
try {
const res = await fetch(url.toString(), {
method: 'GET',
headers: hdrs,
...(controller ? { signal: controller.signal } : {}),
})
if (t !== undefined) clearTimeout(t)
const rawText = await res.text()
if (!res.ok) {
throw new Error(`${params.label} ${res.status}: ${rawText}`)
}
return rawText
} catch (err) {
if (t !== undefined) clearTimeout(t)
throw err
}
}
const apiPostFetch = async (params: {
baseUrl: string
endpoint: string
body: string
token?: string
timeoutMs: number
label: string
}): Promise<string> => {
const base = ensureTrailingSlash(params.baseUrl)
const url = new URL(params.endpoint, base)
const hdrs = buildHeaders({ token: params.token, body: params.body })
const start = Date.now()
const controller = new AbortController()
const t = setTimeout(() => controller.abort(), params.timeoutMs)
try {
const res = await fetch(url.toString(), {
method: 'POST',
headers: hdrs,
body: params.body,
signal: controller.signal,
})
clearTimeout(t)
const rawText = await res.text()
const elapsed = Date.now() - start
if (!res.ok) {
logger.error('api', `POST ${params.endpoint} → ${res.status} (${elapsed}ms)`)
throw new Error(`${params.label} ${res.status}: ${rawText}`)
}
// Skip logging for getUpdates (too frequent), log others
if (params.label !== 'getUpdates') {
logger.info('api', `POST ${params.endpoint} → ${res.status} (${elapsed}ms)`)
}
return rawText
} catch (err) {
clearTimeout(t)
if (err instanceof Error && err.name === 'AbortError') {
// Don't log timeout for long-poll getUpdates
if (params.label !== 'getUpdates') {
logger.warn('api', `POST ${params.endpoint} → timeout (${params.timeoutMs}ms)`)
}
}
throw err
}
}
// ---------------------------------------------------------------------------
// API endpoints
// ---------------------------------------------------------------------------
export const getUpdates = async (
params: GetUpdatesReq & {
baseUrl: string
token?: string
timeoutMs?: number
},
): Promise<GetUpdatesResp> => {
const timeout = params.timeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS
try {
const rawText = await apiPostFetch({
baseUrl: params.baseUrl,
endpoint: 'ilink/bot/getupdates',
body: JSON.stringify({
get_updates_buf: params.get_updates_buf ?? '',
base_info: buildBaseInfo(),
}),
token: params.token,
timeoutMs: timeout,
label: 'getUpdates',
})
return JSONSafe.parse(rawText) as GetUpdatesResp
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
return { ret: 0, msgs: [], get_updates_buf: params.get_updates_buf }
}
throw err
}
}
export const getUploadUrl = async (params: GetUploadUrlReq & WeixinApiOptions): Promise<GetUploadUrlResp> => {
const rawText = await apiPostFetch({
baseUrl: params.baseUrl,
endpoint: 'ilink/bot/getuploadurl',
body: JSON.stringify({
filekey: params.filekey,
media_type: params.media_type,
to_user_id: params.to_user_id,
rawsize: params.rawsize,
rawfilemd5: params.rawfilemd5,
filesize: params.filesize,
thumb_rawsize: params.thumb_rawsize,
thumb_rawfilemd5: params.thumb_rawfilemd5,
thumb_filesize: params.thumb_filesize,
no_need_thumb: params.no_need_thumb,
aeskey: params.aeskey,
base_info: buildBaseInfo(),
}),
token: params.token,
timeoutMs: params.timeoutMs ?? DEFAULT_API_TIMEOUT_MS,
label: 'getUploadUrl',
})
return JSON.parse(rawText) as GetUploadUrlResp
}
export const sendMessage = async (params: WeixinApiOptions & { body: SendMessageReq }): Promise<void> => {
await apiPostFetch({
baseUrl: params.baseUrl,
endpoint: 'ilink/bot/sendmessage',
body: JSON.stringify({ ...params.body, base_info: buildBaseInfo() }),
token: params.token,
timeoutMs: params.timeoutMs ?? DEFAULT_API_TIMEOUT_MS,
label: 'sendMessage',
})
}
export const getConfig = async (
params: WeixinApiOptions & { ilinkUserId: string; contextToken?: string },
): Promise<GetConfigResp> => {
const rawText = await apiPostFetch({
baseUrl: params.baseUrl,
endpoint: 'ilink/bot/getconfig',
body: JSON.stringify({
ilink_user_id: params.ilinkUserId,
context_token: params.contextToken,
base_info: buildBaseInfo(),
}),
token: params.token,
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
label: 'getConfig',
})
return JSON.parse(rawText) as GetConfigResp
}
export const sendTyping = async (params: WeixinApiOptions & { body: SendTypingReq }): Promise<void> => {
await apiPostFetch({
baseUrl: params.baseUrl,
endpoint: 'ilink/bot/sendtyping',
body: JSON.stringify({ ...params.body, base_info: buildBaseInfo() }),
token: params.token,
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
label: 'sendTyping',
})
}
// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------
export const generateId = (prefix: string): string => `${prefix}:${Date.now()}-${crypto.randomBytes(4).toString('hex')}`
+178
View File
@@ -0,0 +1,178 @@
import { apiGetFetch } from './api.js'
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const FIXED_BASE_URL = 'https://ilinkai.weixin.qq.com'
const QR_LONG_POLL_TIMEOUT_MS = 35_000
const DEFAULT_ILINK_BOT_TYPE = '3'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface QRCodeResponse {
qrcode: string
qrcode_img_content: string
}
interface StatusResponse {
status: 'wait' | 'scaned' | 'confirmed' | 'expired' | 'scaned_but_redirect'
bot_token?: string
ilink_bot_id?: string
baseurl?: string
ilink_user_id?: string
redirect_host?: string
}
export type LoginResult = {
botToken: string
accountId: string
baseUrl: string
userId: string
}
export type LoginStatus = 'idle' | 'waiting' | 'scanned' | 'confirmed' | 'failed'
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
const fetchQRCode = async (apiBaseUrl: string, botType: string): Promise<QRCodeResponse> => {
const rawText = await apiGetFetch({
baseUrl: apiBaseUrl,
endpoint: `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(botType)}`,
label: 'fetchQRCode',
})
return JSON.parse(rawText) as QRCodeResponse
}
const pollQRStatus = async (apiBaseUrl: string, qrcode: string): Promise<StatusResponse> => {
try {
const rawText = await apiGetFetch({
baseUrl: apiBaseUrl,
endpoint: `ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`,
timeoutMs: QR_LONG_POLL_TIMEOUT_MS,
label: 'pollQRStatus',
})
return JSON.parse(rawText) as StatusResponse
} catch (err) {
// Network errors are intentionally treated as "wait" here.
// The QR login has a finite lifetime — the server will eventually
// return "expired", so transient failures won't loop forever.
if (err instanceof Error && err.name === 'AbortError') {
return { status: 'wait' }
}
return { status: 'wait' }
}
}
// ---------------------------------------------------------------------------
let loginStatus: LoginStatus = 'idle'
let loginError: string | null = null
let loginQrcodeUrl: string | null = null
let abortLogin: (() => void) | null = null
export const getLoginStatus = (): { status: LoginStatus; error: string | null; qr_url: string | null } => ({
status: loginStatus,
error: loginError,
qr_url: loginQrcodeUrl,
})
export const resetLoginStatus = (): void => {
abortLogin?.()
loginStatus = 'idle'
loginError = null
loginQrcodeUrl = null
abortLogin = null
}
// ---------------------------------------------------------------------------
// Public API: single-call login
// ---------------------------------------------------------------------------
export const startLogin = async (
onConfirmed: (result: LoginResult) => void,
): Promise<{
qrcodeUrl: string
}> => {
// Cancel any existing login
abortLogin?.()
loginStatus = 'waiting'
loginError = null
loginQrcodeUrl = null
const botType = DEFAULT_ILINK_BOT_TYPE
const qrResponse = await fetchQRCode(FIXED_BASE_URL, botType)
loginQrcodeUrl = qrResponse.qrcode_img_content
// Start background polling
let cancelled = false
abortLogin = () => {
cancelled = true
}
const bgPoll = async () => {
let currentBaseUrl = FIXED_BASE_URL
const qrcode = qrResponse.qrcode
while (!cancelled) {
const resp = await pollQRStatus(currentBaseUrl, qrcode)
switch (resp.status) {
case 'wait':
break
case 'scaned':
loginStatus = 'scanned'
break
case 'expired': {
loginStatus = 'failed'
loginError = 'QR code expired, please login again.'
loginQrcodeUrl = null
return
}
case 'scaned_but_redirect': {
if (resp.redirect_host) {
currentBaseUrl = `https://${resp.redirect_host}`
}
break
}
case 'confirmed': {
if (!resp.ilink_bot_id || !resp.bot_token) {
loginStatus = 'failed'
loginError = 'Login failed: incomplete response from server.'
loginQrcodeUrl = null
return
}
const result: LoginResult = {
botToken: resp.bot_token,
accountId: resp.ilink_bot_id,
baseUrl: resp.baseurl ?? FIXED_BASE_URL,
userId: resp.ilink_user_id ?? '',
}
loginStatus = 'confirmed'
loginQrcodeUrl = null
onConfirmed(result)
return
}
}
await new Promise((r) => setTimeout(r, 1000))
}
}
bgPoll().catch((err) => {
loginStatus = 'failed'
loginError = err instanceof Error ? err.message : String(err)
loginQrcodeUrl = null
})
return { qrcodeUrl: qrResponse.qrcode_img_content }
}
+241
View File
@@ -0,0 +1,241 @@
import crypto from 'node:crypto'
import { logger } from '../lib/logger.js'
import type { WeixinApiOptions } from './api.js'
import { getUploadUrl } from './api.js'
import { aesEcbPaddedSize, decryptAesEcb, encryptAesEcb } from './crypto.js'
import { UploadMediaType } from './types.js'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type UploadedFileInfo = {
filekey: string
downloadEncryptedQueryParam: string
aeskey: string // hex-encoded
fileSize: number
fileSizeCiphertext: number
}
// ---------------------------------------------------------------------------
// CDN URL construction
// ---------------------------------------------------------------------------
const DEFAULT_CDN_BASE_URL = 'https://novac2c.cdn.weixin.qq.com/c2c'
export const buildCdnDownloadUrl = (encryptedQueryParam: string, cdnBaseUrl: string = DEFAULT_CDN_BASE_URL): string =>
`${cdnBaseUrl}/download?encrypted_query_param=${encodeURIComponent(encryptedQueryParam)}`
export const buildCdnUploadUrl = (params: { cdnBaseUrl: string; uploadParam: string; filekey: string }): string =>
`${params.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(params.uploadParam)}&filekey=${encodeURIComponent(params.filekey)}`
// ---------------------------------------------------------------------------
// CDN upload (buffer → encrypt → POST)
// ---------------------------------------------------------------------------
const UPLOAD_MAX_RETRIES = 3
export const uploadBufferToCdn = async (params: {
buf: Buffer
uploadFullUrl?: string
uploadParam?: string
filekey: string
cdnBaseUrl: string
label: string
aeskey: Buffer
}): Promise<{ downloadParam: string }> => {
const { buf, uploadFullUrl, uploadParam, filekey, cdnBaseUrl, label, aeskey } = params
const ciphertext = encryptAesEcb(buf, aeskey)
const trimmedFull = uploadFullUrl?.trim()
let cdnUrl: string
if (trimmedFull) {
cdnUrl = trimmedFull
} else if (uploadParam) {
cdnUrl = buildCdnUploadUrl({ cdnBaseUrl, uploadParam, filekey })
} else {
throw new Error(`${label}: CDN upload URL missing (need upload_full_url or upload_param)`)
}
let downloadParam: string | undefined
let lastError: unknown
for (let attempt = 1; attempt <= UPLOAD_MAX_RETRIES; attempt++) {
try {
const start = Date.now()
const res = await fetch(cdnUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: new Uint8Array(ciphertext),
})
if (res.status >= 400 && res.status < 500) {
const errMsg = res.headers.get('x-error-message') ?? (await res.text())
throw new Error(`CDN upload client error ${res.status}: ${errMsg}`)
}
if (res.status !== 200) {
const errMsg = res.headers.get('x-error-message') ?? `status ${res.status}`
throw new Error(`CDN upload server error: ${errMsg}`)
}
downloadParam = res.headers.get('x-encrypted-param') ?? undefined
if (!downloadParam) {
throw new Error('CDN upload response missing x-encrypted-param header')
}
logger.info('cdn', `${label} upload ok size=${buf.length} (${Date.now() - start}ms)`)
break
} catch (err) {
lastError = err
if (err instanceof Error && err.message.includes('client error')) throw err
if (attempt < UPLOAD_MAX_RETRIES) {
logger.warn(
'cdn',
`${label} upload retry attempt=${attempt + 1}/${UPLOAD_MAX_RETRIES}: ${err instanceof Error ? err.message : err}`,
)
}
if (attempt >= UPLOAD_MAX_RETRIES) break
}
}
if (!downloadParam) {
logger.error('cdn', `${label} upload failed after ${UPLOAD_MAX_RETRIES} attempts`)
throw lastError instanceof Error ? lastError : new Error(`CDN upload failed after ${UPLOAD_MAX_RETRIES} attempts`)
}
return { downloadParam }
}
// ---------------------------------------------------------------------------
// Upload pipeline: plaintext buffer → hash → gen key → getUploadUrl → upload
// ---------------------------------------------------------------------------
const uploadMediaToCdn = async (params: {
buf: Buffer
toUserId: string
opts: WeixinApiOptions
cdnBaseUrl: string
mediaType: (typeof UploadMediaType)[keyof typeof UploadMediaType]
label: string
}): Promise<UploadedFileInfo> => {
const { buf, toUserId, opts, cdnBaseUrl, mediaType, label } = params
const rawsize = buf.length
const rawfilemd5 = crypto.createHash('md5').update(buf).digest('hex')
const filesize = aesEcbPaddedSize(rawsize)
const filekey = crypto.randomBytes(16).toString('hex')
const aeskey = crypto.randomBytes(16)
const uploadUrlResp = await getUploadUrl({
...opts,
filekey,
media_type: mediaType,
to_user_id: toUserId,
rawsize,
rawfilemd5,
filesize,
no_need_thumb: true,
aeskey: aeskey.toString('hex'),
})
const uploadFullUrl = uploadUrlResp.upload_full_url?.trim()
const uploadParam = uploadUrlResp.upload_param
if (!uploadFullUrl && !uploadParam) {
throw new Error(`${label}: getUploadUrl returned no upload URL`)
}
const { downloadParam: downloadEncryptedQueryParam } = await uploadBufferToCdn({
buf,
uploadFullUrl: uploadFullUrl || undefined,
uploadParam: uploadParam ?? undefined,
filekey,
cdnBaseUrl,
aeskey,
label,
})
return {
filekey,
downloadEncryptedQueryParam,
aeskey: aeskey.toString('hex'),
fileSize: rawsize,
fileSizeCiphertext: filesize,
}
}
export const uploadImage = async (params: {
buf: Buffer
toUserId: string
opts: WeixinApiOptions
cdnBaseUrl?: string
}): Promise<UploadedFileInfo> =>
uploadMediaToCdn({
...params,
cdnBaseUrl: params.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
mediaType: UploadMediaType.IMAGE,
label: 'uploadImage',
})
export const uploadVideo = async (params: {
buf: Buffer
toUserId: string
opts: WeixinApiOptions
cdnBaseUrl?: string
}): Promise<UploadedFileInfo> =>
uploadMediaToCdn({
...params,
cdnBaseUrl: params.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
mediaType: UploadMediaType.VIDEO,
label: 'uploadVideo',
})
export const uploadFile = async (params: {
buf: Buffer
toUserId: string
opts: WeixinApiOptions
cdnBaseUrl?: string
}): Promise<UploadedFileInfo> =>
uploadMediaToCdn({
...params,
cdnBaseUrl: params.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
mediaType: UploadMediaType.FILE,
label: 'uploadFile',
})
// ---------------------------------------------------------------------------
// CDN download & decrypt
// ---------------------------------------------------------------------------
const parseAesKey = (aesKeyBase64: string, label: string): Buffer => {
const decoded = Buffer.from(aesKeyBase64, 'base64')
if (decoded.length === 16) {
return decoded
}
if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString('ascii'))) {
return Buffer.from(decoded.toString('ascii'), 'hex')
}
throw new Error(`${label}: aes_key must decode to 16 raw bytes or 32-char hex string, got ${decoded.length} bytes`)
}
const fetchCdnBytes = async (url: string, label: string): Promise<Buffer> => {
const res = await fetch(url)
if (!res.ok) {
const body = await res.text().catch(() => '(unreadable)')
throw new Error(`${label}: CDN download ${res.status} ${res.statusText} body=${body}`)
}
return Buffer.from(await res.arrayBuffer())
}
export const downloadAndDecrypt = async (
encryptedQueryParam: string,
aesKeyBase64: string,
cdnBaseUrl: string = DEFAULT_CDN_BASE_URL,
label: string = 'downloadAndDecrypt',
fullUrl?: string,
): Promise<Buffer> => {
const key = parseAesKey(aesKeyBase64, label)
const url = fullUrl ?? buildCdnDownloadUrl(encryptedQueryParam, cdnBaseUrl)
const start = Date.now()
const encrypted = await fetchCdnBytes(url, label)
const decrypted = decryptAesEcb(encrypted, key)
logger.info('cdn', `${label} download ok size=${decrypted.length} (${Date.now() - start}ms)`)
return decrypted
}
+13
View File
@@ -0,0 +1,13 @@
import { createCipheriv, createDecipheriv } from 'node:crypto'
export const encryptAesEcb = (plaintext: Buffer, key: Buffer): Buffer => {
const cipher = createCipheriv('aes-128-ecb', key, null)
return Buffer.concat([cipher.update(plaintext), cipher.final()])
}
export const decryptAesEcb = (ciphertext: Buffer, key: Buffer): Buffer => {
const decipher = createDecipheriv('aes-128-ecb', key, null)
return Buffer.concat([decipher.update(ciphertext), decipher.final()])
}
export const aesEcbPaddedSize = (plaintextSize: number): number => Math.ceil((plaintextSize + 1) / 16) * 16
+5
View File
@@ -0,0 +1,5 @@
export * from './api.js'
export * from './auth.js'
export * from './cdn.js'
export * from './crypto.js'
export * from './types.js'
+183
View File
@@ -0,0 +1,183 @@
/**
* Weixin iLink Bot protocol types.
* 1:1 mirror of @tencent-weixin/openclaw-weixin@2.1.8 src/api/types.ts
*/
export interface BaseInfo {
channel_version?: string
}
export const UploadMediaType = {
IMAGE: 1,
VIDEO: 2,
FILE: 3,
VOICE: 4,
} as const
export interface GetUploadUrlReq {
filekey?: string
media_type?: number
to_user_id?: string
rawsize?: number
rawfilemd5?: string
filesize?: number
thumb_rawsize?: number
thumb_rawfilemd5?: string
thumb_filesize?: number
no_need_thumb?: boolean
aeskey?: string
}
export interface GetUploadUrlResp {
upload_param?: string
thumb_upload_param?: string
upload_full_url?: string
}
export const MessageType = {
NONE: 0,
USER: 1,
BOT: 2,
} as const
export const MessageItemType = {
NONE: 0,
TEXT: 1,
IMAGE: 2,
VOICE: 3,
FILE: 4,
VIDEO: 5,
} as const
export const MessageState = {
NEW: 0,
GENERATING: 1,
FINISH: 2,
} as const
export interface TextItem {
text?: string
}
export interface CDNMedia {
encrypt_query_param?: string
aes_key?: string
encrypt_type?: number
full_url?: string
}
export interface ImageItem {
media?: CDNMedia
thumb_media?: CDNMedia
aeskey?: string
url?: string
mid_size?: number
thumb_size?: number
thumb_height?: number
thumb_width?: number
hd_size?: number
}
export interface VoiceItem {
media?: CDNMedia
encode_type?: number
bits_per_sample?: number
sample_rate?: number
playtime?: number
text?: string
}
export interface FileItem {
media?: CDNMedia
file_name?: string
md5?: string
len?: string
}
export interface VideoItem {
media?: CDNMedia
video_size?: number
play_length?: number
video_md5?: string
thumb_media?: CDNMedia
thumb_size?: number
thumb_height?: number
thumb_width?: number
}
export interface RefMessage {
message_item?: MessageItem
title?: string
}
export interface MessageItem {
type?: number
create_time_ms?: number
update_time_ms?: number
is_completed?: boolean
msg_id?: string
ref_msg?: RefMessage
text_item?: TextItem
image_item?: ImageItem
voice_item?: VoiceItem
file_item?: FileItem
video_item?: VideoItem
}
export interface WeixinMessage {
seq?: number
message_id?: string
from_user_id?: string
to_user_id?: string
client_id?: string
create_time_ms?: number
update_time_ms?: number
delete_time_ms?: number
session_id?: string
group_id?: string
message_type?: number
message_state?: number
item_list?: MessageItem[]
context_token?: string
}
export interface GetUpdatesReq {
get_updates_buf?: string
}
export interface GetUpdatesResp {
ret?: number
errcode?: number
errmsg?: string
msgs?: WeixinMessage[]
get_updates_buf?: string
longpolling_timeout_ms?: number
}
export interface SendMessageReq {
msg?: WeixinMessage
}
export type SendMessageResp = Record<string, never>
export const TypingStatus = {
TYPING: 1,
CANCEL: 2,
} as const
export interface SendTypingReq {
ilink_user_id?: string
typing_ticket?: string
status?: number
}
export interface SendTypingResp {
ret?: number
errmsg?: string
}
export interface GetConfigResp {
ret?: number
errmsg?: string
typing_ticket?: string
}
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0"
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0start.ps1"
if errorlevel 1 pause
+59
View File
@@ -0,0 +1,59 @@
# WeChat iLink Gateway - one-click start (Windows)
$ErrorActionPreference = "Stop"
Set-Location $PSScriptRoot
function Ensure-Bun {
$bun = Get-Command bun -ErrorAction SilentlyContinue
if ($bun) { return }
Write-Host "[*] Bun not found, installing..." -ForegroundColor Yellow
irm https://bun.sh/install.ps1 | iex
$env:Path = "$env:USERPROFILE\.bun\bin;$env:Path"
if (-not (Get-Command bun -ErrorAction SilentlyContinue)) {
Write-Host "[!] Bun installed but not on PATH. Close this window and run start.bat again." -ForegroundColor Red
exit 1
}
}
function Ensure-Env {
if (-not (Test-Path ".env")) {
Copy-Item ".env.example" ".env"
Write-Host "[*] Created .env from .env.example" -ForegroundColor Yellow
}
$lines = Get-Content ".env"
$apiKeyLine = $lines | Where-Object { $_ -match '^\s*API_KEY\s*=' } | Select-Object -First 1
$apiKey = ""
if ($apiKeyLine -match '^\s*API_KEY\s*=\s*(.*)$') {
$apiKey = $Matches[1].Trim().Trim('"').Trim("'")
}
if ([string]::IsNullOrWhiteSpace($apiKey) -or $apiKey.Length -le 12) {
$generated = -join ((1..24) | ForEach-Object { "{0:x}" -f (Get-Random -Max 16) })
$newLines = foreach ($line in $lines) {
if ($line -match '^\s*API_KEY\s*=') { "API_KEY=$generated" } else { $line }
}
Set-Content -Path ".env" -Value $newLines -Encoding utf8
Write-Host "[*] Generated API_KEY in .env: $generated" -ForegroundColor Cyan
}
}
Ensure-Bun
Ensure-Env
if (-not (Test-Path "node_modules")) {
Write-Host "[*] Installing dependencies (bun install)..." -ForegroundColor Yellow
bun install
}
$port = "3456"
$envLine = Get-Content ".env" | Where-Object { $_ -match '^\s*PORT\s*=' } | Select-Object -First 1
if ($envLine -match '^\s*PORT\s*=\s*(\d+)') { $port = $Matches[1] }
Write-Host ""
Write-Host "[+] Starting gateway..." -ForegroundColor Green
Write-Host " Console: http://localhost:$port/console"
Write-Host " Status: http://localhost:$port/status"
Write-Host " Press Ctrl+C to stop"
Write-Host ""
bun run start
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# WeChat iLink Gateway — one-click start (Linux / macOS)
set -euo pipefail
cd "$(dirname "$0")"
ensure_bun() {
if command -v bun >/dev/null 2>&1; then
return
fi
echo "未检测到 Bun,正在安装..."
curl -fsSL https://bun.sh/install | bash
export BUN_INSTALL="${HOME}/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
if ! command -v bun >/dev/null 2>&1; then
echo "Bun 安装后仍不可用,请重新打开终端后再运行。"
exit 1
fi
}
ensure_env() {
if [[ ! -f .env ]]; then
cp .env.example .env
echo "已从 .env.example 创建 .env"
fi
local api_key
api_key="$(grep -E '^\s*API_KEY\s*=' .env | head -n1 | sed 's/^[^=]*=//;s/^[[:space:]]*//;s/[[:space:]]*$//;s/^["'\'']//;s/["'\'']$//')"
if [[ -z "$api_key" || ${#api_key} -le 12 ]]; then
local generated
generated="$(openssl rand -hex 12 2>/dev/null || head -c 24 /dev/urandom | xxd -p | head -c 24)"
if grep -qE '^\s*API_KEY\s*=' .env; then
# portable in-place replace
tmp="$(mktemp)"
sed "s/^[[:space:]]*API_KEY=.*/API_KEY=${generated}/" .env >"$tmp"
mv "$tmp" .env
else
echo "API_KEY=${generated}" >>.env
fi
echo "已自动生成 API_KEY(写入 .env): ${generated}"
fi
}
ensure_bun
ensure_env
if [[ ! -d node_modules ]]; then
echo "正在安装依赖 (bun install)..."
bun install
fi
port="$(grep -E '^\s*PORT\s*=' .env | head -n1 | sed 's/^[^=]*=//;s/[[:space:]]//g' || true)"
port="${port:-3456}"
echo ""
echo "Gateway 启动中..."
echo " 控制台: http://localhost:${port}/console"
echo " 状态: http://localhost:${port}/status"
echo "按 Ctrl+C 停止"
echo ""
exec bun run start
+660
View File
@@ -0,0 +1,660 @@
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
// ---------------------------------------------------------------------------
// Config — reads from env, must match the running server
// ---------------------------------------------------------------------------
const BASE = 'http://localhost:3456'
const API_KEY = process.env.API_KEY || 'test-api-key'
const AUTH = { Authorization: `Bearer ${API_KEY}` }
const JSON_HEADERS = { ...AUTH, 'Content-Type': 'application/json' }
const WEBHOOK_TOKEN = process.env.WEBHOOK_TOKEN || ''
const TEST_IMAGE = readFileSync(join(import.meta.dir, 'fixtures/test-image.png'))
const TEST_FILE = readFileSync(join(import.meta.dir, 'fixtures/test-file.txt'))
const TEST_VIDEO = readFileSync(join(import.meta.dir, 'fixtures/test-video.mp4'))
const LOGIN_POLL_INTERVAL_MS = 2_000
const LOGIN_TIMEOUT_MS = 120_000 // 2 minutes to scan QR
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const get = async (path: string) => fetch(`${BASE}${path}`, { headers: AUTH })
const post = async (path: string, body?: unknown) =>
fetch(`${BASE}${path}`, {
method: 'POST',
headers: JSON_HEADERS,
body: body !== undefined ? JSON.stringify(body) : undefined,
})
const postForm = async (path: string, form: FormData) =>
fetch(`${BASE}${path}`, { method: 'POST', headers: AUTH, body: form })
const json = (res: Response) => res.json() as Promise<Record<string, unknown>>
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
const getStatus = async () => json(await get('/status'))
// ---------------------------------------------------------------------------
// Setup: ensure clean login
// ---------------------------------------------------------------------------
beforeAll(async () => {
const status = await getStatus()
// If already logged in, logout first to test full lifecycle
if (status.logged_in) {
console.log('⏳ Already logged in, logging out first...')
await post('/auth/logout')
const after = await getStatus()
if (after.logged_in) throw new Error('Failed to logout')
console.log('✅ Logged out')
}
}, 10_000)
afterAll(async () => {
// Cleanup: logout after all tests
const status = await getStatus()
if (status.logged_in) {
console.log('🧹 Cleaning up: logging out...')
await post('/auth/logout')
console.log('✅ Logged out')
}
}, 10_000)
// ===========================================================================
// Phase 1: Tests that DON'T require login
// ===========================================================================
describe('1. Bearer auth middleware', () => {
test('missing header → 401', async () => {
const res = await fetch(`${BASE}/status`)
expect(res.status).toBe(401)
expect((await json(res)).message).toBe('Missing Authorization header')
})
test('wrong token → 401', async () => {
const res = await fetch(`${BASE}/status`, {
headers: { Authorization: 'Bearer wrong' },
})
expect(res.status).toBe(401)
expect((await json(res)).message).toBe('Invalid token')
})
})
describe('2. GET /status (before login)', () => {
test('returns not-logged-in status', async () => {
const res = await get('/status')
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(body.logged_in).toBe(false)
expect(body.user_id).toBeNull()
expect(typeof body.polling).toBe('boolean')
expect(Array.isArray(body.webhook_urls)).toBe(true)
})
})
describe('3. Login guard (before login)', () => {
test('all authed routes → 401 Not logged in', async () => {
const routes: [string, string][] = [
['POST', '/messages/send'],
['GET', '/messages/updates'],
['POST', '/media/presign'],
['POST', '/media/download'],
['POST', '/typing/start'],
['POST', '/typing/stop'],
['POST', '/config'],
]
for (const [method, path] of routes) {
const res = method === 'GET' ? await get(path) : await post(path, {})
expect(res.status).toBe(401)
expect((await json(res)).message).toBe('Not logged in')
}
})
})
describe('4. 404 (before login)', () => {
test('unknown route → 401 (login guard catches before 404)', async () => {
const res = await get('/does-not-exist')
expect(res.status).toBe(401)
expect((await json(res)).ok).toBe(false)
})
})
// ===========================================================================
// Phase 2: Login flow
// ===========================================================================
describe('5. POST /auth/login', () => {
test(
'full login flow: get QR → wait for scan → confirmed → wait for first message',
async () => {
// Start login
const res = await post('/auth/login')
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(typeof body.qr_url).toBe('string')
console.log(`\n${'='.repeat(60)}`)
console.log('📱 Please scan QR code to login (2 min timeout)')
console.log('QR URL:', body.qr_url)
console.log(`${'='.repeat(60)}\n`)
// Poll until confirmed
const loginDeadline = Date.now() + LOGIN_TIMEOUT_MS
let confirmed = false
while (Date.now() < loginDeadline) {
await sleep(LOGIN_POLL_INTERVAL_MS)
const status = await getStatus()
if (status.login_status === 'scanned') {
console.log('📱 Scanned, waiting for confirmation...')
}
if (status.logged_in) {
confirmed = true
console.log(`✅ Login success! user_id=${status.user_id}`)
break
}
if (status.login_status === 'failed') {
throw new Error(`Login failed: ${status.login_error}`)
}
}
expect(confirmed).toBe(true)
// Wait for user to send a message so context_token gets cached
console.log(`\n${'='.repeat(60)}`)
console.log('💬 Please send a message to the bot on WeChat (waiting for context_token)')
console.log(`${'='.repeat(60)}\n`)
const msgDeadline = Date.now() + LOGIN_TIMEOUT_MS
let gotMessage = false
while (Date.now() < msgDeadline) {
await sleep(LOGIN_POLL_INTERVAL_MS)
const updatesRes = await get('/messages/updates')
const updates = await json(updatesRes)
if ((updates.count as number) > 0) {
gotMessage = true
console.log(`✅ Message received! count=${updates.count}`)
break
}
}
expect(gotMessage).toBe(true)
},
(LOGIN_TIMEOUT_MS + 10_000) * 2,
)
test('login again → 409 conflict', async () => {
const res = await post('/auth/login')
expect(res.status).toBe(409)
})
})
// ===========================================================================
// Phase 3: Tests that REQUIRE login
// ===========================================================================
describe('6. GET /status (after login)', () => {
test('returns logged-in status', async () => {
const res = await get('/status')
const body = await json(res)
expect(body.ok).toBe(true)
expect(body.logged_in).toBe(true)
expect(typeof body.user_id).toBe('string')
expect(body.polling).toBe(true)
})
})
describe('7. 404 (after login)', () => {
test('unknown route → 404', async () => {
const res = await get('/does-not-exist')
expect(res.status).toBe(404)
expect((await json(res)).ok).toBe(false)
})
})
// ---------------------------------------------------------------------------
// Messages
// ---------------------------------------------------------------------------
describe('8. POST /messages/send — validation', () => {
test('missing to → 400', async () => {
const res = await post('/messages/send', {
items: [{ type: 'text', text: 'hi' }],
})
expect(res.status).toBe(400)
})
test('empty items → 400', async () => {
const res = await post('/messages/send', { to: 'self', items: [] })
expect(res.status).toBe(400)
})
test('invalid item type → 400', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [{ type: 'sticker' }],
})
expect(res.status).toBe(400)
})
test('file without file_name → 400', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [{ type: 'file', cdn: { encrypt_query_param: 'x', aes_key: 'y' } }],
})
expect(res.status).toBe(400)
})
})
describe('9. POST /messages/send — real send', () => {
test('send text to self', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [{ type: 'text', text: `[test] ${new Date().toISOString()}` }],
})
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
const results = body.results as Record<string, unknown>[]
expect(results).toHaveLength(1)
const first = results.at(0)
expect(first).toBeDefined()
expect(first?.type).toBe('text')
expect(first?.ok).toBe(true)
expect(typeof first?.client_id).toBe('string')
})
test('send multiple texts', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [
{ type: 'text', text: '[test] msg 1' },
{ type: 'text', text: '[test] msg 2' },
],
})
const body = await json(res)
expect(body.ok).toBe(true)
expect(body.results as unknown[]).toHaveLength(2)
})
test('send image via url', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [{ type: 'image', url: 'https://wechat.design/uploads/740a6c40367a4d2db0bc8c80ccc8018e.jpg' }],
})
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
const results = body.results as Record<string, unknown>[]
expect(results).toHaveLength(1)
expect(results[0]?.type).toBe('image')
expect(results[0]?.ok).toBe(true)
expect(typeof results[0]?.client_id).toBe('string')
}, 30_000)
})
// ---------------------------------------------------------------------------
// Messages updates
// ---------------------------------------------------------------------------
describe('10. GET /messages/updates', () => {
test('returns message buffer', async () => {
const res = await get('/messages/updates')
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(typeof body.count).toBe('number')
expect(Array.isArray(body.messages)).toBe(true)
})
test('?after=999999999 → empty', async () => {
const res = await get('/messages/updates?after=999999999')
const body = await json(res)
expect(body.count).toBe(0)
})
test('invalid after is ignored', async () => {
const res = await get('/messages/updates?after=not-a-number')
expect(res.status).toBe(200)
})
})
// ---------------------------------------------------------------------------
// Media upload
// ---------------------------------------------------------------------------
describe('11. POST /media/upload — validation', () => {
test('missing file → 400', async () => {
const form = new FormData()
form.append('to', 'self')
const res = await postForm('/media/upload', form)
expect(res.status).toBe(400)
})
test('missing to → 400', async () => {
const form = new FormData()
form.append('file', new File(['x'], 'test.txt'))
const res = await postForm('/media/upload', form)
expect(res.status).toBe(400)
})
})
describe('12. POST /media/upload — real upload', () => {
test('upload image', async () => {
const form = new FormData()
form.append('file', new File([TEST_IMAGE], 'test.png', { type: 'image/png' }))
form.append('to', 'self')
const res = await postForm('/media/upload', form)
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(body.media_type).toBe('image')
expect(body.file_name).toBe('test.png')
expect(typeof body.filekey).toBe('string')
expect(typeof body.encrypt_query_param).toBe('string')
expect(typeof body.aes_key).toBe('string')
expect(typeof body.file_size).toBe('number')
expect(typeof body.file_size_ciphertext).toBe('number')
})
test('upload then send image via cdn reference', async () => {
const form = new FormData()
form.append('file', new File([TEST_IMAGE], 'test.png', { type: 'image/png' }))
form.append('to', 'self')
const uploadRes = await postForm('/media/upload', form)
expect(uploadRes.status).toBe(200)
const uploaded = await json(uploadRes)
expect(uploaded.ok).toBe(true)
const sendRes = await post('/messages/send', {
to: 'self',
items: [
{
type: 'image',
cdn: {
encrypt_query_param: uploaded.encrypt_query_param,
aes_key: uploaded.aes_key,
},
},
],
})
expect(sendRes.status).toBe(200)
const sendBody = await json(sendRes)
expect(sendBody.ok).toBe(true)
const results = sendBody.results as Record<string, unknown>[]
expect(results).toHaveLength(1)
expect(results[0]?.type).toBe('image')
expect(results[0]?.ok).toBe(true)
}, 30_000)
test('upload then send file via cdn reference', async () => {
const form = new FormData()
form.append('file', new File([TEST_FILE], 'test-file.txt', { type: 'text/plain' }))
form.append('to', 'self')
const uploadRes = await postForm('/media/upload', form)
expect(uploadRes.status).toBe(200)
const uploaded = await json(uploadRes)
expect(uploaded.ok).toBe(true)
expect(uploaded.media_type).toBe('file')
const sendRes = await post('/messages/send', {
to: 'self',
items: [
{
type: 'file',
file_name: 'test-file.txt',
cdn: {
encrypt_query_param: uploaded.encrypt_query_param,
aes_key: uploaded.aes_key,
},
},
],
})
expect(sendRes.status).toBe(200)
const sendBody = await json(sendRes)
expect(sendBody.ok).toBe(true)
const results = sendBody.results as Record<string, unknown>[]
expect(results).toHaveLength(1)
expect(results[0]?.type).toBe('file')
expect(results[0]?.ok).toBe(true)
}, 30_000)
test('upload then send video via cdn reference', async () => {
const form = new FormData()
form.append('file', new File([TEST_VIDEO], 'test-video.mp4', { type: 'video/mp4' }))
form.append('to', 'self')
const uploadRes = await postForm('/media/upload', form)
expect(uploadRes.status).toBe(200)
const uploaded = await json(uploadRes)
expect(uploaded.ok).toBe(true)
expect(uploaded.media_type).toBe('video')
const sendRes = await post('/messages/send', {
to: 'self',
items: [
{
type: 'video',
cdn: {
encrypt_query_param: uploaded.encrypt_query_param,
aes_key: uploaded.aes_key,
},
},
],
})
expect(sendRes.status).toBe(200)
const sendBody = await json(sendRes)
expect(sendBody.ok).toBe(true)
const results = sendBody.results as Record<string, unknown>[]
expect(results).toHaveLength(1)
expect(results[0]?.type).toBe('video')
expect(results[0]?.ok).toBe(true)
}, 60_000)
})
// ---------------------------------------------------------------------------
// Media presign
// ---------------------------------------------------------------------------
describe('13. POST /media/presign', () => {
test('missing required fields → 400', async () => {
const res = await post('/media/presign', { to: 'self' })
expect(res.status).toBe(400)
})
test('returns presigned url', async () => {
const res = await post('/media/presign', {
to: 'self',
filekey: `test_fk_${Date.now()}`,
media_type: 1,
rawsize: 100,
rawfilemd5: 'd41d8cd98f00b204e9800998ecf8427e',
filesize: 112,
aeskey: '00112233445566778899aabbccddeeff',
})
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(typeof body.upload_param === 'string' || typeof body.upload_full_url === 'string').toBe(true)
})
})
// ---------------------------------------------------------------------------
// Media download
// ---------------------------------------------------------------------------
describe('14. POST /media/download — validation', () => {
test('missing fields → 400', async () => {
const res = await post('/media/download', { aes_key: 'key' })
expect(res.status).toBe(400)
})
test('invalid url → 400', async () => {
const res = await post('/media/download', {
full_url: 'not-a-url',
aes_key: 'dGVzdA==',
file_name: 'test.txt',
})
expect(res.status).toBe(400)
})
})
// ---------------------------------------------------------------------------
// Typing
// ---------------------------------------------------------------------------
describe('15. POST /typing/start', () => {
test('missing to → 400', async () => {
const res = await post('/typing/start', {})
expect(res.status).toBe(400)
})
test('sends typing indicator', async () => {
const res = await post('/typing/start', { to: 'self' })
expect(res.status).toBe(200)
expect((await json(res)).ok).toBe(true)
})
})
describe('16. POST /typing/stop', () => {
test('missing to → 400', async () => {
const res = await post('/typing/stop', {})
expect(res.status).toBe(400)
})
test('cancels typing indicator', async () => {
const res = await post('/typing/stop', { to: 'self' })
expect(res.status).toBe(200)
expect((await json(res)).ok).toBe(true)
})
})
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
describe('17. POST /config', () => {
test('missing to → 400', async () => {
const res = await post('/config', {})
expect(res.status).toBe(400)
})
test('returns config with typing_ticket', async () => {
const res = await post('/config', { to: 'self' })
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(typeof body.typing_ticket).toBe('string')
})
})
// ---------------------------------------------------------------------------
// Webhook (incoming)
// ---------------------------------------------------------------------------
describe('18. POST /webhook/:token', () => {
test('skips bearer auth', async () => {
const res = await fetch(`${BASE}/webhook/some-token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'test' }),
})
const body = await json(res)
expect(body.message).not.toBe('Missing Authorization header')
})
test('invalid token → 401', async () => {
const res = await fetch(`${BASE}/webhook/definitely-wrong`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'test' }),
})
expect(res.status).toBe(401)
})
test('empty text → 400', async () => {
if (!WEBHOOK_TOKEN) return
const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: ' ' }),
})
expect(res.status).toBe(400)
})
test('send via text/plain', async () => {
if (!WEBHOOK_TOKEN) return
const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: `[test] webhook plain ${new Date().toISOString()}`,
})
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
expect(typeof body.client_id).toBe('string')
})
test('send via JSON', async () => {
if (!WEBHOOK_TOKEN) return
const res = await fetch(`${BASE}/webhook/${WEBHOOK_TOKEN}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `[test] webhook json ${new Date().toISOString()}`,
}),
})
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
})
})
// ===========================================================================
// Phase 4: Logout
// ===========================================================================
describe('19. POST /auth/logout', () => {
test('logout → 200', async () => {
const res = await post('/auth/logout')
expect(res.status).toBe(200)
const body = await json(res)
expect(body.ok).toBe(true)
})
test('status is logged out', async () => {
const status = await getStatus()
expect(status.logged_in).toBe(false)
expect(status.user_id).toBeNull()
})
test('logout again → 400', async () => {
const res = await post('/auth/logout')
expect(res.status).toBe(400)
})
test('authed routes blocked again', async () => {
const res = await post('/messages/send', {
to: 'self',
items: [{ type: 'text', text: 'should fail' }],
})
expect(res.status).toBe(401)
})
})
+1
View File
@@ -0,0 +1 @@
weixin-ilink-gateway test fixture
Binary file not shown.

After

Width:  |  Height:  |  Size: 73 B

Binary file not shown.
+32
View File
@@ -0,0 +1,32 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "Preserve",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Bun types via @types/bun (re-exports bun-types)
"types": ["bun"],
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}