Skip to content

Effect 4 HTTP for the door: cookies, redirects, and the Web Request bridge #117

Closed

Description

@allisonmahmood

Question

What the Effect 4 RC pinned in node_modules offers a server-rendered login door, read from its source and ai-docs, not from memory of Effect 3:

  1. Reading cookies from HttpServerRequest and setting them on HttpServerResponse, with the attributes a session cookie needs (HttpOnly, Secure, SameSite, domain, path, max-age).
  2. Redirect responses.
  3. Turning an HttpServerRequest into a Web-standard Request — or the URL and headers @clerk/backend's authenticateRequest needs — and applying the headers it hands back.
  4. HTML form bodies (urlParamsBody or its RC equivalent) for the device-confirm and company pages, and a pattern for CSRF on those POSTs if Effect offers none.
  5. HttpRouter middleware scoped to a prefix, so the door guards /d/* and nothing else, given the server already installs one global middleware chain in apps/server/src/Server.ts.
  6. What HttpApiTest and NodeHttpServer.layerTest can drive for a cookie-and-redirect flow in a test.

Output: the resolution comment on this ticket, with file paths into node_modules/effect for each API. Feeds the door prototype and the door ticket.

Activity

  1. added
    wayfinder:research
    on Sep 2, 2026
  2. allisonmahmood commented on Sep 2, 2026

    @allisonmahmood
    OwnerAuthor

    Resolution

    Read from [email protected] and @effect/[email protected], the versions pnpm-workspace.yaml pins. This worktree has no node_modules; the files were read from the same pinned versions installed at /home/quan2m/Dev/patchy-cloud/node_modules (effect/package.json and @effect/platform-node/package.json there both say 4.0.0-rc.112), and the repo files cited below are byte-identical between that checkout and this worktree. Paths below are relative to node_modules/. Line numbers are rc.112's.

    1. Cookies: reading and setting

    Reading. HttpServerRequest.cookies: ReadonlyRecord<string, string> is a plain record, parsed lazily from the cookie header by Cookies.parseHeader [effect/src/unstable/http/HttpServerRequest.ts:80; Node impl @effect/platform-node/src/NodeHttpServer.ts:320-326; Web-Request impl HttpServerRequest.ts:730-736, same call]. parseHeader(header: string): Record<string, string>: first occurrence of a name wins, surrounding quotes are stripped, values containing % are decodeURIComponent-ed (falling back to the raw value on failure) [effect/src/unstable/http/Cookies.ts:1088-1136]. Schema-decoded read: HttpServerRequest.schemaCookies(schema, options?) returns Effect<A, Schema.SchemaError, RD | HttpServerRequest> and decodes req.cookies [HttpServerRequest.ts:195-202]. There is no signature/encryption layer; a cookie value is whatever the client sent.

    Setting. On HttpServerResponse (readonly cookies: Cookies.Cookies is a field of the response, separate from headers) [effect/src/unstable/http/HttpServerResponse.ts:54-61]:

    • setCookie(self, name, value, options?) : Effect<HttpServerResponse, Cookies.CookiesError> (dual; validates and fails in the error channel) [HttpServerResponse.ts:697-757]
    • setCookieUnsafe(self, name, value, options?) : HttpServerResponse (throws) [821-878]
    • setCookies(self, Iterable<readonly [name, value, options?]>) : Effect<HttpServerResponse, CookiesError> [1033-1107] and setCookiesUnsafe [1108]
    • expireCookie(self, name, options?: Omit<NonNullable<Cookie["options"]>, "expires" | "maxAge">) : Effect<HttpServerResponse, CookiesError> writes value "", Max-Age=0, Expires=Thu, 01 Jan 1970 00:00:00 GMT; the way out for a session [HttpServerResponse.ts:758-820; Cookies.ts:768-817]. Pass the same path/domain as on set, or the browser will not match it.
    • removeCookie(self, name) only drops the entry from the response's collection; it does not tell the browser anything [636-658]. updateCookies [938], mergeCookies(self, Cookies) [989], replaceCookies [666].
    • The constructors empty, redirect, text, json, ... take options.cookies?: Cookies.Cookies [HttpServerResponse.ts:69-76, 122-130, 143-156, 197-210]. html(string) takes no options (and the template-tag overload returns an Effect and takes none either) [225-265]; set cookies on an HTML response afterwards with setCookie/mergeCookies.

    Attributes (Cookie["options"]) [Cookies.ts:107-124]: domain?: string, expires?: Date, maxAge?: Duration.Input (a "90 days" string, millis number, Duration, and also bigint nanos, [seconds, nanos], a DurationObject, or "Infinity"; serialized as Math.trunc(seconds), non-finite rejected) [Cookies.ts:965-968, 495-497; effect/src/Duration.ts:172-180], path?: string, priority?: "low" | "medium" | "high", httpOnly?: boolean, secure?: boolean, partitioned?: boolean, sameSite?: "lax" | "strict" | "none". serializeCookie emits name=encodeURIComponent(value) then, in this order, Max-Age, Domain, Path, Priority, Expires, HttpOnly, Secure, Partitioned, SameSite [Cookies.ts:954-1032]. Nothing is defaulted: a setCookie with no options yields a bare name=value (session cookie, no Secure, no HttpOnly, no Path). The only place in the tree that defaults secure: true, httpOnly: true is HttpApiBuilder.securitySetCookie (the sole httpOnly: true under effect/src), which is for HttpApi apiKey security, not router routes [effect/src/unstable/httpapi/HttpApiBuilder.ts:547-560].

    Validation happens in makeCookie and again in serializeCookie: name must match /^[!#$%&'*+\-.^_\|~0-9A-Za-z]+$/(so__Host-patchy_sessionis a legal name), the encoded value must match the field-content regex,domain/pathhave their own regexes, andmaxAgemust be finite. Failure isCookiesError (_tag: "CookieError", messageis the reason tag) withreason._tagone ofInvalidCookieName | InvalidCookieValue | InvalidCookieDomain | InvalidCookiePath | CookieInfinityMaxAge[Cookies.ts:172-218, 427-432, 457-497, 954-958]. Because the value isencodeURIComponent-ed on the way out and decoded on the way in, a base64url token round-trips unchanged; a value with ;or,` also survives.

    On the wire. The Node server turns response.cookies into a set-cookie array via Cookies.toSetCookieHeaders and appends any single set-cookie string already present in response.headers [NodeHttpServer.ts:518-526]. HttpServerResponse.toWeb appends each as its own set-cookie [HttpServerResponse.ts:1271-1284]. Do not put a Set-Cookie through setHeaders: Headers.fromInput joins array values with ", " and a record can only hold one string per name [effect/src/unstable/http/Headers.ts:60-63, 187-205].

    2. Redirects

    HttpServerResponse.redirect(location: string | URL, options?: Options.WithContent): HttpServerResponse. Status defaults to 302; options.status, options.statusText, options.headers (merged onto location) and options.cookies are honoured, so one call builds "set the session cookie and send them back to the patch": redirect(next, { status: 303, cookies }) or redirect(next).pipe(HttpServerResponse.setCookie(...)) [HttpServerResponse.ts:92, 143-156]. location is written verbatim (location.toString()), relative paths included. Use 303 after a form POST so the follow-up is a GET; 302 for the GET-to-door hop. An absolute URL for the Clerk hop has to come from PatchesConfig.publicBaseUrl, not from the request (see 3).

    3. Bridging to a Web Request, and applying headers back

    • HttpServerRequest.toWeb(self, options?: { signal? }): Effect<Request, RequestError> [HttpServerRequest.ts:1088-1096] and the synchronous toWebResult(self, { signal?, context? }): Result<Request, RequestError> [1047-1086]. If self.source instanceof Request (the fetch-handler path) the source is returned as is; on Node, where source is http.IncomingMessage [NodeHttpServer.ts:298-306; @effect/platform-node/src/NodeHttpServerRequest.ts:20], it builds new Request(url, { method, headers, body? }), attaching a streaming body only for body-carrying methods (duplex: "half"). For a GET this is a header-only object; cheap.
    • The URL comes from HttpServerRequest.toURL(self): Option<URL>: host is headers.host ?? "localhost", protocol is https only when headers["x-forwarded-proto"] === "https", else http [HttpServerRequest.ts:1025-1034]. Two consequences: (a) behind a TLS-terminating proxy the proxy must send x-forwarded-proto or Clerk is handed an http:// URL; (b) that header is believed from any peer. The repo's TrustedProxies middleware rewrites only remoteAddress, not host or the proto [packages/serving/src/TrustedProxies.ts:110-122], and Effect's HttpMiddleware.xForwardedHeaders acts only when x-forwarded-host is present, rewriting host from it and remoteAddress from x-forwarded-for, with no allow-list and no handling of x-forwarded-proto [effect/src/unstable/http/HttpMiddleware.ts:274-287]. If Clerk's verification is sensitive to the origin it sees, the door should build the URL from publicBaseUrl + request.url rather than trust toURL.
    • Pieces, if a Request is not wanted: request.headers is a lowercase-keyed record that already satisfies HeadersInit [Headers.ts:60-63, 187-205], request.cookies is the decoded record, request.url is path+query, request.originalUrl is the unsliced path [HttpServerRequest.ts:77-80]. Whether @clerk/backend's authenticateRequest accepts these pieces instead of a Request is unverified here: @clerk/backend is not installed in the tree (node_modules/@clerk does not exist).
    • Applying headers Clerk hands back: HttpServerResponse.setHeaders(self, input: Headers.Input) and setHeader(self, key, value) [HttpServerResponse.ts:546-628]; for a Set-Cookie list, Cookies.fromSetCookie(headers: Iterable<string> | string): Cookies [Cookies.ts:267-278] on webHeaders.getSetCookie() then HttpServerResponse.mergeCookies [989-1030]. When the door middleware does not own the response (the handler behind it does), register HttpEffect.appendPreResponseHandler((request, response) => Effect<HttpServerResponse, HttpServerError>) (requires HttpServerRequest in context) [effect/src/unstable/http/HttpEffect.ts:178-193]; HttpApiBuilder.securitySetCookie attaches its cookie through exactly this export [HttpApiBuilder.ts:547-560], and HttpMiddleware.cors uses the same mechanism through the internal appendPreResponseHandlerUnsafe [HttpMiddleware.ts:411-426]. HttpServerResponse.fromWeb(response: Response) exists for wrapping a Response wholesale, moving its Set-Cookie headers onto cookies [HttpServerResponse.ts:1663-1670].

    4. HTML form bodies, and CSRF

    • request.urlParamsBody: Effect<UrlParams, HttpServerError> reads the body as text and parses with new URLSearchParams(text); the content-type is not checked [effect/src/unstable/http/HttpIncomingMessage.ts:63; HttpServerRequest.ts:590-604]. UrlParams.getAll [effect/src/unstable/http/UrlParams.ts:281], getFirst [330], toRecord [671].
    • Schema-first: HttpServerRequest.schemaBodyUrlParams(schema, options?) returns Effect<A, HttpServerError | Schema.SchemaError, HttpServerRequest | RD>, where the schema's encoded side is Record<string, string | ReadonlyArray<string> | undefined> [HttpServerRequest.ts:296-306; HttpIncomingMessage.ts:97-111]. schemaBodyForm also accepts multipart and then requires FileSystem | Path | Scope; not needed for a code-and-button form [HttpServerRequest.ts:268-289].
    • Query parameters (?next=/d/abc): the router provides HttpServerRequest.ParsedSearchParams for every matched route from find-my-way's searchParams [effect/src/unstable/http/HttpRouter.ts:214; effect/src/unstable/http/FindMyWay.ts:64-68; HttpServerRequest.ts:131]; decode with HttpServerRequest.schemaSearchParams(schema) [HttpServerRequest.ts:223-234].
    • CSRF: no helper anywhere under effect/src (grep -ril csrf finds nothing), and nothing in the repo either. A pattern with what is here: (1) session cookie sameSite: "lax" so a cross-site POST never carries it; (2) on every door POST compare request.headers.origin (fallback sec-fetch-site) with publicBaseUrl's origin and refuse otherwise, done once in the door middleware; (3) a synchronizer token only where the form itself is the secret's carrier: the device-confirm page already shows an unguessable code that the user re-enters, so it needs no extra token; the company/admin forms should carry a per-session token minted with @patchy/core's randomToken(byteLength = 32) (randomBytes(...).toString("base64url")) and compared to the session row [packages/core/src/crypto.ts:12-14]. Note HttpServerResponse.html(string) is text(html, { contentType: "text/html" }) and does not escape; the template-tag overload interpolates raw Template.Interpolated values, also unescaped [HttpServerResponse.ts:225-265; effect/src/unstable/http/Template.ts exports only types, make and stream, no escape]; keep using packages/serving/src/render.ts's escapeHtml/escapeAttribute [render.ts:527, 535] for anything user-supplied. The door's own pages need a CSP of their own with form-action 'self'; the patch CSP's form-action 'none' [packages/serving/src/serving-headers.ts:32-39] would refuse the confirm form.

    5. Middleware scoped to /d/*

    The router has two middleware kinds, and only one is global [HttpRouter.ts:970-994]:

    • HttpRouter.middleware(fn | Effect<fn>, { global: true }) returns a Layer that calls router.addGlobalMiddleware; global functions wrap the whole asHttpEffect handler (route lookup included, so they also see RouteNotFound), the first-registered outermost (Arr.reverse over the registration set) [HttpRouter.ts:200-243]. Server.ts already does this once [apps/server/src/Server.ts:91-98].
    • HttpRouter.middleware(fn) (no global) returns a Middleware whose .layer you Layer.provide to the layer that registers routes. addAll reads the middleware stack out of the build context of the layer registering the routes (getMiddleware(context), keyed on effect/http/HttpRouter/Middleware-N context entries) and wraps each route's handler at registration time [HttpRouter.ts:119-160, 1000-1094; docstring: "By default, the middleware only affects the routes that it is provided to" at 936-960]. Route-scoped middleware runs inside the match, so HttpRouter.params, RouteContext and ParsedSearchParams are already in context (Provided) [HttpRouter.ts:853-858, 292-296].

    So the door is route-scoped: split Pages.layer's single HttpRouter.use [packages/serving/src/Pages.ts:94-116] into the /d/:patchId and /d/:patchId/v/:versionNumber registrations (piped through Layer.provide(door.layer)) and everything else (/, /healthz, the /* 404) without it. Nothing in Server.ts's global chain changes; order becomes TrustedProxies → servingHeaders → ApiGuard → route match → door → page handler, so the door sees the proxy-resolved remoteAddress and its responses get the serving headers.

    A typed variant, HttpRouter.middleware<{ provides: CurrentSession }>()(...), lets the door provide a request-scoped service to those two handlers; the route layer then carries a Request.From<"Requires", CurrentSession> marker that the .layer discharges [HttpRouter.ts:806-851, 883-930, 1108-1190]. HttpRouter.provideRequest(layer) is the sugar for providing an ordinary layer per request [HttpRouter.ts:1246-1265].

    router.prefixed("/d") / HttpRouter.addAll(routes, { prefix }) is not a scoping mechanism: it rewrites route paths and slices the prefix off request.url inside the handler (originalUrl keeps it) [HttpRouter.ts:165-185, 208-213, 244-247, 539-565].

    Matching details that touch the door: a * path registers both /d/* and /d [HttpRouter.ts:141-152]; HttpRouter.RouterConfig defaults to {} [HttpRouter.ts:260-263], so find-my-way's own defaults apply: ignoreTrailingSlash: true, ignoreDuplicateSlashes: true, caseSensitive: false, maxParamLength: 100 [effect/src/unstable/http/FindMyWay/internal/router.ts:45-52], so /D/abc/ and /d//abc reach the door too; a HEAD falls back to the GET route [HttpRouter.ts:202-204]; /d/<id>/anything that matches neither route falls to the /* 404 and never meets a route-scoped door. HttpRouter.serve's own middleware option wraps the send as well and cannot modify the response; the doc says to use HttpRouter.middleware for that [HttpRouter.ts:1271-1292].

    6. Testing a cookie-and-redirect flow

    • NodeHttpServer.layerTest is a real Node server on port 0 plus a fresh FetchHttpClient.layer with RequestInit = { keepalive: false }, wrapped by HttpServer.layerTestClient, which prepends http://127.0.0.1:<port> to every request [NodeHttpServer.ts:487-502; effect/src/unstable/http/HttpServer.ts:374-403]. The fetch client spreads that RequestInit first and then sets only method/headers/body/duplex/signal; it never sets redirect and adds no cookie handling [effect/src/unstable/http/FetchHttpClient.ts:53-75]. WHATWG fetch's default redirect is "follow" and Node's fetch keeps no cookie jar; those are platform facts, not in the local source (unverified here), but if they hold the test client follows redirects on its own and a test never sees the 302. Each HttpClientResponse exposes cookies: Cookies parsed from getSetCookie() [effect/src/unstable/http/HttpClientResponse.ts:306-312]. To see the 302, build the client by hand with Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false, redirect: "manual" }) under HttpServer.layerTestClient and NodeHttpServer.layer(createServer, { port: 0 }), since layerTest bakes in its own RequestInit; because of the ...options spread the redirect key does reach fetch.
    • Effect-level helpers, once fetch is on manual: HttpClient.withCookiesRef(client, ref: Ref<Cookies>) merges every response's cookies into the ref (Cookies.merge is a record spread by name; Path/Domain/Expires are ignored) in postprocess, and sends the ref as a cookie header in preprocess [effect/src/unstable/http/HttpClient.ts:1881-1934; Cookies.ts merge]; HttpClient.followRedirects(client, maxRedirects = 10) follows 3xx with a location, turns POST on 301/302 and non-GET/HEAD on 303 into an empty GET, and drops authorization/proxy-authorization/cookie across origins [HttpClient.ts:1957-2011]. They do not compose into a browser. A client's execute is postprocess(preprocess(request)) [HttpClient.ts:736-749], and followRedirects loops by calling self.postprocess(...) directly for every hop after the first, so withCookiesRef's preprocess runs once: with client.pipe(withCookiesRef(ref), followRedirects()) each hop records its Set-Cookie, but the next hop is built from the previous request and does not carry the cookie just recorded; with the opposite order only the final response's cookies are recorded. For the door flow (302 to the door sets the cookie, then back to /d/... expecting it) drive the hops by hand: withCookiesRef on a manual client, read response.headers.location, issue the next request yourself.
    • HttpApiTest.groups(api, groupIds, { baseUrl? }) is HttpApi-only: it builds HttpApiBuilder.layer(api) into an in-memory handler via HttpRouter.toHttpEffect and returns the typed HttpApiClient; no router routes, no Server.ts global chain, and no hook to add cookie or redirect handling [effect/src/unstable/httpapi/HttpApiTest.ts:41-106]. Not the tool for the door.
    • The in-memory tool for router routes is HttpRouter.toHttpEffect(appLayer): it yields the router's handler as Effect<HttpServerResponse, ..., Scope | HttpServerRequest>; feed it HttpServerRequest.fromWeb(new Request("http://localhost/d/abc", { headers: { cookie: "..." } })) and assert on response.status, response.headers.location and Cookies.toSetCookieHeaders(response.cookies) as data, with no socket and no fetch in the way [HttpRouter.ts:582-600; HttpServerRequest.ts:412-413; Cookies.ts:1076]. HttpRouter.toWebHandler(appLayer, { disableLogger }) gives a (Request) => Promise<Response> for the same thing via Web types [HttpRouter.ts:1335; usage example at 936-960]. The Node-socket test in the style of packages/serving/src/Pages.test.ts:47-62 still earns its place to prove the wire text of Set-Cookie. fromWeb/fromClientRequest requests report remoteAddress as None [HttpServerRequest.ts:722-724]; the door must not depend on it.

    Open questions

    1. @clerk/backend is not in the tree, so whether authenticateRequest takes a Request only or { url, headers }, and what headers it returns, is unverified; the companion Clerk ticket owns that.
    2. toURL trusts x-forwarded-proto from any peer and TrustedProxies does not gate it. Decide whether the door derives its origin from publicBaseUrl or whether TrustedProxies grows to cover x-forwarded-proto/x-forwarded-host.
    3. Under Node's undici, does redirect: "manual" return the real 3xx (status and location readable) or a browser-style opaque redirect? Not answerable from local sources; check in the first test. (The redirect option does reach fetch; that part is verified.)
    4. __Host- prefix needs Secure; whether Chrome/Firefox accept a Secure cookie from http://localhost in the dev loop is browser behaviour, not in these sources.
    5. /d/<id>/junk falls through to the plain 404 with no door. Acceptable, or should the door's scope be a /d/* wildcard route ahead of the 404?
    6. Case-insensitive, trailing-slash- and duplicate-slash-tolerant matching means the next URL should be normalized before it is trusted as the post-login destination.

    Verification

    Checked every load-bearing claim against [email protected] / @effect/[email protected] source at /home/quan2m/Dev/patchy-cloud/node_modules (this worktree has no node_modules; the cited repo files are identical in both checkouts). No WebFetch was used.

    Confirmed as written: cookie read/write API and attribute list with no defaults (1); parseHeader semantics and schemaCookies (1); redirect defaults and options (2); toURL/toWeb host and x-forwarded-proto handling and TrustedProxies not gating it (3); Set-Cookie must ride on response.cookies because Headers.fromInput joins arrays and the Node server pushes one manual string (1); route-scoped vs global HttpRouter.middleware and prefix not scoping (5); layerTest/fetch client with no redirect option, HttpApiTest.groups being HttpApi-only, toHttpEffect + fromWeb as the in-memory harness (6); schemaBodyUrlParams, no CSRF helper, html not escaping (4); @clerk/backend absent.

    Changed: (a) the advice to compose withCookiesRef with followRedirects was wrong: followRedirects bypasses preprocess after the first hop, so later hops never send newly recorded cookies; replaced with hand-driven hops. (b) html(string) takes no options, so "every constructor takes options.cookies" was narrowed. (c) HttpMiddleware.xForwardedHeaders is at 274-287, acts only on x-forwarded-host, and never touches x-forwarded-proto; cors uses the internal appendPreResponseHandlerUnsafe at 411-426 (the cited 228-240 and 357-372 were tracer and CORS-header code). (d) find-my-way also defaults ignoreDuplicateSlashes: true. (e) Duration.Input has more forms than listed. (f) Citation fixes: toWebHandler is at HttpRouter.ts:1335; UrlParams.getAll/getFirst are 281/330 (were swapped); crypto helper named randomToken; toWeb/toWebResult/toURL split into 1088-1096 / 1047-1086 / 1025-1034; setCookies range 1033-1107.

    Unverifiable from local sources: that fetch's default redirect is "follow" and that Node's fetch keeps no cookie jar (Web platform behaviour; the local client simply sets neither); undici's behaviour under redirect: "manual" (open question 3); browser handling of Secure on http://localhost (open question 4); anything about @clerk/backend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

wayfinder:research

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions