Derbent: Building a High-Performance SSO Engine on Cloudflare Workers
A technical deep-dive into building a centralized, stateful authentication engine using D1, KV, and Service Bindings.
Contents100%
Managing authentication across multiple independent projects usually leads to “Auth Fragmentation”—each app has its own user table, its own session logic, and its own security vulnerabilities.
To solve this, I built Derbent: a self-hosted, centralized authentication engine designed specifically for the Cloudflare Workers ecosystem. It allows me to manage identity in one place for all my apps while leveraging Cloudflare’s global edge performance.
The Architecture: The “Sidecar” Pattern
Derbent acts as a sidecar service. Instead of the “Consuming App” (e.g., a dashboard or an OMR tool) managing passwords, it communicates with Derbent via Service Bindings. This allows for secure, low-latency communication that never touches the public internet.
Technical Stack
- Routing: Hono (Ultra-fast routing for the Edge)
- Database: Cloudflare D1 (SQL for Identity and Audit Logs)
- Session Store: Cloudflare KV (Stateful session management)
- Email: Cloudflare Queues + Resend (Moving to native Cloudflare Email soon)
Technical Deep Dive: Security & Persistence
1. Identity with UUIDv7
We use UUIDv7 for user IDs. UUIDv7 places a Unix-millisecond timestamp in its most significant bits, giving it better database-index locality than random UUIDv4. This can reduce random B-tree insertions, although strict ordering within a millisecond requires an appropriate generator. It does not guarantee right-edge insertion or prevent fragmentation, and the actual D1 benefit depends on the schema and workload.
2. Stateful Sessions vs. JWTs
While stateless JWTs are popular, they are difficult to revoke before expiration without additional server-side state. Derbent instead uses opaque session tokens stored server-side, so sessions can be deleted.
KV is eventually consistent: Cloudflare notes that updates and deletions may take 60 seconds or more to become visible in other locations. KV alone therefore does not provide immediate global revocation; stronger requirements need a consistency and cache-invalidation strategy.
As defense-in-depth, Derbent records client metadata such as IP address and User-Agent and can treat changes as session-risk signals. The snippet below rejects a request when its User-Agent differs. These attributes can be spoofed or change legitimately, so they can help detect anomalies but do not prevent Session Hijacking or replace secure tokens, cookie protections, expiration, and revocation.
// Session verification logic with fingerprinting
async verifySession(sessionId, appId, clientIp, clientUa) {
const session = await this.sessionRepo.get(sessionId);
if (!session) throw new AppError('Session not found', 401);
// Anomaly detection: UA Check
if (clientUa && session.userAgent !== clientUa) {
await this.auditLogRepo.log({
action: 'security_alert_hijack',
userId: session.userId,
ip: clientIp,
userAgent: clientUa
});
throw new AppError('Session invalid (Client Mismatch)', 401);
}
return session;
}3. Password Hashing
We use PBKDF2 with a variable iteration count. The hash is stored in a iterations:salt:hash format, so verification can use each password record’s work factor when the configured default changes. The internal hash and count should follow current guidance and be benchmarked on Workers. The 100,000-iteration example below is below OWASP’s current recommendations: 600,000 for PBKDF2-HMAC-SHA256 and 220,000 for PBKDF2-HMAC-SHA512. New deployments should choose an appropriate stronger work factor rather than copying that value.
Quality of Life (Developer Experience)
One of the main goals was making Derbent easy to deploy and integrate into new projects.
1-Click Deployment
I’ve integrated the Cloudflare Deploy Button. With one click, the repository is cloned, D1 and KV namespaces are provisioned, and migrations are applied automatically.
Environment-Driven Configuration
All service settings—from the password hashing strength to the SSO root domain—are managed via environment variables in wrangler.jsonc.
"vars": {
"APP_ENV": "production",
"LOG_LEVEL": "warn",
"APP_NAME": "Derbent",
"BASE_URL": "https://derbent.example.com",
"PBKDF2_ITERATIONS": "100000",
"AUDIT_LOG_RETENTION_DAYS": "30",
"COOKIE_DOMAIN": ".example.com",
"RESEND_DOMAIN": "destek.example.com",
},Simple Integration Middleware
Integrating a new app takes minutes. You simply add a Service Binding and a few lines of middleware to check the session:
export async function verifyWithDerbent(c: Context, appId: string) {
const cache = caches.default;
const cookie = c.req.header("Cookie") || "";
// If the cookie is empty, we can skip the fetch entirely to save CPU
if (!cookie) {
return c.json({ error: "Unauthorized" }, 401);
}
const clientIp = c.req.header("cf-connecting-ip") || "127.0.0.1";
const clientUa = c.req.header("user-agent") || "unknown";
// SECURITY: Do not rely on 'Vary: Cookie' to partition these responses.
// Cloudflare does not consider arbitrary Vary values by default.
// Include the application and a cookie-derived value in the explicit cache key.
const encoder = new TextEncoder();
const data = encoder.encode(cookie);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const cookieHash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
// Use a stable HTTPS URL on the consuming Worker's hostname as a synthetic cache key.
const currentUrl = new URL(c.req.url);
const cacheUrl = new URL(`${currentUrl.origin}/_internal_auth_cache`);
cacheUrl.searchParams.set("app_id", appId);
cacheUrl.searchParams.set("cookie_hash", cookieHash);
const cacheKey = new Request(cacheUrl.toString());
let response = await cache.match(cacheKey);
if (!response) {
// The actual request to Derbent via Service Binding.
const fetchReq = new Request(`https://auth.internal/internal/verify?app_id=${appId}`, {
headers: {
Cookie: cookie,
"Derbent-Client-IP": clientIp,
"Derbent-Client-UA": clientUa,
},
});
response = await c.env.DERBENT_SERVICE.fetch(fetchReq);
if (response.ok) {
// Cache the response against our unique cacheKey
await cache.put(cacheKey, response.clone());
}
}
return response;
}A cached successful response is returned without rechecking the session or client metadata. Set a short, deliberate freshness policy and account for revocation; otherwise, this cache can continue authorizing a revoked session until the entry expires or is purged. Cache API entries are local to the originating Cloudflare data center, and cache.delete() only deletes the entry in that data center—it is not a global revocation mechanism.
The Roadmap: Native Edge & Admin Control
Derbent is an evolving project. Here is what is coming next:
1. Moving to Cloudflare Native Email
Currently, Derbent uses Cloudflare Queues to pass email tasks to the Resend API. Cloudflare now provides native outbound email through its Email Service, including a Workers binding, REST API, and SMTP. Email Sending is currently in beta, and plan requirements and recipient limits apply; I will evaluate those constraints before migrating from Resend.
2. Admin Dashboard
I am planning a dedicated Admin Dashboard for Derbent. This will be a separate interface to:
- Manage Users: Block, delete, or update user information.
- Audit Logs: A searchable UI for the
audit_logstable in D1 to monitor security events. - Application Whitelisting: Manage which apps are allowed to authenticate via the SSO engine.
Conclusion
By centralizing authentication on the Edge, I’ve managed to increase the security of my applications while significantly reducing development time for new projects. Derbent proves that with D1, KV, and Service Bindings, you can build a robust, enterprise-grade auth system without the enterprise price tag.