Repository navigation
Conversation
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>
There was a problem hiding this comment.
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
| logFunc := func(msg string) { | ||
| fmt.Fprint(cmd.ErrOrStderr(), msg) | ||
| } | ||
| err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc}) |
There was a problem hiding this comment.
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.)
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>
|
|
||
| if token != "" { | ||
| if device { | ||
| return apierr.ErrUsage("--device signs in through HEY; it takes no --token") |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
🟡 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 rungh pr ready --undo.
Click "Ready for review" or rungh pr readyto 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
| if token != "" { | ||
| if device { | ||
| return apierr.ErrUsage("--device signs in through HEY; it takes no --token") | ||
| } |
| @@ -95,7 +107,22 @@ | |||
| ctx, cancel := context.WithTimeout(cmd.Context(), 6*time.Minute) | |||
| logFunc := func(msg string) { | ||
| fmt.Fprint(cmd.ErrOrStderr(), msg) | ||
| } | ||
| err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc}) |
There was a problem hiding this comment.
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.| if device { | ||
| return apierr.ErrUsage("--device signs in through HEY; it takes no --token") | ||
| } |
There was a problem hiding this 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
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.| if !lastPollTime.IsZero() && now.Sub(lastPollTime) < minInterval { | ||
| t.Errorf("poll %d too soon: %v after previous", pollCount+1, now.Sub(lastPollTime)) | ||
| } |
There was a problem hiding this 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.
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!
| "expires_in": 1, | ||
| "interval": 1, |
There was a problem hiding this 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.
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>
There was a problem hiding this comment.
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
| method = "device" | ||
| } else { | ||
| err = authMgr.LoginDevice(ctx, auth.LoginOptions{NoBrowser: true, Logger: logFunc}) | ||
| if err == nil { |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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>
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>
There was a problem hiding this comment.
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
|
|
||
| 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). |
There was a problem hiding this comment.
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>
| 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", |
There was a problem hiding this comment.
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" |
There was a problem hiding this comment.
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>
| } | ||
| method = "device" | ||
| } else { | ||
| if metadata != nil && metadata.SupportsDeviceFlow() { |
There was a problem hiding this comment.
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>
| if metadata != nil && metadata.SupportsDeviceFlow() { | |
| if !noBrowser && metadata != nil && metadata.SupportsDeviceFlow() { |
| } | ||
|
|
||
| if metadata != nil && metadata.SupportsDeviceFlow() { | ||
| err := m.LoginDevice(ctx, metadata.DeviceAuthorizationEndpoint, opts) |
There was a problem hiding this comment.
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>
Co-authored-by: Rob Zolkos <robzolkos@hey.com>
Co-authored-by: Rob Zolkos <robzolkos@hey.com>
Co-authored-by: Rob Zolkos <robzolkos@hey.com>

Summary
Adds RFC 8628 device code authentication to
hey auth loginusing 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-codeflag forces device flow for headless environments.Implementation
RFC 8414 Metadata Discovery
Both plain
hey auth loginand MCP login now:/.well-known/oauth-authorization-serverdevice_authorization_endpointandurn:ietf:params:oauth:grant-type:device_codeingrant_types_supporteddevice_authorization_endpointinvalid_request/unauthorized_clientare real errors, not "unsupported" signalsForced Device Flow (--device-code)
hey auth login --device-code:MCP Login Unified
hey auth login --mcpnow uses the same discovery logic:Removed Legacy Fallback Logic
ErrDeviceFlowUnavailable: no longer needed with discoverydeviceFlowUnavailable()heuristic: the function that treated 404,invalid_request,unauthorized_clientas "unsupported"Test Coverage
Comprehensive unit tests via httptest fake server with metadata handlers:
Discovery tests:
unauthorized_clientafter discovery errors without fallbackaccess_deniedafter discovery errors without fallbackForced device flow tests:
--device-codesuccess: authorization_pending → approval--device-codeerrors when metadata doesn't advertise device endpointRace detection:
go test -raceOther tests:
hey login --device-codemirroringMutation check: Temporarily broke the fallback condition in discovery →
TestPlainLoginFallsBackWhenNoDeviceEndpointfailed → restored → greenVerification
go test ./...passes (all unit tests green)go test -race ./...passes (no race conditions).surfacesnapshot updateddocs/cli.mdupdated with discovery-based flow selectiondocs/architecture/auth-and-setup.mdupdated with RFC 8414 detailsNot Verified End-to-End
Cannot run against a live HEY dev server in this environment. Smoke testing would verify:
Behavior Summary
hey auth loginhey auth login --device-codehey auth login --mcphey auth login --no-browserSummary by cubic
Adds RFC 8628 device code login with auto-detection, matching basecamp-cli.
hey auth loginandhey loginnow 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.--device-codeflag forces headless sign-in (prints a link and one-time code, never opens a browser) and errors clearly when device flow is unavailable.errDeviceFlowUnavailableerror with metadata discovery via/.well-known/oauth-authorization-server.--device-codecombined with--tokenor--mcp; updates docs and.surface.Written for commit 66ebe92. Summary will update on new commits.
Fix the device login deadline before merging so valid approvals do not fail early.
Findings
Fix with agent prompt
Summary
Adds
--deviceto both login commands, reusing device authorization without opening a browser.robzolkosintentionally chose an error rather than browser fallback when device authorization is unavailable.robzolkosalso 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