Cloudflare Edge Workers
Relevant source files
The following files were used as context for generating this wiki page:
Cloudflare Edge Workers serve as the edge-native backend infrastructure for the Happy ecosystem. This system is designed to enable remote control and session sharing for Claude Code and Codex across devices with a focus on low latency and zero-knowledge end-to-end encryption. By deploying on Cloudflare's global network of 300+ edge locations, the API ensures high availability and performance for real-time WebSocket communication and data synchronization.
Sources: apps/server/workers/README.md:1-12, CLAUDE.md:14-18
The implementation utilizes the Hono v4 framework with OpenAPI 3.1 support to provide a type-safe, performant REST API and WebSocket relay. It leverages Cloudflare-specific features such as D1 (SQLite) for relational data, Durable Objects for WebSocket state management, and R2 (S3-compatible) for object storage.
Sources: apps/server/workers/README.md:130-145, apps/server/workers/src/index.ts:130-145
System Architecture
The architecture consists of a Hono web server running in the Worker context, which interacts with several Cloudflare-native storage and compute resources.
The diagram above illustrates the high-level data flow from the client through the Edge network to the various Cloudflare services.
Sources: apps/server/workers/README.md:105-125, apps/server/workers/src/index.ts:150-185
Core Components
| Component | Technology | Role |
|---|---|---|
| Runtime | Cloudflare Workers | Serverless compute execution environment |
| API Framework | Hono v4 + Zod-OpenAPI | Request routing and schema validation |
| Relational DB | Cloudflare D1 | Stores session metadata, machine info, and accounts |
| Object Storage | Cloudflare R2 | Stores file uploads and session artifacts |
| WebSocket Manager | Durable Objects | Manages real-time connections and event broadcasting |
| ORM | Drizzle ORM | Type-safe database queries and migrations |
| Metrics | Analytics Engine | Tracks sync performance and bundle sizes |
Sources: apps/server/workers/README.md:130-145, apps/server/workers/src/index.ts:50-120
API Implementation
The server uses OpenAPIHono to define routes with integrated Zod validation. This ensures that every request and response conforms to the project's protocol.
Request Lifecycle
- Global Middleware: Every request passes through a series of middleware including
timing,requestId,logger,cors, andsecurityHeaders. - Body Size Limits: Payloads are restricted early (default 10MB for sync) to prevent DoS attacks.
- Environment Validation: The
validateEnvcheck ensures required secrets likeHAPPY_MASTER_SECRETand DB bindings are present. - Auth Initialization: The auth module is initialized per-request due to the stateless nature of Workers.
- Route Handling: The request is routed to specific modules (Sessions, Machines, WebSockets, etc.).
Sources: apps/server/workers/src/index.ts:145-235
Primary Route Modules
- Authentication: Handles Ed25519 public key authentication and terminal pairing (CLI to Mobile).
- Sessions: Manages encrypted session creation, retrieval, and soft deletion.
- Machines: Handles machine registration and "alive" status updates.
- WebSockets: Facilitates real-time updates via user-scoped, session-scoped, or machine-scoped connections.
- Uploads: Manages R2-backed file uploads with metadata storage.
Sources: apps/server/workers/README.md:65-95, apps/server/workers/src/index.ts:250-290
WebSocket and Real-time Sync
Real-time capabilities are provided by Durable Objects via the ConnectionManager. This allows for persistent state in a serverless environment, which is critical for relaying messages between the CLI and mobile clients.
The sequence diagram shows how the Worker acts as a relay, using Durable Objects to maintain the active socket connections required for broadcasting.
Sources: apps/server/workers/README.md:80-95, apps/server/workers/src/index.ts:460-480, apps/server/workers/scripts/smoke-test.sh:110-140
Infrastructure and Configuration
Deployment and infrastructure management are handled via wrangler and custom scripts. The project supports dev and prod environments with specific database and storage IDs.
Environment Bindings
The Worker interacts with its environment through specific bindings defined in the Env interface.
| Binding Name | Type | Description |
|---|---|---|
DB | D1Database | Primary relational storage |
HAPPY_MASTER_SECRET | Secret | Master key for token generation (replaces legacy HANDY_MASTER_SECRET) |
CONNECTION_MANAGER | DurableObjectNamespace | Namespace for WebSocket handling |
UPLOADS | R2Bucket | Bucket for artifacts and avatars |
SYNC_METRICS | AnalyticsEngineDataset | Dataset for performance monitoring |
Sources: apps/server/workers/src/index.ts:55-120, apps/server/workers/scripts/verify-cloudflare-setup.sh:130-170
Maintenance and Scheduled Tasks
The system includes a scheduled handler for cron triggers (e.g., daily at 2 AM UTC) to perform automated maintenance:
- Token Blacklist Cleanup: Removes expired authentication tokens.
- Empty Session Cleanup: Deletes archived sessions that contain no messages.
- Invitation Cleanup: Marks expired share invitations as 'expired'.
Sources: apps/server/workers/src/index.ts:560-610
Development and Verification
The repository includes tools for ensuring the Edge Workers infrastructure is correctly configured before deployment.
Verification Script
scripts/verify-cloudflare-setup.sh performs automated checks on:
- Wrangler CLI: Checks installation and authentication (Account ID
81f483e6767ea3194467ecef42840f79). - D1 Databases: Ensures
happy-devandhappy-prodexist and IDs matchwrangler.toml. - R2 Buckets: Validates the existence of
happy-dev-uploadsandhappy-prod-uploads. - Secrets: Verifies if placeholders in configuration have been replaced with actual values.
Sources: apps/server/workers/scripts/verify-cloudflare-setup.sh:80-160
Testing Strategies
- Unit/Integration: Handled via
vitest. - Smoke Tests:
scripts/smoke-test.shvalidates health, auth, and WebSocket upgrade functionality against a live or local worker. - Load Testing: Utilizes
k6for scenarios ranging from "smoke" (10 VUs) to "extreme" (500+ connections). - Mutation Testing: Uses
Strykerto validate test suite robustness by injecting mutants into the code.
Sources: apps/server/workers/package.json:15-45, apps/server/workers/scripts/smoke-test.sh:1-50
Conclusion
Cloudflare Edge Workers provide the scalable, global foundation for the Happy project. By utilizing the Hono framework alongside Cloudflare's suite of edge services (D1, R2, Durable Objects), the system achieves a zero-knowledge architecture where the server acts as an encrypted relay for Claude Code sessions without ever gaining access to unencrypted user data.