Skip to content

The dev loop and tests with Clerk #124

Closed

Description

@allisonmahmood

Question

pnpm dev and the vitest suite must keep working without a browser and, ideally, without a Clerk account. With the sign-in research and the door decision in hand:

  1. Keys. pnpm dev reads the Clerk development keys from the developer's environment and passes them through; with none set the server still boots, the CLI path works through the seeded machine token, and the door fails closed with a message that names the variables. ➡️ That; no dev-bypass flag.
  2. The seed. One company (Patchy Dev, handle patchy-dev), one admin user, one machine token — the same rows in the dev runner and the vitest template, as today. ➡️ That.
  3. Tests. Sessions are signed with a test keypair and verified through jwtKey, so no test touches Clerk; the door's tests drive cookies and redirects through NodeHttpServer.layerTest. ➡️ That, if the research confirmed jwtKey is supported for it.
  4. The packed-CLI e2e. patchy login is exercised against the real server up to the handoff (URL and code printed as JSON); the confirm half is a server test, not an e2e. ➡️ That.
  5. Docs and skills. docs/DEVELOPMENT.md, the patchy-dev-loop skill and the env registry name the new variables. ➡️ A checklist line on the build ticket.

From the prototype (#119, resolved 2026-09-03)

Question 3 is answered offline on the branch: sessions signed by an RSA-2048 test keypair verify through CLERK_JWT_KEY with zero network (a fetch guard fails any call), the door is driven in memory with HttpRouter.toHttpEffect and on a socket with redirect: "manual", and a pk_live_ fake key reproduces the production shape, return leg included. The session should also decide:

  1. The seeded vitest template is dead everywhere, not just in the it.layer path: Testing.layer creates an empty database and the template's only consumer has no callers (pre-existing; the dev-loop bullet in CLAUDE.md is wrong). ➡️ Either Testing.layer clones the seeded template, or every suite seeds through a shared fixture like the prototype's @patchy/auth/testing.
  2. The packed-CLI e2e dies at its build step until the door's code passes the Effect diagnostics, then fails assertViewer on status and on cache-control. ➡️ It follows The login door on a tier 0 page #120 item 13: publish a public patch for the existing table and add one doored case; CI never has Clerk keys, so the doored case uses the keypair fixture.
  3. CLERK_JWT_KEY. The runner already forwards every CLERK_* name; the key survives dev.env in any quoted form (a one-line \n form needs double quotes; unquoted or single-quoted one-line values yield garbage and a silent sign-in loop); clerk env pull never writes it. The SDK's own JWKS cache makes it a nicety (one 46–227 ms fetch per process per five minutes). ➡️ Do not ship it as configuration, or validate it with createPublicKey at boot if kept; the "no-clobber on re-pull" claim was not tested.
  4. CLERK_AUTHORIZED_PARTIES stays unset locally: two worktrees with per-port lists evict each other's session on every sign-in.
  5. Headless sign-in helpers must send a real Chrome user agent on http (FAPI omits Secure for HeadlessChrome and Safari UAs on an http redirect_url; not on https) and retype the email code when the portal drops it; Playwright's context.request withholds Secure cookies on http://127.0.0.1.

From the door (The login door on a tier 0 page, resolved 2026-09-03)

  • Question 1 changes: the Clerk keys are required at startup, like the bootstrap token. There is no boot-without-keys and no door that fails closed at request time. pnpm dev already hands the keys through; a developer without ~/.config/patchy-cloud/dev.env gets a startup error naming the variables.
  • The doored shell loads Clerk's headless frontend script from the Frontend API host, which does the token refresh. Offline door tests (question 3, item 6) cover the server half: verification through the keypair, the handshake redirect, the 401 shape, the CSP with the FAPI host. Nothing in vitest runs the shell's script.
  • Item 7: the packed-CLI e2e publishes a public patch for the existing viewer assertions and adds one doored case asserting the 401 with no-store from the keypair fixture.
  • Item 8 and 9 stand; CLERK_AUTHORIZED_PARTIES is still per host, and the domain ADR notes that a per-company subdomain later needs one entry per host.

From company and user (Company and user: the minimum that ships, and where the company lives, resolved 2026-09-03)

  • Question 2 stands: one company, one admin user, one machine token; no seeded invites.
  • Inviting calls Clerk's Backend API to send the email, so the invite tests need a Clerk client layer they can swap: an alternate layer that records the call and one that fails, never a network call and never a mock. Create-or-join and deactivation touch no Clerk API and test offline through the keypair sessions.

From the data model (Data model, packages and migration, resolved 2026-09-04)

  • Question 2 sharpens: the seeded token is the seeded admin user's machine token (operator = false), and the operator token is PATCHY_BOOTSTRAP_API_TOKEN as today. The operator cannot publish, so pnpm seed:dev and the packed-CLI e2e publish as the seeded user through PATCHY_API_TOKEN.
  • The migrator is called in four places, not three: the server, the dev runner, test/postgres.ts and apps/server/src/test/server.ts. Item 6's answer must cover all four.
  • The baselines are rewritten (companies 1, auth 2, patches 3); nothing is deployed.

Activity

  1. added
    wayfinder:grilling
    on Sep 2, 2026
  2. allisonmahmood commented on Sep 4, 2026

    @allisonmahmood
    OwnerAuthor

    Resolution

    Grilled on 2026-09-04 in two rounds, with one research pass over Clerk's OpenAPI specs (bapi, fapi), clerk.com/docs and the clerk/javascript source. The findings are at the end of this comment; nothing was branched.

    One seed, cloned by every test (questions 1, 6). Testing.layer clones the seeded vitest template instead of creating an empty database, so every it.layer suite and the server test layer start with Patchy Dev, its admin user and its machine token; package fixtures add their own rows on top, as packages/patches/src/test/fixtures.ts does today. The migrations argument goes, since the template already carries all three baselines; packages/sql keeps one empty-database layer for its own migrator tests; the dead createPostgresTestDatabase is deleted. The migrator then has three call sites (server, dev runner, test/postgres.ts), not the four counted on Data model, packages and migration, and AGENTS.md's dev-loop bullet becomes true again.

    The seed (questions 2, 13). One company (Patchy Dev, handle patchy-dev), one admin user with a fixed clerk_user_id (user_dev), email [email protected], name Patchy Dev, and that user's machine token (patchy-dev-token, operator = false). The Clerk user id is overridable: the runner reads an optional PATCHY_DEV_CLERK_USER_ID from dev.env; when set, the seeded admin is the developer's own Clerk user, so signing in to the local instance lands in Patchy Dev as its admin, owning what the CLI publishes. Unset (tests, fresh clones) the fixed id stands and a real sign-in lands on create-or-join, which is itself a path worth walking locally. No real Clerk key or token is ever committed; offline fixtures use fake keys whose Frontend API host is under .invalid.

    The operator locally (question 14). The runner hands the server a fixed PATCHY_BOOTSTRAP_API_TOKEN, and .local/dev/env exports it as PATCHY_OPERATOR_TOKEN beside PATCHY_API_TOKEN, which stays the seeded user's machine token because that is what the CLI publishes with. Server tests keep bootstrapping dev-token. What the operator token is for, unchanged from Device login and the data-model ticket: the moderation loop (read a flagged patch and who holds it, list that principal's patches, disable, revoke the token) and pin/unpin. It cannot publish. The patchy-mint-token skill is deleted.

    Where the seed lives (questions 3, 16). @patchy/auth gains two entries. @patchy/auth/seed holds DEV_SEED and applyDevSeed, imported by the dev runner, test/postgres.ts and the packed-CLI e2e; Auth depends on Companies, so the seed writes the company and user rows as well as the token. @patchy/auth/testing holds the RSA-2048 keypair, clerkEnv, the session signer and the fetch guard, installed on import, that refuses and records any request not aimed at loopback. Two entries because the runner must never import a module that rewires fetch.

    CLERK_JWT_KEY (question 4). Kept as optional config, validated with createPublicKey at boot so a mangled PEM fails at startup instead of causing a silent sign-in loop. Documented as test-facing; a developer leaves it unset. The offline suite sets it through ConfigProvider; the tested session layer is the production one, only its configuration differs. CLERK_AUTHORIZED_PARTIES stays unset locally.

    CI, two tiers, both required (questions 10, 11, 12).

    • Every PR, no secrets. Vitest with the offline keypair, and the packed-CLI e2e against a server started with fake Clerk keys. This tier proves the door, device login, create-or-join, invites through the swapped layer, deactivation and the operator's controls, on fork and Dependabot PRs alike.
    • Same-repo PRs and main, gated on github.event.pull_request.head.repo.full_name == github.repository. Two jobs against a dedicated CI Clerk application, never the developer's instance. (a) A live vitest config: create a +clerk_test user named for the run id, mint a session through the Backend API (POST /v1/sessions, testing-only and refused on production instances, then POST /v1/sessions/{id}/tokens), send that JWT through the real door verifying against Clerk's JWKS with no CLERK_JWT_KEY, exercise invitation create, list, revoke and re-invite, and delete the user in an always() step. (b) Playwright: sign in at the Account Portal with a +clerk_test address and code 424242 behind a Testing Token, land on a doored patch (login-door spec), and confirm a patchy login from the signed-in browser (patchy-login spec). One spec per workflow, sign-ins few and serial because the Frontend API limits sign-ins per IP and GitHub runners share IPs. A skipped gated job satisfies a required check, so Dependabot RC bumps pass on the offline tier.
    • Locally. The live config and the Playwright specs read CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY from the environment; pnpm test:clerk sources dev.env so a developer runs them against their own development instance, where the run-namespaced +clerk_test users are swept the same way. One code path, two key sources. pnpm test stays offline. Nothing requires local testing; everything allows it.

    The packed-CLI e2e (question 6). Applies the dev seed to its own embedded Postgres, publishes as the seeded user's machine token, exercises patchy login --json up to the handoff, and adds one doored case: a company-scope patch fetched with no cookies answers 401 with cache-control: private, no-store, a local answer that needs no key. The self-service minting cases go. One e2e per workflow, never one spanning everything.

    Invites (questions 7, 15). No HTTP-level fake of Clerk. Companies owns an InviteMail service over @clerk/backend's invitations, with a live layer, a recording layer and a failing layer; the offline suite swaps, the live tier runs the real one. The live layer always sends (notify: true), as production must. The live test invites ci-<run>[email protected]; whether Clerk suppresses invitation mail to +clerk_test addresses is undocumented, and a bounce to a .test domain is the accepted worst case, checked on the first live run.

    Browser helpers (question 8). The prototype's headless portal helpers do not ship. The Playwright specs replace them.

    Docs (questions 9, 17). A checklist line on the build tickets, not a decision: docs/DEVELOPMENT.md names the two Clerk keys as required at startup, CLERK_JWT_KEY as optional and test-facing, the two dev tokens in .local/dev/env, PATCHY_DEV_CLERK_USER_ID, and how to run the live tiers locally; the patchy-dev-loop skill gets the two-token env line; ci.yml gains the gated jobs; the CLI README is untouched.

    Clerk facts the decisions rest on (verified 2026-09-04)

    • POST /v1/sessions (user_id) is "intended only for use in testing, and is not available for production instances"; POST /v1/sessions/{id}/tokens returns { jwt } with expires_in_seconds 30–315360000. Together: a real signed session for a real user, no browser, no Frontend API. POST /v1/sign_in_tokens also exists (ticket exchangeable at the Frontend API with strategy=ticket), unused here.
    • Test emails: any +clerk_test subaddress takes code 424242 and sends no mail; test mode is on by default on development instances. Verification links still send. Test addresses are exempt from the 20 SMS / 100 emails per month cap. docs
    • Testing Tokens (POST /v1/testing_tokens, __clerk_testing_token query param) bypass bot detection only, usable from plain fetch; production instances supported since 2025-08-19. @clerk/testing's setupClerkTestingToken is a Playwright route interceptor that appends the param and flips captcha_bypass; nothing in it helps a Node test. overview
    • @clerk/backend has no official test or mock mode; the monorepo's packages/msw is a private example. jwtKey is documented as networkless verification (authenticate-request); the publishable-key format (pk_test_ + base64 of <frontend-api>$) is source-only (packages/shared/src/keys.ts).
    • Invitations: POST /v1/invitations takes notify (default true, the only no-send switch), ignore_existing, expires_in_days; list with status and query; POST /v1/invitations/{id}/revoke; an existing user cannot be invited. Rate limit 100 per hour.
    • Limits: development instance 100 users, no bulk delete (DELETE /v1/users/{id} in a loop); Backend API 100 requests per 10 s per secret key; Frontend API per IP, 5 sign-in creates and 3 factor attempts per 10 s. system-limits Whether +clerk_test users count toward the 100 is undocumented; assume yes and sweep. Two concurrent runs share every budget, so fixtures are namespaced by run id.
    • Free plan: unlimited applications, so a dedicated CI application costs nothing (pricing). Clerk's rotation guide says to create one secret key per consumer, named for it, e.g. github-actions (rotate-api-keys). A leaked sk_test_ key is a total compromise of its instance.
    • GitHub Actions: secrets are withheld from workflows triggered by fork PRs and by Dependabot; same-repo branch PRs get them. docs

    Carried to the other tickets

    • Spec (Write the auth spec and file the build tickets): the template-cloning Testing.layer and the three migrator call sites; the seed's rows, PATCHY_DEV_CLERK_USER_ID and PATCHY_OPERATOR_TOKEN; the two @patchy/auth entries; CLERK_JWT_KEY as boot-validated optional config; the two CI tiers with the gate expression and the pnpm test:clerk script; the live vitest config and the two Playwright specs as build tickets of their own, blocked on the CI application task below; the packed e2e's seed, handoff and doored case; InviteMail's three layers; the docs checklist above; the patchy-mint-token skill's deletion.
    • New task ticket, HITL: create the dedicated CI Clerk application and add its keys as repository secrets. Filed as a child of the map beside this one.

    Resolved above; decision indexed on the auth map.

  3. allisonmahmood commented on Sep 4, 2026

    @allisonmahmood
    OwnerAuthor

    Resolved above; decision indexed on the auth map.

  4. allisonmahmood commented on Sep 4, 2026

    @allisonmahmood
    OwnerAuthor

    Addendum, 2026-09-04. The operator-as-token parts of this resolution (the operator kind of /api/me, the tok_operator row with user_id NULL and the operator flag, PATCHY_OPERATOR_TOKEN in the dev loop) are reopened on The operator is a company, not a token. Read that ticket's resolution over these lines; the rest of this resolution stands.

  5. allisonmahmood commented on Sep 4, 2026

    @allisonmahmood
    OwnerAuthor

    Addendum, 2026-09-04. Resolved on The operator is Patchy, not a token: the operator is Patchy with its own later login and dashboards, so every operator-as-token part of this resolution is gone — the operator kind of /api/me (one shape now), tok_operator, the nullable user_id and operator flag (user_id NOT NULL), PATCHY_BOOTSTRAP_API_TOKEN and PATCHY_OPERATOR_TOKEN, the admin scope, and the moderation and pin routes. revoke stays only as the bearer revoking itself. The rest stands.

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

Metadata

Metadata

Labels

wayfinder:grilling

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions