Skip to content

feat(serving): require sign-in to open company patches - #153

Merged
allisonmahmood merged 2 commits into
mainfrom
auth/140-login-door
Sep 6, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
auth/140-login-door

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Company patches could be read without signing in. They now use the same login door as /login: active colleagues can open them, and outsiders get the same 404 as a missing patch.

Admission happens before content is fetched. Company pages stay private and uncached, with a headless Clerk shell keeping the session fresh; public pages remain anonymously readable and cache for at most a minute on either URL shape. Includes HEAD handling and updated agent guidance.

Stacked on #150 (auth/146-invite-and-manage-users). This PR targets that branch, not main.

Closes #140.

Verification

  • pnpm test: 246 passed
  • pnpm typecheck and pnpm lint: passed
  • pnpm test:packed-cli-e2e: passed
  • Local dev browser: 401 door → one Sign in click → same patch with 200; reload after more than 90 seconds returned 200 without another handshake or sign-in
  • Both public URL shapes returned 200 with public, max-age=60
  • Standards and spec reviews: no open findings

Production handshake #128 remains deferred as specified. Temporary verification account and helpers were removed; the local instance was stopped.

Implemented with GPT-6 Astra (openai-codex/gpt-6-astra) in the Oh My Pi harness.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 5, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed ffbf46a8d7f039fbfc532cb5f5817b112f421497 against origin/auth/146-invite-and-manage-users (1c30c19987c194f443740eff28b490cb818a1fa1), using git diff origin/auth/146-invite-and-manage-users...HEAD, against issue #140. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

[P1] Intent: out-of-range version URLs reveal whether a company patch exists

packages/serving/src/Pages.ts:53–58

Issue #140 requires “the 401 shape identical for a missing and a foreign patch” and “A signed-in user of another company and a missing id produce identical 404 bodies and headers.”

The metadata lookup can fail before the handler applies admission. versionNumberOf accepts 2147483648, but patch_versions.version_number is a PostgreSQL INTEGER. Patches.find only queries the numbered version after finding the patch. An existing company patch therefore triggers integer overflow, converted here to a 500; a missing patch returns normally through the door.

Reproduced against the whole server on a real socket, requesting /d/<id>/v/2147483648:

Reader Existing company patch Missing patch
No session 500 401
Signed in to another company 500 404

The 500 also lacks the required Cache-Control: private, no-store. Versions 1 and 2147483647 preserve the expected indistinguishable responses.

Smallest fix: constrain the parsed version to the positive PostgreSQL integer range before calling find, and send out-of-range values through the existing invalid-version admission path. Keep a boundary regression covering both signed-out and foreign-company readers; do not blanket-catch database faults as missing patches.

Verification: six existing focused suites passed (65 tests: Serving pages/rendering, Auth pages/session, whole-server routes, and Content). A separate disposable real-socket reproduction failed the concealment assertion: expected 500 to equal 401; it also recorded the foreign-company 500/404 split. No repository source files changed.

Summary: Standards: 0 blockers. Spec: 1 blocker; worst: private-patch existence disclosure through version overflow.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of #153 against 1c30c199 (auth/146-invite-and-manage-users…ffbf46a), with extra passes on #140’s intent, the implementation method, and YAGNI.

Standards

No hard documented-standard violations. Namespace imports, catchTags, it.layer/it.effect, and the Content/Serving split match the specs. UI consistency holds: company wrappers load only escaped Clerk headless + /auth/session.js, public wrappers stay script-free, the iframe sandbox is unchanged, the door reuses /login.

Not violations (checked because they look like they might be):

  • Door.Admission without make (Door.ts). Request-scoped tag provided by HttpRouter.middleware, same as RequireSession.Viewer / SignedIn. The service conventions forbid a fake make = Effect.succeed(...) solely to force Layer.effect, not this.
  • sessionContentSecurityPolicy host interpolation. Host is Session.frontendApiHost, validated at boot. Same interpolation as page.ts. Not user-supplied.
  • clerk.headless.browser.js. Still the configured-host headless script; ui-consistency does not pin the filename.
  • Content.read(version). Matches serving CONTEXT.md: authorize metadata, then read bytes.

Baseline smells (judgement calls):

  • serving-headers.ts HEAD rewrite — type hole. HEAD rewritten via Object.create + as HttpServerRequest.HttpServerRequest. request.modify does not take method; fromWeb would drop the trusted-proxy-resolved address. Load-bearing; still the only as in the change. Mild Divergent Change: HEAD routing landed in the headers module because that is already the global middleware seam.
  • Door.ts / RequireSession.ts — Duplicated Code. The unenrolled 303 /join?return=… is copied. Extract next to resolveViewer.
  • Pages.ts servePatch — cookie threading. withCookies at four exits because public must not get session cookies. Handler orchestration of admission/find/read/visit is expected; a single doored wrapper would shrink the cascade.

Spec

Authoritative lines are from #140.

(a) Missing or partial

Handler does not decide the wrong-person states. Spec: “the door is route-scoped middleware … providing the viewer or nothing. The handler that loaded the patch decides: public serves as today; else no session is the 401 …; no user row is a 303 …; another company is the 404 …; a deactivated user gets the deactivated page.”

Door.Admission is Viewer | HttpServerResponse. Middleware already emits handshake 307, signed-out 401, unenrolled 303, deactivated 403, plus unasked 502/503. servePatch only special-cases public vs company-match 404 and otherwise forwards Door’s response.

HEAD is not fixed at the router. Spec: “Fix HEAD at the router for every route.” The only rewrite is in servingHeaders (global middleware, HEAD→GET via Object.create). No router HEAD registration. Behavior is tested; the site is not what the ticket named.

Nothing else from the Do / Done-when list is absent: two CSPs, cache-by-scope, no WWW-Authenticate, Auth door template, three wrong-person states + public path in memory and on a socket, 401 shape for signed-out missing/foreign, packed e2e doored / public parked, listed docs, handshake #128 not run.

(b) Scope creep

  • SessionClaims.name NullOr → "", plus the email-only serving test. Not in feat(serving): the login door on a tier 0 page #140. (Without it, a real colleague with an email-only Clerk account 401s.)
  • Door SessionError 502 / SqlError 503 pages. Spec’s signed-out answer is 401; these copy Auth’s first-party error pages.
  • clerk.headless.js → clerk.headless.browser.js in shared sessionScripts, so first-party /login changes too. Spec only: “the shell loads Clerk’s headless script from that host and nothing else.”

Cookie-free deleted-patch packed e2e moving 200/404 → 401 matches “every published patch fetched with no cookies answers 401” and “the 401 shape identical for a missing and a foreign patch.” Not creep.

(c) Specified but implemented wrong

Public still authenticates, and a live handshake is discarded. Spec: “A public patch serves exactly as today” and middleware provides “the viewer or nothing.” Door always runs authenticate and, if signed in, resolveViewer before Patches.find. Public 200s by discarding that result — including a successful handshake 307 and its Set-Cookie — then answering public, max-age=60 (Pages.ts 59–68, 114). Broken credentials are correctly ignored (tests pin “invalid credentials never challenge”). A successful handshake is not a challenge and should still be returned so cookies land on private, no-store, not on a cacheable document.

Until sharing lands this is latent: every live patch is company-scoped, so the door’s redirect_url is a company URL. The public path is built and tested in this PR, so the short-circuit is already the wrong shape.

401 vs 404 split itself is correct: signed-out missing/foreign → 401 door; signed-in other company / missing → identical 404. Do not treat the packed deleted 401 as a miss.

Intent vs #140

The product promise of #140 is the door in front of a tier 0 page: paste a company link, one Sign in at Clerk, land back on that URL; a signed-in colleague just gets the page; another company and a missing id are indistinguishable. Public stays today’s anonymous page. The patch never runs script; the host may know who opened a company page.

What shipped matches that promise on the response: 401 HTML door with one link and x-patchy-sign-in-url, no Location, no WWW-Authenticate; machine token ignored; foreign vs missing 404 match body+headers; no visit on refusal; two CSPs; sandbox=""; cache keyed to sharing; /login shares the renderer; skill / home / docs updated.

Two intent divergences:

  1. The ticket’s model was “middleware provides the viewer or nothing; the handler that loaded the patch decides.” The PR’s model is “middleware always authenticates and may already be a response; the handler keeps it unless the row is public.” Outcome-equivalent for company patches, not for public ones (handshake, Clerk hit, refreshClaims).
  2. “Public serves exactly as today” holds on the response (locked CSP, no script, no Set-Cookie, max-age=60 on both URLs). It does not hold on the request: every /d/* authenticates before the handler knows the scope.

The door is a moment on the way to the patch, not a destination: the patch URL itself is the 401; redirect_url is that path; the served page has no chrome. The patch cannot watch you is honored (sandbox, no patch script). Nobody knows you were here is correctly not promised for company pages.

Method

The method is sound. It copies the prototype’s shape (two HttpRouter.use layers, door provided only to /d/*) and not its files.

Admission = Viewer | Response is the smallest model that actually works. Wrapping servePatch in withViewer would 401 signed-out readers of public patches. The door must compute identity and let the handler keep or drop it once Patches.find knows scope. Handshake / 401 / 303 / 403 don’t need the patch; only public vs 404 vs 200 does. Always authenticating /d/* is the issue 117 §5 / 120 tradeoff: public pays a Clerk hit, then ignores a refusal and strips cookies.

Splitting Content.read is the right domain cut. Serving never talks to the store. Patches.find → admit → Content.read(version) is exactly “metadata authorized before Content reads HTML.” Without the split, a private object miss 500s and leaks that the row existed. The storage-fault test is the proof.

HEAD via Object.create is a justified hack at the right moment (wildcard /* ate find-my-way’s HEAD→GET fallback; global rewrite before match; adapter still suppresses the body) and the wrong file. It does not belong in serving-headers.ts. A sibling middleware would be cleaner. Not a door concern.

Extracting RequireSession.admission is the right share with first-party pages. Cookie threading is honest: applying cookies in middleware would Set-Cookie public 200s and break ADR-0006. { provides: Admission } is typed Effect HTTP middleware, not a fake service.

The one method bug is the public short-circuit treating handshake as just another admission response. Handshake is completing sign-in, not refusing it. Return 307 + cookies regardless of scope; only skip 401 / 303 / 403 when isPublic.

YAGNI

Mostly beautiful YAGNI.

Credit: Content.read is store.get after the handler authorized; Served and find+get are gone. Cache follows scope, not URL shape; the year-immutable version header is gone. RequireSession.admission is the second-consumer extract withSession needed. Invalid /v/x mapping to none so signed-out missing and junk versions are both 401 (existence).

Keep (real constraints): HEAD→GET, handshake query strip, referrer overlay so /logout Origin is not null, Door 502/503 copying Auth’s error pages.

Door.Admission as a request-scoped {result, cookies} tag is that slot, not a new capability — no make, one handler. Leave it.

SessionClaims.name NullOr is necessary Clerk behavior, not speculative. SchemaGetter.transform is heavier than ?? "" at the decode site — judgement on API, not on the behavior.

The second if (Option.isNone(served)) after the !isPublic block is runtime-dead and exists for TypeScript narrowing of served.value. Don’t delete it without restructuring; a find then scope branch would make the same fact obvious.

Duplicated join-303: ~15 lines. Live with it or one Auth helper that returns {result, cookies}. Do not add a third wrapper.

Tests match what #140 asked (memory + socket, two CSPs, cache-by-scope, identical 401, HEAD). Storage-fault and nameless-session are existence/Clerk, not smoke.

Surfaces

Hit-every-surface is mostly done: CONTEXT.md / CONTEXT-MAP / product.md / ADR-0006 / skill + skills-lock.json hash / cli README / DEVELOPMENT.md / patchy-dev-loop / ui-consistency / packed e2e / home copy. Wire contract N/A (/d/* is not HttpApi). Migrations N/A. Reverse state already exists (POST /logout).

Small leftovers, not #140 blockers:

  • packages/serving/src/serving-headers.ts NO_REFERRER_POLICY comment still says “An unlisted page's URL is the only thing keeping it unlisted.”
  • examples/plan.html still describes “a public, unlisted review URL” / “Anyone with the link…”. The ticket asked the home page to stop describing public hosting (renderHome did); this sample artifact did not.

Summary

  • Standards: 0 hard violations, 3 judgement-call smells. Worst: HEAD rewrite via Object.create + as living in serving-headers.ts.
  • Spec: 2 partial, 3 creep, 1 wrong. Worst: public short-circuit discards a live Clerk handshake (and its cookies) onto a public, max-age=60 response.

Reviewed with Grok 4.6.

@allisonmahmood

allisonmahmood commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed both reviews in 8778407 (fix(serving): close version leaks and preserve sign-in returns).

Fixed

  • Astra P1 — version overflow reveals existence: constrain URL versions to the positive PostgreSQL INTEGER range before Patches.find. Out-of-range values follow the existing invalid-version admission path; real database faults are not caught as missing patches. The socket regression checks signed-out 401s, byte-identical foreign/missing 404s and headers, private, no-store, and that version 2147483647 still serves an authorized reader. It failed with 500 != 401 before the fix.
  • Grok — a public destination drops a completed handshake: Session now distinguishes a verified handshake return from handshake initiation. Serving preserves the completed 307 and its cookies on an uncached response, then serves the public document with public, max-age=60 and no cookies. A real-socket regression drives both URL shapes through that hop and uses the resulting cookie to open a company patch. It failed with 200 != 307 before the fix. A cold public read still returns 200 without a redirect or cookies; forwarding every 307 would incorrectly make public access depend on Clerk.
  • Stale referrer comment: corrected it to distinguish URL disclosure from sharing-scope access control.

Kept, with reasons

  • Admission model and eager identity resolution: Door.Admission remains request-scoped Viewer | Response; the middleware computes a candidate response, not an early response sent to the reader. The metadata-owning handler still decides whether admission applies. This preserves public access and reuses Auth's handshake/refusal rendering without introducing a second state machine. The two doored route registrations, optional admission, and public authentication work remain the existing design tradeoff. No fake make is needed for a request-scoped tag.
  • HEAD normalization in the global router middleware: it runs before route lookup and fixes every route, including those masked by the wildcard. The prototype-preserving request override retains the proxy-resolved address; modify cannot replace method. Moving it to a sibling file would not change behavior and would add wiring solely for this organizational preference.
  • Explicit cookie exits and final Option guard: public documents must not inherit session cookies; keeping that decision visible is preferable to another wrapper. The final guard retains TypeScript narrowing. Repeated join redirect: the small duplication does not justify another Auth abstraction in this fix.
  • Nullable Clerk names and the browser headless bundle: both stay. The original live verification found that email-only accounts were rejected and the previous bundle did not initialize window.Clerk.load; these are prerequisites for the requested working sign-in/session-refresh flow, not speculative features. The configured host and CSP remain validated and restricted.
  • 502/503 admission pages: these represent authentication/company-service failures, not signed-out users. They reuse Auth's failure behavior rather than misreport an outage as invalid credentials.
  • examples/plan.html: left unchanged as a sample uploaded artifact, outside the serving homepage and product-contract copy requested by feat(serving): the login door on a tier 0 page #140. Its old public-hosting narrative is not the server's access policy; changing this sample is non-blocking and outside these behavioral fixes.
  • The reviews' other checked non-issues remain unchanged: validated CSP host interpolation, metadata-before-content authorization, and the cookie-free deleted-patch 401 contract.

Verification

Latest commit 8778407358ebc06ab54d2088ce723a474916d0b1: all six configured checks passed. CI run: test (22), test (24), lint (format/lint/typecheck), cli-smoke, and dependency-review; PR labels: label. The stacked base has no enforced required status checks. GitHub reports MERGEABLE / CLEAN, with no unresolved review threads or new findings. No unresolved merge blockers; ready to merge into auth/146-invite-and-manage-users. Not merged by this task.

Review remediation by GPT-6 Astra in Oh My Pi.

@vsrikar08

Copy link
Copy Markdown
Collaborator
  1. it asks for signing in before publising a patch. Like tf why. We don't need multiple of these.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

@vsrikar08 Following up on your sign-in comment: Allison will walk through the experience personally before deciding on a change.

This PR adds the sign-in door for reading company patches. Publishing uses the CLI's saved machine token after login; it should not require signing in for every publish. The comment doesn't yet establish which step is repeating, so this remains an investigation, with no implementation change requested yet.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

@vsrikar08 what do you mean it asks for signin

patchy cloud is for companies. we don't allow anonymous uploads. once you are signed in once you are fine

@allisonmahmood
allisonmahmood force-pushed the auth/146-invite-and-manage-users branch from e64e93a to 59dfead Compare September 6, 2026 12:51
Base automatically changed from auth/146-invite-and-manage-users to main September 6, 2026 12:54
@allisonmahmood
allisonmahmood merged commit 58e6d9c into main Sep 6, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the auth/140-login-door branch September 6, 2026 12:58
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:cli Touches the cli area area:docs Touches the docs area 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.

feat(serving): the login door on a tier 0 page

2 participants