Skip to content

feat(auth): sign in with Clerk and create or join a company - #149

Merged
allisonmahmood merged 4 commits into
mainfrom
auth/138-clerk-sign-in-create-company
Sep 6, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
auth/138-clerk-sign-in-create-company

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

People had no browser sign-in flow or way to create or join their company after signing in.

Adds Clerk sign-in, create-or-join, and sign-out using plain server-rendered forms. Sessions are verified server-side, first-party posts enforce same-origin requests, and the shared page shell keeps Clerk sessions refreshed. Includes offline authentication coverage and development setup guidance.

Stacked on #148 (auth/137-companies-users-machine-tokens); this PR targets that branch and contains only the follow-on browser-auth changes. Merge the parent first.

Fixes #138.

Verification: pnpm typecheck, pnpm lint, and pnpm test pass (213 tests across 31 files). Standards and Spec review findings are resolved. Live Google sign-in has not been exercised; authentication coverage uses offline Clerk fixtures.

Built with OpenAI GPT-6 Astra using 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:core Touches the core 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 d983b561c1d32e8266dbc934653b3d36e54c1adf against origin/auth/137-companies-users-machine-tokens (e802c3f915af505cb52d5613c1bc13b3903d4154), using the three-dot diff and issue #138. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

Intent — block: return-path normalization permits an off-site redirect

packages/auth/src/page.ts:18–28

Issue #138 requires the “validated return”; its parent spec §7 confines this to “a same-origin path.” The helper rejects // before URL normalization, but returns the normalized pathname without checking it again. return=/.//attacker.invalid passes the initial checks; new URL(value, base) retains the local origin while normalizing its pathname to //attacker.invalid. Returning that string loses the origin guarantee.

The next URL construction in signInUrl interprets it as an authority, so /login emits redirect_url=https://attacker.invalid/. The existing-member /join path also passes it directly to the 303 redirect (caller), without relying on Clerk accepting the destination.

Fix: validate the normalized output before returning it—at minimum reject a pathname beginning //—and retain a focused regression for dot-segment normalization. The downstream redirect must remain on the configured origin.

Reproduced with the production helpers: /.//attacker.invalid, /safe/..//attacker.invalid, and /%2e//attacker.invalid all returned //attacker.invalid and generated the off-site Account Portal return URL.

Verification: 52 tests passed across 6 focused files (Session, in-memory and socket AuthPages, startup configuration, developer environment, and Serving rendering). The normalization reproducer also completed successfully and demonstrated the bypass; no live Clerk account was used.

Summary: Standards: 0 blockers. Spec: 1 blocker; the same-origin return-path guarantee is bypassable.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of PR 149 (auth/138-clerk-sign-in-create-company vs origin/auth/137-companies-users-machine-tokens, HEAD d983b56). Extra passes for issue #138 intent, implementation method, and YAGNI, as requested. Seven review agents ran in parallel so the axes would not pollute each other.

Commits: e5bc70a feat, 55a87a0 disable Clerk telemetry, d983b56 session/enrollment review fixes.


Standards

No hard documented-standard breaches. Session follows the service file order (errors → tag → make → layer), acquires config with yield*, uses catchTags at callers, and tests go through it.layer / NodeHttpServer.layerTest with alternate layers. Auth pages compose htmlPage; the patch wrapper stays separate; Clerk JS is external with telemetry off (ADR-0006 / ui-consistency). Create-or-join stays on Patchy tables (ADR-0007). CONTEXT-MAP, glossaries, and the shell move to core were updated.

Documented standards

None that need a change. Tooling already covers namespace imports, inline Schema compiles, and manual test runtimes.

Baseline smells (judgement)

Feature Envy — packages/companies/src/Join.ts (handle, ~95–110). Companies owns the page (CONTEXT), but handle yields HttpServerRequest for method and urlParamsBody instead of taking a parsed form from Auth. AuthPages already has the request and only maps redirect / sign-out around the result.

export const handle = Effect.fn("Join.handle")(function* (
  claims: Claims,
  membership: { readonly company: { readonly name: string } } | null,
  returnTo: string | null
) {
  const request = yield* HttpServerRequest.HttpServerRequest;
  if (membership) { /* ... */ }
  if (request.method !== "POST") return yield* render(claims, returnTo);
  const fields = Object.fromEntries(yield* request.urlParamsBody);

Smallest fix: AuthPages reads method/body; Join.handle stays domain + HTML.

Divergent Change — packages/auth/src/RequireSession.ts (resolveViewer, ~114–136). One helper returns Viewer | null | HttpServerResponse (deactivated HTML). withViewer / forEnrollment both special-case isHttpServerResponse. Admission is mixed with page rendering.

Smallest fix: return a deactivated marker; let the middleware call pageResponse.

Duplicated Code — the localRevocation stub (Session.make then revoke: () => Effect.void) is copied in AuthPages.test.ts (~291–297) and AuthPages.socket.test.ts (~21–27). Hoist next to the other Clerk test seams in testing.ts.

Effect service conventions (separate pass)

packages/auth/src/Session.ts:101, 111, 123–132 — make throws new Error(...) inside Effect.try only so catch can fill required SessionError.cause ("Missing publishable key terminator", "Clerk key environments differ", "Expected a public PEM", "Unsupported Clerk RSA key"). Rule: do not manufacture an Error merely to populate cause; validation errors with no underlying failure do not need one. Expected: yield* new SessionError({ operation: "configuration", setting }) at those checks; keep cause only when wrapping atob / decodeFrontendHost / decodeSecretKey / createPublicKey; make cause optional.

Near-misses (judgement-call):

  • Session.ts:14–23 — One SessionError with operation plus a message branch on setting vs ${operation}. Allowed as a multi-value operation error; configuration vs authenticate/revoke could still be separate classes.
  • RequireSession.ts:34, 45 — signInUrl / door take Session.Session["Service"] but only read origin/host/key. Pass those fields (or SessionShell) rather than the service instance.
  • auth/src/index.ts:8 — export { Viewer } beside export * as RequireSession. Unused; callers should use RequireSession.Viewer.
  • RequireSession.ts:144–159 — withViewer / Viewer have no production page consumer (test probe only).
  • Join.ts:100–110 — companies module yields HttpServerRequest instead of taking parsed method/form from Auth.
  • Session.ts:211–218 — handshake recovery inspects Effect.result _tag instead of Effect.catchTags({ SessionError: ... }).

UI consistency (separate pass)

No UI consistency findings.


Spec

Primary spec: issue #138. Parent spec this ticket implements: #135 §7 (session/door), §8 (pages), §11 (dev loop/tests). Ticket 138 says no /d/* yet; /login return defaults to /join until Your machines exists.

(a) Missing or partial

  • Live Google sign-in was not done. Ticket Done when: “On a pnpm dev instance with dev.env keys: /join signed out answers 401 with the door; after a Google sign-in with PATCHY_DEV_CLERK_USER_ID set, /join says the developer is in Patchy Dev; without it, /join creates a company and the next /join says so.” PR body: “Live Google sign-in has not been exercised; authentication coverage uses offline Clerk fixtures.” Offline tests cover the analogous hops; the live acceptance criterion is unmet.

(b) Scope creep

None material. Extra 400/502/503 pages and Clerk telemetry off are defensive, not new product surface. /auth/session.js is how the doored shell loads Clerk with “no inline script”.

(c) Implemented but wrong

None of the checked paths look wrong:

  • Handshake rebuilds the response with only Location + Set-Cookie (307); tests assert x-clerk-auth-* and Access-Control-* stay off. Signed-out handshake returns Sign-in could not complete and logs reason, no Location follow.
  • signOutCookies() expires every constants.Cookies name (and suffix) at Path=/, plus ClientUat/Handshake/HandshakeNonce on hostname suffixes — the setter scopes the tests model. Logout jar is empty with no user row.
  • First-party POST: 403 on foreign or missing Origin (ticket 138). Sec-Fetch-Site: same-origin is not accepted; that matches 138, not parent §7’s parenthetical.
  • Viewer comes from Users.refreshClaims (update then findByClerkId); email/name refresh is tested.
  • Create and consume each run in one transaction with the user row. Refusals: already in a company, handle taken, reserved, malformed.
  • Already in a company: GET with a non-/join return → 303; bare /join → You are in <Company>; POST → 409.
  • Fetch guard on @patchy/auth/testing import; test/setup.ts asserts no recorded request. Packed e2e starts with clerkEnv() fake keys. Seed stays a separate entry.
  • Startup Config requires DATABASE_URL, PATCHY_PUBLIC_BASE_URL, CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY and names the missing one before listen.

Intent (issue #138)

Issue intent in one sentence: “A person signs in and lands in a company.”

The product is real, not just Session plumbing. Signed-out /join is a 401 door with one Account Portal Sign in link; handshake, create-or-join, and POST /logout work. After create, or with PATCHY_DEV_CLERK_USER_ID, the person is a company member.

They do not land in a company as a place to work. They land on /join's "You are in <Company>" line. That is the ticket's own stand-in: "/join for a person already in a company sends them to their return or /join's own "you are in <Company>" line until /company exists." RequireSession.withViewer exists, but no production route uses it (only a test probe). Membership is true; a company surface is not.

Slice boundaries honored ("No /d/* route changes yet; the company page and invitations are the next ticket."):

  • Serving /d/* routes untouched; render.ts only moved the shell to core.
  • No /company, no /machines. Login return defaults to /join.
  • Invite consume on /join is in this ticket. No admin invite-send UI.
  • Sign-out from create-or-join and deactivated, including no user row.

Still "plain server-rendered forms, Clerk holds the session." Extra, not a different product: /auth/session.js, 400/502/503 retry pages, Clerk telemetry off. CSRF is Origin-only (ticket), stricter than spec §7's Sec-Fetch-Site alternative.

PR body is honest about live Google. Docs describe that path as how to use pnpm dev, not as verified. Offline tests cover door, create, membership line, sign-out, fetch guard, missing-env naming.

For a person: one Sign in link, a name/handle form, Not you? Sign out. After success, a sentence and no next action — fine for this slice. For pnpm dev: keys, seed override, and /join landing are in docs/DEVELOPMENT.md and patchy-dev-loop. Agents still publish with the seeded machine token.


Method

The method is the smallest model that keeps Clerk as the session and Patchy as the company. It copies the prototype’s seam, then drops the prototype’s half-up state and instrumentation.

Session is a thin adapter, not a second session. Wraps authenticateRequest / revokeSession and answers signed-in / signed-out / handshake. No Patchy cookie, no sessions table — ADR-0006. Rebuilding the Request from PATCHY_PUBLIC_BASE_URL and pinning host / x-forwarded-* (Session.ts:188–207) is the right seam. Stripping inbound authorization and forwarded headers, then forwarding only Location + Set-Cookie, is honest handshake plumbing. Cookie expiry from SDK constants.Cookies plus suffix and parent-domain candidates is Clerk’s cookie model.

Middleware, not per-route checks. Handshake, door, claim refresh, and deactivation are shared admission. withSession / forEnrollment / withViewer match three real states (logout before a user row; join with optional membership; ordinary Viewer). Extra ceremony: Enrollment is a Viewer | null service for one consumer, and resolveViewer returns HttpServerResponse | Viewer | null — mixed control flow, still smaller than three route copies.

Join belongs in companies. ADR-0007: membership is transactional beside the company. Companies.create / consumeInvite already own sql.withTransaction; Join.handle maps those refusals onto the page. Auth only supplies claims. The leak: Join.ts reads HttpServerRequest. AuthPages should parse the POST; Companies should stay HTTP-free.

htmlPage in core is earned; auth CSS is not. Serving and auth are two consumers, so the shell leaves render.ts. Auth-card rules in core/src/html.ts:359–401 are premature — Join.styles already injects page-local CSS. Home/404 now ship unused auth chrome.

Testing seam is right. RSA-2048 + CLERK_JWT_KEY exercises the real verifier offline. Fetch guard on import, not a mock Session. Socket hops by hand is the honest handshake test. The guard reimplements redirect following because native fetch would bypass it — heavy, but the constraint is real.

Origin CSRF matches SameSite=None. Clerk session cookies are None. A CSRF token would be a second secret beside Clerk’s cookie. referrer-policy: same-origin keeps browsers sending Origin on form POSTs.

None of the extra indirection invents a Patchy session. The one method that would be more honest: keep Join’s HTML in companies, move form parsing to AuthPages.


YAGNI

Simple, keep it. One htmlPage, one pageResponse (card wrap, no-store, doored CSP, Clerk <head>). Serving home/404 still call htmlPage; the patch wrapper stays its own document. returnPath, signOutForm, sameOrigin, and /auth/session.js are tiny. Join.handle is one GET/POST with catchTags back onto the same form. Session is the ticket’s three calls; boot schemas fail before Postgres; withCookies is ugly for a real reason (duplicate Domain/Path names). No /d/*. withViewer is specified and only probed in tests.

Shell grew

The moved tokens/layout match Serving’s old htmlPage. Growth is head/styles (used) plus ~45 lines of auth CSS that home/404 now ship unused. pageResponse already injects styles; that CSS belongs there with Join.styles, not in core. :disabled has no disabled control.

body:has(.auth-card) { min-height: 100vh; display: flow-root; }
.auth-card { ... }
.auth-action:disabled { opacity: .6; cursor: not-allowed; }

Dead surface

door sets x-patchy-sign-in-url. Not in #138, not asserted, nobody reads it. Parent spec §7 does ask for “the sign-in URL in a header” on the /d/* door this ticket is not building yet — so this is either a one-line gift to #140 or unused API. Enrollment is a Service whose comment admits one consumer. export { Viewer } duplicates RequireSession.Viewer with no production importer.

Test slop

The fetch guard was required. The 70-line WHATWG redirect replay plus the execFile subprocess that only tests the fixture was not. Socket logout/origin overlaps the in-memory suite.

Not flagged: keypair fixture, Origin check, cookie Domain/Path, handshake filtering, boot required-four, handshake-failed door.


Standards: 3 judgement smells, 1 Effect convention finding, 0 UI findings — worst: manufactured Error objects to fill SessionError.cause (Session.ts boot checks).
Spec: 1 missing (live Google Done-when), 0 creep, 0 wrong — worst: live Google sign-in not exercised (code looks complete; verification is not).

@allisonmahmood

allisonmahmood commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner Author

Reviewed both agent comments against the source. Pushed fixes in 1d02ee9.

Fixed

  • Normalized-return open redirect: reject normalized pathnames beginning //, not just raw input. Regression coverage drives both the Account Portal link and an existing member’s direct /join redirect. Both regressions failed before the fix and pass afterward. A real local-server request with /%2e//attacker.invalid/ now produces the local /join destination.
  • Manufactured configuration-error causes: validation now yields SessionError directly, without invented exceptions. cause is optional for those failures; actual base64, schema-decoding, and createPublicKey failures retain their immediate causes. Existing boot rejection tests still pass.
  • Frozen-lockfile failure: ran pnpm install, corrected Auth’s @effect/platform-node importer specifier to the workspace override’s resolved 4.0.0-rc.112, and verified pnpm install --frozen-lockfile passes. Normal installation alone reused local state without repairing that entry.
  • Unused surface: removed the duplicate top-level Viewer export and the unused .auth-action:disabled rule. RequireSession.Viewer remains the canonical export.

Kept as is

  • Join’s HTTP parsing: Join.ts is the Companies-owned page adapter, not the domain service. Keeping form parsing, validation and rendering together avoids teaching Auth the company form contract; business transactions remain in Companies.
  • resolveViewer response union: this private helper belongs to HTTP middleware. Returning the terminal deactivation response lets both admission paths share one rendering decision; a new marker would add translation without fixing behavior.
  • Local revocation fixtures: the short alternate layers explicitly replace only the external revocation capability in each suite. Hoisting them into the otherwise lightweight RSA/fetch fixture would couple that fixture to production service construction for little gain.
  • SessionError operation model and configuration arguments to door helpers: current error operations preserve their messages and callers handle one tag. The helpers only read configuration, not service methods; splitting errors or narrowing these parameters is optional cleanup, not a correctness repair.
  • Viewer, withViewer, and Enrollment: ordinary Viewer admission is explicitly required by feat(auth): sign in with Clerk and create a company #138 even before a production company page consumes it. Enrollment is request-scoped optional membership, not a new runtime capability or layer.
  • Handshake Effect.result: the two outcomes explicitly distinguish a recoverable returning-handshake failure from a normal authentication error. Replacing this with a null marker and tag catch would not simplify that decision.
  • Remaining shared auth CSS: card/action/email/sign-out rules serve login, enrollment, deactivation and error pages; Join-only fields and invitation styling already live in Join.styles. Home/404 carrying a small unused shared style block is not a merge-blocking defect. Removed the genuinely unused disabled rule.
  • Sign-in URL header: the shared door’s header is explicitly requested by parent Auth: Clerk, companies and machine tokens on tier 0 #135 §7; retaining it does not introduce any /d/* route changes.
  • Redirect guard and socket coverage: validating only the initial fetch URL would let native redirect following escape the offline guard. The subprocess isolates deliberate blocked requests from the suite’s zero-external-request assertion. Socket tests exercise actual cookie serialization/manual hops; in-memory tests cover admission, deactivation and refusal behavior, so the overlap protects different boundaries.

Verification and remaining acceptance blocker

  • Local pnpm install --frozen-lockfile, typecheck, lint and formatting pass. Full suite: 213 tests across 31 files. Final focused auth/session/render run: 44 tests passed.
  • Latest CI run passed on 1d02ee9: test (22), test (24), lint (format/lint/typecheck), cli-smoke (lifecycle probes and packed CLI against a real server), and dependency-review. The separate label check also passed. Frozen installation passed in all four install jobs. GitHub reports MERGEABLE / CLEAN; it reports no explicitly required checks for this stacked base, and all six available checks are green. Dependency review emitted non-blocking OpenSSF score advisories for three transitive packages.
  • Live Google acceptance remains blocked: using the configured Clerk development keys, the real isolated pnpm dev instance reached Clerk’s Account Portal and then Google’s Email or phone screen. Completing this requires an interactive Google login; no authenticated Google session was available. Therefore neither the seeded-developer membership nor unseeded create-company Google scenario is claimed as verified. Shared developer configuration was not changed; the temporary instance was stopped and removed.
  • This PR remains stacked on feat(companies): make patches belong to users, not tokens #148; preserve the stated parent-first merge order. I have not merged either PR.

@allisonmahmood allisonmahmood linked an issue Sep 5, 2026 that may be closed by this pull request
5 tasks
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Visual reference for the first-party pages this stack introduces.

Both pages are public but unlisted.

@vsrikar08

Copy link
Copy Markdown
Collaborator

bit of a weird caveat. Company emails change and we don't want to be blocking someone because of that so have the ability for an admin to change that shit or something. fringe case scenario and we dont really need it right now.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

@vsrikar08 Following up on your email-change concern: existing membership is keyed by the stable Clerk user ID, and the local email/name refresh from verified claims when the user returns. An email change on that same Clerk account therefore doesn't itself require rejoining the company.

A separate admin-driven identity migration or company-domain management flow is outside this PR. No additional change requested here.

@allisonmahmood
allisonmahmood force-pushed the auth/137-companies-users-machine-tokens branch from e802c3f to ffe36ca Compare September 6, 2026 12:44
Base automatically changed from auth/137-companies-users-machine-tokens to main September 6, 2026 12:47
@allisonmahmood
allisonmahmood force-pushed the auth/138-clerk-sign-in-create-company branch from 1d02ee9 to 266e5ce Compare September 6, 2026 12:47
@allisonmahmood
allisonmahmood merged commit f83f9d7 into main Sep 6, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the auth/138-clerk-sign-in-create-company branch September 6, 2026 12:51
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:core Touches the core 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(auth): sign in with Clerk and create a company

2 participants