Skip to content

prototype(serving): the login door end to end on the development instance (#119) - #127

Closed
allisonmahmood wants to merge 10 commits into
mainfrom
prototype/login-door
Closed

allisonmahmood wants to merge 10 commits into
mainfrom
prototype/login-door

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

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's authenticateRequest, 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.middleware on the two /d/* routes plus GET/POST /login/device and POST /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, a prototype_users table with a just-in-time row (PrototypeUsers.prototype.ts, migration 0090), a headless-Chromium driver that signs in with a +clerk_test user and prints every hop and cookie (scripts/prototype/login-door.mjs), an offline vitest suite over a test RSA keypair and CLERK_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 every CLERK_* name from dev.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).

allisonmahmood and others added 8 commits September 2, 2026 20:58
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]>
…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]>
@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling size:l 501-1,000 changed lines labels Sep 3, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Sol review

Blocking findings only:

  1. Intent — this does not test the required seeded-user lookup. seedDevAccount (packages/auth/src/testing.ts:128-135) seeds only an account and token. A missing Clerk user is instead admitted by createJustInTime (packages/serving/src/LoginDoor.prototype.ts:475-488), and the test explicitly expects the request to create that row (LoginDoor.prototype.test.ts:146-173). That makes every authenticated Clerk user a member of acct_dev unless their email contains a magic sentinel. It also makes the first load SELECT + INSERT + SELECT while the [door] line reports only the first SELECT timing. This cannot answer issue 119's “one database read matching the Clerk user to a seeded user row.” Seed the exact Clerk user id returned by the driver before navigation, deny a miss, and remove the JIT path.

  2. Intent — the requested result is still missing. Issue 119 requires a branch link and a resolution comment answering the handshake/CSP result, production limitations, human round trip, and per-load network/database cost, including the seven named probes. The issue still contains only the pre-experiment prompt; the PR body points to a resolution comment that does not exist. The implementation and local instrumentation are not the requested answer. Post the measured evidence and conclusions on the issue before closing this review vehicle.

  3. Method — most of the test infrastructure is contrary to the prototype brief. The issue says “throwaway branch, no tests, no polish” and asks for exactly one redirect: "manual" assertion. Instead this adds a 630-line offline suite, a 174-line exported @patchy/auth/testing surface, and rewrites the existing Pages/server suites around fabricated Clerk sessions. testing.ts:25-39 also replaces process-global fetch at module evaluation and never restores it. Keep the one Undici assertion and the live browser driver; delete the reusable fake-Clerk framework and changes to unrelated permanent suites.

  4. YAGNI — remove future product behavior unrelated to issue 119. PROTOTYPE_R2_6 adds alternate one/two-read company authorization paths (LoginDoor.prototype.ts:65-76,349-373,447-510), while GET/POST /login/device builds a device-confirm UI (Pages.ts:126-128, LoginDoor.prototype.ts:265-309,531-552). The POST does not confirm or deny anything; it only renders copy claiming it did. Neither multi-company authorization nor device confirmation is part of this handshake experiment. They materially obscure the door shape being evaluated and must be removed rather than carried as future switches.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of origin/main...HEAD (26c7adc...c68a528, 8 commits) for #119. Extra passes on intent, method, and YAGNI, because this PR asked whether the door’s shape is the one the real door should take.

This PR is a review vehicle and should stay unmerged. Findings are about the lesson, not a merge checklist.


Standards

Effect services (.agents/skills/effect-service-conventions/SKILL.md)

Hard — hidden globals. ClerkSession.make mutates globalThis.fetch and a process-wide counter (netCalls / fetchWrapped, lines 99–127, 158). Rule: do not hide dependencies in module globals or closures over singleton services. Cost belongs on Clock/Effect.timed, not a patched fetch.

Hard — untyped failure channel. authenticate maps every throw to signed-out:

    const state = yield* Effect.tryPromise({
      try: () => client.authenticateRequest(web, { ... }),
      catch: (cause) => cause
    }).pipe(Effect.option);
    ...
    if (Option.isNone(state)) {
      return { outcome: { _tag: "signed-out", reason: "authenticate-request-threw", ... } }

Rule: keep failures typed (Schema.TaggedError); do not collapse a pipeline into one generic outcome.

Hard — Auth must not know companies. PrototypeUsers joins accounts and returns accountId / accountName (PrototypeUsers.prototype.ts 34–40, 63–70); accountIdFor routes by email into acct_dev / acct_other. packages/auth/CONTEXT.md: “nothing here knows what a company is.” User-in-company is Companies; Auth resolves session → user.

Package ownership (CONTEXT-MAP.md, packages/serving/CONTEXT.md)

Hard — Serving queries patches itself. LoginDoor.prototype.ts 349–373 (patchAccountRow / foldRow) reads patches.account_id and rebuilds PrototypeUser. Map: “the login door asks Auth who opened the page and Patches whether they may.” Serving reads through Patches, never the table.

Judgement — Feature Envy / Duplicated Code: foldRow copies PrototypeUsers.find SQL. Divergent Change: one 615-line module owns middleware, HTML, SQL, device login, sign-out. Device login (Pages.ts 129–131, device / deviceConfirm) is Auth’s term (packages/auth/CONTEXT.md), not the login door.

Serving guarantees

Hard. Door stamps every doored answer private, no-store (LoginDoor.prototype.ts 513–516), including version URLs. Serving CONTEXT: “URL-shaped caching stay as tier 0’s guarantees.” Pages.test.ts 114 / 136 now asserts that wipe.

UI (.agents/skills/ui-consistency/SKILL.md)

Door/outsider/device/not-configured compose htmlPage; user values go through escapeHtml / escapeAttribute. Hard: the same button (and input) treatment is inline, three times (LoginDoor.prototype.ts 202–206, 281–285) — padding, radius, border, shadow. Rule: durable chrome gets a named shared class in the shell; keep color at the call site.

No CLI surface. htmlPage export-only: no render.test.ts gap.

Effect conventions (detail)

ClerkSession.prototype.ts:99-127, 158, 219-228 — Hidden runtime / module globals. make mutates globalThis.fetch, ticks process-wide netCalls/fetchWrapped, and times with Date.now(). Those are not in the layer environment, so TestClock and a replaceable Fetch cannot see them. Fix: drop wrapFetch; time with Effect.timed; if call-counting stays, take Fetch/HttpClient from the environment.

ClerkSession.prototype.ts:76-79, 221-240 — Untyped swallow. authenticate is Effect<Verdict> with no error channel; tryPromise({ catch: (cause) => cause }).pipe(Effect.option) maps any throw to signed-out / authenticate-request-threw and drops cause. Fix: wrap as e.g. ClerkAuthenticateFailed({ cause }) (same shape as ClerkRevokeFailed). Either put it on authenticate’s error channel and Effect.catchTags in the door, or catchTags inside authenticate. Do not Effect.option an untyped cause.

LoginDoor.prototype.ts:347-373, 456-476, 493-497 — Second SQL owner. LoginDoor.make yields SqlClient and decodes prototype_users (foldRow) and patches.account_id (patchAccountRow) while PrototypeUsers already owns the user read and Patches.find already returns accountId. The door should only call those methods. DoorAuth without make/layer is fine (request-scoped, same as CurrentIdentity).

UI consistency (detail)

LoginDoor.prototype.ts:34-35 — door CSP drops the shell grain. htmlPage’s body::before noise is a data:image/svg+xml background. default-src 'none' with no img-src blocks that fetch, so door chrome will not match home/404. Wrapper form-action 'none' vs door form-action 'self' is the right split. Fix: add img-src data: to DOOR_CONTENT_SECURITY_POLICY.

202-206, 279-286 — duplicated button chrome as inline style. Sign out, Confirm, and Deny repeat the same ink border, radius, padding, shadow, and weight instead of a named shell class. Fix: add .btn (call-site background for green Confirm) and drop the copied button style=s.

228-245 (trigger 480-482) — outsider copy is the wrong wrong-person state. H1 is no-company; the lede says the account “is not part of the company this patch is shared in,” which confirms the patch exists. Glossary/product: same-company outside scope → owner + request access; other company / missing → 404 “no such patch”; no company → create or join. This page is none of those.

293-309, 542-551 — device done page asserts a grant that did not happen. POST only logs; the page says the machine “was confirmed.” Fix: copy that the prototype recorded the choice and minted nothing, or omit the completion page until the POST actually confirms.

513-515 — wrapper cache flattened. Every successful doored response, including renderPatchWrapper, is forced to private, no-store, wiping URL-shaped caching (max-age=60 / year immutable) that Serving still says stays after auth. Door chrome no-store is fine. Fix: leave servedPatchCacheControl on the wrapper (prefix private if needed); keep no-store on door pages only.


Spec

(a) Missing / partial

  • The answer itself. Spec: “Link the branch from this ticket; the answer is the resolution comment.” PR 127 claims “The findings are the resolution comment on The login door end to end on the development instance #119.” #119 has one comment (the seven questions). PR 127 is a cross-reference, not findings. Q1–Q5 and Q7’s live measurements (azp on/off, first-visit chain, handshake cost cold vs 60s, Domain on Set-Cookie, accepted redirect_url, next GET after sign-out) are unposted.

  • Seeded match, one read. Spec: “one database read matching the Clerk user to a seeded user row.” Seed never inserts prototype_users. First visit is find miss → createJustInTime INSERT → find again.

  • Q1 on and off. Spec: “Try the door with authorizedParties on and off.” clerkEnv always sets CLERK_AUTHORIZED_PARTIES. Offline sessions always carry azp. No off case.

  • Q7 next document request. Spec: “does the next document request land on the door with no handshake loop?” T5 expires cookies and revokes; it never GETs /d/* after. T8 shows leftover __clerk_handshake mints the session again.

  • Other-company / missing patch (named state). Product: “Signed in from a different company, or the link points at nothing: ‘no such patch’.” Only behind PROTOTYPE_R2_6 (default off). Default: any row is served.

(b) Scope creep

  • Fake device login. GET/POST /login/device shows a code, Confirm/Deny, logs, returns “Done.” No machine token. The login door end to end on the development instance #119 does not ask for this; product patchy login is a later door.

  • 403 outsider page for +outsider emails (“You are not in a company,” email in the body). Not a named state. Product: “Guests — a named outsider with a login — are not a thing Patchy does yet.”

  • R2-6 / +other → acct_other. Issue did not list a company-check experiment. Allowed as a probe of the named state, but extra surface and off by default.

(c) Implemented, wrong

  • JIT vs seeded (same spec line as (a)). T1 asserts the door created user_test, the opposite of a seeded match.

  • Outsider 403 vs “no such patch”. Product: different company or nothing “sees ‘no such patch’, confirming nothing.” Outsider page confirms the signed-in email at 403.

  • Q5 URL bridge. Spec: “Confirm the Frontend API gets a redirect_url it accepts when the URL is built from PATCHY_PUBLIC_BASE_URL instead.” Door builds publicUrl then copies request Host onto the Web Request. T2: handshake redirect_url is https://127.0.0.1:${port}/d/..., not https://patchy.example.


Intent (#119 vs what landed)

#119 was trying to lock the door’s design, not to ship one. The ticket: “Prove the riskiest assumption before the door’s design is locked” — Node/Effect, no ClerkJS, authenticateRequest in front of /d/<id>, Account Portal, handshake on a document request “under a script-free CSP, in a development instance,” and “one database read matching the Clerk user to a seeded user row.” “Throwaway branch, no tests, no polish. … the answer is the resolution comment.” Allison then listed seven facts primary sources could not settle; “the prototype’s answer should cover each.” That comment is still the only one. The issue is OPEN.

PR 127 shipped the lab, not the notebook. Eight commits, ~2.6k lines: route-scoped middleware (LoginDoor.prototype.ts), an Effect wrapper around @clerk/backend (ClerkSession.prototype.ts), JIT prototype_users (PrototypeUsers.prototype.ts), a 671-line Playwright driver, a 630-line offline suite, three experiment flags. The PR says “The findings are the resolution comment on #119.” They are not.

The seven questions

  1. azp. Door logs azp= (LoginDoor.prototype.ts:176). Tests mint azp themselves (testing.ts:92) with authorizedParties always on. Never tried FAPI on vs off.
  2. First visit / __clerk_db_jwt. Driver can watch hops. T6a proves a bare pk_test_ GET is dev-browser-missing. T9 comments “confirmed against the real instance” that FAPI returns ?__clerk_handshake=, not the query the ticket named. No hop table on the ticket.
  3. Network cost. [clerk-net] + net= exist. T2 shows format on the handshake URL. Cold vs 60s-window round trips are unmeasured unless --wait N ran off-repo.
  4. Cookie Domain. Fixture assumes __client_uat has Domain= and __session is host-only (testing.ts:154–155). Not a live header dump.
  5. URL bridge. Answered: door passes PATCHY_PUBLIC_BASE_URL, but T2 found the SDK rebuilds origin from Host, so the socket wins.
  6. redirect: "manual". T2 answers yes — the one assertion the throwaway was asked for.
  7. Sign-out. Route exists; T5 expires cookies offline; T8 found __clerk_handshake survives and replays. Live “no handshake loop” unproven.

The handshake was not recorded on #119 as a live run. The suite is an offline facsimile that signs its own JWTs. Matching a seeded user became JIT INSERT into acct_dev plus an optional second company read (PROTOTYPE_R2_6) — provisioning, not the one SELECT the ticket named.

The 630-line suite honors Q6 and buries one real finding (Q5). The rest — device pages, outsider, suffix-fix, production return-leg T8 — is a product-shaped door the ticket forbade, then offered for design review (“does the door’s shape hold up”) instead of writing answers. The missing resolution comment is the prototype missing its actual job.

Verdict: partially met. Biggest gap: no resolution comment, so the seven facts remain unwritten.


Method

The assumption being proven: a Node/Effect server with no ClerkJS can gate /d/* with @clerk/backend authenticateRequest, complete the Account Portal handshake on a document request under a script-free CSP, and match the Clerk user with one read.

The door’s skeleton is the right shape. Several things hung on that skeleton are experiments or conveniences, not the door.

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.

  1. +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.

  2. 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.

  3. R2-6 off by default. Any row opens any patch. Cross-company must be 404, not 200. Pages.test.ts publishes as acct_pages and JITs the reader into acct_dev, so the serving suite encodes that mismatch.

  4. Every /d/* doored, tests now require cookies, cache forced private, 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: ClerkSession hiding a process-wide fetch wrap, and Serving querying patches itself 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.

allisonmahmood and others added 2 commits September 3, 2026 10:49
…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]>
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reply to the reviews

Thanks 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:

  • 9d9cbef — the code corrections.
  • acd0d25 — the copy corrections.

Fixed

  1. The Request comment in ClerkSession.prototype.ts was false. It said the SDK builds the handshake's redirect_url from the public URL. It does not: deriveUrlFromHeaders rebuilds the origin from X-Forwarded-Host (else Host) and X-Forwarded-Proto and ignores the URL's host — which is exactly what T2 caught, and what grok's Q5 line and its "keep as lesson but rewrite" row say. The comment now states what actually happens and that the real door must pin host and the x-forwarded-* headers from publicBaseUrl as well as the URL. Behaviour unchanged; the prototype keeps the wrong answer visible with the right label on it.

  2. Sign-out now expires __clerk_handshake and __clerk_handshake_nonce (plain and suffixed, like the other families). This is the real defect T8 found and then asserted as if it were acceptable: nothing else clears the cookie, its payload is a standing __session directive, so a browser that kept it was signed in again on the next document GET. T8's replay assertion is flipped — the 303 expires the pair, and the GET after it is the door, not the patch. pnpm --filter @patchy/serving test is green.

  3. img-src data: added to DOOR_CONTENT_SECURITY_POLICY. grok's catch, and correct: default-src 'none' with no img-src blocks the shared shell's data: SVG grain, so door pages did not match home/404.

  4. Device done page no longer claims a grant that did not happen. It now says the prototype recorded the choice and minted nothing. (grok, UI detail 293-309.)

  5. Outsider page lede no longer mixes the no-company state with the wrong-company one. It now says the account is not in any company yet, and that the product's answer is create-or-join, which this prototype does not build. (grok, UI detail 228-245, and the same point in the tenancy section.)

Kept as is — deliberate experiments, each with a finding

Both 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.

  • Device confirm stub (GET/POST /login/device) — run for Device login: the protocol, and the machine token's columns #122's route question: does a query string survive the portal round trip, and how does a POST behave once the token has expired. Both answered. It was never meant to mint a token, and grok's own method table keeps the lesson ("the door wraps first-party chrome, not only /d/*", confirm-not-type).
  • Outsider page and the +other company switch (PROTOTYPE_R2_6) — run for The login door on a tier 0 page #120's wrong-person states. The finding is the one grok reached independently: other-company and missing must share one 404 in the handler that loaded the patch, and there is no refuse-to-serve state on a patch URL.
  • PROTOTYPE_DOOR_MODE (page vs redirect) — the person's round trip from pasted link to page, which is a question The login door end to end on the development instance #119 asks in so many words. Finding: page is the product.
  • PROTOTYPE_DOOR_SUFFIX_FIX — the SDK's refresh defect across cookie suffix families. Finding: mirror or pin, never a switch. The switch existed so the defect could be watched with it on and off.
  • Just-in-time user rows — this was how the "signed in but no company" state got reached at all, and it kept every test user out of the seed. Finding, stated plainly: JIT into the seed company is not the product path; a sign-in with no company lands on create-or-join.
  • The fetch wrapper and the [door] / [clerk-net] lines — "what does the door cost per page load" is one of the four things The login door end to end on the development instance #119 asks for. This is how the JWKS and BAPI calls were counted. grok's YAGNI section already reaches the same verdict: keep on the branch, never promote.
  • The offline test spike — The login door end to end on the development instance #119's own question 6 asked for one redirect: "manual" assertion, and The dev loop and tests with Clerk #124 asked whether sessions can be tested with a keypair through jwtKey. Both answered, and the suite is the cheapest freeze of the handshake answers. It is a spike for The dev loop and tests with Clerk #124's test story, not a permanent suite.

The runner forwarding only PROTOTYPE_DOOR_MODE is intentional: the other two switches are for hand-run servers.

Kept as is — throwaway code quality

All true, all deliberate on a branch that gets deleted. Fixing them would cost the branch its instrumentation without changing what anyone learns.

  • Effect diagnostics failing typecheck on ClerkSession.prototype.ts, console.log throughout, Date.now() instead of Clock, the untyped Effect.tryPromise(...).pipe(Effect.option) swallow, the process-wide netCalls counter, LoginDoor.prototype.ts at 615 lines owning middleware + HTML + SQL + device + sign-out, foldRow duplicating PrototypeUsers.find, and the inline button chrome repeated three times.
  • Sol's item 1 contains one real observation inside the JIT complaint: on a first visit the [door] line's dbMs reports only the first SELECT, while the visit actually does SELECT, INSERT, SELECT. Correct, and the log is staying as it is — the resolution comment states it, so nobody reads the number as the cost of one read.

Agreed as lessons for the real door — on #119

Not changes to this branch; these are the parts of the reviews that survive it.

  • grok's steal / do not steal table is largely right, and matches what the branch found: doored vs open route layers, middleware providing a per-request viewer tag, ClerkSession as Auth's fail-closed SDK seam, public URL and Host from publicBaseUrl, Set-Cookie only via response.cookies, 307 for handshake, sign-out as a same-origin POST with Domain on __client_uat — and now the handshake pair too.
  • Serving must not read patches itself. patchAccountRow / foldRow were an A/B on where the company check lives; the answer is that the door authenticates and the handler that already loaded the patch decides.
  • DoorAuth's payload is too wide. The right tag carries the viewer (user, company), not Clerk's wire state.
  • Auth must not know companies. User ↔ company is Companies' vocabulary; the prototype's PrototypeUsers join is a prototype convenience and does not travel.
  • The cache-control tension is a real open decision, not a prototype accident: a public cache cannot survive a cookie gate, so what private, no-store does to tier 0's URL-shaped caching is a product decision the real door still has to make. This branch should not be read as having made it.
  • Sol's tenancy points and grok's product-states section agree with each other and with the branch's own finding: cross-company and missing are the same 404, and gating all of /d/* is a different product question from "can a company patch have a door".

The resolution comment

Both 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.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Closing unmerged, as planned: this PR was the review vehicle for the #119 prototype. The branch prototype/login-door stays as the primary source, the resolution is on #119, and the lessons both reviews and the reply agreed on are folded into the questions on #120, #122 and #124.

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

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant