Skip to content

feat(auth): confirm device logins and manage machines - #156

Merged
allisonmahmood merged 3 commits into
mainfrom
auth/141-device-login-server
Sep 6, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
auth/141-device-login-server

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner

Machines need a way to become their user, and people need a way to revoke machines they no longer trust.

Adds browser-confirmed device login: the person checks the terminal's code, then the terminal's poll mints a token exactly once. Your machines lists live keys, revokes one or all, and signs the browser out. Confirm and Deny return their informational outcome directly with HTTP 200 and private, no-store; later GETs read the current code state. Invalid machine names render the specified 422 page. Includes bounded device request bodies, the wire docs, glossary updates and machine-token ADR.

Stacked on auth/139-sharing-scope. This PR targets that branch and contains only the device-login work above it.

Closes #141.

Verified:

  • pnpm test — 306 tests passed.
  • pnpm typecheck, pnpm lint, pnpm format:check, and packed CLI e2e passed.
  • Real Clerk development-session/browser flow: direct Confirm/Deny POST 200 with no-store and no redirect; later code GET 410 already used; poll completes once or answers denied; GET after consumption 404.
  • Earlier live flow also verified whoami, machine revocation to 401, sign-out with an empty cookie jar, and mobile blank/overlong names returning 422.

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 git diff origin/auth/139-sharing-scope...HEAD: base 4caf94c624d69837722679fe66db6c1847d8250e, PR head 1166c182cf910a65e1c6e9c170101199ac277def (feat(auth): add device login and Your machines), against #141 and its referenced protocol/page decisions. One pass, no subagents; merge blockers only.

Standards

P1 · Method — Bound the anonymous request bodies using the existing reader

packages/auth/src/AuthApi.ts:53–61, also the start handler at lines 31–39.

Both handlers call request.json directly. Effect's Node implementation buffers the complete body before parsing, and MaxBodySize defaults to undefined; the server supplies no global cap. The poll bypasses the per-address guard, and an unknown device code returns before consuming any device-code limit. No credential or valid login is needed to repeatedly send arbitrarily large bodies. Start additionally persists the unrestricted hint. This exposes unbounded memory consumption, with unauthenticated database growth on start, rather than merely accepting an unusual machine name.

Reproduced against the actual Server.layer, on an ephemeral socket and isolated Postgres: an anonymous start accepted an 8 MiB hint with 201 and stored 8,388,608 bytes. Anonymous polls with 8,388,625-byte JSON bodies returned 410 unknown, both with a declared length and with chunked transfer; neither was cut off.

Smallest fix: use the existing @patchy/api readBody(maxBytes), already used by the patch handlers, with a small fixed limit appropriate to these login payloads. Keep the refusal declared in the wire contract and rendered docs, and cover declared-length and streaming overflow. The new POST /login/device form reader also needs a bound: it buffers urlParamsBody before session admission. No new abstraction or rate-limit subsystem is needed.

Spec

No merge-blocking intent or YAGNI findings. The specified state machine, one-time mint/replacement transaction, reverse states, machine revocation, sign-out, analytics and ADR are represented in the change.

Verification: 7 focused suites passed, 68 tests (DeviceLogins, DevicePages, MachineTokens, AuthApi, AuthPages, AuthPages.socket and ApiGuard). The isolated body-ingestion reproduction exited 0. No source changes; no production or existing dev instance touched. Live Clerk/browser acceptance was not rerun.

Summary: Standards: 1 blocker — unbounded anonymous body ingestion. Spec: 0 blockers.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Fixed point: auth/139-sharing-scope (4caf94c…1166c18). Spec: #141.

This is a two-axis review (Standards vs Spec), plus the extra questions asked: #141's intent vs what landed, the method, and whether the code is the smallest correct model.

Standards

Documented

  • DeviceLogins.poll returns the /api/login/device/token body, and AuthApi forwards it (DeviceLogins.ts PollResult / poll, AuthApi.ts ~59–62). Hard. ADR-0002: one schema per wire shape, only in packages/api; the server encodes through those schemas. Effect conventions: map domain failures onto HttpApiError at the handler. Start already does new DeviceLoginStarted(...). Poll should return a domain result / fail with tagged errors, and AuthApi should construct DeviceLoginPoll / refuse(DeviceLoginGone, …).
  • DeviceLoginPoll is an anonymous Schema.Union of structs (packages/api/src/schemas.ts). Hard (ADR-0002). Success bodies are Schema.Class; refusals may be Schema.Struct. The handler cannot construct a schema instance the way it does DeviceLoginStarted.
  • Denied has no tagged error (DeviceLogins.poll ~272–274). Hard (effect-service-conventions / errors). Expired and unknown have Schema.TaggedError classes whose message is the wire string; denied is a distinct caller-visible code plus "This device login was denied." with no tag. Add DeviceLoginDenied (or one poll-failure type with a multi-value discriminator) and map it in the handler.
  • packages/cli/CONTEXT.md “Login handoff” still reads “Once device login lands”. Hard (Hit every surface / vocabulary). The HTTP flow has landed; point the term at start’s URL/code and the forthcoming patchy login.
  • .auth-card .device-code (white-space: nowrap + clamp(1.65rem, 7vw, 3rem)) (DevicePages.ts). Hard (ui-consistency: inspect emitted CSS / preserve responsive geometry). On a ~320px viewport the card content is ~224px; clamp floors at 1.65rem, so XXXX-XXXX + letter-spacing can overflow (nowrap beats parent overflow-wrap). Lower the floor or allow wrap.

Smells (judgement)

  • Duplicated Code — lookup / confirm / deny: readPending + isAnswerError + re-yield* instead of failing inside the transaction.
  • Duplicated Code — postDevice: lookup then confirm/deny, each readPending; an invalid name also pays renderConfirm’s lookup. POST burns two lookup tokens.
  • Duplicated Code — .machines-list / .machine-row vs CompanyPage .company-list / .company-row. Same list-row treatment; two owners now.
  • Mysterious Name — DeviceLoginAnswered: covers confirmed and denied; poll’s denied is a different state.

No runPromise / named "effect" imports / Layer.succeed in production services. Pages go through htmlPage via pageResponse; user values are escaped; no inline script. Dedicated Effect-service and UI-consistency passes reported no additional violations. Shotgun file list is required by Hit every surface — not a smell here.

Spec

(a) Missing / partial

(b) Not asked for

(c) Implemented but wrong

  • Receipts do not read the row. GET ?code=…&result=confirmed (or denied) always shows that copy while the login can still be pending. Spec reverse states are outcomes, not query flags.
  • token.minted replaced. feat(auth): device login on the server, the confirm page and Your machines #141 / §9: whether an old key was replaced. replaced = revokeOwned() !== null, so an already-revoked same-user key still reports replaced: true (alreadyRevoked). The “expired and revoked old keys still lend their names” test does not assert the event.

Copy that does match (not defects): #141’s two rewrites beat §8 and #131 A — re-login is “which stops working once your terminal finishes logging in” (not “when you confirm”); confirmed is “Confirmed. Your terminal finishes logging in on its own within a few seconds. You can close this tab.” (no §8 parenthetical). Confirm does not mint; poll does.

Wire, guard (two anonymous POSTs, start 5/min), poll-once + concurrent unknown, deny/expiry/slow_down, same-user revoke only, abandoned confirm, deactivate-between-confirm-and-poll, /login default /machines, POST /logout cookies, glossary, ADR-0008, docs/API.md preamble, CI future tense, and the listed tests are present.

Intent vs #141

#141’s product sentence: a person in a signed-in browser authorizes a machine; they never type a code. Confirm records the user and name and mints nothing; the terminal’s poll mints the user-owned 90/30 token once, deletes the row, and a second poll is 410. Your machines lists live tokens with revoke one, revoke all, and browser sign-out.

The PR implements that protocol. Drift is nearby, not a different product: POST/redirect/GET receipts so reload stays readable after the poll deletes the row; confirmed copy follows #141’s short line, not spec §8’s parenthetical; browser POST /logout clears Clerk only (ADR-0008, not a bug).

Person-facing: code first, company/person/email, name the machine, Confirm or Deny, “terminal finishes on its own.” Machine-facing: unauthenticated start → pending/slow_down → one complete mint → second poll 410 unknown. Concurrent polls, abandoned confirm, and deactivation-between-confirm-and-poll match.

Verdict: mostly faithful with notes. The lying receipt (?result=confirmed without a confirm) is the one a person can actually see.

Method

The split is the one #141 names: DeviceLogins (state), DevicePages (HTML + PRG), AuthApi (wire), MachineTokens (credential). JSON, session HTML, and minting have different doors; folding /machines into AuthPages would mix unrelated routes.

Poll order is sound: FOR UPDATE → expiry/denied delete (no limit) → consume interval → pending return → mint (user FOR UPDATE, UserUnavailable → delete + unknown) → revokeOwned only for the confirming user → delete → plaintext from memory. Lock-before-limit is why the concurrent loser is unknown, not slow_down. Nested mint is a savepoint; the delete-trigger test proves mint + replace roll back together. Analytics track after commit is correct (track never fails; do not hold FOR UPDATE for PostHog).

Receipt GET is not a spec dodge by itself: lookup only accepts pending, poll deletes the row, reload must not re-POST. The method smell is that result= is a query flag, not a read of the login.

postDevice looking up then confirming is the complexity that is not justified: confirm itself is unlimited, so the extra lookup exists to bound blind POSTs, and invalid names pay twice. Fold limits.consume into confirm/deny (one transaction). Same spec, fewer round trips.

PollResult as DeviceLoginPoll ∪ DeviceLoginGone is a layer leak. Pending/complete belong in the service; expired|denied|unknown should be TaggedErrors mapped at the API boundary, like lookup.

Mint-on-confirm + a plaintext column (the prototype) would fail #141. This transaction and hash-only row are the justified complexity.

YAGNI

This is already close to the smallest correct model. Mint-at-poll is the design. The guard adds a device-login kind instead of a path table. page.heading is the only shell tweak. The 571/571 test files are coincidence: different suites, spec-shaped, not copy-paste.

Leave alone: lock-before-limit, mint under user FOR UPDATE, signed-out POST that keeps only the code (never the name), cookie Domain/Path clearing, sec-fetch-site only when Origin is absent.

Nits, not architecture: DevicePages SchemaError and HttpServerError are the same 400 page; a couple of DeviceLogins tests re-prove expiry/unknown. Do not share the AuthPages/DevicePages error mappers (copy differs). Do not extract a handleRaw helper for the two anonymous routes.

Overall: good with nits. Spec-faithful, not architecturally impressive — which is the right shape.

Surfaces

Wire (api → AuthApi → docs/API.md) applied; CLI N/A until the login ticket; vocab/product/ADR-0008 applied; device_logins already in the auth baseline (no new migration); reverse states (deny, revoke one/all, browser sign-out) applied. schemas.test.ts dropped the OpenAPI path inventory; api-md.test.ts still pins docs/API.md. New device-login schemas are not in the round-trip cases.


Summary: Standards: 5 documented findings, 4 smells; worst is poll returning the wire body (ADR-0002). Spec: 2 missing/partial, 4 extras, 2 wrong; worst is receipt URLs that do not read login state (and token.minted.replaced treating an already-revoked key as a replacement).

@github-actions github-actions Bot added the area:cli Touches the cli area label Sep 5, 2026
@allisonmahmood

allisonmahmood commented Sep 5, 2026 •

Copy link
Copy Markdown
Owner Author

Correction: direct informational outcomes, not signed receipts

My prior receipt reasoning was wrong. Confirmed and denied copy is informational, not authorization; signing it with a per-process secret added machinery without protecting a real permission boundary. 802a884 removes that change (270 net lines removed).

  • Removed AnswerReceipt, the random signing secret, HMAC/signature verification, receipt encoding/decoding, receipt URLs, and receipt-specific tests.
  • Confirm and Deny now return their outcome page directly from the POST: 200, Cache-Control: private, no-store, no Location header.
  • Later GETs read the code's actual state: pending renders the form; confirmed or denied returns 410 already used; once the poll deletes the row, GET returns 404 unknown. No outcome survives in a second store or signed artifact.
  • Removed the receipt-only lookup union, extra pending-state discriminator and deny's receipt-only user recording. Existing tests now assert the direct response contract.
  • Corrected the development documentation and this PR's description. This supersedes my previous signed-receipt disposition and POST/redirect/GET claims.

Real fixes retained

Review finding Disposition and reason
Unbounded anonymous JSON and pre-session device forms Kept the 4096-byte body limits. Both JSON routes use the existing bounded reader; the form is bounded before parsing/session admission. Declared overflow returns 413; Effect's Node reader terminates streaming overflow. Socket regressions ensure no oversized hint is stored or polling allowance consumed.
Poll returns wire bodies / anonymous success structs / denied has no tag Kept domain poll successes without ok, named wire success classes, and tagged expired/denied/unknown errors mapped explicitly at AuthApi. Terminal deletion still commits before a tagged failure is raised; wire JSON is unchanged.
Repeated transaction-error propagation and POST lookups Kept direct typed failure handling for page transactions and a shared per-user allowance on lookup/confirm/deny. Invalid form rendering consumes one lookup, not two.
Stale Publishing Login handoff glossary Kept the distinction between the available server HTTP flow and the forthcoming CLI command.

Findings kept or dismissed

  • Receipt authenticity / separately readable confirmed and denied outcomes: rejected as a security requirement. The person receives the informational outcome from their POST. The pending-only GET answers already used while the row exists; the poll intentionally deletes it. No HMAC or persistent outcome is warranted.
  • 320px device-code overflow: false positive on the actual rendered page: 152.05px code text inside 220px content, document width 320px. CSS unchanged.
  • Company/machine row CSS: kept small page-owned layout rules; different child geometry does not warrant a shared component or additional coupling.
  • DeviceLoginAnswered naming: kept; it names an attempted second answer, whether the first action was Confirm or Deny. DeviceLoginDenied is the distinct terminal poll failure.
  • No extra expiry sweeper: Auth: Clerk, companies and machine tokens on tier 0 #135 §3 explicitly chooses deletion on start with no second background job; feat(auth): device login on the server, the confirm page and Your machines #141 requires that behavior, superseding the older Device login: the protocol, and the machine token's columns #122 note.
  • refreshed notice / unenrolled POST return: kept only the code through authentication/enrollment, never the action or machine name. The notice prompts another explicit confirmation and grants nothing.
  • 429 page and Retry-After: kept as the usable refusal for the required per-user lookup limit.
  • Origin-less POST with same-origin Fetch Metadata: kept as explicitly required by Auth: Clerk, companies and machine tokens on tier 0 #135 §7; an explicit foreign Origin is still rejected.
  • replaced=true for a dead same-user predecessor: kept as re-login succession, not a newly-performed revocation count; documented and tested for expired/revoked predecessors. Absent/foreign predecessors remain false.
  • Similar 400 handlers and expiry tests: kept the distinct form-read/parse boundaries and lifecycle assertions (page expiry preserves the row, terminal polling consumes it, start cleans up). No extra error-mapper abstraction.
  • Generic schema round-trip inventory: not expanded; actual HTTP tests already encode and assert pending/slow_down/complete responses and all three 410 outcomes, and generated API docs are checked.

Verification on the simplified implementation

  • Focused changed-path suites: 42 tests passed.
  • Full suite: 36 files, 306 tests passed. One initial concurrent run hit the unchanged ExpirySweep scheduling assertion; that suite passed in isolation and the complete rerun passed without source changes.
  • pnpm typecheck: 23 tasks passed; pnpm lint, pnpm format:check, and packed CLI e2e passed.
  • Real Clerk development-session JWT + browser on this worktree's pnpm dev: pending form rendered; both Confirm and Deny produced POST 200, private/no-store, no redirect, with the existing outcome copy. A later GET returned 410 already used in both cases. The terminal received complete/200 or denied/410; GET after polling returned 404.
  • Real body-bound socket tests still pass for declared and chunked overflow on both anonymous API routes and the form.
  • Disposable Clerk user deleted, minted machine key revoked, browser closed, local supervisor/server/Postgres confirmed stopped. No production or configuration changes.

Latest-commit merge readiness

CI run 33962420139 passed for 802a884. All available checks are green: test (22), test (24), lint (including typecheck/format), cli-smoke, dependency-review, label. GitHub reports MERGEABLE / CLEAN against the unchanged stacked base auth/139-sharing-scope. No newer review findings or unresolved blockers; not merged. The base has no enforced required-check rules configured.

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

Copy link
Copy Markdown
Collaborator
  1. i feel like this is out of scope for a v1. The thing seems unimportant for now. like the machines and trust aspect. it can come later.
    other than that lgtm

@allisonmahmood

Copy link
Copy Markdown
Owner Author

@vsrikar08 Following up on your scope feedback: Allison disagrees with deferring machines and trust. Keeping the device-login confirmation and machine-management flow in v1. No change requested on this point.

Base automatically changed from auth/139-sharing-scope to main September 6, 2026 13:01
Implement #141: confirm device logins in the browser, mint once at poll, and manage user-owned machine tokens and browser sign-out.
@allisonmahmood
allisonmahmood force-pushed the auth/141-device-login-server branch from 802a884 to 5ee3700 Compare September 6, 2026 13:01
@allisonmahmood
allisonmahmood merged commit 52b656e into main Sep 6, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the auth/141-device-login-server branch September 6, 2026 13:05
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:cli Touches the cli 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): device login on the server, the confirm page and Your machines

2 participants