Skip to content

ci: verify browser sign-in and CLI login with Clerk - #159

Merged
allisonmahmood merged 3 commits into
mainfrom
auth/144-playwright-specs
Sep 6, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
auth/144-playwright-specs

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

The live Clerk tier did not exercise the Account Portal login door or a browser-confirmed patchy login end to end.

Add serial Playwright specs for both workflows against an isolated, seeded server and the packed CLI. Cover session renewal, cross-company refusal, machine revocation and run-scoped Clerk cleanup. Run them through pnpm test:clerk and the gated clerk-live job, with local headed-run instructions.

Stacked on #158 (auth/143-live-clerk-vitest-tier); this PR targets that branch, not main.

Closes #144.

Validation: combined live tier passed locally (2 Vitest tests and both browser specs), final device-login spec passed after review, and cleanup verified zero run-scoped users. All 322 offline tests, typechecking, lint and formatting passed. Standards and spec reviews completed; the 401 assertion finding was fixed. CI results for this PR are pending.

Implemented with OpenAI 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: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 f8839efa...b08366a7 (origin/auth/143-live-clerk-vitest-tier...HEAD) against issue #144. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings. The test-only harness supports the requested checkout server, isolated seed, packed CLI and resource teardown. I would not require an abstraction or idiomatic rewrite before merging.

Spec

No merge-blocking intent findings. Both workflows cover the requested portal handshake, expired-token reload, cross-company refusal, browser-confirmed CLI login and browser revocation. Testing Tokens, serial sign-ins, run-scoped cleanup, CI wiring and headed local-run instructions are present.

Surfaces checked: test runner/dev-loop documentation and CI; no production wire contract, CLI behavior, migrations or rendered-page behavior changed.

Evidence

  • The clerk-live job tested the reviewed head against the specified base: both Vitest tests and both browser specs passed. The runner's final sweep and the separate always() sweep each reported zero run-scoped users.
  • Local playwright test --config playwright.clerk.config.ts --list discovered exactly two tests in two files using placeholder credentials. I did not rerun the live developer-application workflows; their local success is reported in the PR description, not independently verified by this review.

Summary: Standards 0 blockers; Spec 0 blockers. No worst issue on either axis.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 159 vs issue 144

Pinned against auth/143-live-clerk-vitest-tier (f8839efa...b08366a). Two commits. clerk-live is green on this HEAD (~2m48s).

This review is two separate axes (Standards vs Spec) plus the extra questions asked of it: issue 144's intent, the implementation method, and whether the code is the smallest model that makes the behavior unsurprising.


Spec

Spec-axis review, PR 159 vs issue 144. clerk-live on HEAD b08366a is green (including the always() sweep). Local developer-instance pass was not re-run here.

(a) Missing / partial

None of the specified workflows are absent. Wiring matches the ticket: two Playwright files, serial one-worker run, checkout server with CLERK_AUTHORIZED_PARTIES = origin, Backend-API +clerk_test user then applyDevSeed(…, clerkUserId), company patch as DEV_SEED.token, Testing Token on FAPI /v1/, page-driven (not context.request), Chrome UA, code retype, pnpm test:clerk + clerk-live, DEVELOPMENT.md names both specs and --headed.

The signed-out 401, handshake, and first shell render live only in openSeededPatch when page.url() === "about:blank". Spec assigns them to login-door. A full default-order run still executes them; they are not re-asserted inside login-door.spec.ts itself.

(b) Scope creep

Spec: “be refused the seeded company's patch with the 404 a missing id gets.” After that 404, login-door also requires GET /company 200 and heading “Browser outsider company.”

Spec: “open the verificationUrl, confirm with a machine name.” patchy-login also requires the confirm page to show userCode, the browser email, and “Patchy Dev.”

(c) Looks implemented, looks wrong

Spec: “a reload after the token expires is not a sign-in.” The test decodes __session and fails if remaining TTL ≥ 90s, then sleeps exp+6s. That is stricter than the spec; a longer Clerk session-token TTL would fail the spec run even if reload-without-sign-in worked.

Spec: “revoke on /machines makes the next whoami a 401.” The spec asserts CLI exit 2 and wire error Missing or invalid API token. (the CLI’s 401 mapping), not an HTTP 401. That matches ADR-0004; it is not a missing 401.

No other specified login-door / patchy-login / sweep / CI-app isolation behavior looks unimplemented.


Standards

No documented-standard violations.

Effect (effect-service-conventions/SKILL.md, CLAUDE.md): no new service/layer. Effect.runPromise is at the scripts/test-clerk.ts runner and the Playwright worker fixture — harness boundaries, not domain make. Namespace imports are correct; liveClient / sweep / liveSettings are helpers, not make/layer. Schema compilers sit at module scope.

ESLint: process.env allowlist on playwright.clerk.config.ts, test/browser/fixtures.ts, test/browser/instance.ts matches the existing “test entrypoints configure workers and child processes” comment. Specs are not .test.ts Effect suites; they do not call Effect.run*. Skip the rest — tooling holds it.

Surfaces: docs/DEVELOPMENT.md and ci.yml (pnpm test:clerk) cover the new browser tier. Seed comment matches applyDevSeed(…, clerkUserId). Vitest Postgres template stays default (browser uses the real server migrator). CLI/API/skill docs are untouched because the CLI did not change; patchy-login.spec.ts asserts ADR-0004 (--json, exit 2, empty stdout, kind: "rejected"). Sweep now deletes all three run emails (way out). Offline pnpm test does not pick up *.spec.ts.

Judgement-call smells (not defects; repo harness shape wins):

Duplicated Code — test/browser/instance.ts vs scripts/packed-cli-e2e.mjs / test/postgres.ts: pack CLI, embed Postgres (dynamic import, strip async-exit-hook listeners), spawn server, env isolation, process-group kill, Windows pnpm/kill. Do not extract into the 3550-line e2e (probes/lifecycle) or the vitest clone template; this is a third lifecycle (real server + packed CLI + live Clerk).

Duplicated Code — publishable-key Frontend API decode:

// packages/auth/live/fixtures.ts
if (publishableKey.startsWith("pk_test_")) frontendApi = atob(publishableKey.slice(8));

// test/browser/fixtures.ts
const frontendHost = Buffer.from(
  process.env.CLERK_PUBLISHABLE_KEY!.replace(/^pk_test_/, ""),
  "base64"
)
  .toString()
  .replace(/\$$/, "");

Could live on LiveSettings; not required.


Intent (issue 144)

Issue 144's problem: live Clerk only had Backend-API vitest. CI needed to make the Account Portal handshake and packed patchy login unsurprising against patchy-cloud-ci, never the developer app, with few serial sign-ins and a sweep.

The PR solves that problem, not a different one.

Faithful. Two serial specs, isolated checkout server + packed CLI, seed bound to a Backend-API +clerk_test user, company patch as DEV_SEED.token, Testing Token on FAPI, Chrome UA, page-driven hops (not context.request), retype-424242 fallback, gated clerk-live via pnpm test:clerk, always() sweep of browser+outsider emails. Prototype helpers do not ship. Headed run is documented. clerk-live is green.

Looks like drift; implements the ticket. Worker-shared sign-in is the “few and serial” budget and patchy-login “from that signed-in browser.” JWT wait is “a reload after the token expires is not a sign-in.” Outsider 404 compared to /d/000000000000 is “the 404 a missing id gets” (issue 119’s byte-identical rule).

Extra adjacent, not a different product. CI publishable-key fingerprint (super-whale-1225.clerk.accounts.dev$) hard-fails the wrong app before any Clerk call; __clerk_handshake observer; /company enrollment heading.

Under-aim. None material.

Intent matched.


Method

The method matches issue 144 and the #119 facts. It is the smallest path that actually proves both workflows; most of the weight is Clerk/CI constraints, not taste.

Choice Verdict
Isolated checkout server + embedded Postgres + packed CLI Load-bearing. pnpm dev would mutate .local/dev. NodeHttpServer.layerTest never exposes a TCP origin Clerk can 307 to. Reusing scripts/packed-cli-e2e.mjs wholesale is the wrong harness (fake Clerk cookies, not the portal).
Worker-scoped fixture, workers: 1, no retries, shared seededPage Load-bearing. Frontend API rate-limits sign-ins per IP; GitHub runners share IPs.
Real Account Portal + Testing Token via context.route Load-bearing. Backend-minted cookies skip the portal and handshake. HeadlessChrome drops Secure cookies on HTTP; Chrome UA and page-driven nav are required. Helpers stay in test/browser/ — not shipped.
Real-clock wait on session JWT exp Load-bearing for the expiry requirement. TestClock cannot expire Clerk’s token. Biggest CI-time cost; currently fine (clerk-live ~2m48s).
Outsider in a second BrowserContext The spec: isolation from seeded cookies, byte-identical 404.
Packed node dist/index.js + clean HOME Load-bearing. pnpm patchy is workspace source and would see developer ~/.patchy.

Caveats, not a rewrite.

  • Job env PATCHY_PUBLIC_BASE_URL=http://127.0.0.1:3000 (an azp default for in-memory vitest) makes instance.ts bind :3000 with no reservation and no EADDRINUSE retry. Locally it uses availablePort() then closes it before listen (TOCTOU). packed-cli-e2e holds the socket until spawn. Vitest live tests use in-memory fromWeb, so nothing currently occupies 3000 between tiers — but the browser server is the first real listener, and it should own a held ephemeral port instead of inheriting the job URL.
  • JWT wait fails if Clerk lengthens session TTL past ~84s, even if renewal works. ADR-0006 assumes ~60s; the bound encodes that assumption as a test failure.
  • Triple sweep after a green CI run (vitest teardown → runner finally → always()) is idempotent waste, not a leak.
  • instance.ts swallows subprocess output so credentials never leak; failures are then undiagnosable. Accepted by the credential rule; painful when pack/install/boot breaks.
  • 401 door is status + cache-control only. A 401 that still embedded the patch iframe would pass this spec (serving tests cover the HTML door elsewhere).

Method is sound with caveats. The one method change worth making: always bind a held ephemeral port (packed-cli-e2e’s reservation-until-listen) and stop inheriting the job’s :3000 PATCHY_PUBLIC_BASE_URL for the browser server.


YAGNI

YAGNI mixed. Worst extra: Windows process-group / pnpm / env in instance.ts for a Linux-only job.

Reusing the 3550-line packed-cli-e2e script is not simpler. It is a top-level-await program (fake Clerk, probe modes, not a library). Extracting a shared harness would drag that monster into Playwright and live keys. A 416-line subset that packs the CLI, boots postgres/server, seeds a Clerk user, and tears down a process group is the spec. Justified copy. Do not extract a third supervisor.

Fat inside instance.ts is accidental:

  • Windows pnpm/execPath, SystemRoot/COMSPEC/APPDATA, and terminate’s non-group kill (instance.ts ~57–90, 193–197, 389–397). CI is ubuntu-latest; packed-cli-e2e already rejects win32 e2e. POSIX detached + kill(-pid) is enough.
  • Env allowlist (~25 names) vs packed-cli-e2e’s “copy env, strip PATCHY_*”. Isolating PATCHY_API_TOKEN is a real login-test constraint; listing WINDIR is not.

Necessary: worker-scoped live + openSeededPatch (two serial portal sign-ins); testing-token interceptor; signIn retype; test-clerk.ts vitest→playwright + --browser + signal-then-sweep; CI frontend-API check; JWT exp wait.

Borderline: four Schema.decodeUnknownSync helpers in patchy-login.spec.ts for a partial CLI JSON. Module-level decode matches eslint; JSON.parse + expect would be smaller. Not worth a shared decoder package.

The extra confirm-page and /company assertions are cheap locks on the happy path, not new machinery. Leave them.


Summary

  • Spec: 4 findings. Worst: login-door fails if remaining session TTL ≥ 90s, which is stricter than “reload after expiry is not a sign-in.”
  • Standards: 0 hard violations, 2 judgement-call duplication smells. Worst: instance.ts copies packed-cli-e2e’s lifecycle (leave it; do not share the 3550-line script).

Axes kept separate on purpose: the code can follow every convention and still encode Clerk’s current JWT lifetime as a pass/fail, which is a spec-axis problem, not a style one.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Review dispositions

Addressed the concrete gaps from both reviews in 2602396. No product behavior or branch-protection changes.

Fixed

  • Session lifetime assumption: removed the <90s assertion. login-door waits until the observed JWT expiry plus clock skew and adds that wait to the Playwright timeout. A longer Clerk token lifetime is no longer a test failure by itself; CI's overall job deadline remains the resource limit.
  • Browser port ownership: the browser server always uses its own ephemeral loopback port, reserved through setup and released immediately before spawn. It no longer inherits the in-memory Vitest tier's PATCHY_PUBLIC_BASE_URL/:3000. Postgres also holds its reservation through initialization. Both reservations are released on startup failure/teardown; the existing child-readiness check still fails closed if the unavoidable release-to-bind handoff loses a race. Removed the now-unused settings argument and updated development docs.
  • Signed-out content leak coverage: the 401 check now also rejects the fixture's private content in the response body and any iframe on the door. A status-correct response that exposes the patch no longer passes.

Kept as is, with reasons

  • Shared/conditional openSeededPatch: the first workflow performs the signed-out door and portal handshake checks; both standalone selections use the same path. Reusing the signed-in browser preserves the ticket's few, serial sign-ins rather than adding another login merely to move assertions between files.
  • Enrollment and confirmation-page assertions: company, email, terminal code and resulting company page prove the intended identity/enrollment, within the same requested workflows. They do not add product scope or another lifecycle.
  • 401 through CLI JSON: the CLI intentionally omits numeric HTTP status. Exit 2 plus the canonical Unauthorized wire literal checks its public contract without changing ADR-0004.
  • Separate instance harness: the packed offline e2e is a top-level program with fake Clerk credentials and lifecycle probes; Vitest owns a cloned database instead of this real server. Extracting a shared supervisor would couple different lifecycles without simplifying this change.
  • Frontend-API decode duplication: two small local operations serve different boundaries (exact CI fingerprint versus the route's hostname). No shared abstraction is needed for correctness.
  • Windows branches and environment allowlist: retained the existing local-run portability paths rather than narrowing platform support in a review fix. The closed environment prevents ambient Clerk, product, storage and Node overrides from contaminating the server/packed CLI. Windows behavior is not claimed as verified by Linux CI.
  • Multiple sweeps: Vitest teardown supports standalone execution, runner finally covers browser failures/interruption, and CI always() is the cancellation backstop. Their idempotence is intentional failure containment, not redundant success-only work.
  • Sanitized subprocess diagnostics: retained stage-only failures rather than exposing credential-bearing output/causes. More detailed safe diagnostics would be a separate change.
  • Module-level Schema decoders: retain typed JSON validation and the repo's compile-once convention; replacing them with unchecked JSON.parse would not improve this workflow.

Verification

  • Before the fix, pointing the browser tier at an occupied loopback URL reproduced Browser instance failed while starting server; cleanup verified zero users.
  • After the fix, both browser specs passed with that same occupied PATCHY_PUBLIC_BASE_URL/CLERK_AUTHORIZED_PARTIES and --timeout 45000. login-door ran for about 78 seconds, proving its expiry wait extends the base timeout. The unrelated listener remained intact; the final sweep verified zero run-scoped users.
  • Standalone harness TypeScript checking and pnpm lint passed. The owned collision probe was stopped and generated browser artifacts were removed.

Latest-head CI / merge readiness

CI run 33970043136 completed successfully for 2602396. All seven reported checks passed: test (22), test (24), clerk-live, cli-smoke, lint, dependency-review, and label.

The live-tier log shows both Vitest tests and both browser specs passing; the runner and separate always() sweep each report Clerk sweep 33970043136-1: zero users remain.

GitHub reports no required checks configured for this stacked target; none were added or bypassed. All available checks are green, mergeability is MERGEABLE / CLEAN against auth/143-live-clerk-vitest-tier, and no newer reviewer findings or unresolved blockers are present. Ready to merge into the stacked base; not merged by this action.

@allisonmahmood allisonmahmood linked an issue Sep 6, 2026 that may be closed by this pull request
3 tasks
@allisonmahmood
allisonmahmood force-pushed the auth/143-live-clerk-vitest-tier branch from f8839ef to c89c326 Compare September 6, 2026 13:09
Base automatically changed from auth/143-live-clerk-vitest-tier to main September 6, 2026 13:14
@allisonmahmood
allisonmahmood force-pushed the auth/144-playwright-specs branch from 2602396 to 7c075c1 Compare September 6, 2026 13:14
@allisonmahmood
allisonmahmood merged commit 27d2f86 into main Sep 6, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the auth/144-playwright-specs branch September 6, 2026 13:18
allisonmahmood added a commit that referenced this pull request Sep 6, 2026
## What changed

The auth build is complete, but its docs still mix the old publishing
model, shipped auth behavior and future plans. This pass reconciles the
map, glossaries, product, ADRs and setup recipes so a fresh agent can
sign in, log in the CLI, publish and open a page without reading an
issue.

**Rebased onto `main` after the auth stack merged.** This PR contains
the final documentation pass over PRs #147–#159, preserving the newer
invitation-expiry and current-public-version rules throughout the docs
and skills.

Closes #145.

## Surface audit

| Surface | What this pass found |
| --- | --- |
| Wire contract | Corrected deletion cleanup timing in endpoint prose
and regenerated `docs/API.md`; wire shapes unchanged. |
| CLI | Aligned login completion, credential precedence, sharing and
browser-only company reads across README, skill and onboarding;
refreshed the skill hash. |
| Dev loop | Reconciled Clerk keys, seed binding, isolated CLI state,
lifecycle and both live test tiers. |
| Vocabulary and product | Unified the five glossaries, corrected
context relationships, separated shipped behavior from future plans and
audited ADRs 0002–0008; none is superseded. |
| Migrations | Verified the three baselines at server, dev-runner and
Vitest composition sites; documentation clarified, migrations unchanged.
|
| Served pages | Corrected the example's publishing/access copy; no
product UI or HTML-policy changes. |
| Reverse states | Covered denial, logout, revocation, reactivation and
sharing reversal. |
| Repository layout | Updated package responsibilities, agent guidance
and authoritative versus generated skill paths. |

Removed obsolete route assertions while retaining general API-guard
coverage. The retired-concept sweep leaves only legitimate lexical
matches: dependency/origin pinning, sharing/cookie scopes and Effect's
`Command.unlisted`.

## How it was verified

- [x] `pnpm lint`, `pnpm typecheck`, `pnpm test` — 322 tests across 38
files.
- [x] `pnpm test:packed-cli-e2e` — complete packed CLI real-server
contract.
- [x] `pnpm test:clerk` — two Backend-API tests and two Playwright
workflows; cleanup confirmed zero test users remain.
- [x] Local dev startup, publishing, both sharing transitions at both
URL shapes, login handoff/pending/logout and rendered-example
inspection.
- [x] Skill hash and generated-bundle parity; relative Markdown file
links; 62 unique glossary headings with no duplicates.
- Standards review: two vocabulary findings fixed. Spec review:
state-directory default clarified. No open findings.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — documentation, endpoint-description and
obsolete-test cleanup only; runtime behavior and wire shapes unchanged.

Model: OpenAI GPT-6 Astra. Harness: Oh My Pi.

Integration verification: local formatting, lint, typecheck and all 322
offline tests pass. Reconciled both rounds of rebase conflicts,
refreshed the public skill hash, corrected ADR-0007’s stale no-expiry
claim, and documented the invitation-expiry migration. Final-head CI,
including live Clerk/browser and packed CLI checks, is the merge gate.

Integration: GPT-6 in the Codex harness.
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: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.

ci: Playwright specs login-door and patchy-login

1 participant