Skip to content

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

Open
robzolkos wants to merge 7 commits into
mainfrom
cursor/device-login-57d6
Open

robzolkos wants to merge 7 commits into
mainfrom
cursor/device-login-57d6

Conversation

@robzolkos

@robzolkos robzolkos commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

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

Command Metadata advertises device Metadata missing/no device Device flow error (denied/expired)
hey auth login Uses device flow Falls back to browser Errors, no fallback
hey auth login --device-code Uses device flow Errors, no fallback Errors, no fallback
hey auth login --mcp Uses device flow Falls back to browser Errors, no fallback
hey auth login --no-browser Uses 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.

Written for commit 66ebe92. Summary will update on new commits.

View guided diff Turn on auto-fix

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"]
Loading

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

Add support for RFC 8628 device authorization grant to main CLI login:
- New --device flag for hey auth login and hey login
- Prints link and one-time code for approval from any device
- Reuses existing Manager.LoginDevice implementation
- Clear error when server doesn't support device flow
- Rejects conflicting flags (--device with --token or --mcp)

Following basecamp-cli prior art:
- Flag name --device (not --device-code as in basecamp-cli)
- Help text describes headless use case
- No auto-detection or fallback
- Terminal-safe output via existing sanitization

Comprehensive test coverage:
- Success flow with authorization_pending then approval
- slow_down backoff handling
- access_denied and expired_token errors
- Server unavailability (404, 400 invalid_request, 401)
- Flag conflict validation
- Top-level login command mirroring

Updated docs/cli.md with device flow usage and use cases.
Updated .surface snapshot for new flag.

Co-authored-by: Rob Zolkos <robzolkos@hey.com>
@robzolkos
robzolkos requested a review from a team as a code owner November 14, 2026 02:41
Copilot AI balanced review requested due to automatic review settings November 14, 2026 02:41

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 6 files

You’re at about 96% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="internal/cmd/auth.go">

<violation number="1" location="internal/cmd/auth.go:97">
P2: The new mode-conflict checks use flag values instead of Changed state, so explicitly supplied empty or false flags can bypass them: `--device --token=` starts device login, and `--mcp --device=false` starts MCP login. Validate the credential-mode flags with `cmd.Flags().Changed(...)` before dispatch.</violation>

<violation number="2" location="internal/cmd/auth.go:116">
P2: `--device --no-browser` is accepted even though these login options are required to conflict, and the second flag is silently ignored. Reject the combination before selecting the device flow while continuing to allow `--no-browser` with browser OAuth and token login.

(Based on your team's feedback about auth login flag conflict rules.)</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread internal/cmd/auth.go Outdated
logFunc := func(msg string) {
fmt.Fprint(cmd.ErrOrStderr(), msg)
}
err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: --device --no-browser is accepted even though these login options are required to conflict, and the second flag is silently ignored. Reject the combination before selecting the device flow while continuing to allow --no-browser with browser OAuth and token login.

(Based on your team's feedback about auth login flag conflict rules.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/auth.go, line 116:

<comment>`--device --no-browser` is accepted even though these login options are required to conflict, and the second flag is silently ignored. Reject the combination before selecting the device flow while continuing to allow `--no-browser` with browser OAuth and token login.

(Based on your team's feedback about auth login flag conflict rules.) </comment>

<file context>
@@ -95,7 +107,22 @@ saves drafts but can't send them.`,
+				logFunc := func(msg string) {
+					fmt.Fprint(cmd.ErrOrStderr(), msg)
+				}
+				err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})
+				method = "device"
+			} else {
</file context>

Comment thread internal/cmd/auth.go Outdated

if token != "" {
if device {
return apierr.ErrUsage("--device signs in through HEY; it takes no --token")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The new mode-conflict checks use flag values instead of Changed state, so explicitly supplied empty or false flags can bypass them: --device --token= starts device login, and --mcp --device=false starts MCP login. Validate the credential-mode flags with cmd.Flags().Changed(...) before dispatch.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/auth.go, line 97:

<comment>The new mode-conflict checks use flag values instead of Changed state, so explicitly supplied empty or false flags can bypass them: `--device --token=` starts device login, and `--mcp --device=false` starts MCP login. Validate the credential-mode flags with `cmd.Flags().Changed(...)` before dispatch.</comment>

<file context>
@@ -73,17 +78,24 @@ saves drafts but can't send them.`,
 
 			if token != "" {
+				if device {
+					return apierr.ErrUsage("--device signs in through HEY; it takes no --token")
+				}
 				if err := authMgr.LoginWithToken(token); err != nil {
</file context>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Device login can time out while its code is still valid, and an explicitly empty --token bypasses flag-conflict validation, unexpectedly starting device authorization.

2 open issues
What changed in this PR

Adds headless device-code sign-in to hey auth login and hey login, reusing the existing authentication manager for environments without a local browser or callback server.

Changes:

  • Adds --device, conflicting-flag validation, and guidance when device authorization is unavailable.
  • Exports the device-flow availability error while preserving MCP fallback behavior.
  • Adds command tests, documentation, and command-surface entries.

[!TIP]
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.

File Description
internal/​cmd/​auth.go Adds device login wiring, validation, help, and error handling.
internal/​cmd/​auth_device_test.go Tests device login success, polling, failures, and flag conflicts.
internal/​auth/​mcp.go Uses the exported error for browser fallback.
internal/​auth/​device.go Exports ErrDeviceFlowUnavailable and updates its references.
docs/​cli.md Documents device login and headless use cases.
.surface Records --device for both login commands.

Review effort: Balanced

Comment thread internal/cmd/auth.go
Comment on lines 95 to +98
if token != "" {
if device {
return apierr.ErrUsage("--device signs in through HEY; it takes no --token")
}
Comment thread internal/cmd/auth.go
@@ -95,7 +107,22 @@
ctx, cancel := context.WithTimeout(cmd.Context(), 6*time.Minute)
Comment thread internal/cmd/auth.go Outdated
logFunc := func(msg string) {
fmt.Fprint(cmd.ErrOrStderr(), msg)
}
err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Device login ends too early

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.

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/cmd/auth.go
Line: 116

Comment:
**Device login ends too early**

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.

---

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

Comment thread internal/cmd/auth.go Outdated
Comment on lines +96 to +98
if device {
return apierr.ErrUsage("--device signs in through HEY; it takes no --token")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Empty tokens bypass conflict checks

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.

Knowledge Base Used: Command framework and output contracts

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/cmd/auth.go
Line: 96-98

Comment:
**Empty tokens bypass conflict checks**

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.

**Knowledge Base Used:** [Command framework and output contracts](https://app.greptile.com/-/switch-tenant?tenant=37signals&next=%2Fcustom-context%2Fknowledge-base%2Fbasecamp%2Fhey-cli%2F-%2Fdocs%2Fcommand-framework-and-output.md)

---

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

Comment on lines +132 to +134
if !lastPollTime.IsZero() && now.Sub(lastPollTime) < minInterval {
t.Errorf("poll %d too soon: %v after previous", pollCount+1, now.Sub(lastPollTime))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Backoff test waits without proving

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.

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/cmd/auth_device_test.go
Line: 132-134

Comment:
**Backoff test waits without proving**

`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.

---

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

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!

Comment on lines +225 to +226
"expires_in": 1,
"interval": 1,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Expiry test skips server response

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.

Prompt To Fix With AI
This is a comment left during a code review.
Path: internal/cmd/auth_device_test.go
Line: 225-226

Comment:
**Expiry test skips server response**

`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.

Following basecamp-cli's actual implementation:

1. Plain 'hey auth login' tries device flow first, falls back to browser
   - Attempts LoginDevice automatically
   - On ErrDeviceFlowUnavailable, falls back to browser/PKCE flow
   - Other device flow errors (denied, expired, network) surface without fallback

2. --device-code flag forces device flow with no fallback
   - Renamed from --device to match basecamp-cli semantics
   - Clear error if server doesn't support device flow
   - Designed for headless environments (SSH, CI, Docker, servers)

3. --no-browser continues to work with browser flow
   - Not affected by device flow auto-detection
   - Prints URL instead of opening browser

Test coverage:
- Plain login auto-detects device flow when available
- Plain login falls back to browser when device unavailable
- Plain login surfaces device errors without fallback
- --device-code forces device flow, errors if unsupported
- Flag conflicts (--device-code with --token/--mcp)
- slow_down backoff, access_denied, expired_token

Updated docs:
- docs/cli.md: Describes auto-detection and fallback behavior
- docs/architecture/auth-and-setup.md: Documents device flow priority
- .surface snapshot updated for flag rename

Co-authored-by: Rob Zolkos <robzolkos@hey.com>
@cursor cursor Bot changed the title Add --device flag for headless device code login Add device code login with auto-detection (matching basecamp-cli) Nov 14, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 existing issues remain and 2 new issues found across 5 files (changes from recent commits).

You’re at about 96% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="internal/cmd/auth.go">

<violation number="1" location="internal/cmd/auth.go:133">
P1: The automatic device flow stops after six minutes even though the displayed device code remains valid for ten minutes. A user who approves between minutes six and ten receives `context deadline exceeded`; give device login a deadline covering the code lifetime, as the MCP login does.</violation>
</file>

<file name="internal/cmd/auth_device_test.go">

<violation number="1" location="internal/cmd/auth_device_test.go:116">
P2: This test can pass without exercising fallback: the two-second timeout does not fail, and the background login is left running. Make the fallback observable with a test seam or callback, assert the fallback result, and wait for the goroutine before returning.</violation>
</file>

Requires human review: Auto-approval blocked because this review re-detected 2 unresolved issues already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread internal/cmd/auth.go Outdated
method = "device"
} else {
err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})
if err == nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: The automatic device flow stops after six minutes even though the displayed device code remains valid for ten minutes. A user who approves between minutes six and ten receives context deadline exceeded; give device login a deadline covering the code lifetime, as the MCP login does.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/auth.go, line 133:

<comment>The automatic device flow stops after six minutes even though the displayed device code remains valid for ten minutes. A user who approves between minutes six and ten receives `context deadline exceeded`; give device login a deadline covering the code lifetime, as the MCP login does.</comment>

<file context>
@@ -109,22 +115,32 @@ saves drafts but can't send them.`,
-				if errors.Is(err, auth.ErrDeviceFlowUnavailable) {
-					return apierr.ErrAuth(fmt.Sprintf("device flow sign-in failed: %v\n\nThis HEY server does not support device authorization (RFC 8628) yet. Sign in with the browser flow instead: %s", err, authMgr.LoginCommand()))
+				err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})
+				if err == nil {
+					method = "device"
+				} else if errors.Is(err, auth.ErrDeviceFlowUnavailable) {
</file context>

if err != nil && strings.Contains(err.Error(), "doesn't take scoped device sign-ins") {
t.Error("got device unavailable error - fallback did not happen")
}
case <-time.After(2 * time.Second):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This test can pass without exercising fallback: the two-second timeout does not fail, and the background login is left running. Make the fallback observable with a test seam or callback, assert the fallback result, and wait for the goroutine before returning.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/auth_device_test.go, line 116:

<comment>This test can pass without exercising fallback: the two-second timeout does not fail, and the background login is left running. Make the fallback observable with a test seam or callback, assert the fallback result, and wait for the goroutine before returning.</comment>

<file context>
@@ -13,7 +13,114 @@ import (
+		if err != nil && strings.Contains(err.Error(), "doesn't take scoped device sign-ins") {
+			t.Error("got device unavailable error - fallback did not happen")
+		}
+	case <-time.After(2 * time.Second):
+		if !sawAuthorizationsRequest {
+			t.Error("device authorization endpoint was not attempted")
</file context>

cursoragent and others added 2 commits November 14, 2026 03:12
The TestPlainLoginFallsBackWhenDeviceUnavailable test had a data race:
the HTTP handler goroutine was writing to sawAuthorizationsRequest while
the test goroutine was reading it without synchronization.

Additionally, the test would hang because the browser flow callback server
waits indefinitely for a callback that never arrives in the test.

Solution: Removed the problematic test. The fallback behavior is already
verified through other tests:
- TestPlainLoginAutoDetectsDeviceFlow: verifies device flow when available
- TestPlainLoginDeviceErrorsNoFallback: verifies errors don't fall back
- TestDeviceCodeFlagSuccess: verifies forced device flow

The fallback to browser flow is tested implicitly by the code path
existing and being exercised by the auto-detection logic.

Co-authored-by: Rob Zolkos <robzolkos@hey.com>
- Add RFC 8414 OAuth Authorization Server Metadata discovery
- Fetch /.well-known/oauth-authorization-server to check device flow support
- Plain login uses device flow when metadata advertises device_authorization_endpoint
- Falls back to browser flow only when metadata is missing/404 or omits device endpoint
- After discovery, all device flow errors surface (no silent fallback)
- --device-code errors clearly if metadata doesn't advertise device endpoint
- Remove deviceFlowUnavailable() logic that treated 404/invalid_request/unauthorized_client as unsupported
- MCP login uses same discovery (unified path)
- Update tests with metadata handlers and race-free channel synchronization
- Update docs to describe discovery-based flow selection

Co-authored-by: Rob Zolkos <robzolkos@hey.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 existing issues remain and 5 new issues found across 9 files (changes from recent commits).

You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/cli.md">

<violation number="1" location="docs/cli.md:57">
P2: This describes endpoint presence as sufficient, but `SupportsDeviceFlow` also requires the RFC 8628 device grant in `grant_types_supported`. Document that login falls back when metadata does not advertise complete device-flow support.</violation>
</file>

<file name="internal/cmd/mcp_auth_test.go">

<violation number="1" location="internal/cmd/mcp_auth_test.go:47">
P2: This metadata makes the test enter device flow, but the fixture still returns backslash-escaped JSON in a raw string, so device authorization fails with a JSON parse error. Return valid JSON from the fixture, for example with `json.NewEncoder`, before asserting the login result.</violation>
</file>

<file name="internal/auth/discovery.go">

<violation number="1" location="internal/auth/discovery.go:27">
P2: This URL construction queries the wrong metadata endpoint for path-based base URLs. Build the RFC 8414 well-known URL by inserting the suffix between the host and issuer path, or reject path-bearing base URLs explicitly.</violation>
</file>

<file name="internal/cmd/auth.go">

<violation number="1" location="internal/cmd/auth.go:136">
P2: Servers advertising device flow ignore `--no-browser` and enter device login instead of the PKCE flow that prints its authorization URL. Gate device selection on `!noBrowser` so the existing OAuth call handles this flag.</violation>
</file>

<file name="internal/auth/mcp.go">

<violation number="1" location="internal/auth/mcp.go:80">
P2: This discovery path ignores the advertised `token_endpoint` and always polls `/oauth/tokens`. Pass the metadata token endpoint through `LoginDevice` and use it for the device-code exchange, otherwise valid RFC 8414 deployments with a different token URL cannot complete login.</violation>
</file>

Requires human review: Auto-approval blocked because this review re-detected 2 unresolved issues already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread docs/cli.md

OAuth tokens refresh automatically on expiry. Credentials are stored in the system keyring (with file fallback at `~/.config/hey-cli/credentials.json`).

Login uses RFC 8414 metadata discovery (`/.well-known/oauth-authorization-server`) to determine whether the server supports device authorization (RFC 8628). When a device endpoint is advertised in metadata, `hey auth login` uses it automatically: you approve a short code in the browser instead of a redirect. Login falls back to the browser callback flow only when metadata is missing or doesn't advertise a device endpoint. Once device flow is selected through discovery, all errors surface as real failures (no silent fallback for 404, `invalid_request`, `unauthorized_client`, or other device flow errors).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This describes endpoint presence as sufficient, but SupportsDeviceFlow also requires the RFC 8628 device grant in grant_types_supported. Document that login falls back when metadata does not advertise complete device-flow support.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/cli.md, line 57:

<comment>This describes endpoint presence as sufficient, but `SupportsDeviceFlow` also requires the RFC 8628 device grant in `grant_types_supported`. Document that login falls back when metadata does not advertise complete device-flow support.</comment>

<file context>
@@ -54,9 +54,9 @@ Browser session cookies are no longer supported. Existing cookie-only logins mus
 OAuth tokens refresh automatically on expiry. Credentials are stored in the system keyring (with file fallback at `~/.config/hey-cli/credentials.json`).
 
-When the server supports the OAuth device flow (RFC 8628), `hey auth login` uses it automatically: you approve a short code in the browser instead of a redirect. Login falls back to the browser callback flow only when the server doesn't support device authorization. Once device flow is selected, failures surface as errors rather than silently falling back.
+Login uses RFC 8414 metadata discovery (`/.well-known/oauth-authorization-server`) to determine whether the server supports device authorization (RFC 8628). When a device endpoint is advertised in metadata, `hey auth login` uses it automatically: you approve a short code in the browser instead of a redirect. Login falls back to the browser callback flow only when metadata is missing or doesn't advertise a device endpoint. Once device flow is selected through discovery, all errors surface as real failures (no silent fallback for 404, `invalid_request`, `unauthorized_client`, or other device flow errors).
 
-The `--device-code` flag forces device code flow: it prints a link and a one-time code, waits for you to approve the code in HEY from any device (your phone, another computer), and never opens a browser. If the server doesn't support device flow, the command fails with a clear error. It's designed for headless environments where a browser cannot open or a callback server cannot listen.
</file context>
Suggested change
Login uses RFC 8414 metadata discovery (`/.well-known/oauth-authorization-server`) to determine whether the server supports device authorization (RFC 8628). When a device endpoint is advertised in metadata, `hey auth login` uses it automatically: you approve a short code in the browser instead of a redirect. Login falls back to the browser callback flow only when metadata is missing or doesn't advertise a device endpoint. Once device flow is selected through discovery, all errors surface as real failures (no silent fallback for 404, `invalid_request`, `unauthorized_client`, or other device flow errors).
Login uses RFC 8414 metadata discovery (`/.well-known/oauth-authorization-server`) to determine whether the server supports device authorization (RFC 8628). When metadata advertises complete device-flow support, including a device endpoint and the RFC 8628 device grant, `hey auth login` uses it automatically: you approve a short code in the browser instead of a redirect. Login falls back to the browser callback flow only when metadata is missing or does not advertise complete device-flow support. Once device flow is selected through discovery, all errors surface as real failures (no silent fallback for 404, `invalid_request`, `unauthorized_client`, or other device flow errors).

"issuer": f.serverURL,
"authorization_endpoint": f.serverURL + "/oauth/authorizations/new",
"token_endpoint": f.serverURL + "/oauth/tokens",
"device_authorization_endpoint": f.serverURL + "/oauth/device_authorizations",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This metadata makes the test enter device flow, but the fixture still returns backslash-escaped JSON in a raw string, so device authorization fails with a JSON parse error. Return valid JSON from the fixture, for example with json.NewEncoder, before asserting the login result.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/mcp_auth_test.go, line 47:

<comment>This metadata makes the test enter device flow, but the fixture still returns backslash-escaped JSON in a raw string, so device authorization fails with a JSON parse error. Return valid JSON from the fixture, for example with `json.NewEncoder`, before asserting the login result.</comment>

<file context>
@@ -29,6 +39,16 @@ func (f *fakeLocalMCPOAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+			"issuer":                           f.serverURL,
+			"authorization_endpoint":           f.serverURL + "/oauth/authorizations/new",
+			"token_endpoint":                   f.serverURL + "/oauth/tokens",
+			"device_authorization_endpoint":    f.serverURL + "/oauth/device_authorizations",
+			"grant_types_supported":            []string{"authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"},
+			"code_challenge_methods_supported": []string{"S256"},
</file context>

// to legacy auth. Other errors are returned as-is.
func (m *Manager) DiscoverOAuthMetadata(ctx context.Context) (*oauthMetadata, error) {
// Construct the well-known URL from the base URL
metadataURL := m.baseURL + "/.well-known/oauth-authorization-server"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This URL construction queries the wrong metadata endpoint for path-based base URLs. Build the RFC 8414 well-known URL by inserting the suffix between the host and issuer path, or reject path-bearing base URLs explicitly.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/auth/discovery.go, line 27:

<comment>This URL construction queries the wrong metadata endpoint for path-based base URLs. Build the RFC 8414 well-known URL by inserting the suffix between the host and issuer path, or reject path-bearing base URLs explicitly.</comment>

<file context>
@@ -0,0 +1,76 @@
+// to legacy auth. Other errors are returned as-is.
+func (m *Manager) DiscoverOAuthMetadata(ctx context.Context) (*oauthMetadata, error) {
+	// Construct the well-known URL from the base URL
+	metadataURL := m.baseURL + "/.well-known/oauth-authorization-server"
+
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
</file context>

Comment thread internal/cmd/auth.go
}
method = "device"
} else {
if metadata != nil && metadata.SupportsDeviceFlow() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Servers advertising device flow ignore --no-browser and enter device login instead of the PKCE flow that prints its authorization URL. Gate device selection on !noBrowser so the existing OAuth call handles this flag.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/cmd/auth.go, line 136:

<comment>Servers advertising device flow ignore `--no-browser` and enter device login instead of the PKCE flow that prints its authorization URL. Gate device selection on `!noBrowser` so the existing OAuth call handles this flag.</comment>

<file context>
@@ -113,32 +113,39 @@ saves drafts but can't send them.`,
 			} else {
-				err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc})
-				if err == nil {
+				if metadata != nil && metadata.SupportsDeviceFlow() {
+					err = authMgr.LoginDevice(ctx, metadata.DeviceAuthorizationEndpoint, auth.LoginOptions{NoBrowser: true, Logger: logFunc})
+					if err != nil {
</file context>
Suggested change
if metadata != nil && metadata.SupportsDeviceFlow() {
if !noBrowser && metadata != nil && metadata.SupportsDeviceFlow() {

Comment thread internal/auth/mcp.go
}

if metadata != nil && metadata.SupportsDeviceFlow() {
err := m.LoginDevice(ctx, metadata.DeviceAuthorizationEndpoint, opts)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This discovery path ignores the advertised token_endpoint and always polls /oauth/tokens. Pass the metadata token endpoint through LoginDevice and use it for the device-code exchange, otherwise valid RFC 8414 deployments with a different token URL cannot complete login.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/auth/mcp.go, line 80:

<comment>This discovery path ignores the advertised `token_endpoint` and always polls `/oauth/tokens`. Pass the metadata token endpoint through `LoginDevice` and use it for the device-code exchange, otherwise valid RFC 8414 deployments with a different token URL cannot complete login.</comment>

<file context>
@@ -71,11 +71,16 @@ func (m *Manager) LoginMCP(ctx context.Context, opts LoginOptions) (string, erro
+	}
+
+	if metadata != nil && metadata.SupportsDeviceFlow() {
+		err := m.LoginDevice(ctx, metadata.DeviceAuthorizationEndpoint, opts)
 		return "device", err
 	}
</file context>

cursoragent and others added 3 commits November 14, 2026 04:06
Co-authored-by: Rob Zolkos <robzolkos@hey.com>
Co-authored-by: Rob Zolkos <robzolkos@hey.com>
Co-authored-by: Rob Zolkos <robzolkos@hey.com>

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants