Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

add beacon login

Justin D'Souzacb50ba7919a4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cfd94ac4..7c6e9774 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -68,7 +68,7 @@ jobs:
./beacon endpoint integrations claude-cowork --help > /tmp/beacon-cowork-help.txt
./beacon endpoint wazuh --help > /tmp/beacon-wazuh-help.txt
./beacon endpoint rapid7 --help > /tmp/beacon-rapid7-help.txt
- for forbidden in login init update claude cursor dep-scan config whoami; do
+ for forbidden in init update claude cursor dep-scan config whoami; do
if grep -E "^[[:space:]]+$forbidden([[:space:]]|$)" /tmp/beacon-help.txt; then
echo "forbidden command exposed: $forbidden"
exit 1
diff --git a/cli/beacon/cmd/login.go b/cli/beacon/cmd/login.go
new file mode 100644
index 00000000..1e75e570
--- /dev/null
+++ b/cli/beacon/cmd/login.go
@@ -0,0 +1,110 @@
+package cmd
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+)
+
+type loginOptions struct {
+ dashboardURL string
+ force bool
+}
+
+type loginService interface {
+ Login(auth.LoginOptions) (*auth.Credentials, error)
+ LoadCredentials() (*auth.Credentials, error)
+ SaveCredentials(*auth.Credentials) error
+ IsLoggedIn() bool
+}
+
+type defaultLoginService struct{}
+
+func (defaultLoginService) Login(opts auth.LoginOptions) (*auth.Credentials, error) {
+ return auth.Login(opts)
+}
+
+func (defaultLoginService) LoadCredentials() (*auth.Credentials, error) {
+ return auth.LoadCredentials()
+}
+
+func (defaultLoginService) SaveCredentials(creds *auth.Credentials) error {
+ return auth.SaveCredentials(creds)
+}
+
+func (defaultLoginService) IsLoggedIn() bool {
+ return auth.IsLoggedIn()
+}
+
+var (
+ loginOpts = loginOptions{}
+
+ newLoginService = func() loginService {
+ return defaultLoginService{}
+ }
+)
+
+var loginCmd = &cobra.Command{
+ Use: "login",
+ Short: "Log in to the Asymptote dashboard",
+ Long: "Log in to the Asymptote dashboard using your browser. Beacon endpoint telemetry remains local-only unless you explicitly use cloud features.",
+ SilenceUsage: true,
+ Args: cobra.NoArgs,
+ RunE: runLogin,
+}
+
+func init() {
+ loginCmd.Flags().StringVar(&loginOpts.dashboardURL, "dashboard-url", "", "Asymptote dashboard URL (defaults to "+auth.DefaultDashboardURL+", or "+auth.DashboardURLEnv+")")
+ loginCmd.Flags().BoolVar(&loginOpts.force, "force", false, "Replace existing saved credentials")
+ rootCmd.AddCommand(loginCmd)
+}
+
+func runLogin(cmd *cobra.Command, args []string) error {
+ service := newLoginService()
+ out := cmd.OutOrStdout()
+
+ if !loginOpts.force && service.IsLoggedIn() {
+ creds, err := service.LoadCredentials()
+ if err != nil {
+ return fmt.Errorf("failed to load saved credentials: %w", err)
+ }
+ if creds != nil {
+ if creds.Email != "" {
+ fmt.Fprintf(out, "Already logged in as %s\n", creds.Email)
+ } else {
+ fmt.Fprintln(out, "Already logged in.")
+ }
+ if creds.OrgName != "" {
+ fmt.Fprintf(out, "Organization: %s\n", creds.OrgName)
+ }
+ fmt.Fprintln(out, "Run 'beacon login --force' to log in as a different user.")
+ return nil
+ }
+ }
+
+ creds, err := service.Login(auth.LoginOptions{
+ DashboardURL: loginOpts.dashboardURL,
+ Out: out,
+ })
+ if err != nil {
+ return fmt.Errorf("login failed: %w", err)
+ }
+ if err := service.SaveCredentials(creds); err != nil {
+ return fmt.Errorf("failed to save credentials: %w", err)
+ }
+
+ fmt.Fprintln(out)
+ if creds.Email != "" {
+ fmt.Fprintf(out, "Success! Logged in as %s\n", creds.Email)
+ } else {
+ fmt.Fprintln(out, "Success! Logged in successfully.")
+ }
+ if creds.OrgName != "" {
+ fmt.Fprintf(out, "Organization: %s\n", creds.OrgName)
+ }
+ fmt.Fprintln(out)
+ fmt.Fprintln(out, "Beacon endpoint telemetry remains local-only unless you explicitly use cloud features.")
+ return nil
+}
diff --git a/cli/beacon/cmd/login_test.go b/cli/beacon/cmd/login_test.go
new file mode 100644
index 00000000..e51ef12e
--- /dev/null
+++ b/cli/beacon/cmd/login_test.go
@@ -0,0 +1,173 @@
+package cmd
+
+import (
+ "bytes"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+)
+
+type stubLoginService struct {
+ creds *auth.Credentials
+ loginCreds *auth.Credentials
+ loginErr error
+ saveErr error
+ loggedIn bool
+ loginCalled bool
+ saveCalled bool
+ capturedOpts auth.LoginOptions
+}
+
+func (s *stubLoginService) Login(opts auth.LoginOptions) (*auth.Credentials, error) {
+ s.loginCalled = true
+ s.capturedOpts = opts
+ if s.loginErr != nil {
+ return nil, s.loginErr
+ }
+ return s.loginCreds, nil
+}
+
+func (s *stubLoginService) LoadCredentials() (*auth.Credentials, error) {
+ return s.creds, nil
+}
+
+func (s *stubLoginService) SaveCredentials(creds *auth.Credentials) error {
+ s.saveCalled = true
+ s.creds = creds
+ return s.saveErr
+}
+
+func (s *stubLoginService) IsLoggedIn() bool {
+ return s.loggedIn
+}
+
+func TestLoginCommandRegistered(t *testing.T) {
+ cmd, _, err := rootCmd.Find([]string{"login"})
+ if err != nil {
+ t.Fatalf("Find login returned error: %v", err)
+ }
+ if cmd == nil {
+ t.Fatal("login command not registered")
+ }
+ if cmd.Flags().Lookup("dashboard-url") == nil {
+ t.Fatal("login command missing --dashboard-url")
+ }
+ if cmd.Flags().Lookup("force") == nil {
+ t.Fatal("login command missing --force")
+ }
+}
+
+func TestRunLoginAlreadyLoggedIn(t *testing.T) {
+ service := &stubLoginService{
+ loggedIn: true,
+ creds: &auth.Credentials{
+ Email: "[email protected]",
+ OrgName: "Example Org",
+ },
+ }
+ restore := setLoginServiceForTest(t, service)
+ defer restore()
+ restoreOpts := setLoginOptsForTest(t, loginOptions{})
+ defer restoreOpts()
+
+ cmd := &cobra.Command{}
+ var out bytes.Buffer
+ cmd.SetOut(&out)
+ if err := runLogin(cmd, nil); err != nil {
+ t.Fatalf("runLogin returned error: %v", err)
+ }
+ got := out.String()
+ for _, want := range []string{
+ "Already logged in as [email protected]",
+ "Organization: Example Org",
+ "beacon login --force",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("output = %q, want %q", got, want)
+ }
+ }
+ if service.loginCalled {
+ t.Fatal("Login called despite existing credentials")
+ }
+}
+
+func TestRunLoginForceReplacesCredentials(t *testing.T) {
+ service := &stubLoginService{
+ loggedIn: true,
+ creds: &auth.Credentials{Email: "[email protected]"},
+ loginCreds: &auth.Credentials{
+ Token: "secret-token",
+ TokenPrefix: "asym_123",
+ UserID: "user-1",
+ Email: "[email protected]",
+ OrgName: "Example Org",
+ },
+ }
+ restore := setLoginServiceForTest(t, service)
+ defer restore()
+ restoreOpts := setLoginOptsForTest(t, loginOptions{force: true, dashboardURL: "https://dashboard.example"})
+ defer restoreOpts()
+
+ cmd := &cobra.Command{}
+ var out bytes.Buffer
+ cmd.SetOut(&out)
+ if err := runLogin(cmd, nil); err != nil {
+ t.Fatalf("runLogin returned error: %v", err)
+ }
+ if !service.loginCalled {
+ t.Fatal("Login was not called")
+ }
+ if !service.saveCalled {
+ t.Fatal("SaveCredentials was not called")
+ }
+ if service.capturedOpts.DashboardURL != "https://dashboard.example" {
+ t.Fatalf("DashboardURL = %q, want override", service.capturedOpts.DashboardURL)
+ }
+ got := out.String()
+ for _, want := range []string{
+ "Success! Logged in as [email protected]",
+ "Organization: Example Org",
+ "Beacon endpoint telemetry remains local-only",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("output = %q, want %q", got, want)
+ }
+ }
+}
+
+func TestRunLoginReturnsLoginError(t *testing.T) {
+ service := &stubLoginService{loginErr: errors.New("browser closed")}
+ restore := setLoginServiceForTest(t, service)
+ defer restore()
+ restoreOpts := setLoginOptsForTest(t, loginOptions{})
+ defer restoreOpts()
+
+ cmd := &cobra.Command{}
+ err := runLogin(cmd, nil)
+ if err == nil {
+ t.Fatal("runLogin error = nil, want error")
+ }
+ if !strings.Contains(err.Error(), "login failed: browser closed") {
+ t.Fatalf("error = %v, want login failure", err)
+ }
+}
+
+func setLoginServiceForTest(t *testing.T, service loginService) func() {
+ t.Helper()
+ old := newLoginService
+ newLoginService = func() loginService {
+ return service
+ }
+ return func() { newLoginService = old }
+}
+
+func setLoginOptsForTest(t *testing.T, opts loginOptions) func() {
+ t.Helper()
+ old := loginOpts
+ loginOpts = opts
+ return func() { loginOpts = old }
+}
diff --git a/cli/beacon/internal/auth/auth_test.go b/cli/beacon/internal/auth/auth_test.go
new file mode 100644
index 00000000..9c9a4c53
--- /dev/null
+++ b/cli/beacon/internal/auth/auth_test.go
@@ -0,0 +1,205 @@
+package auth
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestGeneratePKCECreatesVerifierChallengeAndState(t *testing.T) {
+ params, err := GeneratePKCE()
+ if err != nil {
+ t.Fatalf("GeneratePKCE returned error: %v", err)
+ }
+ base64URL := regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
+ for name, value := range map[string]string{
+ "code verifier": params.CodeVerifier,
+ "code challenge": params.CodeChallenge,
+ "state": params.State,
+ } {
+ if len(value) != 43 {
+ t.Fatalf("%s length = %d, want 43", name, len(value))
+ }
+ if !base64URL.MatchString(value) {
+ t.Fatalf("%s contains non-base64url characters: %q", name, value)
+ }
+ }
+ hash := sha256.Sum256([]byte(params.CodeVerifier))
+ wantChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
+ if params.CodeChallenge != wantChallenge {
+ t.Fatalf("CodeChallenge = %q, want %q", params.CodeChallenge, wantChallenge)
+ }
+}
+
+func TestSaveLoadCredentialsPrivatePermissions(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ creds := &Credentials{
+ Token: "secret-token",
+ TokenPrefix: "asym_123",
+ UserID: "user-1",
+ Email: "[email protected]",
+ OrgName: "Example Org",
+ }
+ if err := SaveCredentials(creds); err != nil {
+ t.Fatalf("SaveCredentials returned error: %v", err)
+ }
+ path, err := CredentialsPath()
+ if err != nil {
+ t.Fatalf("CredentialsPath returned error: %v", err)
+ }
+ if got, want := path, filepath.Join(home, ".beacon", "auth", "credentials.json"); got != want {
+ t.Fatalf("CredentialsPath = %q, want %q", got, want)
+ }
+ dirInfo, err := os.Stat(filepath.Dir(path))
+ if err != nil {
+ t.Fatalf("stat credentials dir: %v", err)
+ }
+ if got, want := dirInfo.Mode().Perm(), os.FileMode(0700); got != want {
+ t.Fatalf("credentials dir permissions = %o, want %o", got, want)
+ }
+ fileInfo, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("stat credentials file: %v", err)
+ }
+ if got, want := fileInfo.Mode().Perm(), os.FileMode(0600); got != want {
+ t.Fatalf("credentials permissions = %o, want %o", got, want)
+ }
+
+ loaded, err := LoadCredentials()
+ if err != nil {
+ t.Fatalf("LoadCredentials returned error: %v", err)
+ }
+ if loaded.Token != "secret-token" || loaded.Email != "[email protected]" {
+ t.Fatalf("credentials did not round-trip: %#v", loaded)
+ }
+ if !IsLoggedIn() {
+ t.Fatal("IsLoggedIn = false, want true")
+ }
+}
+
+func TestIsLoggedInRejectsExpiredCredentials(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ if err := SaveCredentials(&Credentials{
+ Token: "expired-token",
+ UserID: "user-1",
+ ExpiresAt: time.Now().Add(-time.Minute),
+ }); err != nil {
+ t.Fatalf("SaveCredentials returned error: %v", err)
+ }
+ if IsLoggedIn() {
+ t.Fatal("IsLoggedIn = true, want false for expired credentials")
+ }
+}
+
+func TestCallbackServerExchangesCodeForToken(t *testing.T) {
+ var gotRequest exchangeCodeRequest
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/cli/auth/exchange" {
+ t.Fatalf("exchange path = %q, want /api/cli/auth/exchange", r.URL.Path)
+ }
+ if r.Method != http.MethodPost {
+ t.Fatalf("exchange method = %q, want POST", r.Method)
+ }
+ if err := json.NewDecoder(r.Body).Decode(&gotRequest); err != nil {
+ t.Fatalf("decode exchange request: %v", err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"token":"secret-token","token_prefix":"asym_123","user_id":"user-1","email":"[email protected]","org_id":"org-1","org_name":"Example Org"}`))
+ }))
+ defer backend.Close()
+
+ server, err := NewCallbackServer("state-123", "verifier-123", backend.URL, backend.Client())
+ if err != nil {
+ t.Fatalf("NewCallbackServer returned error: %v", err)
+ }
+ defer func() { _ = server.Shutdown() }()
+ server.Start()
+
+ callbackURL := url.URL{
+ Scheme: "http",
+ Host: "127.0.0.1:" + strconv.Itoa(server.Port()),
+ Path: "/callback",
+ RawQuery: "exchange_code=code-123&state=state-123",
+ }
+ go func() {
+ resp, err := http.Get(callbackURL.String())
+ if err == nil {
+ _ = resp.Body.Close()
+ }
+ }()
+
+ result, err := server.Wait(2 * time.Second)
+ if err != nil {
+ t.Fatalf("Wait returned error: %v", err)
+ }
+ if result.Error != "" {
+ t.Fatalf("callback result error = %q", result.Error)
+ }
+ if result.Token != "secret-token" || result.Email != "[email protected]" || result.OrgName != "Example Org" {
+ t.Fatalf("unexpected callback result: %#v", result)
+ }
+ if gotRequest.ExchangeCode != "code-123" || gotRequest.State != "state-123" || gotRequest.CodeVerifier != "verifier-123" {
+ t.Fatalf("unexpected exchange request: %#v", gotRequest)
+ }
+}
+
+func TestCallbackServerRejectsStateMismatch(t *testing.T) {
+ backendCalled := false
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ backendCalled = true
+ t.Fatal("backend should not be called on state mismatch")
+ }))
+ defer backend.Close()
+
+ server, err := NewCallbackServer("expected-state", "verifier", backend.URL, backend.Client())
+ if err != nil {
+ t.Fatalf("NewCallbackServer returned error: %v", err)
+ }
+ defer func() { _ = server.Shutdown() }()
+ server.Start()
+
+ go func() {
+ resp, err := http.Get("http://127.0.0.1:" + strconv.Itoa(server.Port()) + "/callback?exchange_code=code&state=wrong-state")
+ if err == nil {
+ _ = resp.Body.Close()
+ }
+ }()
+ result, err := server.Wait(2 * time.Second)
+ if err != nil {
+ t.Fatalf("Wait returned error: %v", err)
+ }
+ if !strings.Contains(result.Error, "state mismatch") {
+ t.Fatalf("result error = %q, want state mismatch", result.Error)
+ }
+ if backendCalled {
+ t.Fatal("backend was called on state mismatch")
+ }
+}
+
+func TestResolveDashboardURL(t *testing.T) {
+ t.Setenv(DashboardURLEnv, "")
+ if got := ResolveDashboardURL(""); got != DefaultDashboardURL {
+ t.Fatalf("ResolveDashboardURL empty = %q, want default", got)
+ }
+ t.Setenv(DashboardURLEnv, "https://env.example/")
+ if got := ResolveDashboardURL(""); got != "https://env.example" {
+ t.Fatalf("ResolveDashboardURL env = %q, want env without trailing slash", got)
+ }
+ if got := ResolveDashboardURL("https://flag.example///"); got != "https://flag.example" {
+ t.Fatalf("ResolveDashboardURL flag = %q, want flag without trailing slash", got)
+ }
+}
diff --git a/cli/beacon/internal/auth/browser.go b/cli/beacon/internal/auth/browser.go
new file mode 100644
index 00000000..39ba9b0b
--- /dev/null
+++ b/cli/beacon/internal/auth/browser.go
@@ -0,0 +1,22 @@
+package auth
+
+import (
+ "fmt"
+ "os/exec"
+ "runtime"
+)
+
+func OpenBrowser(url string) error {
+ var cmd *exec.Cmd
+ switch runtime.GOOS {
+ case "darwin":
+ cmd = exec.Command("open", url)
+ case "windows":
+ cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
+ case "linux":
+ cmd = exec.Command("xdg-open", url)
+ default:
+ return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
+ }
+ return cmd.Start()
+}
diff --git a/cli/beacon/internal/auth/credentials.go b/cli/beacon/internal/auth/credentials.go
new file mode 100644
index 00000000..7cee30a3
--- /dev/null
+++ b/cli/beacon/internal/auth/credentials.go
@@ -0,0 +1,150 @@
+package auth
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+const (
+ ConfigDirName = ".beacon"
+ AuthDirName = "auth"
+ CredentialsFileName = "credentials.json"
+)
+
+type Credentials struct {
+ Token string `json:"token"`
+ TokenPrefix string `json:"token_prefix"`
+ ExpiresAt time.Time `json:"expires_at"`
+ UserID string `json:"user_id"`
+ Email string `json:"email,omitempty"`
+ OrgID string `json:"org_id,omitempty"`
+ OrgName string `json:"org_name,omitempty"`
+}
+
+func ConfigDir() (string, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(home, ConfigDirName, AuthDirName), nil
+}
+
+func EnsureConfigDir() (string, error) {
+ dir, err := ConfigDir()
+ if err != nil {
+ return "", err
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return "", err
+ }
+ return dir, nil
+}
+
+func CredentialsPath() (string, error) {
+ dir, err := ConfigDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, CredentialsFileName), nil
+}
+
+func SaveCredentials(creds *Credentials) error {
+ if creds == nil {
+ return fmt.Errorf("credentials are required")
+ }
+ if _, err := EnsureConfigDir(); err != nil {
+ return fmt.Errorf("failed to create auth directory: %w", err)
+ }
+ path, err := CredentialsPath()
+ if err != nil {
+ return fmt.Errorf("failed to resolve credentials path: %w", err)
+ }
+ data, err := json.MarshalIndent(creds, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal credentials: %w", err)
+ }
+ if err := os.WriteFile(path, data, 0600); err != nil {
+ return fmt.Errorf("failed to write credentials: %w", err)
+ }
+ return os.Chmod(path, 0600)
+}
+
+func LoadCredentials() (*Credentials, error) {
+ path, err := CredentialsPath()
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve credentials path: %w", err)
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("failed to read credentials: %w", err)
+ }
+ var creds Credentials
+ if err := json.Unmarshal(data, &creds); err != nil {
+ return nil, fmt.Errorf("failed to parse credentials: %w", err)
+ }
+ return &creds, nil
+}
+
+func DeleteCredentials() error {
+ path, err := CredentialsPath()
+ if err != nil {
+ return fmt.Errorf("failed to resolve credentials path: %w", err)
+ }
+ if err := os.Remove(path); err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return fmt.Errorf("failed to delete credentials: %w", err)
+ }
+ return nil
+}
+
+func IsLoggedIn() bool {
+ creds, err := LoadCredentials()
+ if err != nil || creds == nil {
+ return false
+ }
+ return !creds.IsExpired()
+}
+
+func (c *Credentials) IsExpired() bool {
+ if c == nil || c.ExpiresAt.IsZero() {
+ return false
+ }
+ return time.Now().After(c.ExpiresAt)
+}
+
+func (c *Credentials) ExpiresIn() string {
+ if c == nil || c.ExpiresAt.IsZero() {
+ return "never"
+ }
+ if c.IsExpired() {
+ return "expired"
+ }
+ duration := time.Until(c.ExpiresAt)
+ days := int(duration.Hours() / 24)
+ if days > 1 {
+ return fmt.Sprintf("%d days", days)
+ }
+ if days == 1 {
+ return "1 day"
+ }
+ hours := int(duration.Hours())
+ if hours > 1 {
+ return fmt.Sprintf("%d hours", hours)
+ }
+ if hours == 1 {
+ return "1 hour"
+ }
+ minutes := int(duration.Minutes())
+ if minutes > 1 {
+ return fmt.Sprintf("%d minutes", minutes)
+ }
+ return "less than a minute"
+}
diff --git a/cli/beacon/internal/auth/login.go b/cli/beacon/internal/auth/login.go
new file mode 100644
index 00000000..89eb0378
--- /dev/null
+++ b/cli/beacon/internal/auth/login.go
@@ -0,0 +1,123 @@
+package auth
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+)
+
+const (
+ DefaultDashboardURL = "https://asymptotelabs.ai"
+ DashboardURLEnv = "BEACON_DASHBOARD_URL"
+ AuthTimeout = 5 * time.Minute
+)
+
+type LoginOptions struct {
+ DashboardURL string
+ OpenBrowser func(string) error
+ HTTPClient *http.Client
+ Out io.Writer
+ Timeout time.Duration
+}
+
+func Login(opts LoginOptions) (*Credentials, error) {
+ dashboardURL := ResolveDashboardURL(opts.DashboardURL)
+ timeout := opts.Timeout
+ if timeout == 0 {
+ timeout = AuthTimeout
+ }
+ openBrowser := opts.OpenBrowser
+ if openBrowser == nil {
+ openBrowser = OpenBrowser
+ }
+ out := opts.Out
+ if out == nil {
+ out = io.Discard
+ }
+
+ pkce, err := GeneratePKCE()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate PKCE parameters: %w", err)
+ }
+ server, err := NewCallbackServer(pkce.State, pkce.CodeVerifier, dashboardURL, opts.HTTPClient)
+ if err != nil {
+ return nil, err
+ }
+ defer func() {
+ _ = server.Shutdown()
+ }()
+ server.Start()
+
+ authURL, err := buildAuthURL(dashboardURL, pkce.CodeChallenge, pkce.State, server.Port())
+ if err != nil {
+ return nil, err
+ }
+ fmt.Fprintf(out, "Opening browser to %s/cli/auth...\n", dashboardURL)
+ if err := openBrowser(authURL); err != nil {
+ fmt.Fprintln(out, "Failed to open browser automatically.")
+ fmt.Fprintf(out, "Please open this URL in your browser:\n%s\n", authURL)
+ }
+ fmt.Fprintln(out, "Waiting for authentication...")
+
+ result, err := server.Wait(timeout)
+ if err != nil {
+ return nil, err
+ }
+ if result.Error != "" {
+ return nil, fmt.Errorf("authentication failed: %s", result.Error)
+ }
+ var expiresAt time.Time
+ if result.ExpiresAt != "" {
+ expiresAt, err = time.Parse(time.RFC3339, result.ExpiresAt)
+ if err != nil {
+ expiresAt, err = time.Parse("2006-01-02T15:04:05", result.ExpiresAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse expiration time: %w", err)
+ }
+ }
+ }
+ return &Credentials{
+ Token: result.Token,
+ TokenPrefix: result.TokenPrefix,
+ ExpiresAt: expiresAt,
+ UserID: result.UserID,
+ Email: result.Email,
+ OrgID: result.OrgID,
+ OrgName: result.OrgName,
+ }, nil
+}
+
+func ResolveDashboardURL(flagValue string) string {
+ if flagValue != "" {
+ return normalizeDashboardURL(flagValue)
+ }
+ if envValue := os.Getenv(DashboardURLEnv); envValue != "" {
+ return normalizeDashboardURL(envValue)
+ }
+ return DefaultDashboardURL
+}
+
+func buildAuthURL(dashboardURL, codeChallenge, state string, port int) (string, error) {
+ u, err := url.Parse(normalizeDashboardURL(dashboardURL) + "/cli/auth")
+ if err != nil {
+ return "", fmt.Errorf("failed to parse dashboard URL: %w", err)
+ }
+ q := u.Query()
+ q.Set("code_challenge", codeChallenge)
+ q.Set("state", state)
+ q.Set("port", fmt.Sprintf("%d", port))
+ u.RawQuery = q.Encode()
+ return u.String(), nil
+}
+
+func normalizeDashboardURL(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ raw = DefaultDashboardURL
+ }
+ return strings.TrimRight(raw, "/")
+}
diff --git a/cli/beacon/internal/auth/pkce.go b/cli/beacon/internal/auth/pkce.go
new file mode 100644
index 00000000..7656c962
--- /dev/null
+++ b/cli/beacon/internal/auth/pkce.go
@@ -0,0 +1,41 @@
+package auth
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+)
+
+const (
+ CodeVerifierLength = 32
+ StateLength = 32
+)
+
+type PKCEParams struct {
+ CodeVerifier string
+ CodeChallenge string
+ State string
+}
+
+func GeneratePKCE() (*PKCEParams, error) {
+ verifierBytes := make([]byte, CodeVerifierLength)
+ if _, err := rand.Read(verifierBytes); err != nil {
+ return nil, err
+ }
+ codeVerifier := base64.RawURLEncoding.EncodeToString(verifierBytes)
+
+ hash := sha256.Sum256([]byte(codeVerifier))
+ codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
+
+ stateBytes := make([]byte, StateLength)
+ if _, err := rand.Read(stateBytes); err != nil {
+ return nil, err
+ }
+ state := base64.RawURLEncoding.EncodeToString(stateBytes)
+
+ return &PKCEParams{
+ CodeVerifier: codeVerifier,
+ CodeChallenge: codeChallenge,
+ State: state,
+ }, nil
+}
diff --git a/cli/beacon/internal/auth/server.go b/cli/beacon/internal/auth/server.go
new file mode 100644
index 00000000..f40db597
--- /dev/null
+++ b/cli/beacon/internal/auth/server.go
@@ -0,0 +1,227 @@
+package auth
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "html"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+type CallbackResult struct {
+ Token string
+ TokenPrefix string
+ ExpiresAt string
+ UserID string
+ Email string
+ OrgID string
+ OrgName string
+ State string
+ Error string
+}
+
+type exchangeCodeRequest struct {
+ ExchangeCode string `json:"exchange_code"`
+ State string `json:"state"`
+ CodeVerifier string `json:"code_verifier"`
+}
+
+type exchangeCodeResponse struct {
+ Token string `json:"token"`
+ TokenPrefix string `json:"token_prefix"`
+ ExpiresAt *string `json:"expires_at"`
+ UserID string `json:"user_id"`
+ Email string `json:"email"`
+ OrgID string `json:"org_id"`
+ OrgName string `json:"org_name"`
+}
+
+type CallbackServer struct {
+ port int
+ listener net.Listener
+ server *http.Server
+ resultCh chan *CallbackResult
+ once sync.Once
+ state string
+ codeVerifier string
+ dashboardURL string
+ httpClient *http.Client
+}
+
+func NewCallbackServer(expectedState, codeVerifier, dashboardURL string, httpClient *http.Client) (*CallbackServer, error) {
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ return nil, fmt.Errorf("failed to start callback server: %w", err)
+ }
+ if httpClient == nil {
+ httpClient = &http.Client{Timeout: 30 * time.Second}
+ }
+ cs := &CallbackServer{
+ port: listener.Addr().(*net.TCPAddr).Port,
+ listener: listener,
+ resultCh: make(chan *CallbackResult, 1),
+ state: expectedState,
+ codeVerifier: codeVerifier,
+ dashboardURL: normalizeDashboardURL(dashboardURL),
+ httpClient: httpClient,
+ }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/callback", cs.handleCallback)
+ cs.server = &http.Server{
+ Handler: mux,
+ ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 10 * time.Second,
+ }
+ return cs, nil
+}
+
+func (cs *CallbackServer) Port() int {
+ return cs.port
+}
+
+func (cs *CallbackServer) Start() {
+ go func() {
+ if err := cs.server.Serve(cs.listener); err != nil && err != http.ErrServerClosed {
+ cs.resultCh <- &CallbackResult{Error: fmt.Sprintf("server error: %v", err)}
+ }
+ }()
+}
+
+func (cs *CallbackServer) Wait(timeout time.Duration) (*CallbackResult, error) {
+ select {
+ case result := <-cs.resultCh:
+ return result, nil
+ case <-time.After(timeout):
+ return nil, fmt.Errorf("timeout waiting for authentication callback")
+ }
+}
+
+func (cs *CallbackServer) Shutdown() error {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ return cs.server.Shutdown(ctx)
+}
+
+func (cs *CallbackServer) handleCallback(w http.ResponseWriter, r *http.Request) {
+ cs.once.Do(func() {
+ query := r.URL.Query()
+ if errMsg := query.Get("error"); errMsg != "" {
+ cs.resultCh <- &CallbackResult{Error: errMsg}
+ cs.sendResponse(w, false, errMsg)
+ return
+ }
+ state := query.Get("state")
+ if state != cs.state {
+ cs.resultCh <- &CallbackResult{Error: "state mismatch - possible CSRF attack"}
+ cs.sendResponse(w, false, "Security error: state mismatch")
+ return
+ }
+ exchangeCode := query.Get("exchange_code")
+ if exchangeCode == "" {
+ cs.resultCh <- &CallbackResult{Error: "no exchange code received"}
+ cs.sendResponse(w, false, "No exchange code received")
+ return
+ }
+ tokenResp, err := cs.exchangeCodeForToken(r.Context(), exchangeCode, state, cs.codeVerifier)
+ if err != nil {
+ message := fmt.Sprintf("failed to exchange code: %v", err)
+ cs.resultCh <- &CallbackResult{Error: message}
+ cs.sendResponse(w, false, message)
+ return
+ }
+ result := &CallbackResult{
+ Token: tokenResp.Token,
+ TokenPrefix: tokenResp.TokenPrefix,
+ UserID: tokenResp.UserID,
+ Email: tokenResp.Email,
+ OrgID: tokenResp.OrgID,
+ OrgName: tokenResp.OrgName,
+ State: state,
+ }
+ if tokenResp.ExpiresAt != nil {
+ result.ExpiresAt = *tokenResp.ExpiresAt
+ }
+ cs.resultCh <- result
+ cs.sendResponse(w, true, "")
+ })
+}
+
+func (cs *CallbackServer) exchangeCodeForToken(ctx context.Context, exchangeCode, state, codeVerifier string) (*exchangeCodeResponse, error) {
+ bodyBytes, err := json.Marshal(exchangeCodeRequest{
+ ExchangeCode: exchangeCode,
+ State: state,
+ CodeVerifier: codeVerifier,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal request: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, cs.dashboardURL+"/api/cli/auth/exchange", bytes.NewReader(bodyBytes))
+ if err != nil {
+ return nil, fmt.Errorf("failed to create exchange request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "beacon-cli")
+
+ resp, err := cs.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("failed to call exchange endpoint: %w", err)
+ }
+ defer resp.Body.Close()
+ respBody, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read exchange response: %w", err)
+ }
+ if resp.StatusCode != http.StatusOK {
+ var errResp struct {
+ Detail string `json:"detail"`
+ Error string `json:"error"`
+ }
+ if json.Unmarshal(respBody, &errResp) == nil {
+ if errResp.Detail != "" {
+ return nil, fmt.Errorf("%s", errResp.Detail)
+ }
+ if errResp.Error != "" {
+ return nil, fmt.Errorf("%s", errResp.Error)
+ }
+ }
+ return nil, fmt.Errorf("exchange failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody)))
+ }
+ var tokenResp exchangeCodeResponse
+ if err := json.Unmarshal(respBody, &tokenResp); err != nil {
+ return nil, fmt.Errorf("failed to parse exchange response: %w", err)
+ }
+ return &tokenResp, nil
+}
+
+func (cs *CallbackServer) sendResponse(w http.ResponseWriter, success bool, errorMsg string) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ if success {
+ _, _ = w.Write([]byte(`<!DOCTYPE html>
+<html>
+<head><title>Beacon Login Complete</title></head>
+<body>
+ <h1>Authentication Successful</h1>
+ <p>You can close this window and return to the terminal.</p>
+</body>
+</html>`))
+ return
+ }
+ _, _ = fmt.Fprintf(w, `<!DOCTYPE html>
+<html>
+<head><title>Beacon Login Failed</title></head>
+<body>
+ <h1>Authentication Failed</h1>
+ <p>%s</p>
+ <p>Please return to the terminal and try <code>beacon login</code> again.</p>
+</body>
+</html>`, html.EscapeString(errorMsg))
+}