hybrid, not a port verdict below to change. Full research, with every
number and URL below sourced and dated, is in
.superpowers/sdd/2026-09-03-alexandria-improvement-program/research/cloudflare-platform.md
(checked live 2026-09-03).
The hybrid verdict, and why
Alexandria stays a Node process (on Cave, or Railway) that consumes Cloudflare services over HTTP, rather than a port of the server itself onto Workers. Three of this repo’s own runtime dependencies rule a full port out today:node:sqliteis a non-functional stub under Workers’nodejs_compat(“can be imported or required, but does not provide a working implementation”).StateStore, the quota ledger, the result cache, the routing cache, andSqliteCacheStore(the RFC 9111 undici cache) all need a new backend - Durable Objects SQLite or D1 - before any of that code could run on Workers at all.- Workers’
fetchdoesn’t honour undici dispatchers. Per-requestdispatcher:options and undici’sAgent/interceptorsAPI are not supported (Cloudflare built a bespoke shim only for its own Vitest integration).src/utils/dispatcher.ts’sguardedDispatcheris what pins the fetch tier’s actual TCP connection to the address the SSRF guard just validated (src/web/fetchTier.ts’sresolveFetchTarget) - closing a DNS-rebinding TOCTOU gap between validation and connect. On Workers that pin can’t be expressed (noconnect.lookuphook), so the guard would collapse to pre-resolve-then-allowlist, a strictly weaker guarantee than what runs today. - Workers Paid caps a single invocation at 6 simultaneous connections
“waiting for response headers” (relaxed 2026-04-09 so body streaming no
longer counts, but the header-wait cap itself is unchanged).
library_askfanning out to ~20 slow upstream library APIs would serialize into ~4 sequential header-wait rounds on Workers - a real latency regression against Node’s unlimited sockets, not a hypothetical one.
/mcp this server already
serves. A full Workers port is rated M-L effort in the research doc, buys
no new capability Alexandria needs, and costs a measurable security
regression on the SSRF pin - not undertaken here.
AI Gateway: BYOK for the LLM roles
Every LLM/embedding call already goes throughsrc/utils/providers.ts’s
per-role table (router/synth/research/embeddings/rerank), each
resolved from ALEXANDRIA_<ROLE>_BASE_URL/_API_KEY/_MODEL falling back
to the shared ALEXANDRIA_BASE_URL/ALEXANDRIA_API_KEY. Pointing a role at
AI Gateway is exactly that fallback chain with a Cloudflare URL - no code
change, same as the README’s existing LiteLLM recipe.
New unified endpoint (api.cloudflare.com, OpenAI SDK-compatible,
added 2026-05-21):
ALEXANDRIA_API_KEY.
Targeting a named, non-default gateway on this endpoint needs one more
thing: Cloudflare’s REST API routes to a named gateway via the
cf-aig-gateway-id request header, not the URL path. ALEXANDRIA_GATEWAY_ID
(shared) / ALEXANDRIA_<ROLE>_GATEWAY_ID (per-role override, same
precedence as ALEXANDRIA_BASE_URL/_API_KEY) set that header on every
request src/utils/providers.ts’s clientFor() makes, via the openai
SDK’s defaultHeaders client option:
ALEXANDRIA_GATEWAY_ID unset for the account’s default gateway -
the header is only added when it (or a per-role override) is configured.
Legacy endpoint (gateway.ai.cloudflare.com, still supported, the one
already documented in the README’s “Pointing roles at a
gateway”
section): the gateway ID lives in the URL path itself, so it needs no
extra header and is the simpler choice for a single named gateway:
embeddings role if the same text is ever re-embedded expecting a fresh
result through a different path (e.g. library_ingest’s corpus-as-cache).
Workers AI: embeddings and rerank roles
Workers AI’s OpenAI-compatible endpoints (/v1/embeddings,
/v1/chat/completions) live at the same unified base URL as above:
bge-m3 is $0.012/M input tokens, 1024-d, multilingual, 60k-token context
- the cheapest embedding model in Cloudflare’s catalog and, per Task 10’s
report, the exact model already exercised end to end against a LiteLLM
gateway front (
ALEXANDRIA_EMBEDDINGS_MODEL=BAAI/bge-m3).
rerank is a true cross-encoder backend added in Task 10
(ALEXANDRIA_RERANK=workers-ai, src/utils/rerank.ts). Unlike the
embeddings/chat roles, this one POSTs directly to the model’s per-account
run URL (not the OpenAI-compatible path), with Cloudflare’s own
{query, contexts} request shape:
bge-reranker-base is a 2023 278M
cross-encoder, weaker than newer hosted rerank models; there’s no
OpenAI-shaped /rerank route, which is why this backend needed its own
~30-line adapter rather than reusing the cohere backend’s request shape.
Browser Run: fetch tier 4
src/web/browserRun.ts adds Browser Run’s REST /markdown Quick Action
as a fourth fetch tier, tried after crawl4ai and only when both
CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_BROWSER_RUN_TOKEN are set:
119853733/128292352,
so a site that fingerprints or blocks known bot traffic can and does block
it. /crawl honours robots.txt with a 0.5s default per-request delay.
This is the opposite of a stealth spider: it’s a cheap, legitimate,
self-identifying JS-render tier for cooperative sites - the same
Jina-reader-class tradeoff tier 2 already makes, not a way past sites that
actively resist automated access.
Tunnel + Access: a private /mcp
src/httpGuards.ts already guards /mcp with Host/Origin validation
(ALEXANDRIA_ALLOWED_ORIGINS) and a per-client-IP rate limit
(ALEXANDRIA_HTTP_RATE_LIMIT). Putting a Cloudflare Tunnel plus Access in
front of it adds authentication Alexandria itself never implements:
Set ALEXANDRIA_ALLOWED_ORIGINS to the tunnel hostname. Without it,
Host-header validation is off entirely (see the README HTTP section:
enforcing it with no allowlist would 403 every request that arrives with
this deployment’s real hostname in Host), so a tunnelled /mcp runs
without DNS-rebinding protection until the variable is set. The server logs
one warning at startup when it is missing.
This matters more for a tunnel than for a direct listener: cloudflared
connects to localhost:PORT and forwards the PUBLIC hostname in Host, so
the tunnel hostname - not localhost - is what the guard sees, and it is
the value the allowlist has to name.
-
Run
cloudflared tunnelpointing at this server’sTRANSPORT=httplistener (no public port opened on the box - the tunnel is outbound-only). - Add an Access application over the tunnel’s hostname, with a policy restricting who/what can reach it.
-
Desktop MCP clients can’t complete Access’s browser-based OAuth
login - use an Access service token instead: create one in the
Zero Trust dashboard, then pass its
CF-Access-Client-Id/CF-Access-Client-Secretas headers on every request. Claude Desktop’s config (which only takes a bare URL) needsmcp-remotein between to inject them:
ALEXANDRIA_TRUSTED_PROXY: per-client rate limiting behind a proxy
checkRateLimit’s token bucket keys on req.socket.remoteAddress by
default - which, once traffic reaches this server through a Tunnel or any
PaaS edge (Railway included), is the proxy’s address for every caller,
not the caller’s. Left unset, that collapses the whole rate limiter into
one shared bucket: the first handful of distinct real clients exhaust it
together, and every later, unrelated client is rejected until it refills.
Setting ALEXANDRIA_TRUSTED_PROXY=1 switches the key to CF-Connecting-IP
(set by Cloudflare on every request that reaches your origin through it),
falling back to the first X-Forwarded-For entry when that header is
absent, and only falling back further to the socket address when neither
is present. This is an explicit opt-in, off by default, because trusting
either header from a caller you haven’t put behind a proxy would let
that caller pick its own rate-limit bucket by sending a spoofed header
directly - only set it once /mcp is actually reachable exclusively
through a proxy that sets these headers itself.
WAF rate-limiting: a public /mcp
If /mcp is exposed directly through a Cloudflare zone (not behind
Access), a WAF rate-limiting rule adds edge-level throttling in front of
ALEXANDRIA_HTTP_RATE_LIMIT’s in-process one. Availability is
plan-gated: Free allows 1 rate-limiting rule per 10-second period, Pro 2,
Business 5 - thin, but free, and it blocks abusive traffic before it ever
reaches this process. Bot Fight Mode and WAF custom rules are free on every
plan and compose with it.
R2 via S3: cached full texts (documented, not implemented)
R2 buckets speak the S3 API, so a Node process (this one, unmodified) can read/write them with any S3-compatible client - no Workers code required. At the stated scenario (5 GB of cached texts/PDFs), R2’s free tier (10 GB storage, 1M Class A + 10M Class B operations/month) covers it at $0, with free egress. This is a real, low-effort option for durable full-text storage if disk on the current host ever becomes the constraint that matters, but nothing in this task wires it in -library_ingest’s storage
path stays Supabase/pgvector today; adding an R2-backed
VectorStoreProvider/text-cache would be its own, separate task.
What a full Workers port would cost
Beyond the three blockers in the verdict above:node:worker_threads and
node:child_process are also stubs (Defuddle’s off-thread extraction
worker and the repo’s one child_process call site would both need
rewriting), and node:fs under Workers is a memory-only VFS with no
writable persistent path (/tmp is per-request, not shared) - ruling out
anywhere this server writes a file today. The research doc rates the
rewrite of stateStore, dispatcher, and fetchTier alone as M-L effort,
with the SSRF-pin regression above as a permanent cost, not a migration
hiccup. At the stated traffic scenario, hosting cost is a wash either way
(~$5.50-6/month on Workers Paid, driven mostly by the $5 plan minimum,
versus effectively $0 marginal cost on infrastructure already running).
The one thing a port buys is not running a box you already run - not
reason enough on its own to accept the security and latency regressions
above.