Repository navigation
prototype(serving): the login door end to end on the development instance (#119) - #127
allisonmahmood wants to merge 10 commits into
Conversation
Throwaway prototype for the login-door ticket. Every /d/* page (and two door-only routes, /login/device and /sign-out) now sits behind route-scoped router middleware that hands the request to @clerk/backend's authenticateRequest, copies Clerk's headers back, redirects for the handshake, shows a script-free door page when signed out, and matches the Clerk user to a prototype_users row (migration 0090, just-in-time into acct_dev) before serving with private, no-store caching. ClerkSession.prototype.ts is the Effect service over the SDK; it builds without keys so the server boots and the door fails closed. It wraps globalThis.fetch to log every outbound call as [clerk-net], and the door logs one [door] line per request with the verdict, timings, network count and the Set-Cookie attributes Clerk returned (values redacted). The dev runner forwards every CLERK_* key from dev.env plus PROTOTYPE_DOOR_MODE. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…119 node scripts/prototype/login-door.mjs <patchUrl> walks the whole trip a person makes: the pasted link to the door page, the Account Portal sign-in with a +clerk_test address and code 424242, and back to the served patch, recording every main-frame hop with its status and Set-Cookie attributes, the cookie jar, and the [door]/[clerk-net] lines from dev.log. --wait N reloads after N seconds, --sign-out exercises the device page and the sign-out form, --print-jwt-key derives CLERK_JWT_KEY from the JWKS. Co-Authored-By: Claude Fable 5.1 <[email protected]>
… families (#119 experiment)
…edirects, in-memory router (#119) Seven offline tests over the login door prototype: a session signed by an RSA-2048 test keypair verifies through CLERK_JWT_KEY with no network and the door serves it; a hand-built fetch client on redirect: manual sees the SDK's handshake 307, its Location and the __clerk_redirect_count cookie; HttpRouter.toHttpEffect with HttpServerRequest.fromWeb drives the door in memory; HttpClient.withCookiesRef carries the loop-guard cookie across hand-driven hops until the SDK gives up; an expired session handshakes only a document GET and sign-out still expires every Clerk cookie while the BAPI revoke fails offline; and a pk_live_ key answers a cookie-less document GET with the door where a pk_test_ key handshakes. The fake instance, keypair, session signing, fetch guard and acct_dev seed live in @patchy/auth/testing so the other suites can be put behind the same door. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…uites green (#119) Pages.test.ts and the server's booted-whole test broke when the door went in front of /d/*: ClerkSession was not provided in one and the door failed closed with a 503 in the other. Both now take the offline instance's keys through their ConfigProvider, seed acct_dev for the door's just-in-time user row, and send a signed-in reader's cookies; a doored page is private, no-store, so the cache expectations follow. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sol reviewBlocking findings only:
|
|
Two-axis review of This PR is a review vehicle and should stay unmerged. Findings are about the lesson, not a merge checklist. StandardsEffect services (
|
| Choice | Verdict |
|---|---|
Route-scoped HttpRouter.middleware vs global vs inline in servePatch |
Keep. / and /healthz stay open; /d/* plus the door’s chrome share one gate. Global would handshake /healthz and mix cookies with bearer. Inline in servePatch misses /sign-out. Same move as Authorization / CurrentIdentity. Do not steal patchAccountRow / foldRow: authenticate in the middleware; “may this viewer open this patch” in the handler that already loaded the patch. |
DoorAuth as Context.Service provided per request (no make/layer) |
Keep, narrower payload. House pattern (CurrentIdentity). Today it carries the full Clerk Verdict plus the user, and servePatch never reads it. Real tag: the viewer (user, company), not Clerk’s wire state. |
Request from PATCHY_PUBLIC_BASE_URL instead of toWeb/toURL |
Keep as lesson but rewrite. Handshake redirect_url must be the public URL. They pass that URL, then copy incoming Host. T2: the SDK rebuilds origin from Host, so the test socket wins. Real door must set Host and the URL from PATCHY_PUBLIC_BASE_URL. |
Copying Clerk headers; Set-Cookie via response.cookies |
Keep as lesson but rewrite. Node joins duplicate headers with commas; Expires contains commas; comma-joined Set-Cookie is a broken cookie. Cookies.fromSetCookie / mergeCookies is the only correct bridge. Sign-out’s Domain on __client_uat is also real. Do not append every header Clerk returns. T8 lands access-control-allow-origin: null on the served patch. Real door copies Set-Cookie and handshake Location (as 307), and drops Clerk’s CORS and debug headers. |
Wrapping globalThis.fetch to count network cost |
Artefact, delete. Process-wide counter, wrap installed even when Clerk is unconfigured. Real door: jwtKey present vs absent plus a span on authenticateRequest. The test fetch guard in @patchy/auth/testing is a different thing. |
Offline jwtKey RSA fixture + Chromium driver |
Keep the fixture as the regression seam. Treat the driver as a lesson and delete it from the product tree. RSA-2048 e=65537 because loadClerkJwkFromPem is that picky; redirect: "manual" so 307 is visible (item 6). Install the test fetch guard in the layer, not at module load. |
ClerkSession + PrototypeUsers in auth, LoginDoor in serving |
Keep the split; rewrite the user table’s home. User ↔ company is not Auth’s vocabulary. Serving importing @patchy/auth is intended. Serving SELECT … FROM patches is not. Fail-closed when keys are missing (server boots, door 503s, /healthz still answers) is the right boot policy. |
| Experiment flags | Artefact, delete as flags. Commit the findings: page is the product (not bounce-to-portal); suffix-family mismatch is a real SDK bug — always mirror or pin Clerk, no env switch; other-company / missing share one 404 in the handler that loaded the patch, not a second path in the door. |
| Device login routes that do not issue a token | Artefact, delete the stubs. Keep the lesson that the door wraps first-party chrome, not only /d/*. Real device login is Auth’s, issues a machine token, and is a different ticket. |
| Just-in-time user rows vs a seeded match | Artefact, delete JIT and +outsider / +other email routers. The ticket asked for one read against a seeded row. JIT into acct_dev hides the product state: a sign-in with no company lands on create-or-join, not auto-join. |
The skeleton is the smallest method that could actually prove the assumption. Issue 119 also asked seven facts a handshake-only stub would miss; those belong in the prototype.
What is not smallest, and not the real door: three env flags, JIT plus email hacks, tokenless device chrome, company SQL in the middleware, a process-wide fetch monkeypatch, and blindly replaying every Clerk header onto a served page. R2-6 moved the PR from “does the handshake work” to “does authorization live in the door,” which is the wrong lesson.
Steal: doored vs open route layers; middleware that provides a per-request viewer tag; ClerkSession as Auth’s fail-closed SDK seam; public URL (and Host) from PATCHY_PUBLIC_BASE_URL; Set-Cookie only via response.cookies; 307 for handshake and for Location-bearing states; sign-out as a same-origin POST that revokes and expires both cookie families, with Domain on __client_uat; door chrome as its own script-free CSP (form-action 'self'); offline jwtKey tests.
Do not steal: global fetch, flags, JIT, the device stub, or the door reading patches itself. The real door authenticates in serving, asks Auth who, and lets the patch handler decide whether that person may see it.
On cache: Standards says wiping URL-shaped caching is a serving-guarantee breach. Method says a public cache cannot survive a cookie gate, so private, no-store on anything that consulted a session is a real product change, not a prototype accident. That tension is the decision the real door still has to make; this PR rewrote Pages.test.ts as if it were already decided.
YAGNI
PR 127 answers #119: handshake on a script-free document GET, what a pk_test_ instance cannot show about production, the person's round trip, cost per load. Two layers.
A) Throwaway instrumentation. The [door]/[clerk-net] lines, authMs/dbMs/netCalls, hop tables, cookie jars, and the offline T8/T9 return-leg suite are the prototype. They are not YAGNI. wrapFetch plus a process-wide counter is ugly, but it is how they counted JWKS/BAPI; keep it on the branch, do not promote it. testing.ts (fake keys, handshake JWT, fetch guard) is the cheapest freeze of those answers.
What does not produce an answer is product surface: GET/POST /login/device that logs confirm/deny and returns “done”; JIT createJustInTime plus +outsider/+other email routing; three env-flag dialects (PROTOTYPE_DOOR_MODE, PROTOTYPE_DOOR_SUFFIX_FIX, PROTOTYPE_R2_6=off|1|fold). The 671-line driver then grows --device, --device-delay, --then-email, --save-cookies to walk that surface. The runner forwards only PROTOTYPE_DOOR_MODE, so the other two flags are a second dialect. Sign-out is the one extra route that earns its keep (expired POST, unsigned sid, Domain on __client_uat).
B) Durable shape. The smallest model is already written: route-scoped middleware, tagged authenticateRequest verdict, Clerk headers copied with Set-Cookie on response.cookies, public URL from publicBaseUrl, fail-closed when keys are missing, one user-row read, company mismatch as the same 404 Pages would serve. Everything else is speculative generality.
LoginDoor.prototype.ts is a 615-line god-file: HTML, SQL, tenancy, device stub, sign-out, three Config maps. foldRow reimplements PrototypeUsers.find plus a LEFT JOIN so a flag can pick fold vs second read — duplicated code in service of an A/B. Suffix mirroring is a measured workaround; a flag that turns it on is a dual path the real door must not keep.
Delete for the lesson-extract: device routes, pages, and driver flags; PROTOTYPE_DOOR_MODE (pick one); PROTOTYPE_R2_6 and foldRow (one company check, in the user lookup); JIT and email heuristics; wrapFetch/netCalls from durable ClerkSession.
Keep verbatim: withClerkHeaders; the suffix-family comment on mirrorRefreshedSession; Domain on __client_uat in sign-out; sidFromCookie; publicUrl construction; cookieSuffixOf/frontendApiOf/accountPortalOf; T8/T9 comments; HeadlessChrome UA note; DOOR_CONTENT_SECURITY_POLICY; route-scoped DoorAuth.
YAGNI mixed. Worst complexity: three env-flag dialects plus foldRow vs find inside a 615-line door that also stubs device login.
Product states (tenancy)
Product, “What the wrong person sees”: not signed in, the login door, then the patch if they may open it. Signed in, in the same company, but outside the scope: “you don’t have access…”, who owns it, and a request access button… existence is not a secret. Signed in from a different company, or the link points at nothing: “no such patch”, confirming nothing.
Survive. Signed-out → script-free door, redirect_url back onto the patch, door in front of /d/* not inside the page. Signed-in and allowed → the patch; host knows who (DoorAuth); CSP still has no script. R2-6 on: other-company and missing patch share Pages’ 404. Device page shape is right: show the code, Confirm/Deny, name the machine — confirmation, not code-entry.
Lies — do not teach the real door these.
-
+outsider→ 403 “You are not in a company.” Dead end, sign-out only. Copy also says the account “is not part of the company this patch is shared in,” mixing no-company with wrong-company. Product: “There is no person without a company. A sign-in with no company behind it lands on create or join.” A 403 on a patch URL confirms the patch and invents a refuse-to-serve state that must not exist. -
JIT into
acct_dev. Unknown Clerk user is silently a member. Product path is invite, verified-domain join, or create-or-join — not insert-into-the-seed-company. -
R2-6 off by default. Any row opens any patch. Cross-company must be 404, not 200.
Pages.test.tspublishes asacct_pagesand JITs the reader intoacct_dev, so the serving suite encodes that mismatch. -
Every
/d/*doored, tests now require cookies, cache forcedprivate, no-store. Collapses “anyone with the link, no login” into company-default. Gating all/d/*answers “can a company patch have a door?”; rewriting the serving suite as “cookies required, uncacheable” answers a different product.
Gaps, not lies. No same-company outside-scope / request-access page (default is company-wide; do not 404 that — existence is not a secret). Device POST only logs; fake “confirmed” is incomplete.
Verdict: keep door → land-back, host-knows-who, script-free page, other-company = missing = 404, device confirm-not-type. Throw away outsider-403, JIT membership, default no tenancy check, and “all /d/* private no-store.”
Summary
- Standards: 6 hard + 3 judgement (plus Effect/UI detail). Worst:
ClerkSessionhiding a process-widefetchwrap, and Serving queryingpatchesitself for tenancy. - Spec: 8 missing/partial, 3 creep, 3 wrong. Worst: no resolution comment on The login door end to end on the development instance #119 — the prototype’s actual deliverable is still unwritten.
The skeleton (route-scoped middleware, fail-closed ClerkSession, cookies on response.cookies, public URL not toWeb) is the lesson. The rest is the lab still running after the handshake already completed. Write the seven answers on #119 before anyone copies this into the real door.
…RL comment tells the truth (#119) Three corrections from the review round, so the branch reads as a true primary source for the real door: - `__clerk_handshake` and `__clerk_handshake_nonce` join what `/sign-out` expires, plain and suffixed. Nothing else clears them and the payload is a standing `__session` directive, so a browser that kept the cookie was signed in again on its next document GET. T8 now asserts the 303 expires the pair and the next GET is the door. - The comment over the Web `Request` claimed the SDK builds the handshake's `redirect_url` from the public URL. It does not: `deriveUrlFromHeaders` rebuilds the origin from `X-Forwarded-Host` / `Host` and `X-Forwarded-Proto`. The comment now says so, and says the real door has to pin those headers from `publicBaseUrl` too. - The door CSP gains `img-src data:` so the shared shell's grain is not blocked on door pages. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…what did not happen (#119) Copy only, from the review round. The device done page said the machine "was confirmed", but the POST only logs the choice and mints nothing. The outsider lede said the account "is not part of the company this patch is shared in", which is the wrong-company state; the page is the no-company one, whose product answer is create or join. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Reply to the reviewsThanks both. Reading these as reviews of the real door is the right instinct, and most of what they say about the real door is right — but this branch is a wayfinder prototype for #119 and will be closed unmerged. The brief from the auth map's owner was "go broad and wide, we want to learn as much as possible from this prototype so we know how all the parts will work". So the switches, the stub pages and the offline suite are the lab, not scope creep: each one was run to answer a named question, and each has a finding. Two commits went on the branch for this round, because a throwaway branch is still the primary source people will read when they build the door, and it has to tell the truth:
Fixed
Kept as is — deliberate experiments, each with a findingBoth reviews ask for these to be deleted. They are the lab; they are going away with the branch, and their findings are what survives. Kept as is: deliberate experiment, throwaway branch, finding recorded on #119.
The runner forwarding only Kept as is — throwaway code qualityAll true, all deliberate on a branch that gets deleted. Fixing them would cost the branch its instrumentation without changing what anyone learns.
Agreed as lessons for the real door — on #119Not changes to this branch; these are the parts of the reviews that survive it.
The resolution commentBoth reviews' biggest finding is that #119 has no resolution comment. Correct, and it is the one thing not fixed here: the resolution is the orchestrator's deliverable and lands on #119 after this review round, written from the findings above rather than from the diff. Once it is up, this PR closes unmerged and #119 carries the answer. Claude Opus in Claude Code, addressing the review round for the auth map's foreman. |
Throwaway prototype for #119, opened as a review vehicle only: this PR closes unmerged and the branch stays as the primary source. Do not merge.
The problem. The auth map's riskiest assumption was unproven: that a Node/Effect server with no ClerkJS on the page can gate
/d/<id>with@clerk/backend'sauthenticateRequest, send the person to Clerk's Account Portal, get the session back through the handshake on a document request under a script-free CSP, and match the Clerk user to a Patchy row with one read.What this does. A route-scoped
HttpRouter.middlewareon the two/d/*routes plusGET/POST /login/deviceandPOST /sign-out(packages/serving/src/LoginDoor.prototype.ts), an Effect service over@clerk/backend(packages/auth/src/ClerkSession.prototype.ts) that also logs every outbound Clerk call, aprototype_userstable with a just-in-time row (PrototypeUsers.prototype.ts, migration0090), a headless-Chromium driver that signs in with a+clerk_testuser and prints every hop and cookie (scripts/prototype/login-door.mjs), an offline vitest suite over a test RSA keypair andCLERK_JWT_KEY(LoginDoor.prototype.test.ts, fixture@patchy/auth/testing), and experiment switches (PROTOTYPE_DOOR_MODE,PROTOTYPE_DOOR_SUFFIX_FIX,PROTOTYPE_R2_6). The dev runner forwards everyCLERK_*name fromdev.env.The findings are the resolution comment on #119. Review for: does the door's shape (route-scoped middleware providing the session per request, cookies on
response.cookies, the URL built from the request) hold up as the shape the real door should take, and what in here is an artefact of the prototype rather than a lesson.Built by Claude Fable 5.1 and Claude Opus subagents in Claude Code, orchestrated as the foreman for the auth map (#112).