nkuntz1934/matrix-workers

GitHub: nkuntz1934/matrix-workers

在 Cloudflare Workers 边缘平台上完整实现 Matrix v1.17 协议的家庭服务器原型,支持 E2EE 加密通信和服务器联邦。

Stars: 113 | Forks: 25

# Cloudflare Workers 上的 Matrix Homeserver [![Security](https://static.pigsec.cn/wp-content/uploads/repos/2026/03/fd39c701c9112003.svg)](https://github.com/nkuntz1934/matrix-workers/actions/workflows/security.yml) [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/nkuntz1934/matrix-workers) 这是一个完全运行在 Cloudflare 边缘基础设施上的 Matrix homeserver 概念验证实现。它的构建是为了证明在 Cloudflare Workers 平台上利用 Matrix 协议通过 Element X 实现 E2EE。它旨在作为一个示例原型,目前并不建议用于生产环境。 我在 Claude Code Opus 4.5 的协助下完成了此实现,以加快展示你可以利用 Element Web 和 Element X App 通过 Cloudflare Workers 进行消息传递。欢迎提交 issue,fork 该项目将其变成你自己的,或者继续基于此示例进行构建! ## 在线演示 有一个实例正在 `m.easydemo.org` 上运行。你可以使用 [Matrix Federation Tester](https://federationtester.matrix.org/#m.easydemo.org) 验证联邦兼容性,或查看 [完整 JSON 报告](https://federationtester.matrix.org/api/report?server_name=m.easydemo.org)。 ## 快速开始 ### 一键部署 部署最快的方式是使用本 README 顶部的“Deploy to Cloudflare”按钮。点击后: 1. Cloudflare 自动配置所有资源 2. 你需要将 `SERVER_NAME` 更新为你的域名 3. 运行数据库迁移 4. 配置你的自定义域名 **完整说明请参阅 [DEPLOYMENT.md](./DEPLOYMENT.md)。** ### 手动部署 ``` # Clone 和 install git clone https://github.com/SilentHeroes/matrix-worker cd matrix-worker npm install # 创建资源(从输出中保存 ID) npx wrangler d1 create my-matrix-db npx wrangler kv namespace create SESSIONS npx wrangler kv namespace create DEVICE_KEYS npx wrangler kv namespace create ONE_TIME_KEYS npx wrangler kv namespace create CROSS_SIGNING_KEYS npx wrangler kv namespace create CACHE npx wrangler kv namespace create ACCOUNT_DATA npx wrangler r2 bucket create my-matrix-media # 使用你的资源 ID 和 SERVER_NAME 更新 wrangler.jsonc # 然后运行 migrations 并 deploy(详见 DEPLOYMENT.md) ``` **完整的分步指南请参阅 [DEPLOYMENT.md](./DEPLOYMENT.md)。** ### 邮箱验证(可选) 如需 3PID 邮箱验证支持,请配置 [Cloudflare Email Service](https://developers.cloudflare.com/email-service/)(目前处于封闭测试阶段): 1. 在 Cloudflare 仪表板中,前往 **Compute & AI > Email Service > Email Sending** 2. 选择 **Onboard Domain** 并选择你的域名(必须使用 Cloudflare DNS) 3. 等待 SPF/DKIM DNS 记录传播(通常需要 5–15 分钟) 4. 设置发件人地址密钥: ``` npx wrangler secret put EMAIL_FROM # 示例:noreply@m.easydemo.org ``` ## 规范合规性 **[Matrix Specification v1.17](https://spec.matrix.org/v1.17/) 合规性** | 规范章节 | 实现位置 | 规范参考 | |--------------|----------------|----------------| | [Client-Server API](https://spec.matrix.org/v1.17/client-server-api/) | [`src/api/`](src/api/) | 认证、同步、房间、消息传递、个人资料 | | [Server-Server API](https://spec.matrix.org/v1.17/server-server-api/) | [`src/api/federation.ts`](src/api/federation.ts) | 联邦、PDU、EDU、密钥交换 | | [Room Versions](https://spec.matrix.org/v1.17/rooms/) | [`src/services/events.ts`](src/services/events.ts) | v1-v12、事件认证、状态解析 | | [End-to-End Encryption](https://spec.matrix.org/v1.17/client-server-api/#end-to-end-encryption) | [`src/api/keys.ts`](src/api/keys.ts), [`src/api/key-backups.ts`](src/api/key-backups.ts) | 设备密钥、OTK、交叉签名、密钥备份 | | [OAuth 2.0 API](https://spec.matrix.org/v1.17/client-server-api/#oauth-20-api) | [`src/api/oauth.ts`](src/api/oauth.ts), [`src/api/oidc-auth.ts`](src/api/oidc-auth.ts) | MSC3861, MSC2965, MSC2967, MSC4191 | | [Discovery](https://spec.matrix.org/v1.17/client-server-api/#server-discovery) | [`src/index.ts`](src/index.ts) | `.well-known/matrix/client`, `/versions` | | [Content Repository](https://spec.matrix.org/v1.17/client-server-api/#content-repository) | [`src/api/media.ts`](src/api/media.ts) | 上传、下载、缩略图、MSC3916 | | [Push Notifications](https://spec.matrix.org/v1.17/client-server-api/#push-notifications) | [`src/api/push.ts`](src/api/push.ts), [`src/workflows/`](src/workflows/) | 推送规则、推送器 | | [Presence](https://spec.matrix.org/v1.17/client-server-api/#presence) | [`src/api/presence.ts`](src/api/presence.ts) | 在线/离线状态 | | [Typing Notifications](https://spec.matrix.org/v1.17/client-server-api/#typing-notifications) | [`src/api/typing.ts`](src/api/typing.ts) | 输入指示器 | | [Receipts](https://spec.matrix.org/v1.17/client-server-api/#receipts) | [`src/api/receipts.ts`](src/api/receipts.ts) | 已读回执 | | [Spaces](https://spec.matrix.org/v1.17/client-server-api/#spaces) | [`src/api/spaces.ts`](src/api/spaces.ts) | Space 层级结构 | | [VoIP](https://spec.matrix.org/v1.17/client-server-api/#voice-over-ip) | [`src/api/voip.ts`](src/api/voip.ts), [`src/api/calls.ts`](src/api/calls.ts) | TURN 服务器、MatrixRTC | | [Account Data](https://spec.matrix.org/v1.17/client-server-api/#client-config) | [`src/api/account-data.ts`](src/api/account-data.ts) | 用户/房间账户数据 | | [3PID Management](https://spec.matrix.org/v1.17/client-server-api/#adding-account-administrative-contact-information) | [`src/api/account.ts`](src/api/account.ts) | 邮箱验证、3PID 绑定 | **不稳定功能** | 功能 | 实现位置 | MSC | |---------|----------------|-----| | Sliding Sync | [`src/api/sliding-sync.ts`](src/api/sliding-sync.ts) | [MSC3575](https://github.com/matrix-org/matrix-spec-proposals/pull/3575), [MSC4186](https://github.com/matrix-org/matrix-spec-proposals/pull/4186) | | Authenticated Media | [`src/api/media.ts`](src/api/media.ts) | [MSC3916](https://github.com/matrix-org/matrix-spec-proposals/pull/3916) | | Cross-signing Reset | [`src/api/keys.ts`](src/api/keys.ts), [`src/api/oauth.ts`](src/api/oauth.ts) | [MSC4312](https://github.com/matrix-org/matrix-spec-proposals/pull/4312) | | Account Management | [`src/api/oidc-auth.ts`](src/api/oidc-auth.ts) | [MSC4191](https://github.com/matrix-org/matrix-spec-proposals/pull/4191) | ## 功能特性 - **完整 E2EE 支持**:设备密钥、交叉签名、密钥备份、一次性密钥、联邦密钥查询 - **Token 刷新**:通过单次使用刷新 token 进行安全 token 轮换(基于 KV,支持自动过期) - **Sliding Sync**:MSC3575 和 MSC4186(为 Element X 简化的 Sliding Sync) - **实时**:通过 Durable Objects 进行同步协调,带有 KV 缓存的 presence - **联邦**:完整的服务器间通信,包括 E2EE、knock 协议、媒体和目录 - **媒体存储**:基于 R2 的媒体存储,支持缩略图生成和认证媒体 (MSC3916) - **推送通知**:APNs 支持(iOS 直接推送) - **视频通话**:MatrixRTC,集成 LiveKit 和 Cloudflare Calls SFU - **Knock 协议**:支持通过联邦进行 knock-to-join 房间 - **房间版本**:完整支持房间版本 1-12 - **管理仪表板**:功能齐全的 Web UI,包含图表、用户管理、键盘快捷键 - **Synapse API 兼容性**:标准的 `/_synapse/admin/*` 端点,用于工具兼容性 ## 架构 ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ Cloudflare Edge Network │ ├─────────────────────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ Workers │ │ Durable │ │ D1 │ │ R2 │ │ │ │ (Hono) │──│ Objects │──│ (SQLite) │ │ (Object Storage) │ │ │ │ │ │ │ │ │ │ │ │ │ │ • Routing │ │ • Room DO │ │ • users │ │ • Media files │ │ │ │ • Auth │ │ • Sync DO │ │ • rooms │ │ • Thumbnails │ │ │ │ • API │ │ • Fed DO │ │ • events │ │ • Avatars │ │ │ │ • Rate Lim │ │ • Keys DO │ │ • keys │ │ │ │ │ └─────────────┘ │ • Push DO │ │ • tokens │ └─────────────────────┘ │ │ │ │ • Admin DO │ └─────────────┘ │ │ │ │ │ • Call DO │ │ │ │ │ │ • Rate DO │ │ │ │ │ └─────────────┘ │ │ │ │ ┌──────┴─────────────────────────────────┴───────────────────┴───────────┐ │ │ │ KV Namespaces │ │ │ │ SESSIONS · DEVICE_KEYS · CACHE · ONE_TIME_KEYS · CROSS_SIGNING_KEYS │ │ │ │ ACCOUNT_DATA │ │ │ └────────────────────────────────────────────────────────────────────────┘ │ │ ┌────────────────────────────────────────────────────────────────────────┐ │ │ │ Workflows (Durable Execution) │ │ │ │ RoomJoinWorkflow · PushNotificationWorkflow │ │ │ └────────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` ## API 覆盖范围 ### Client-Server API | 类别 | 端点 | 状态 | |----------|-----------|--------| | 认证 | `/login`, `/register`, `/logout`, `/refresh`, `/auth_metadata`, `/login/get_token` | ✅ | | 同步 | `/sync`, Sliding Sync (MSC3575/MSC4186), 过滤器持久化与应用 | ✅ | | 房间 | 创建、加入、离开、邀请、踢出、封禁、knock、升级、摘要 | ✅ | | 消息传递 | 发送、删除、编辑、回复 | ✅ | | 状态 | 房间状态、权限级别 | ✅ | | E2EE | 设备密钥、OTK、交叉签名、密钥备份 | ✅ | | To-Device | 加密消息中继 | ✅ | | 推送 | 推送规则、推送器 | ✅ | | 媒体 | 上传、下载、缩略图 (MSC3916 认证) | ✅ | | 个人资料 | 显示名称、头像、自定义个人资料键 | ✅ | | Presence | 在线/离线状态(带 KV 缓存) | ✅ | | 输入 | 输入指示器 | ✅ | | 回执 | 已读回执 | ✅ | | 账户数据 | 用户设置、房间标签 | ✅ | | 目录 | 房间目录、别名 | ✅ | | 发现 | `.well-known/matrix/*` (client, server, support) | ✅ | | 举报 | 举报事件、房间、用户 | ✅ | | 管理 | 用户会话信息 (`/admin/whois`)、完整管理 API | ✅ | | 3PID | 邮箱验证、3PID 管理 | ✅ | | 时间戳 | `timestamp_to_event` 用于事件查找 | ✅ | ### Server-Server (Federation) API | 类别 | 端点 | 用途 | 状态 | |----------|----------|---------|--------| | **发现** | `GET /_matrix/federation/v1/version` | 服务器版本信息 | ✅ | | **密钥** | `GET /_matrix/key/v2/server` | 服务器签名密钥 | ✅ | | | `GET /_matrix/key/v2/server/{keyId}` | 特定签名密钥 | ✅ | | | `POST /_matrix/key/v2/query` | 批量密钥查询 | ✅ | | | `GET /_matrix/key/v2/query/{serverName}` | 公证人密钥查询 | ✅ | | | `GET /_matrix/key/v2/query/{serverName}/{keyId}` | 特定公证人密钥 | ✅ | | **E2EE** | `POST /_matrix/federation/v1/user/keys/query` | 查询设备密钥 | ✅ | | | `POST /_matrix/federation/v1/user/keys/claim` | 索要一次性密钥 | ✅ | | | `GET /_matrix/federation/v1/user/devices/{userId}` | 获取用户设备 | ✅ | | **事件** | `PUT /_matrix/federation/v1/send/{txnId}` | 接收 PDU/EDU | ✅ | | | `GET /_matrix/federation/v1/event/{eventId}` | 获取单个事件 | ✅ | | | `GET /_matrix/federation/v1/state/{roomId}` | 获取房间状态 | ✅ | | | `GET /_matrix/federation/v1/state_ids/{roomId}` | 获取状态事件 ID | ✅ | | | `GET /_matrix/federation/v1/event_auth/{roomId}/{eventId}` | 获取认证链 | ✅ | | | `GET /_matrix/federation/v1/backfill/{roomId}` | 获取历史事件 | ✅ | | | `POST /_matrix/federation/v1/get_missing_events/{roomId}` | 填充事件缺口 | ✅ | | | `GET /_matrix/federation/v1/timestamp_to_event/{roomId}` | 按时间戳查找事件 | ✅ | | **加入** | `GET /_matrix/federation/v1/make_join/{roomId}/{userId}` | 准备加入 | ✅ | | | `PUT /_matrix/federation/v1/send_join/{roomId}/{eventId}` | 完成加入 (v1) | ✅ | | | `PUT /_matrix/federation/v2/send_join/{roomId}/{eventId}` | 完成加入 (v2) | ✅ | | **离开** | `GET /_matrix/federation/v1/make_leave/{roomId}/{userId}` | 准备离开 | ✅ | | | `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}` | 完成离开 (v1) | ✅ | | | `PUT /_matrix/federation/v2/send_leave/{roomId}/{eventId}` | 完成离开 (v2) | ✅ | | **Knocking** | `GET /_matrix/federation/v1/make_knock/{roomId}/{userId}` | 准备 knock | ✅ | | | `PUT /_matrix/federation/v1/send_knock/{roomId}/{eventId}` | 完成 knock | ✅ | | **邀请** | `PUT /_matrix/federation/v1/invite/{roomId}/{eventId}` | 接收邀请 (v1) | ✅ | | | `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}` | 接收邀请 (v2) | ✅ | | **媒体** | `GET /_matrix/federation/v1/media/download/{mediaId}` | 下载媒体 | ✅ | | | `GET /_matrix/federation/v1/media/thumbnail/{mediaId}` | 获取缩略图 | ✅ | | **目录** | `GET /_matrix/federation/v1/query/directory` | 解析房间别名 | ✅ | | | `GET /_matrix/federation/v1/query/profile` | 查询用户资料 | ✅ | | |GET /_matrix/federation/v1/publicRooms` | 列出公开房间 | ✅ | | | `POST /_matrix/federation/v1/publicRooms` | 搜索公开房间 | ✅ | | **Spaces** | `GET /_matrix/federation/v1/hierarchy/{roomId}` | 获取 Space 层级结构 | ✅ | | **OpenID** | `GET /_matrix/federation/v1/openid/userinfo` | 验证 OpenID token | ✅ | ### Matrix v1.17 合规性新增内容 添加了以下端点以实现完全符合 Matrix Specification v1.17: | 类别 | 端点 | 用途 | |----------|----------|---------| | **房间摘要** | `GET /_matrix/client/v1/room_summary/{roomIdOrAlias}` | 不加入即可预览房间 | | **认证元数据** | `GET /_matrix/client/v1/auth_metadata` | 认证方法发现 | | **登录 Token** | `POST /_matrix/client/v1/login/get_token` | 生成短期登录 token(二维码登录) | | **自定义个人资料** | `GET /_matrix/client/v3/profile/{userId}/{keyName}` | 获取自定义个人资料属性 | | | `PUT /_matrix/client/v3/profile/{userId}/{keyName}` | 设置自定义个人资料属性 | | | `DELETE /_matrix/client/v3/profile/{userId}/{keyName}` | 删除自定义个人资料属性 | | **举报** | `POST /_matrix/client/v3/rooms/{roomId}/report` | 举报房间 | | | `POST /_matrix/client/v3/users/{userId}/report` | 举报用户 | | **管理** | `GET /_matrix/client/v3/admin/whois/{userId}` | 获取用户会话/设备信息 | | **时间戳** | `GET /_matrix/client/v3/rooms/{roomId}/timestamp_to_event` | 按时间戳查找事件 | | **3PID** | `POST /_matrix/client/v3/account/3pid/email/requestToken` | 请求邮箱验证 | | | `POST /_matrix/client/v3/account/3pid/submit_token` | 提交验证码 | | | `POST /_matrix/client/v3/account/3pid/add` | 将已验证的 3PID 添加到账户 | | **联邦** | `PUT /_matrix/federation/v1/exchange_third_party_invite/{roomId}` | 第三方邀请交换 | | **同步过滤器** | 过滤器加载和应用 | 过滤器现在在同步期间应用 | ## 管理仪表板 在服务器的 `/admin` 路径访问管理仪表板(例如 `https://m.easydemo.org/admin`)。 **功能:** - **仪表板** - 服务器统计、活动图表、用户分布可视化 - **用户管理** - 创建、停用、清除用户;重置密码;批量操作 - **房间管理** - 查看房间、成员、状态;删除房间;浏览事件 - **媒体管理** - 查看上传内容、隔离/删除媒体 - **举报** - 审核并处理内容举报 - **联邦** - 监控与其他服务器的联邦状态 - **身份提供商** - 配置 OIDC/OAuth 提供商(Google 等) - **设置** - 切换注册、发送服务器通知 **键盘快捷键:** - `Cmd/Ctrl+K` - 命令面板 - `g h` - 前往仪表板 - `g u` - 前往用户 - `g r` - 前往房间 - `/` - 聚焦搜索 - `?` - 显示快捷键帮助 **Synapse API 兼容性:** 标准的 `/_synapse/admin/*` 端点可用,以兼容现有的 Matrix 管理工具。 ## 开发 ``` # Install 依赖 npm install # 本地运行 npm run dev # Type 检查 npm run typecheck # 运行 tests npm run test # 本地应用 migrations npm run db:migrate:local ``` ## Cloudflare Bindings | 绑定名称 | 类型 | 用途 | |---------|------|---------| | `DB` | D1 | 用于持久化数据的 SQLite 数据库 | | `SESSIONS` | KV | Access token 和 refresh token(带 TTL) | | `DEVICE_KEYS` | KV | E2EE 设备密钥 | | `ONE_TIME_KEYS` | KV | Olm 预密钥 | | `CROSS_SIGNING_KEYS` | KV | 交叉签名密钥 | | `CACHE` | KV | 通用缓存(presence、联邦事务、同步过滤器) | | `ACCOUNT_DATA` | KV | 用户账户数据 | | `MEDIA` | R2 | 媒体文件存储 | | `ROOMS` | Durable Object | 房间协调 | | `SYNC` | Durable Object | 同步状态管理 | | `FEDERATION` | Durable Object | 联邦队列 | | `CALL_ROOMS` | Durable Object | 视频通话房间协调 | | `USER_KEYS` | Durable Object | E2EE 密钥操作 | | `PUSH` | Durable Object | 推送通知队列 | | `ADMIN` | Durable Object | 管理操作 | | `RATE_LIMIT` | Durable Object | 速率限制 | | `ROOM_JOIN_WORKFLOW` | Workflow | 异步房间加入处理 | | `PUSH_NOTIFICATION_WORKFLOW` | Workflow | 异步推送投递 | ## 安全性 - **密码哈希**:PBKDF2-SHA256(100,000 次迭代) - **Token 格式**:带用户绑定的安全随机数 - **Token 刷新**:单次使用刷新 token,支持自动轮换 - **速率限制**:通过 Durable Objects 实现基于 IP 和用户的滑动窗口 - **联邦认证**:Ed25519 请求签名与 X-Matrix 头验证 - **PDU 验证**:对传入联邦事件进行签名验证 - **媒体认证**:认证媒体端点 (MSC3916) ## 兼容性 测试对象: - Element Web - Element X (iOS) - Element X (Android) 联邦测试对象: - matrix.org ([查看测试结果](https://federationtester.matrix.org/api/report?server_name=m.easydemo.org)) ## 限制 | 约束 | 限制 | 备注 | |------------|-------|-------| | Worker CPU | 30s | 使用 Workflows 处理长时间操作 | | Worker Memory | 128MB | 流式传输大响应 | | D1 Database | 10GB | 如需要可归档旧事件 | | R2 Object | 5GB | 支持分块上传 | | KV Value | 25MB | 拆分大数据集 | ## 许可证 MIT
标签:Cloudflare KV, D1 Database, DNS解析, Durable Objects, E2EE, Element Web, Element X, Homeserver, IM, Matrix, PoC, Serverless, TypeScript, Web API, Wrangler, 分布式系统, 即时通讯, 原型验证, 去中心化通信, 响应大小分析, 安全插件, 开源项目, 暴力破解, 程序员工具, 端到端加密, 网络安全, 网络安全, 联邦协议, 自动化攻击, 自动化攻击, 边缘计算, 配置审计, 隐私保护, 隐私保护