Skip to content

About

Matrix homeserver running entirely on Cloudflare Workers (Hono + D1/KV/R2 + Durable Objects) — live at codebam.ca with verified two-way matrix.org federation (room versions 1-12, incl. 2022-era v9 rooms), full E2EE, native admin bots, and a webhook-driven Telegram bridge.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

Matrix Homeserver on Cloudflare Workers

CI Security

Deploy to Cloudflare Workers

Fork status: codebam's fork of fuzzywigg/matrix-workers (itself a fork of nkuntz1934/matrix-workers, "Tuwunel"), running live at codebam.ca with a second instance at dev.codebam.ca for federation testing. See DEPLOY.md for setup and docs/federation-handoff.md for hard-won federation debugging notes.

What began as a proof-of-concept homeserver on Cloudflare's edge is now a working homeserver in daily use: Element clients with full E2EE, verified live federation with matrix.org (including 2022-era v9 rooms), and native bots including a Telegram bridge. The sections below describe exactly what is implemented and what is verified working in production.

Production Status (verified working, Nov 2026)

Everything in this list is live on codebam.ca and verified against real peers — not implemented-but-untested:

Federation (server-to-server) — the hard part, now done:

  • Live, two-way message delivery with matrix.org verified in-room: messages sent from this server display in remote rooms, including a 2022-era v9 room whose events carry pre-2023 Synapse origin/prev_state fields (per-spec v1–10 redaction keep-list — the deepest of four stacked ID bugs fixed along the way; see the handoff doc).
  • Federation tester: FederationOK: true for codebam.ca.
  • Join handshakes (make_join/send_join, v1+v2) with fallback to the inviter/participating servers when the resident domain is dead; invites, leaves, kicks, bans, knocks; post-join timeline backfill (federation /backfill, so fresh joins show room history, not just members); outbound member/state fanout; E2EE key queries/claims over federation; remote media with R2 caching; 8448-only peers via raw TLS socket transport.
  • All room versions v1–v12, including MSC4291 (v12 domainless room IDs) and MSC4289 (creator power), with version-correct redaction, reference hashes, and signature checks on both the send and receive sides.
  • A second instance at dev.codebam.ca (own D1/KV/R2, FEDERATION_STRICT_AUTH=true for Synapse-receive-side rules) exists purely to reproduce resident-server rejections against a live peer; prod↔dev delivery, joins, and heals are validated end-to-end.

Client experience:

  • Element Web and FluffyChat in daily use; full E2EE (device keys, cross-signing, secret storage bootstrap, key backup, dehydrated devices) verified live against real clients; encrypted messages and megolm key shares federate.
  • Long-polling /sync with correct per-stream tokens, sliding sync (MSC3575/MSC4186) for Element X, to-device messaging, presence, typing, receipts, push.
  • Invite-only registration with single/multi-use registration tokens (admin API + in-room bot command).

Native bots (first-class users the homeserver acts for — no password, so bot accounts can never log in):

  • Admin console bot in a management room: !admin commands for status/counts, registration-token mint/list/revoke, user list/create/deactivate/reset-password, federation peer status, room kick/ban/unban (executed as the bot, governed by the room's power levels), and server notices — admin-gated, replies as m.notice.
  • Telegram bridge (@BotFather token via admin API only — never via room messages): webhook-driven (no polling), one Telegram chat ↔ one Matrix room, bidirectional — Telegram messages land as [TG] Name (@user): text, and room messages (including federated users') relay out with display-name prefixes. Loop-proof by construction (all integrations skip bot senders).

Quality bar: 345 test files / ~45,400 tests green (npm test), tsc --noEmit clean, CI on every push. In-process mock-Synapse peer tests reproduce resident-server auth rejections (the "HTTP 200 but never displayed" class) before they reach production.

Quick Start

One-Click Deploy

The fastest way to deploy is using the Deploy to Cloudflare button at the top of this README. After clicking:

  1. Cloudflare provisions all resources automatically
  2. You need to update SERVER_NAME to your domain
  3. Run database migrations
  4. Configure your custom domain

See DEPLOYMENT.md for complete instructions.

Manual Deploy

# Clone and install
git clone https://github.com/codebam/matrix-workers
cd matrix-workers
npm install

# Create resources (save IDs from output) — or run: bash scripts/setup.sh
npx wrangler d1 create 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 matrix-media

# Update wrangler.jsonc with your resource IDs and SERVER_NAME
# Then run migrations and deploy (see DEPLOY.md for details)

See DEPLOY.md for the fork-specific step-by-step guide, or DEPLOYMENT.md for the upstream general guide.

Email Verification (Optional)

For 3PID email verification support, configure Cloudflare Email Service (currently in closed beta):

  1. In the Cloudflare dashboard, go to Compute & AI > Email Service > Email Sending
  2. Select Onboard Domain and choose your domain (must use Cloudflare DNS)
  3. Wait for SPF/DKIM DNS records to propagate (typically 5–15 minutes)
  4. Set the from address secret:
npx wrangler secret put EMAIL_FROM
# Example: noreply@codebam.ca

Spec Compliance

Matrix Specification v1.17 Compliance

Spec Section Implementation Spec Reference
Client-Server API src/api/ Auth, sync, rooms, messaging, profiles
Server-Server API src/api/federation.ts Federation, PDUs, EDUs, key exchange
Room Versions src/services/event-auth.ts, room-versions.ts, state-resolution.ts v1-v12, event auth, state resolution
End-to-End Encryption src/api/keys.ts, src/api/key-backups.ts Device keys, OTKs, cross-signing, key backup
OAuth 2.0 API src/api/oauth.ts, src/api/oidc-auth.ts MSC3861, MSC2965, MSC2967, MSC4191
Discovery src/index.ts .well-known/matrix/client, /versions
Content Repository src/api/media.ts Upload, download, thumbnails, MSC3916
Push Notifications src/api/push.ts, src/workflows/ Push rules, pushers
Presence src/api/presence.ts Online/offline status
Typing Notifications src/api/typing.ts Typing indicators
Receipts src/api/receipts.ts Read receipts
Spaces src/api/spaces.ts Space hierarchy
VoIP src/api/voip.ts, src/api/calls.ts TURN servers, MatrixRTC
Account Data src/api/account-data.ts User/room account data
3PID Management src/api/account.ts Email verification, 3PID binding

Unstable Features (MSCs)

Feature Implementation MSC
Sliding Sync src/api/sliding-sync.ts MSC3575, MSC4186
Authenticated Media src/api/media.ts MSC3916
Cross-signing Reset src/api/keys.ts, src/api/oauth.ts MSC4312
Account Management src/api/oidc-auth.ts MSC4191

Features

  • Full E2EE Support: Device keys, cross-signing, key backup, one-time keys, federation key queries — verified live against Element Web
  • Federation, verified in production: two-way delivery with matrix.org (incl. pre-2023 Synapse event IDs), join handshakes with participating-server fallback, post-join timeline backfill, member/state fanout, invites/knocks, remote media, 8448 socket transport
  • Native Bots: passwordless bot accounts, invite auto-accept, in-room admin console (!admin …), webhook-driven Telegram bridge (bidirectional, loop-proof)
  • Token Refresh: Secure token rotation with single-use refresh tokens (KV-backed with auto-expiry)
  • Sliding Sync: MSC3575 and MSC4186 (Simplified Sliding Sync for Element X)
  • Real-time: Sync coordination via Durable Objects, presence with KV caching
  • Invite-only Registration: single/multi-use registration tokens with revocation, via admin API, dashboard, or the admin bot
  • Media Storage: R2-backed media with thumbnail generation and authenticated media (MSC3916)
  • Push Notifications: APNs support (iOS direct push)
  • Video Calling: MatrixRTC with LiveKit and Cloudflare Calls SFU integration
  • Knock Protocol: Support for knock-to-join rooms via federation
  • Room Versions: Full support for room versions 1-12, with per-version redaction rules (v1–10 keep origin/prev_state; v11+ drop them) and MSC4291/MSC4289 v12 semantics
  • Admin Dashboard: Full-featured web UI with charts, user management, keyboard shortcuts
  • Synapse API Compatibility: Standard /_synapse/admin/* endpoints for tool compatibility
  • Strict-auth dev mode: FEDERATION_STRICT_AUTH=true enforces Synapse receive-side auth selection checks on inbound PDUs, reproducing resident rejections in staging before they reach prod

Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                           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 Coverage

Client-Server API

Category Endpoints Status
Authentication /login, /register, /logout, /refresh, /auth_metadata, /login/get_token ✅
Sync /sync, Sliding Sync (MSC3575/MSC4186), filter persistence & application ✅
Rooms Create, join, leave, invite, kick, ban, knock, upgrade, summary ✅
Messaging Send, redact, edit, reply ✅
State Room state, power levels ✅
E2EE Device keys, OTKs, cross-signing, key backup ✅
To-Device Encrypted message relay ✅
Push Push rules, pushers (APNs/FCM) ✅
Media Upload, download, thumbnails (MSC3916 auth) ✅
Profile Display name, avatar, custom profile keys ✅
Presence Online/offline status with KV caching ✅
Typing Typing indicators ✅
Receipts Read receipts ✅
Account Data User settings, room tags ✅
Directory Room directory, aliases ✅
Discovery .well-known/matrix/* (client, server, support) ✅
Reporting Report events, rooms, users ✅
Admin User session info (/admin/whois), full admin API ✅
3PID Email verification, 3PID management ✅
Timestamps timestamp_to_event for event lookup ✅

Server-Server (Federation) API

Category Endpoint Purpose Status
Discovery GET /_matrix/federation/v1/version Server version info ✅
Keys GET /_matrix/key/v2/server Server signing keys ✅
GET /_matrix/key/v2/server/{keyId} Specific signing key ✅
POST /_matrix/key/v2/query Batch key query ✅
GET /_matrix/key/v2/query/{serverName} Notary key query ✅
GET /_matrix/key/v2/query/{serverName}/{keyId} Specific notary key ✅
E2EE POST /_matrix/federation/v1/user/keys/query Query device keys ✅
POST /_matrix/federation/v1/user/keys/claim Claim one-time keys ✅
GET /_matrix/federation/v1/user/devices/{userId} Get user devices ✅
Events PUT /_matrix/federation/v1/send/{txnId} Receive PDUs/EDUs ✅
GET /_matrix/federation/v1/event/{eventId} Fetch single event ✅
GET /_matrix/federation/v1/state/{roomId} Get room state ✅
GET /_matrix/federation/v1/state_ids/{roomId} Get state event IDs ✅
GET /_matrix/federation/v1/event_auth/{roomId}/{eventId} Get auth chain ✅
GET /_matrix/federation/v1/backfill/{roomId} Fetch historical events ✅
POST /_matrix/federation/v1/get_missing_events/{roomId} Fill event gaps ✅
GET /_matrix/federation/v1/timestamp_to_event/{roomId} Find event by timestamp ✅
Joining GET /_matrix/federation/v1/make_join/{roomId}/{userId} Prepare join ✅
PUT /_matrix/federation/v1/send_join/{roomId}/{eventId} Complete join (v1) ✅
PUT /_matrix/federation/v2/send_join/{roomId}/{eventId} Complete join (v2) ✅
Leaving GET /_matrix/federation/v1/make_leave/{roomId}/{userId} Prepare leave ✅
PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId} Complete leave (v1) ✅
PUT /_matrix/federation/v2/send_leave/{roomId}/{eventId} Complete leave (v2) ✅
Knocking GET /_matrix/federation/v1/make_knock/{roomId}/{userId} Prepare knock ✅
PUT /_matrix/federation/v1/send_knock/{roomId}/{eventId} Complete knock ✅
Inviting PUT /_matrix/federation/v1/invite/{roomId}/{eventId} Receive invite (v1) ✅
PUT /_matrix/federation/v2/invite/{roomId}/{eventId} Receive invite (v2) ✅
Media GET /_matrix/federation/v1/media/download/{mediaId} Download media ✅
GET /_matrix/federation/v1/media/thumbnail/{mediaId} Get thumbnail ✅
Directory GET /_matrix/federation/v1/query/directory Resolve room alias ✅
GET /_matrix/federation/v1/query/profile Query user profile ✅
GET /_matrix/federation/v1/publicRooms List public rooms ✅
POST /_matrix/federation/v1/publicRooms Search public rooms ✅
Spaces GET /_matrix/federation/v1/hierarchy/{roomId} Get space hierarchy ✅
OpenID GET /_matrix/federation/v1/openid/userinfo Validate OpenID token ✅

Matrix v1.17 Compliance Additions

The following endpoints were added to achieve full Matrix Specification v1.17 compliance:

Category Endpoint Purpose
Room Summary GET /_matrix/client/v1/room_summary/{roomIdOrAlias} Preview room without joining
Auth Metadata GET /_matrix/client/v1/auth_metadata Authentication method discovery
Login Token POST /_matrix/client/v1/login/get_token Generate short-lived login token (QR code login)
Custom Profile GET /_matrix/client/v3/profile/{userId}/{keyName} Get custom profile attribute
PUT /_matrix/client/v3/profile/{userId}/{keyName} Set custom profile attribute
DELETE /_matrix/client/v3/profile/{userId}/{keyName} Delete custom profile attribute
Reporting POST /_matrix/client/v3/rooms/{roomId}/report Report a room
POST /_matrix/client/v3/users/{userId}/report Report a user
Admin GET /_matrix/client/v3/admin/whois/{userId} Get user session/device info
Timestamps GET /_matrix/client/v3/rooms/{roomId}/timestamp_to_event Find event by timestamp
3PID POST /_matrix/client/v3/account/3pid/email/requestToken Request email verification
POST /_matrix/client/v3/account/3pid/submit_token Submit verification code
POST /_matrix/client/v3/account/3pid/add Add verified 3PID to account
Federation PUT /_matrix/federation/v1/exchange_third_party_invite/{roomId} Third-party invite exchange
Sync Filters Filter loading and application Filters are now applied during sync

Admin Dashboard

Access the admin dashboard at /admin on your server (e.g., https://codebam.ca/admin).

Features:

  • Dashboard - Server stats, activity charts, user breakdown visualization
  • User Management - Create, deactivate, purge users; reset passwords; bulk operations
  • Room Management - View rooms, members, state; delete rooms; browse events
  • Media Management - View uploads, quarantine/delete media
  • Reports - Review and resolve content reports
  • Federation - Monitor federation status with other servers
  • Identity Providers - Configure OIDC/OAuth providers (Google, etc.)
  • Settings - Toggle registration, send server notices

Keyboard Shortcuts:

  • Cmd/Ctrl+K - Command palette
  • g h - Go to Dashboard
  • g u - Go to Users
  • g r - Go to Rooms
  • / - Focus search
  • ? - Show shortcuts help

Synapse API Compatibility: Standard /_synapse/admin/* endpoints are available for compatibility with existing Matrix admin tools.

Development

# Install dependencies
npm install

# Run locally
npm run dev

# Type check
npm run typecheck

# Run tests
npm run test

# Apply migrations/schema.sql only (local; not 002–019)
npm run db:migrate:local

Numbered files migrations/002_*.sql … migrations/024_*.sql are separate — see DEPLOY.md / scripts/setup.sh.

Cloudflare Bindings

Binding Type Purpose
DB D1 SQLite database for persistent data
SESSIONS KV Access tokens and refresh tokens (with TTL)
DEVICE_KEYS KV E2EE device keys
ONE_TIME_KEYS KV Olm prekeys
CROSS_SIGNING_KEYS KV Cross-signing keys
CACHE KV General caching (presence, federation txns, sync filters)
ACCOUNT_DATA KV User account data
MEDIA R2 Media file storage
ROOMS Durable Object Room coordination
SYNC Durable Object Sync state management
FEDERATION Durable Object Federation queue
CALL_ROOMS Durable Object Video call room coordination
USER_KEYS Durable Object E2EE key operations
PUSH Durable Object Push notification queue
ADMIN Durable Object Admin operations
RATE_LIMIT Durable Object Rate limiting
DELAYED_EVENTS Durable Object Scheduled/delayed event delivery
ROOM_JOIN_WORKFLOW Workflow Async room join processing
PUSH_NOTIFICATION_WORKFLOW Workflow Async push delivery
EMAIL Send Email 3PID email verification via Cloudflare Email Service (optional)

Durable Object Migrations (new_sqlite_classes)

Every Durable Object class must be declared in a migrations entry in wrangler.jsonc using new_sqlite_classes (SQLite-backed storage). This repo declares all eight DO classes across migration tags v1–v6.

  • When adding a new DO: export the class from src/index.ts, add its binding under durable_objects.bindings, and add a new migration tag with the class name in new_sqlite_classes. Do not edit already-deployed migration tags.
  • Why new_sqlite_classes and not new_classes: new_classes creates legacy key-value-backed DOs, which are unavailable on the Workers Free plan and are not what this codebase expects — deploys will fail or the DO gets the wrong storage backend. SQLite-backed DOs are the current Cloudflare recommendation and the only option on the free plan.

The D1 database name in wrangler.jsonc is matrix-db (binding DB); the db:migrate npm scripts target that name.

Security

  • Password Hashing: PBKDF2-SHA256 (100,000 iterations)
  • Token Format: Secure random with user binding
  • Token Refresh: Single-use refresh tokens with automatic rotation
  • Rate Limiting: Sliding window per-IP and per-user via Durable Objects
  • Federation Auth: Ed25519 request signing with X-Matrix header validation
  • PDU Validation: Signature verification on incoming federation events
  • Media Auth: Authenticated media endpoints (MSC3916)

Compatibility

Tested with:

  • Element Web (daily use, full E2EE verified: secret storage bootstrap, key backup, dehydrated devices)
  • FluffyChat (joins, messaging, verification requests)
  • Element X (iOS/Android) via sliding sync — this fork's original target platform

Federation verified against matrix.org in production (November 2026): two-way message delivery in a 2022-era v9 room, joins with participating-server fallback, timeline backfill, E2EE key exchange, and remote media. The federation tester reports "FederationOK": true for codebam.ca. A second instance at dev.codebam.ca exists for staging federation tests against a live peer (FEDERATION_STRICT_AUTH=true); Telegram bots bridge bidirectionally through webhooks (no polling).

Limitations

Constraint Limit Notes
Worker CPU time Free: 10 ms; Paid: 5 min Cloudflare CPU-time limits (not wall-clock). waitUntil may continue ~30s after the response; use Workflows for long operations
Worker Memory 128MB Stream large responses
D1 Database Free: 500 MB; Paid: 10 GB Per-database max size (Cloudflare D1 limits). Archive or shard if needed
R2 Object Single-part: 5 GiB; Multipart: 5 TiB Cloudflare R2 platform max. This homeserver media API caps uploads at 50 MB (MAX_UPLOAD_SIZE); no multipart chunked upload
KV Value 25MB Split large datasets

License

MIT

About

Matrix homeserver running entirely on Cloudflare Workers (Hono + D1/KV/R2 + Durable Objects) — live at codebam.ca with verified two-way matrix.org federation (room versions 1-12, incl. 2022-era v9 rooms), full E2EE, native admin bots, and a webhook-driven Telegram bridge.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages