r/CloudFlare • u/congoblue • 2h ago
r/CloudFlare • u/GiovaDev • 19h ago
An Effect v4 BFF on Workers: sealed OAuth sessions, ETag compare-and-swap on Drive, and proxied bodies that never hit the heap
I run a self-hosted notes app on a Worker and the interesting problems were all in the BFF, so here are the three that shaped it. Code is MIT if you want to read it: https://github.com/giovacalle/markyard, under bff/ and docs/adr/.
OAuth tokens never reach the browser. Sessions are AES-256-GCM sealed HttpOnly __Host- cookies, and the Worker holds the Google access and refresh tokens while proxying Drive calls. The app therefore needs no token in JS, which is what lets the frontend run under default-src 'self' with no nonces and nothing inline. A stolen XSS payload is worth a lot less when there is no token in reach.
Saves are compare-and-swap, and the precondition belongs to the backend. Drive v3 has no If-Match, so the save path uses v2 with If-Match on the file etag: read the etag, PATCH with If-Match, and a 412 means someone else wrote, so return the conflict and let the client merge. Doing it server side covers the other writers instead of racing them: Drive for desktop, Google's own .md editor and a plain v3 upload all move the etag. The known hole is that the etag tracks modifiedTime, so a writer that preserves it (rclone copying source timestamps) can still slip a change through; md5Checksum and version move in that case, but checking them is a read before the write, not a precondition.
Byte proxies should not touch the JS heap. Images and downloads stream Drive's response body straight through as a new ReadableStream, no arrayBuffer(), no new Response(await res.blob()). On Workers that is the difference between working and failing to allocate once the files get big.
The framework choice: the BFF is TypeScript with Effect v4, deployed with Alchemy. Structured concurrency and typed errors made the token refresh and retry paths readable, and it runs on the Workers runtime with no node: imports. That constraint is enforced in CI, next to a style= scanner that keeps the CSP clean.
Optional state sync (settings, last opened note) is duck-typed against D1: bind STATE_DB and it works, leave it unbound and the feature turns itself off, so the same code deploys stateless.
Happy to answer anything about this shape of deployment, the Drive quirks, or what Effect v4 costs in bundle size and cold start, though on the last one I only have my own numbers and they are not the interesting kind of benchmark.