Add device code login with auto-detection (matching basecamp-cli)

RO
14d ago
+858-52

Summary

Adds RFC 8628 device code authentication to hey auth login using RFC 8414 OAuth Authorization Server Metadata discovery. Plain login automatically uses device flow when the server advertises it via /.well-known/oauth-authorization-server, falling back to browser flow only when metadata is missing or doesn't advertise a device endpoint. The --device-code flag forces device flow for headless environments.

Implementation

RFC 8414 Metadata Discovery

Both plain hey auth login and MCP login now:

  1. Fetch OAuth metadata from /.well-known/oauth-authorization-server
  2. Check for device support: looks for device_authorization_endpoint and urn:ietf:params:oauth:grant-type:device_code in grant_types_supported
  3. Use device flow when advertised: all discovered device endpoints are taken from metadata (no hardcoded paths)
  4. Fall back to browser flow only when:
    • Metadata is missing (404)
    • Metadata doesn't advertise device_authorization_endpoint
  5. Surface all errors after discovery: once device flow is selected, 404/invalid_request/unauthorized_client are real errors, not "unsupported" signals

Forced Device Flow (--device-code)

hey auth login --device-code:

  • Performs metadata discovery first
  • Errors clearly if metadata doesn't advertise device endpoint
  • Never opens browser, designed for SSH, CI, Docker, servers
  • No fallback: all errors surface

MCP Login Unified

hey auth login --mcp now uses the same discovery logic:

  • Discovers metadata to determine device flow availability
  • Uses device flow when advertised, browser flow otherwise
  • Consistent with CLI login behavior

Removed Legacy Fallback Logic

  • Removed ErrDeviceFlowUnavailable: no longer needed with discovery
  • Removed deviceFlowUnavailable() heuristic: the function that treated 404, invalid_request, unauthorized_client as "unsupported"
  • After discovery, all errors are real: no silent fallback for device flow errors

Test Coverage

Comprehensive unit tests via httptest fake server with metadata handlers:

Discovery tests:

  • ✅ Plain login uses device flow when metadata advertises endpoint
  • ✅ Plain login falls back when metadata omits device endpoint
  • ✅ Plain login falls back when metadata returns 404
  • ✅ unauthorized_client after discovery errors without fallback
  • ✅ access_denied after discovery errors without fallback

Forced device flow tests:

  • ✅ --device-code success: authorization_pending → approval
  • ✅ --device-code errors when metadata doesn't advertise device endpoint
  • ✅ slow_down backoff handling
  • ✅ access_denied error
  • ✅ expired_token error

Race detection:

  • ✅ Tests use channel synchronization to avoid race conditions
  • ✅ All tests pass under go test -race

Other tests:

  • ✅ Flag conflicts (--device-code + --token, --device-code + --mcp)
  • ✅ Top-level hey login --device-code mirroring
  • ✅ MCP login uses discovery for device flow selection

Mutation check: Temporarily broke the fallback condition in discovery → TestPlainLoginFallsBackWhenNoDeviceEndpoint failed → restored → green

Verification

  • go test ./... passes (all unit tests green)
  • go test -race ./... passes (no race conditions)
  • .surface snapshot updated
  • docs/cli.md updated with discovery-based flow selection
  • docs/architecture/auth-and-setup.md updated with RFC 8414 details

Not Verified End-to-End

Cannot run against a live HEY dev server in this environment. Smoke testing would verify:

  • RFC 8414 metadata discovery with production HEY server
  • Device flow selection based on real metadata
  • Fallback to browser flow on servers without metadata
  • Token storage and subsequent auth status

Behavior Summary

CommandMetadata advertises deviceMetadata missing/no deviceDevice flow error (denied/expired)
hey auth loginUses device flowFalls back to browserErrors, no fallback
hey auth login --device-codeUses device flowErrors, no fallbackErrors, no fallback
hey auth login --mcpUses device flowFalls back to browserErrors, no fallback
hey auth login --no-browserUses device flow (prints URL)Falls back to browser (prints URL)Errors, no fallback
Open in Web Open in Cursor 

Summary by cubic

Adds RFC 8628 device code login with auto-detection, matching basecamp-cli.

  • Plain hey auth login and hey login now fetch RFC 8414 metadata to auto-detect device flow, falling back to browser OAuth with PKCE only when the server doesn't advertise a device endpoint.
  • A new --device-code flag forces headless sign-in (prints a link and one-time code, never opens a browser) and errors clearly when device flow is unavailable.
  • Device flow errors (denied, expired, network) surface without fallback. MCP login uses the same discovery logic.
  • Replaces the old try-and-fallback errDeviceFlowUnavailable error with metadata discovery via /.well-known/oauth-authorization-server.
  • Rejects --device-code combined with --token or --mcp; updates docs and .surface.

RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

Fix the device login deadline before merging so valid approvals do not fail early.

Findings

  1. P1 Device login ends too early ▶
  2. P2 Empty tokens bypass conflict checks ▶
  3. P2 Backoff test waits without proving ▶
  4. P2 Expiry test skips server response ▶
Fix with agent prompt
### Issue 1
internal/cmd/auth.go:116
The new device path inherits the browser flow's six-minute deadline. Existing `loginMCP` allows twelve minutes because device codes live for ten minutes. Someone who approves after minute six finds that the CLI has already stopped with `context deadline exceeded`, even though their code is still valid. Give device login enough time to cover the code's lifetime.

### Issue 2
internal/cmd/auth.go:96-98
An explicitly empty `--token` skips this check because it sits inside `if token != ""`. For example, `hey login --device --token="$TOKEN"` starts device sign-in when `TOKEN` is unset instead of reporting conflicting flags. Check `cmd.Flags().Changed("token")`, as the `--mcp` branch already does.

### Issue 3
internal/cmd/auth_device_test.go:132-134
`TestDeviceLoginSlowDown` spends about 25 seconds sleeping, but its 100-millisecond check also passes without any backoff. Existing `TestMCPDeviceLoginStopsOnDenialAndBacksOffOnSlowDown` already checks five seconds followed by ten seconds using a fake wait. Keep the command test short and use that approach for timing checks.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 4
internal/cmd/auth_device_test.go:225-226
`TestDeviceLoginExpiredToken` sets both `expires_in` and `interval` to one second. The local expiry check therefore ends login before the first token request, so the server's `expired_token` response is not tested. Advertise a longer lifetime, assert that the token endpoint was called, and check the specific expiry message.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds --device to both login commands, reusing device authorization without opening a browser.

  • CLI login can finish through a device code without opening a browser.

robzolkos intentionally chose an error rather than browser fallback when device authorization is unavailable. robzolkos also noted that live-server smoke testing was not performed.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["hey login / hey auth login"] --> B{"Login option"}
  B -->|"--token"| C["Store supplied token"]
  B -->|"--device"| D["Request device code"]
  B -->|"default"| E["Browser OAuth with PKCE"]
  D --> F["Print sanitized link and user code to stderr"]
  F --> G["Poll HEY until approval, expiry, or cancellation"]
  G --> H["Store CLI credentials and clear cache"]
  E --> H
  D -->|"Unsupported server"| I["Return error; no browser fallback"]

Reviews (1) · Last reviewed commit: "Add --device flag for headless device co..." · Reviewed by Greptile