Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .surface
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ hey attachment save --force
hey attachment save --output
hey auth
hey auth login
hey auth login --device-code
hey auth login --mcp
hey auth login --no-browser
hey auth login --token
Expand Down Expand Up @@ -282,6 +283,7 @@ hey label view --all
hey label view --limit
hey label view --page
hey login
hey login --device-code
hey login --mcp
hey login --no-browser
hey login --token
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/auth-and-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Authentication supports three methods, all managed through `internal/auth/`:

1. **Browser-based OAuth with PKCE** (primary) — `hey auth login` opens a browser for OAuth authentication against HEY's own OAuth server (`/oauth/authorizations/new`), using PKCE (S256) for security. A local callback server on an ephemeral `127.0.0.1` port (RFC 8252 §7.3) receives the authorization code, which is exchanged for access and refresh tokens at `/oauth/tokens`.
1. **OAuth authentication** (primary) — `hey auth login` authenticates against HEY's OAuth server. Login uses RFC 8414 metadata discovery to determine whether the server supports device authorization (RFC 8628): it fetches `/.well-known/oauth-authorization-server` and checks for `device_authorization_endpoint` and `urn:ietf:params:oauth:grant-type:device_code` in `grant_types_supported`. When device flow is advertised, login uses it: a device code request to the discovered endpoint returns a short code and verification URL, polling the token endpoint exchanges the approved code for access and refresh tokens. When metadata is missing (404) or doesn't advertise a device endpoint, login falls back to browser-based OAuth with PKCE: it opens a browser for `/oauth/authorizations/new`, a local callback server on an ephemeral `127.0.0.1` port (RFC 8252 §7.3) receives the authorization code, which is exchanged at `/oauth/tokens`. Once device flow is selected through discovery, all errors surface as real failures (no fallback for 404, `invalid_request`, `unauthorized_client`, or other device errors). `--device-code` forces device code flow via discovery and fails clearly if no device endpoint is advertised. MCP sign-in (`--mcp`) uses the same discovery logic.
2. **Pre-generated bearer token** — `hey auth login --token TOKEN` stores a token directly.
3. **Environment variable** — Set `HEY_TOKEN` to use a token without storing it.

Expand Down
9 changes: 8 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,12 @@ scripts and agents can handle it.
## Authentication

```bash
# Browser-based OAuth against HEY's own OAuth server (primary method)
# OAuth authentication (automatically uses device flow when server supports it)
hey auth login

# Force device code flow for headless environments (SSH, servers, CI, Docker)
hey auth login --device-code

# Or use a pre-generated token
hey auth login --token TOKEN
```
Expand All @@ -51,6 +54,10 @@ 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`).

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


The `--device-code` flag forces device code flow: it performs metadata discovery, prints a link and a one-time code if the endpoint is advertised, waits for you to approve the code in HEY from any device (your phone, another computer), and never opens a browser. If metadata doesn't advertise a device endpoint, the command fails with a clear error. It's designed for headless environments where a browser cannot open or a callback server cannot listen.

```bash
hey auth status # check auth status
hey auth token # print the bearer token for scripting
Expand Down
33 changes: 6 additions & 27 deletions internal/auth/device.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ import (
// a scoped request is refused with invalid_request (or, on #9041 alone, the row with
// unauthorized_client), and the sign-in falls back to loopback authorization.

// errDeviceFlowUnavailable means this HEY can't serve a scoped device sign-in, so the
// caller should sign in by loopback instead.
var errDeviceFlowUnavailable = errors.New("this HEY doesn't take scoped device sign-ins yet")

// deviceGrantType is RFC 8628 §3.4's grant type.
const deviceGrantType = "urn:ietf:params:oauth:grant-type:device_code"
Expand All @@ -45,16 +42,15 @@ type deviceAuthorization struct {
}

// LoginDevice signs in with the device authorization grant, asking for the manager's
// scope. It returns errDeviceFlowUnavailable, wrapped with HEY's answer, when this HEY
// can't serve the request, so the caller can fall back to Login.
func (m *Manager) LoginDevice(ctx context.Context, opts LoginOptions) error {
// scope. The deviceAuthzEndpoint parameter comes from OAuth metadata discovery.
func (m *Manager) LoginDevice(ctx context.Context, deviceAuthzEndpoint string, opts LoginOptions) error {
tokenEndpoint := m.baseURL + "/oauth/tokens"
installID, err := m.store.InstallID()
if err != nil {
return fmt.Errorf("install id: %w", err)
}

authorization, err := m.requestDeviceAuthorization(ctx)
authorization, err := m.requestDeviceAuthorization(ctx, deviceAuthzEndpoint)
if err != nil {
return err
}
Expand Down Expand Up @@ -121,22 +117,19 @@ func webLink(link string) bool {
return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != ""
}

// requestDeviceAuthorization asks HEY for a device code (POST /oauth/device_authorizations).
func (m *Manager) requestDeviceAuthorization(ctx context.Context) (*deviceAuthorization, error) {
// requestDeviceAuthorization asks HEY for a device code at the given endpoint.
func (m *Manager) requestDeviceAuthorization(ctx context.Context, endpoint string) (*deviceAuthorization, error) {
form := url.Values{"client_id": {m.clientID}}
if m.scope != "" {
form.Set("scope", m.scope)
}
status, body, err := m.postForm(ctx, m.baseURL+"/oauth/device_authorizations", form)
status, body, err := m.postForm(ctx, endpoint, form)
if err != nil {
return nil, fmt.Errorf("device authorization request failed: %w", err)
}

if status != http.StatusOK {
code := oauthErrorCode(body)
if deviceFlowUnavailable(status, code) {
return nil, fmt.Errorf("%w (HTTP %d %s)", errDeviceFlowUnavailable, status, code)
}
return nil, fmt.Errorf("device authorization failed: HTTP %d %s", status, code)
}

Expand All @@ -150,20 +143,6 @@ func (m *Manager) requestDeviceAuthorization(ctx context.Context) (*deviceAuthor
return &authorization, nil
}

// deviceFlowUnavailable reports whether a refused device request means this HEY can't
// serve it at all: no endpoint (an older HEY), the rollout switch off (invalid_request
// for a request naming scope, haystack#9085), or a row the device flow refuses
// (unauthorized_client, #9041 without #9085).
func deviceFlowUnavailable(status int, code string) bool {
switch status {
case http.StatusNotFound, http.StatusMethodNotAllowed:
return true
case http.StatusBadRequest, http.StatusUnauthorized:
return code == "invalid_request" || code == "unauthorized_client" || code == "unsupported_grant_type"
default:
return false
}
}

// pollDeviceToken asks the token endpoint once whether the device code is approved. It
// returns the token, or the RFC 8628 §3.5 error code HEY answered.
Expand Down
76 changes: 76 additions & 0 deletions internal/auth/discovery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package auth

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)

// oauthMetadata represents RFC 8414 OAuth Authorization Server Metadata.
type oauthMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint,omitempty"`
TokenEndpoint string `json:"token_endpoint"`
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
}

// DiscoverOAuthMetadata fetches RFC 8414 OAuth Authorization Server Metadata
// from the well-known path for the given base URL. Returns nil metadata with
// no error when the metadata document is not found (404), allowing fallback
// 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>


req, err := http.NewRequestWithContext(ctx, http.MethodGet, metadataURL, nil)
if err != nil {
return nil, fmt.Errorf("building metadata request: %w", err)
}

resp, err := m.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("fetching OAuth metadata: %w", err)
}
defer resp.Body.Close()

// 404 means no metadata document - not an error, just means fallback to legacy
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("OAuth metadata request failed: HTTP %d", resp.StatusCode)
}

body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if err != nil {
return nil, fmt.Errorf("reading OAuth metadata: %w", err)
}

var metadata oauthMetadata
if err := json.Unmarshal(body, &metadata); err != nil {
return nil, fmt.Errorf("parsing OAuth metadata: %w", err)
}

return &metadata, nil
}

// SupportsDeviceFlow reports whether the metadata advertises device authorization support.
func (md *oauthMetadata) SupportsDeviceFlow() bool {
if md == nil {
return false
}
if md.DeviceAuthorizationEndpoint == "" {
return false
}
for _, grant := range md.GrantTypesSupported {
if grant == "urn:ietf:params:oauth:grant-type:device_code" {
return true
}
}
return false
}
17 changes: 11 additions & 6 deletions internal/auth/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ func (m *Manager) ClientID() string {
return m.clientID
}

// LoginMCP signs in the local MCP client. It uses the device flow where HEY serves
// scoped device requests, and otherwise loopback authorization with the same scope,
// returning which one it used ("device" or "oauth").
// LoginMCP signs in the local MCP client. It uses RFC 8414 metadata discovery to
// determine whether device flow is available, using it when present and falling back
// to loopback authorization otherwise. Returns which flow was used ("device" or "oauth").
func (m *Manager) LoginMCP(ctx context.Context, opts LoginOptions) (string, error) {
switch m.clientID {
case "":
Expand All @@ -71,11 +71,16 @@ func (m *Manager) LoginMCP(ctx context.Context, opts LoginOptions) (string, erro
return "", fmt.Errorf("the configured MCP client id is the CLI's own; set the HEY MCP (local) client id")
}

err := m.LoginDevice(ctx, opts)
if !errors.Is(err, errDeviceFlowUnavailable) {
metadata, err := m.DiscoverOAuthMetadata(ctx)
if err != nil {
return "", fmt.Errorf("OAuth metadata discovery failed: %w", err)
}

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>

return "device", err
}
opts.log(fmt.Sprintf("\n%v, so signing in through the browser instead.\n", err))

return "oauth", m.Login(ctx, opts)
}

Expand Down
42 changes: 34 additions & 8 deletions internal/auth/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ type fakeHEYOAuth struct {
t *testing.T

mu sync.Mutex
// metadataStatus controls metadata discovery; 404 means no metadata, 0 serves metadata.
// When metadataStatus is 0 and metadataOmitDevice is true, metadata omits device_authorization_endpoint.
metadataStatus int
metadataOmitDevice bool
serverURL string
// deviceStatus and deviceError answer the device authorization request; zero
// serves a device code.
deviceStatus int
Expand Down Expand Up @@ -56,6 +61,23 @@ func (f *fakeHEYOAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

switch {
case r.Method == http.MethodGet && r.URL.Path == "/.well-known/oauth-authorization-server":
if f.metadataStatus != 0 {
w.WriteHeader(f.metadataStatus)
return
}
metadata := map[string]any{
"issuer": f.serverURL,
"authorization_endpoint": f.serverURL + "/oauth/authorizations/new",
"token_endpoint": f.serverURL + "/oauth/tokens",
"grant_types_supported": []string{"authorization_code", "refresh_token"},
"code_challenge_methods_supported": []string{"S256"},
}
if !f.metadataOmitDevice {
metadata["device_authorization_endpoint"] = f.serverURL + "/oauth/device_authorizations"
metadata["grant_types_supported"] = []string{"authorization_code", "refresh_token", "urn:ietf:params:oauth:grant-type:device_code"}
}
json.NewEncoder(w).Encode(metadata)
case r.Method == http.MethodPost && r.URL.Path == "/oauth/device_authorizations":
f.deviceRequests = form
if f.deviceStatus != 0 {
Expand Down Expand Up @@ -127,6 +149,7 @@ func newMCPRig(t *testing.T) *mcpRig {
t.Setenv("HEY_NO_KEYRING", "")
rig := &mcpRig{hey: &fakeHEYOAuth{t: t}, keyring: newFakeKeyring()}
rig.server = httptest.NewServer(rig.hey)
rig.hey.serverURL = rig.server.URL
t.Cleanup(rig.server.Close)

configDir := t.TempDir()
Expand Down Expand Up @@ -216,6 +239,7 @@ func TestMCPLoginStoresApartInThePlaintextFallbackToo(t *testing.T) {
t.Setenv("HEY_NO_KEYRING", "1")
hey := &fakeHEYOAuth{t: t}
server := httptest.NewServer(hey)
hey.serverURL = server.URL
t.Cleanup(server.Close)
dir := t.TempDir()

Expand Down Expand Up @@ -247,17 +271,18 @@ func keysOf(all map[string]*Credentials) []string {
}

func TestMCPLoginFallsBackToLoopbackWithTheSameScope(t *testing.T) {
for name, refusal := range map[string]struct {
status int
code string
tests := map[string]struct {
metadataStatus int
metadataOmitDevice bool
}{
"rollout switch off (haystack#9085)": {http.StatusBadRequest, "invalid_request"},
"row refused by the device flow (#9041)": {http.StatusBadRequest, "unauthorized_client"},
"no device endpoint": {http.StatusNotFound, ""},
} {
"no device endpoint": {0, true},
"metadata 404": {http.StatusNotFound, false},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
rig := newMCPRig(t)
rig.hey.deviceStatus, rig.hey.deviceError = refusal.status, refusal.code
rig.hey.metadataStatus = tc.metadataStatus
rig.hey.metadataOmitDevice = tc.metadataOmitDevice

method, err := rig.mcp.LoginMCP(context.Background(), quiet)
if err != nil {
Expand All @@ -284,6 +309,7 @@ func TestMCPLoginFallsBackToLoopbackWithTheSameScope(t *testing.T) {

func TestMCPLoginDoesntFallBackOnOtherRefusals(t *testing.T) {
rig := newMCPRig(t)
// Metadata advertises device endpoint, but device request fails with invalid_client
rig.hey.deviceStatus, rig.hey.deviceError = http.StatusUnauthorized, "invalid_client"
if _, err := rig.mcp.LoginMCP(context.Background(), quiet); err == nil {
t.Fatal("an unknown client id signed in")
Expand Down
Loading
Loading