Skip to content

Auth map — Clerk, companies and machine tokens on tier 0 #112

Closed
18 of 18 issues completed
Closed

Description

@allisonmahmood

Destination

Patchy Cloud has an auth layer, built and working on tier 0 patches: a person signs in through Clerk, lands in exactly one company, opens a patch shared with their company behind the login door, and their agent publishes with a machine token from patchy login. A patch belongs to a user; self-service minting is gone. The company and admin surfaces are the smallest set that makes that sentence true, shaped so groups, domains and SSO can be added without re-cutting the tables. The map is done when the decisions below are locked, the auth spec is written, and the build is filed as ready-for-agent sub-issues one agent session each — the build runs from those, as the Effect port did from Effect v4 port map, and mid-build decisions come back here as grilling tickets.

Notes

  • The product is decided; this map decides the build and the first slice. docs/product.md § Companies and § Identity and access — from Company and tenancy and Identity and access — are the shape: Clerk is the identity provider and holds the browser session; Patchy holds the company, access and machines; sign-in is Google, Microsoft or an emailed code, never a password; patchy login is a device login (URL plus short code, confirmed in a signed-in browser, machine named on first login) that mints a Patchy-owned machine token expiring 90 days after login or 30 idle; a user is in exactly one company; two roles, member and admin, everyone builds; the owner alone changes a patch, admins see everything; the login door sits in front of the page at every tier. Reopen one of those only when a Clerk fact makes it unbuildable, and say so on the ticket.
  • MVP: minimal company and admin. In: a company created at first sign-in with its handle, its creator as admin, one way to add a second user and the way to remove them, member and admin. Out, listed below: groups, verified domains, SSO, request access, addresses, the portal, billing. "Ready to expand" means the tables and packages are cut for those, not that they exist.
  • Agent-native on both surfaces. The CLI stays the primary interface — ADR-0004's exit codes and --json, the login handoff as JSON — and the browser gets the fewest pages that make sign-in, the door, device confirmation and Your machines work.
  • Nothing is deployed. ADR-0003 rewrote the baseline migrations on that basis; assumed still true, so this build may rewrite them again. The data-model ticket confirms before the spec relies on it.
  • Sequencing. patches: drop expiry, add retire and delete waits on ownership landing here and is not this map's.
  • Skills every session consults: grilling and domain-modeling on grilling tickets; research on research tickets — findings go in the ticket's resolution comment, never on a branch; prototype on the prototype; effect-service-conventions and node_modules/effect/AGENTS.md before writing Effect code; the Hit every surface list in AGENTS.md before calling any build done.
  • Every grilling question carries context, consequences and a recommendation, so a session can be answered from the ticket alone.

Assumed while charting (2026-09-02, not grilled — correct these on the map)

Charted from Allison's brief and the documented decisions without a live grilling round.

  1. The destination has the port map's shape: decisions → spec → ready-for-agent build tickets; nothing is built under the map itself.
  2. "Minimal company and admin" is the in/out split in the Notes.
  3. The fog is the build — how the serving host reads a Clerk session on a script-free page, whether the company is a Clerk Organization, the device-login protocol, the data model, the dev loop without a browser — not the product's shape.
  4. The riskiest assumption, that Clerk's session can gate a page that runs no script, is proven by a prototype before the door's design is locked. Proven on the login door end to end on 2026-09-03; its evidence reshapes The login door on a tier 0 page #120 question 1 into "Clerk on every request, or Clerk at the door only".
  5. The bootstrap token was assumed to carry over as the operator's credential, and three resolutions built on it. Corrected 2026-09-04 on The operator is Patchy, not a token: the operator is Patchy running the platform, with its own login and dashboards as a later effort; nothing operator-shaped exists in this slice, and the device-login, data-model and dev-loop lines below are amended.

Decisions so far

  • Clerk on a server with no frontend: reading the session on a script-free page: yes, a script-free page can be gated. @clerk/backend 3.17.0's authenticateRequest(Request) answers signed-in, signed-out or handshake; the handshake is a pure 307 chain (app → Frontend API → app) that the SDK completes by turning the payload into Set-Cookie on the server's own response, eligible only for GET document navigations, so /api/* never redirects. Token verification is local with jwtKey, but completing a handshake calls the Backend API, so the door is not networkless. __session is host-only on the app, __client_uat on the registrable domain: pages, API and Account Portal must share one registrable domain (production Frontend API is a CNAME clerk.<domain>). Email and name are not default claims; add them under "Customize session token". No hosted sign-out page: sign-out is a Patchy POST that revokes the session and clears the cookies. Open: azp on handshake-minted tokens once authorizedParties is on.

  • Clerk Organizations as the company: what they give, cost, and forbid: the Patchy table wins for this slice. Organizations cap at 20 members without the $100/mo B2B add-on, which is also what verified domains and per-organization SSO need; a user's memberships are unlimited by design, so exactly-one-company is Patchy's rule either way, and the last-admin rule is only proven in Clerk's UI. Enabling them adds a choose-organization session task and pending-session handling. Webhooks are Svix, eventually consistent, and need a tunnel or Clerk's new clerk webhooks listen relay per dev instance; Clerk's own guide says to read from the session token first, so just-in-time user rows are the simpler path. Without organizations Patchy builds invite by verified-email match (Clerk's application-level invitations and invite-only sign-up remain available) and gives up nothing it could have had for free.

  • Clerk sign-in as decided, the hosted pages, and the test story: Google and Microsoft use Clerk's shared credentials in development and own OAuth apps in production; email code is a 10-minute OTP; passwords off affects new users only, so turn it off before the first real user. Account Portal sign-in is https://<slug>.accounts.dev/sign-in?redirect_url=… in development and accounts.<domain> in production, with redirect_url confined to the instance's domain (localhost works in development). Free plan: 50k monthly users, a fixed 7-day session lifetime, a 100-user development cap. Tests: @clerk/testing is Playwright and Cypress only; a session JWT signed by an RSA-2048 (e=65537) test keypair verifies through jwtKey with no network, because the PEM parser hard-codes that key shape, mirroring Clerk's own suite but not a documented contract, so pin @clerk/backend and keep one test on the parser.

  • Device login: the protocol facts, and whether Clerk's machine auth changes anything: the decision stands; nothing in Clerk changes it. RFC 8628 §3.3.1 is the confirm-not-enter form by name; its worked code is eight characters from BCDFGHJKLMNPQRSTVWXZ as XXXX-XXXX, the device code and the confirm URL's id carry the real entropy, and §5.4 says the page must say a machine is being authorised, name it, show the code and expire fast. Every 2025–2026 phishing incident (Storm-2372, APT29, GitHub device-code phishing, EvilTokens, Entra now blocking the flow by default) has the victim typing the attacker's code, so confirm-only removes that lure but the page must still name the machine and the company. gh and Vercel enter the code, Fly has none and names the session by hostname, Stripe's confirm-plus-device-name flow is now its legacy path. Clerk's API keys, M2M and OAuth tokens give no idle expiry and no Patchy-side listing; its device grant is support-gated with no public contract.

  • Effect 4 HTTP for the door: cookies, redirects, and the Web Request bridge: rc.112 has every primitive. Cookies read as a record and set through HttpServerResponse.setCookie / expireCookie with no defaults (set httpOnly, secure, sameSite, path yourself; cookies ride on response.cookies, never setHeaders); redirect(location, { status, cookies }); HttpServerRequest.toWeb builds a Fetch Request, but toURL trusts x-forwarded-proto from any peer and TrustedProxies does not gate it, so the door builds its URL from publicBaseUrl. Forms through schemaBodyUrlParams; no CSRF helper, so SameSite=Lax plus an Origin check plus a per-session token; the door's pages need their own CSP with form-action 'self'. Route-scoped HttpRouter.middleware(fn) provided only to the two /d/* registrations, so Pages.layer splits into doored and undoored routes and the global chain in Server.ts is untouched. The test fetch client follows redirects and keeps no cookies: drive hops by hand with redirect: "manual", or test in memory with HttpRouter.toHttpEffect and HttpServerRequest.fromWeb.

  • Create the Clerk application and hand its development keys to the dev loop: done. Application patchy-cloud (app_3ImZuFeZJb8038U0oFds84rupA2), development instance only; Account Portal https://engaging-earwig-3123.accounts.dev (sign-in at /sign-in?redirect_url=…), Frontend API engaging-earwig-3123.clerk.accounts.dev. Google, Microsoft and email code on, passwords off, Organizations off, email and name added as session claims. Keys in ~/.config/patchy-cloud/dev.env (CLERK_PUBLISHABLE_KEY, CLERK_SECRET_KEY, written by clerk env pull --app … --file), which the dev runner now hands to the server (commit 1cedc43 on t3code/afc9820c, to land by PR). Clerk CLI 3.3.0 installed and signed in; clerk config and clerk env pull drive the instance with --app, no clerk init or clerk link.

  • The login door end to end on the development instance: proven, on prototype/login-door. A script-free page completes the handshake; one click and 4.0–5.4 s from Sign in to the patch, of which the door's own hops are under 20 ms and one FAPI round trip ~250 ms; a fresh-token load is ~1 ms of local verification, one read and no Clerk traffic; past 60 s every idle return is one Backend API refresh or a three-hop handshake, and the SDK refreshes on every load unless the door mirrors or steers the cookie family, so The login door on a tier 0 page #120 q1 is really "Clerk per request or Clerk at the door only". azp is present and authorizedParties works (a wrong list is a silent loop); the dev FAPI returns the handshake in token form, so completion is local; __session is host-only, __client_uat carries the host Domain; the SDK derives redirect_url from Host/X-Forwarded-*, so the door must pin them from the public base URL; undici's redirect: "manual" exposes the 307 and nine offline keypair-through-jwtKey tests cover both key shapes; sign-out works and must clear the handshake cookies with the setter's Domain. Revocation reaches a page in up to 65 s. Dev cannot show the production cookie leg or whether FAPI honours format=nonce there. Review round on PR #127, closed unmerged. Questions added to The login door on a tier 0 page #120 (8–15), Device login: the protocol, and the machine token's columns #122 (9–10) and The dev loop and tests with Clerk #124 (6–10).

  • The login door on a tier 0 page: Clerk holds the browser session and Patchy owns only the machine token; the no-script guarantee is the patch's, so the doored shell loads Clerk's headless script to keep the token fresh and the server just verifies locally with the handshake for cold returns (no server-side refresh, no cookie mirror, no session table). First-party pages server-rendered. Scopes company (default) and public, set by upload --share and patchy share. Three wrong-person states: door, create-or-join, the missing-patch 404; no "no access" page until owner-only returns. Doored responses private, no-store, public patches keep URL-shaped caching. One registrable domain as an ADR (subdomains share by default; a customer domain is a paid satellite). Sign-out on Your machines only. Origin pinned from PATCHY_PUBLIC_BASE_URL, its default dropped; Clerk keys required at startup, no 503 branch. Signed-out is one 401 with the door as body, no redirect. The machine token never opens /d/*; agents read company patches through the browser. The production handshake leg is Run the production handshake leg once against a live Clerk instance, blocked on the spec.

  • Company and user: the minimum that ships, and where the company lives: Patchy holds the company, Clerk knows the user; Organizations return with SSO. Create-or-join with a typed name and an editable handle (lowercase, digits, hyphens, 3–32, reserved list, fixed once created); join is the session email matching a Patchy invite row that never expires, while Clerk's application-level invitation sends the mail (30-day link, revoke and resend both hit Clerk). The user row is born in create-or-join's transaction, so a user always has a company. Invites carry a role, default member; removing yourself is not offered; the last admin can neither demote nor deactivate themself. "Remove" is deactivation: a timestamp, no Clerk call, tokens revoked in the same act, reactivate on the same page. One company page, admins act, members read. The arrow reverses: Companies owns users and the lookup, Auth depends on it and hands out one identity; each package serves its own first-party pages. No CLI company commands.

  • How agent-driven CLIs hand off a device login: 18 of 20 CLIs block inside one process; only Stripe and Netlify hand the URL back and finish on a later call, each as one JSON document that names the next command (next_step, agent_next_steps). Stripe gates on "is an agent driving me" (CLAUDECODE, CURSOR_AGENT, CODEX_* and kin), not on isatty, because an agent with a real TTY must not block; wrangler is the counter-example, blocking 120 s in CI. Payload on stdout, progress on stderr is ADR-0004 already. Wrangler, Turborepo and Railway print the bare code even when the URL carries it (RFC 8628 §3.3.1; one URL survives an agent transcript). Unattended machines get a pre-minted token through an env var, never argv. Recommended for the prototype: Stripe's shape, a blocking patchy login for a human at a TTY and one JSON document plus patchy login --complete <code> under --json, non-TTY or a detected agent. Supabase's confirm page is the only open-source copy to design against.

  • Device login: the protocol, and the machine token's columns: every question closed. Two unauthenticated routes admitted beside the mint (start: device code, user code, confirm URL with and without it, 5 s interval, 10 min expiry; poll: pending / slow_down / complete once / 410 expired, denied, unknown, the row leaving with the poll that reports it); the code confirmed never typed; the name field always on the page, prefilled from the old key or the hostname, re-login as the rename path with the old key revoked in confirm's transaction; expires_at 90 days and hourly-stamped last_used_at for 30 idle; /api/me one shape (user, company, role, machine; the operator kind and flag were dropped by The operator is Patchy, not a token), scopes gone, POST /api/tokens gone; Your machines plus patchy logout (local delete first, revoke as a courtesy, unreachable is a warning not an exit code); CI out of this slice; upload with no token is local and never starts a login.

  • patchy login end to end: the handoff, the confirm page, the token: Stripe's gate plus resume. patchy login blocks only for a human at a TTY (stdin a terminal, no --json, no agent variable set; isatty alone is wrong, since an agent's shell tool has a TTY and sees nothing before exit); otherwise one JSON document with next and agentNextSteps, and a rerun resumes the pending login rather than minting another; --complete [code] is the explicit form, pending after --wait (default 60 s), denied / expired / unknown are the server's answers and exit 2. The URL carries the code (/login/device?code=XXXX-XXXX, one click and ~5 s through the door and portal), a bare /login/device is a message page only, and the confirm page is variant A, code first, its copy and every reverse page quoted on the ticket; the item-9 bounce returns with a "press Confirm again" notice. Branch prototype/patchy-login, PR #132 closed unmerged.

  • Data model, packages and migration: nothing is deployed, so three rewritten baselines in dependency order (companies 1, auth 2, patches 3); users has its own id with clerk_user_id unique, lowercased unique email and name refreshed from the session claims on change; every enumerated column TEXT plus CHECK; patches carries both company_id and owner_user_id, NOT NULL. The tok_operator row, the nullable user_id, the operator flag and PATCHY_BOOTSTRAP_API_TOKEN were dropped by The operator is Patchy, not a token: machine_tokens.user_id is NOT NULL, every bearer is a user. The machine token is minted by the poll, not confirm, so no plaintext is ever stored; stale device logins are deleted on the next start. CurrentIdentity stays in @patchy/api (the middleware must be declared there; Auth already imports it), Auth exports a Viewer for the door; the bearer lookup is one SQL join across the three tables. Five services: Companies, Users, Session, MachineTokens, DeviceLogins. Four migrator call sites, not three.

  • The dev loop and tests with Clerk: Testing.layer clones the seeded vitest template, so tests and pnpm dev share one seed (Patchy Dev, admin user_dev, machine token patchy-dev-token; three migrator call sites, not four); PATCHY_DEV_CLERK_USER_ID in dev.env makes the seeded admin the developer's own Clerk user; PATCHY_OPERATOR_TOKEN and the bootstrap token were dropped by The operator is Patchy, not a token. @patchy/auth gets seed and testing entries (RSA keypair, clerkEnv, fetch guard). CLERK_JWT_KEY stays as optional config validated at boot. CI runs two required tiers: offline keypair plus packed e2e on every PR, and a live tier gated to same-repo PRs against a dedicated CI Clerk application (Backend API POST /v1/sessions mints real JWTs, testing-only by Clerk's own doc; a live vitest config and two Playwright specs, login-door and patchy-login, with +clerk_test users swept per run), both runnable locally via pnpm test:clerk. No official Clerk mock exists, so InviteMail's service boundary is the seam: live, recording and failing layers. The packed e2e seeds itself and asserts the cookie-less 401 with no-store. New task: Create the CI Clerk application and its repository secrets.

  • The operator is Patchy, not a token: the operator is Patchy running the platform, with a separate login and separate dashboards as a later, undesigned effort; never a company in the product, never in the patchy CLI. Nothing operator-shaped is built here: the bootstrap token, tok_operator, the nullable user_id and operator flag, PATCHY_OPERATOR_TOKEN, the admin scope and hasScope, and the moderation and pin routes (read, listByPrincipal, disable, pin, unpin) all go; /api/me is one shape; revoke stays only as the bearer revoking itself; taking a page down is SQL by hand until the operator effort. Bootstrap principal leaves Auth's glossary, Operator in Companies' and product.md gains the one line above.

  • Create the CI Clerk application and its repository secrets: done from the Clerk CLI. Application patchy-cloud-ci (app_3It8wycjSiHb6VXaFuUeeeE1g9k), development instance only; Frontend API super-whale-1225.clerk.accounts.dev, Account Portal https://super-whale-1225.accounts.dev; config mirrored from patchy-cloud (Google, Microsoft, email code; passwords and Organizations off; email and name claims; test mode on; sessions at the defaults). CLERK_SECRET_KEY and CLERK_PUBLISHABLE_KEY are repository secrets, the key held nowhere else. The mint path (+clerk_test user, POST /v1/sessions, token, delete) works; the JWT carries email and name and a null azp. The Backend API rejects .test addresses, so the live tier's users are ci-<run>[email protected]. patchy-cloud has Apple sign-in on, undecided; the CI app does not.

  • Write the auth spec and file the build tickets: the spec is Auth: Clerk, companies and machine tokens on tier 0 and the build is its eleven ready-for-agent sub-issues, chore(patches): remove the operator's routes, the admin scope and pins #136 to feat(companies): invite and manage the company's users #146, blocking wired natively: prefactor, baselines and seed, sign in and create a company, the company page, the door, sharing scope (after the door, so nothing promises privacy before it is enforced), device login on the server, patchy login, the live vitest tier, the Playwright specs, the docs pass. Reshaped once on 2026-09-05 after a second model's review (the guard-less revoke route, sharing before the door, the immutable year versus share … company, invites unique per company, the credential chain under logout, sign-out reachable from every session state). Three baselines rewritten; the wire, the pages, the CLI's --json documents and the docs checklist are in the spec; the calls the spec made on its own (quota per user, the revocation freeze gone, pins gone whole, /login, the deactivated page, the shell in core, the Origin check) are listed under its Further Notes. Run the production handshake leg is the one open ticket, blocked on the door ticket and a deployment.

  • Run the production handshake leg once against a live Clerk instance: closed under Allison’s revised scope after live development verification; all three browser checks passed, including handshake/cookie observations, session renewal, company isolation and CLI login/revocation. No production deployment exists, so production-specific handshake and CNAME behavior remain unverified until deployment.

Not yet specified

Nothing: the spec is filed and every earlier patch of fog graduated into it (the wire and glossary changes into #137 and #145, the skill and README text into #142). A mid-build decision comes back here as a grilling ticket.

Out of scope

  • Leaving a company of one to accept an invite: needs company deletion, which is out of scope, so the invite is refused (Company and user).
  • A Patchy-owned mail sender: Clerk's invitation email is the only mail this slice sends; a sender returns when a page needs mail Clerk cannot send.
  • CLI company management (patchy company invite and kin): browser only; /api/me tells an agent where its user is.
  • A token for a machine nobody sits at (CI): the only way to a machine token is patchy login, so Your machines has no create; returns with the company-owned token (Device login, round two).
  • Groups, the owner-plus-named-users scope, addresses (company/patch), the portal that lists what you can open, request access, verified domains, SSO, company deletion, deactivation beyond removing a user, billing and onboarding-with-card. docs/product.md keeps them; each returns as its own effort once auth is live.
  • The operator's surfaces: Patchy's own login and dashboards for managing customers, moderation, suspension and quotas. A separate effort, deliberately unconstrained here: no placeholder issue, no seam kept in the spec (The operator is Patchy, not a token).
  • Tier 1: the viewer's claims in the browser and the identity patch code acts as. Serving gets the door; the runtime is its own map.
  • Deployment: the production Clerk instance needs the deployment's domain, which the deployment effort owns, and with it the production sign-in polish (Google consent screen in production, Microsoft publisher verification, the CNAMEs). This map builds against a Clerk development instance.
  • patches: drop expiry, add retire and delete with a recovery window #93, drop expiry and add retire and delete.
  • Whether a deactivated user's owner-only patches go dark: #93's, once ownership lands.

Sub-issues

Sub-issues

18 of 18 Issues completed
Loading 18 sub-issues

Activity

  1. added
    wayfinder:map
    on Sep 2, 2026
  2. allisonmahmood commented on Sep 6, 2026

    @allisonmahmood
    OwnerAuthor

    The auth map is complete: all child tickets are closed. The final live development verification passed, as recorded in Run the production handshake leg once against a live Clerk instance. Allison explicitly accepted closing after development verification because no production deployment exists yet. Production handshake and CNAME cookie behavior remain unverified until deployment; this closure does not claim otherwise.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    wayfinder:map

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions