Repository navigation
Description
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 loginis 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:
grillinganddomain-modelingon grilling tickets;researchon research tickets — findings go in the ticket's resolution comment, never on a branch;prototypeon the prototype;effect-service-conventionsandnode_modules/effect/AGENTS.mdbefore writing Effect code; the Hit every surface list inAGENTS.mdbefore 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.
- The destination has the port map's shape: decisions → spec →
ready-for-agentbuild tickets; nothing is built under the map itself. - "Minimal company and admin" is the in/out split in the Notes.
- 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.
- 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".
- 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/backend3.17.0'sauthenticateRequest(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 intoSet-Cookieon the server's own response, eligible only for GET document navigations, so/api/*never redirects. Token verification is local withjwtKey, but completing a handshake calls the Backend API, so the door is not networkless.__sessionis host-only on the app,__client_uaton the registrable domain: pages, API and Account Portal must share one registrable domain (production Frontend API is a CNAMEclerk.<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:azpon handshake-minted tokens onceauthorizedPartiesis 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-organizationsession task and pending-session handling. Webhooks are Svix, eventually consistent, and need a tunnel or Clerk's newclerk webhooks listenrelay 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 andaccounts.<domain>in production, withredirect_urlconfined 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/testingis Playwright and Cypress only; a session JWT signed by an RSA-2048 (e=65537) test keypair verifies throughjwtKeywith no network, because the PEM parser hard-codes that key shape, mirroring Clerk's own suite but not a documented contract, so pin@clerk/backendand 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
BCDFGHJKLMNPQRSTVWXZasXXXX-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/expireCookiewith no defaults (sethttpOnly,secure,sameSite,pathyourself; cookies ride onresponse.cookies, neversetHeaders);redirect(location, { status, cookies });HttpServerRequest.toWebbuilds a FetchRequest, buttoURLtrustsx-forwarded-protofrom any peer andTrustedProxiesdoes not gate it, so the door builds its URL frompublicBaseUrl. Forms throughschemaBodyUrlParams; no CSRF helper, so SameSite=Lax plus an Origin check plus a per-session token; the door's pages need their own CSP withform-action 'self'. Route-scopedHttpRouter.middleware(fn)provided only to the two/d/*registrations, soPages.layersplits into doored and undoored routes and the global chain inServer.tsis untouched. The test fetch client follows redirects and keeps no cookies: drive hops by hand withredirect: "manual", or test in memory withHttpRouter.toHttpEffectandHttpServerRequest.fromWeb. -
Create the Clerk application and hand its development keys to the dev loop: done. Application
patchy-cloud(app_3ImZuFeZJb8038U0oFds84rupA2), development instance only; Account Portalhttps://engaging-earwig-3123.accounts.dev(sign-in at/sign-in?redirect_url=…), Frontend APIengaging-earwig-3123.clerk.accounts.dev. Google, Microsoft and email code on, passwords off, Organizations off,emailandnameadded as session claims. Keys in~/.config/patchy-cloud/dev.env(CLERK_PUBLISHABLE_KEY,CLERK_SECRET_KEY, written byclerk env pull --app … --file), which the dev runner now hands to the server (commit1cedc43ont3code/afc9820c, to land by PR). Clerk CLI 3.3.0 installed and signed in;clerk configandclerk env pulldrive the instance with--app, noclerk initorclerk 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".azpis present andauthorizedPartiesworks (a wrong list is a silent loop); the dev FAPI returns the handshake in token form, so completion is local;__sessionis host-only,__client_uatcarries the hostDomain; the SDK derivesredirect_urlfromHost/X-Forwarded-*, so the door must pin them from the public base URL; undici'sredirect: "manual"exposes the 307 and nine offline keypair-through-jwtKeytests cover both key shapes; sign-out works and must clear the handshake cookies with the setter'sDomain. Revocation reaches a page in up to 65 s. Dev cannot show the production cookie leg or whether FAPI honoursformat=noncethere. 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) andpublic, set byupload --shareandpatchy share. Three wrong-person states: door, create-or-join, the missing-patch 404; no "no access" page until owner-only returns. Doored responsesprivate, 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 fromPATCHY_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 onisatty, 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 blockingpatchy loginfor a human at a TTY and one JSON document pluspatchy 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_at90 days and hourly-stampedlast_used_atfor 30 idle;/api/meone shape (user, company, role, machine; theoperatorkind and flag were dropped by The operator is Patchy, not a token), scopes gone,POST /api/tokensgone; Your machines pluspatchy logout(local delete first, revoke as a courtesy, unreachable is a warning not an exit code); CI out of this slice;uploadwith no token islocaland never starts a login. -
patchy login end to end: the handoff, the confirm page, the token: Stripe's gate plus resume.
patchy loginblocks only for a human at a TTY (stdin a terminal, no--json, no agent variable set;isattyalone is wrong, since an agent's shell tool has a TTY and sees nothing before exit); otherwise one JSON document withnextandagentNextSteps, and a rerun resumes the pending login rather than minting another;--complete [code]is the explicit form,pendingafter--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/deviceis 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. Branchprototype/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);
usershas its own id withclerk_user_idunique, lowercased unique email and name refreshed from the session claims on change; every enumerated columnTEXTplusCHECK;patchescarries bothcompany_idandowner_user_id,NOT NULL. Thetok_operatorrow, the nullableuser_id, theoperatorflag andPATCHY_BOOTSTRAP_API_TOKENwere dropped by The operator is Patchy, not a token:machine_tokens.user_idisNOT 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.CurrentIdentitystays in@patchy/api(the middleware must be declared there; Auth already imports it), Auth exports aViewerfor 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.layerclones the seeded vitest template, so tests andpnpm devshare one seed (Patchy Dev, adminuser_dev, machine tokenpatchy-dev-token; three migrator call sites, not four);PATCHY_DEV_CLERK_USER_IDindev.envmakes the seeded admin the developer's own Clerk user;PATCHY_OPERATOR_TOKENand the bootstrap token were dropped by The operator is Patchy, not a token.@patchy/authgetsseedandtestingentries (RSA keypair,clerkEnv, fetch guard).CLERK_JWT_KEYstays 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 APIPOST /v1/sessionsmints real JWTs, testing-only by Clerk's own doc; a live vitest config and two Playwright specs,login-doorandpatchy-login, with+clerk_testusers swept per run), both runnable locally viapnpm test:clerk. No official Clerk mock exists, soInviteMail's service boundary is the seam: live, recording and failing layers. The packed e2e seeds itself and asserts the cookie-less 401 withno-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
patchyCLI. Nothing operator-shaped is built here: the bootstrap token,tok_operator, the nullableuser_idandoperatorflag,PATCHY_OPERATOR_TOKEN, theadminscope andhasScope, and the moderation and pin routes (read,listByPrincipal,disable,pin,unpin) all go;/api/meis one shape;revokestays 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 APIsuper-whale-1225.clerk.accounts.dev, Account Portalhttps://super-whale-1225.accounts.dev; config mirrored frompatchy-cloud(Google, Microsoft, email code; passwords and Organizations off;emailandnameclaims; test mode on; sessions at the defaults).CLERK_SECRET_KEYandCLERK_PUBLISHABLE_KEYare repository secrets, the key held nowhere else. The mint path (+clerk_testuser,POST /v1/sessions, token, delete) works; the JWT carriesemailandnameand a nullazp. The Backend API rejects.testaddresses, so the live tier's users areci-<run>[email protected].patchy-cloudhas 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-agentsub-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 versusshare … company, invites unique per company, the credential chain underlogout, sign-out reachable from every session state). Three baselines rewritten; the wire, the pages, the CLI's--jsondocuments 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 incore, 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 inviteand kin): browser only;/api/metells 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.mdkeeps 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.
Activity
allisonmahmood commentedon Sep 6, 2026
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.