The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Add Beacon account authentication commands
Justin D'Souzaf9108bd78944
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d032dc9c..a613b43d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -221,7 +221,7 @@ jobs:./beacon scan --help > /tmp/beacon-scan-help.txt./beacon rules --help > /tmp/beacon-rules-help.txt./beacon rules lint --help > /tmp/beacon-rules-lint-help.txt- for forbidden in init update claude cursor dep-scan config whoami; do+ for forbidden in init update claude cursor dep-scan config; doif grep -E "^[[:space:]]+$forbidden([[:space:]]|$)" /tmp/beacon-help.txt; thenecho "forbidden command exposed: $forbidden"exit 1diff --git a/CLAUDE.md b/CLAUDE.mdindex 30d0ab23..10b0cfc7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -24,6 +24,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.+- `beacon login` is the optional account-identity channel for interactive users. It uses browser PKCE against beacon.sh, stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory), and is separate from endpoint enrollment: signing in alone never starts forwarding or sends telemetry. Keep account credentials out of endpoint config, hook environments, logs, and command output.- Asymptote Managed forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is opt-in and Vector-shaped: Beacon writes local JSONL, Vector ships new lines after browser approval, and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Asymptote ingest contract because no Vector/service manager/browser/persistent disk exists there.- `beacon endpoint install` has a bounded onboarding channel for open-source attribution and destination choice. It is interactive TTY only, once per machine, skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`, and failures never fail install. It sends install context only, never prompts, events, file content, or command output. Implementation lives in `cli/beacon/internal/onboarding` and `cli/beacon/cmd/endpoint_onboarding.go`; keep `docs/cli/endpoint-onboarding.mdx` in sync with payload changes and do not copy the field list into the README.- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.diff --git a/README.md b/README.mdindex 4ea21e0d..bf25f56d 100644--- a/README.md+++ b/README.md@@ -123,6 +123,13 @@ Or inspect the raw event stream:> [!NOTE]> Local by default: no account, no API key, and nothing leaves your machine unless you configure it to.+Account sign-in is a separate, optional step and does not enable telemetry forwarding:++```bash+beacon login+beacon whoami+```+---## 🧠 Turn Session History Into Memorydiff --git a/cli/beacon/README.md b/cli/beacon/README.mdindex 1511a2c4..9b2c582e 100644--- a/cli/beacon/README.md+++ b/cli/beacon/README.md@@ -12,6 +12,8 @@ make build```bash./beacon endpoint install+./beacon login+./beacon whoami./beacon endpoint status --json./beacon endpoint connect./beacon endpoint disconnect@@ -20,6 +22,7 @@ make build./beacon traces./beacon endpoint dashboard./beacon endpoint uninstall --keep-logs+./beacon logout```Endpoint commands use per-user paths by default so hook and OTLP telemetry sharediff --git a/cli/beacon/cmd/account.go b/cli/beacon/cmd/account.gonew file mode 100644index 00000000..4872d2d3--- /dev/null+++ b/cli/beacon/cmd/account.go@@ -0,0 +1,182 @@+package cmd++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"+)++var accountOpts struct {+ baseURL string+ noBrowser bool+ json bool+}++var (+ accountLogin = account.Login+ accountSave = account.Save+ accountLoad = account.Load+ accountRemove = account.Remove+ accountInspect = account.Inspect+ accountRevoke = account.Revoke+ accountNow = time.Now+)++var loginCmd = &cobra.Command{+ Use: "login",+ Short: "Sign in to Beacon through beacon.sh",+ SilenceUsage: true,+ RunE: runLogin,+}++var logoutCmd = &cobra.Command{+ Use: "logout",+ Short: "Sign out and remove the local Beacon session",+ SilenceUsage: true,+ RunE: runLogout,+}++var whoamiCmd = &cobra.Command{+ Use: "whoami",+ Short: "Show the current Beacon account",+ SilenceUsage: true,+ RunE: runWhoami,+}++func init() {+ loginCmd.Flags().StringVar(&accountOpts.baseURL, "auth-url", "", "Beacon authentication URL (defaults to "+account.DefaultBaseURL+", or "+account.BaseURLEnv+")")+ loginCmd.Flags().BoolVar(&accountOpts.noBrowser, "no-browser", false, "Print the sign-in URL instead of opening a browser")+ for _, command := range []*cobra.Command{loginCmd, logoutCmd, whoamiCmd} {+ command.Flags().BoolVar(&accountOpts.json, "json", false, "Print machine-readable JSON")+ rootCmd.AddCommand(command)+ }+}++func runLogin(cmd *cobra.Command, args []string) error {+ flowOut := cmd.OutOrStdout()+ if accountOpts.json {+ flowOut = cmd.ErrOrStderr()+ }+ session, err := accountLogin(commandContext(cmd), account.LoginOptions{+ BaseURL: accountOpts.baseURL,+ Version: version.GetVersion(),+ NoBrowser: accountOpts.noBrowser,+ Out: flowOut,+ Now: accountNow,+ })+ if err != nil {+ return err+ }+ if err := accountSave(*session); err != nil {+ return fmt.Errorf("store Beacon session: %w", err)+ }+ status := accountInspect(accountNow())+ if accountOpts.json {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(status)+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Signed in to Beacon as %s.\n", displayAccountUser(status.User))+ if status.ActiveOrganization != nil {+ fmt.Fprintf(cmd.OutOrStdout(), "Organization: %s\n", displayOrganization(*status.ActiveOrganization))+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Session: %s (0600; access token is never printed)\n", status.SessionPath)+ return nil+}++func runLogout(cmd *cobra.Command, args []string) error {+ session, loadErr := accountLoad()+ var revokeErr error+ if loadErr == nil {+ ctx, cancel := context.WithTimeout(commandContext(cmd), 10*time.Second)+ revokeErr = accountRevoke(ctx, *session, &http.Client{Timeout: 10 * time.Second})+ cancel()+ } else if !errors.Is(loadErr, account.ErrNotSignedIn) {+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: could not read the existing session before logout: %v\n", loadErr)+ }+ if err := accountRemove(); err != nil {+ return fmt.Errorf("remove local Beacon session: %w", err)+ }+ if revokeErr != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: signed out locally; server revocation could not be confirmed: %v\n", revokeErr)+ }+ if accountOpts.json {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{+ "signed_out": true,+ "revocation_pending": revokeErr != nil,+ })+ }+ if errors.Is(loadErr, account.ErrNotSignedIn) {+ fmt.Fprintln(cmd.OutOrStdout(), "Not signed in.")+ return nil+ }+ fmt.Fprintln(cmd.OutOrStdout(), "Signed out of Beacon. Local credentials removed.")+ return nil+}++func commandContext(cmd *cobra.Command) context.Context {+ if ctx := cmd.Context(); ctx != nil {+ return ctx+ }+ return context.Background()+}++func runWhoami(cmd *cobra.Command, args []string) error {+ status := accountInspect(accountNow())+ if accountOpts.json {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(status)+ }+ if !status.SignedIn {+ fmt.Fprintln(cmd.OutOrStdout(), "Not signed in. Run `beacon login`.")+ fmt.Fprintf(cmd.OutOrStdout(), "Session: %s\n", status.SessionPath)+ return nil+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Signed in as %s\n", displayAccountUser(status.User))+ if status.ActiveOrganization != nil {+ fmt.Fprintf(cmd.OutOrStdout(), "Organization: %s\n", displayOrganization(*status.ActiveOrganization))+ } else if len(status.Organizations) > 0 {+ names := make([]string, 0, len(status.Organizations))+ for _, organization := range status.Organizations {+ names = append(names, displayOrganization(organization))+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Organizations: %s\n", strings.Join(names, ", "))+ }+ if !status.ExpiresAt.IsZero() {+ label := "expires"+ if status.Expired {+ label = "expired"+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Session %s: %s\n", label, status.ExpiresAt.UTC().Format(time.RFC3339))+ }+ fmt.Fprintf(cmd.OutOrStdout(), "Authentication service: %s\n", status.BaseURL)+ fmt.Fprintf(cmd.OutOrStdout(), "Session: %s\n", status.SessionPath)+ return nil+}++func displayAccountUser(user account.User) string {+ switch {+ case user.Name != "" && user.Email != "":+ return fmt.Sprintf("%s <%s>", user.Name, user.Email)+ case user.Email != "":+ return user.Email+ default:+ return user.ID+ }+}++func displayOrganization(organization account.Organization) string {+ if organization.Name != "" {+ return organization.Name+ }+ if organization.Slug != "" {+ return organization.Slug+ }+ return organization.ID+}diff --git a/cli/beacon/cmd/account_test.go b/cli/beacon/cmd/account_test.gonew file mode 100644index 00000000..e67cc679--- /dev/null+++ b/cli/beacon/cmd/account_test.go@@ -0,0 +1,142 @@+package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"+)++func withAccountFakes(t *testing.T) {+ t.Helper()+ originalLogin := accountLogin+ originalSave := accountSave+ originalLoad := accountLoad+ originalRemove := accountRemove+ originalInspect := accountInspect+ originalRevoke := accountRevoke+ originalNow := accountNow+ originalOpts := accountOpts+ t.Cleanup(func() {+ accountLogin = originalLogin+ accountSave = originalSave+ accountLoad = originalLoad+ accountRemove = originalRemove+ accountInspect = originalInspect+ accountRevoke = originalRevoke+ accountNow = originalNow+ accountOpts = originalOpts+ })+ accountOpts = struct {+ baseURL string+ noBrowser bool+ json bool+ }{}+}++func accountFixture() (*account.Session, account.Status) {+ expires := time.Date(2026, 9, 22, 8, 0, 0, 0, time.UTC)+ organization := account.Organization{ID: "org_1", Name: "Acme"}+ session := &account.Session{+ BaseURL: "https://beacon.sh",+ AccessToken: "never-print-this-token",+ TokenType: "Bearer",+ ExpiresAt: expires,+ User: account.User{ID: "usr_1", Email: "[email protected]", Name: "Beacon User"},+ ActiveOrganization: &organization,+ }+ status := account.Status{+ SignedIn: true,+ BaseURL: session.BaseURL,+ ExpiresAt: expires,+ User: session.User,+ ActiveOrganization: &organization,+ SessionPath: "/tmp/session.json",+ }+ return session, status+}++func TestRunLoginStoresSessionWithoutPrintingToken(t *testing.T) {+ withAccountFakes(t)+ session, status := accountFixture()+ var saved account.Session+ accountLogin = func(context.Context, account.LoginOptions) (*account.Session, error) { return session, nil }+ accountSave = func(value account.Session) error { saved = value; return nil }+ accountInspect = func(time.Time) account.Status { return status }+ accountNow = func() time.Time { return time.Date(2026, 9, 21, 8, 0, 0, 0, time.UTC) }+ var out bytes.Buffer+ loginCmd.SetOut(&out)+ loginCmd.SetErr(&out)++ if err := runLogin(loginCmd, nil); err != nil {+ t.Fatalf("runLogin returned error: %v", err)+ }+ if saved.AccessToken != session.AccessToken {+ t.Fatalf("saved session = %#v", saved)+ }+ if strings.Contains(out.String(), session.AccessToken) {+ t.Fatalf("output leaked access token: %s", out.String())+ }+ for _, want := range []string{"Beacon User <[email protected]>", "Organization: Acme", "0600"} {+ if !strings.Contains(out.String(), want) {+ t.Fatalf("output missing %q: %s", want, out.String())+ }+ }+}++func TestRunWhoamiJSONExcludesCredential(t *testing.T) {+ withAccountFakes(t)+ session, status := accountFixture()+ accountInspect = func(time.Time) account.Status { return status }+ accountOpts.json = true+ var out bytes.Buffer+ whoamiCmd.SetOut(&out)++ if err := runWhoami(whoamiCmd, nil); err != nil {+ t.Fatalf("runWhoami returned error: %v", err)+ }+ var payload map[string]any+ if err := json.Unmarshal(out.Bytes(), &payload); err != nil {+ t.Fatalf("JSON output: %v (%s)", err, out.String())+ }+ if payload["signed_in"] != true || strings.Contains(out.String(), session.AccessToken) || strings.Contains(out.String(), "access_token") {+ t.Fatalf("unsafe whoami output: %s", out.String())+ }+}++func TestRunLogoutRemovesCredentialWhenRevocationFails(t *testing.T) {+ withAccountFakes(t)+ session, _ := accountFixture()+ removed := false+ accountLoad = func() (*account.Session, error) { return session, nil }+ accountRevoke = func(context.Context, account.Session, *http.Client) error { return errors.New("offline") }+ accountRemove = func() error { removed = true; return nil }+ var out, stderr bytes.Buffer+ logoutCmd.SetOut(&out)+ logoutCmd.SetErr(&stderr)++ if err := runLogout(logoutCmd, nil); err != nil {+ t.Fatalf("runLogout returned error: %v", err)+ }+ if !removed {+ t.Fatal("local credential was not removed")+ }+ if !strings.Contains(stderr.String(), "signed out locally") || strings.Contains(out.String()+stderr.String(), session.AccessToken) {+ t.Fatalf("logout output stdout=%q stderr=%q", out.String(), stderr.String())+ }+}++func TestAccountCommandsAreRegistered(t *testing.T) {+ for _, name := range []string{"login", "logout", "whoami"} {+ command, _, err := rootCmd.Find([]string{name})+ if err != nil || command.Name() != name {+ t.Fatalf("root command %q = %v, %v", name, command, err)+ }+ }+}diff --git a/cli/beacon/cmd/endpoint_connect_test.go b/cli/beacon/cmd/endpoint_connect_test.goindex 41991788..84e4786b 100644--- a/cli/beacon/cmd/endpoint_connect_test.go+++ b/cli/beacon/cmd/endpoint_connect_test.go@@ -30,7 +30,7 @@ func TestEndpointConnectAndDisconnectCommandsRegistered(t *testing.T) {if disconnect.Flags().Lookup("keep-credentials") == nil {t.Fatal("disconnect missing --keep-credentials")}- for _, removed := range []string{"login", "ingest"} {+ for _, removed := range []string{"ingest"} {if cmd, _, err := rootCmd.Find([]string{removed}); err == nil && cmd != nil && cmd.Use == removed {t.Fatalf("removed command %q is still registered", removed)}diff --git a/cli/beacon/internal/account/login.go b/cli/beacon/internal/account/login.gonew file mode 100644index 00000000..e49ebf4b--- /dev/null+++ b/cli/beacon/internal/account/login.go@@ -0,0 +1,287 @@+package account++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "os"+ "runtime"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"+)++const (+ DefaultBaseURL = "https://beacon.sh"+ BaseURLEnv = "BEACON_AUTH_URL"+ LoginPagePath = "/cli/auth"+ LoginInitPath = "/api/cli/auth/init"+ ExchangePath = "/api/cli/auth/exchange"+ RevokePath = "/api/cli/auth/revoke"+ defaultTimeout = 30 * time.Second+ loginWait = 5 * time.Minute+ CLIClientName = "beacon-cli"+ CLIGrantVersion = "2026-09-01"+ ScopeProfileRead = "profile:read"+ ScopeDeviceEnroll = "device:enroll"+)++type LoginOptions struct {+ BaseURL string+ Version string+ NoBrowser bool+ OpenBrowser func(string) error+ HTTPClient *http.Client+ Out io.Writer+ Timeout time.Duration+ Now func() time.Time+}++type clientInfo struct {+ Name string `json:"name"`+ Version string `json:"version,omitempty"`+ OS string `json:"os"`+ Arch string `json:"arch"`+ GrantVersion string `json:"grant_version"`+}++type loginInitRequest struct {+ CodeChallenge string `json:"code_challenge"`+ CodeChallengeMethod string `json:"code_challenge_method"`+ State string `json:"state"`+ RedirectPort int `json:"redirect_port"`+ Client clientInfo `json:"client"`+ Scopes []string `json:"scopes"`+}++type exchangeRequest struct {+ ExchangeCode string `json:"exchange_code"`+ State string `json:"state"`+ CodeVerifier string `json:"code_verifier"`+}++type exchangeResult struct {+ AccessToken string `json:"access_token"`+ TokenType string `json:"token_type"`+ ExpiresAt time.Time `json:"expires_at"`+ User User `json:"user"`+ Organizations []Organization `json:"organizations,omitempty"`+ ActiveOrganization *Organization `json:"active_organization,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+}++func Login(ctx context.Context, opts LoginOptions) (*Session, error) {+ baseURL := ResolveBaseURL(opts.BaseURL)+ if !secureURL(baseURL) {+ return nil, fmt.Errorf("Beacon auth URL must use https://: %s", baseURL)+ }+ client := opts.HTTPClient+ if client == nil {+ client = &http.Client{Timeout: defaultTimeout}+ }+ out := opts.Out+ if out == nil {+ out = io.Discard+ }+ openBrowser := opts.OpenBrowser+ if openBrowser == nil {+ openBrowser = auth.OpenBrowser+ }+ timeout := opts.Timeout+ if timeout == 0 {+ timeout = loginWait+ }+ now := opts.Now+ if now == nil {+ now = time.Now+ }++ pkce, err := auth.GeneratePKCE()+ if err != nil {+ return nil, fmt.Errorf("generate PKCE parameters: %w", err)+ }++ var exchanged *exchangeResult+ exchange := func(ctx context.Context, exchangeCode, state, codeVerifier string) error {+ var result exchangeResult+ if err := auth.PostJSON(ctx, client, baseURL+ExchangePath, exchangeRequest{+ ExchangeCode: exchangeCode,+ State: state,+ CodeVerifier: codeVerifier,+ }, &result); err != nil {+ return err+ }+ if err := validateExchange(&result, now()); err != nil {+ return err+ }+ exchanged = &result+ return nil+ }+ callback, err := auth.NewCallbackServer(pkce.State, pkce.CodeVerifier, exchange, client.Timeout)+ if err != nil {+ return nil, err+ }+ callback.SetSuccessPage("Beacon: signed in", "You are signed in to Beacon. You can close this tab and return to the terminal.")+ defer callback.Shutdown()+ callback.Start()++ if err := auth.PostJSON(ctx, client, baseURL+LoginInitPath, loginInitRequest{+ CodeChallenge: pkce.CodeChallenge,+ CodeChallengeMethod: "S256",+ State: pkce.State,+ RedirectPort: callback.Port(),+ Client: clientInfo{+ Name: CLIClientName,+ Version: opts.Version,+ OS: runtime.GOOS,+ Arch: runtime.GOARCH,+ GrantVersion: CLIGrantVersion,+ },+ Scopes: []string{ScopeProfileRead, ScopeDeviceEnroll},+ }, nil); err != nil {+ return nil, fmt.Errorf("start Beacon sign-in: %w", err)+ }++ loginURL := buildLoginURL(baseURL, pkce.State, callback.Port())+ if opts.NoBrowser {+ fmt.Fprintf(out, "Open this URL to sign in to Beacon:\n%s\n", loginURL)+ } else {+ fmt.Fprintf(out, "Opening %s in your browser...\n", baseURL)+ if err := openBrowser(loginURL); err != nil {+ fmt.Fprintln(out, "Could not open a browser automatically.")+ fmt.Fprintf(out, "Open this URL to sign in to Beacon:\n%s\n", loginURL)+ }+ }+ fmt.Fprintln(out, "Waiting for Beacon sign-in...")++ result, err := callback.Wait(timeout)+ if err != nil {+ return nil, err+ }+ if result.Error != "" {+ return nil, fmt.Errorf("Beacon sign-in failed: %s", result.Error)+ }+ if exchanged == nil {+ return nil, errors.New("Beacon sign-in finished without a session")+ }+ return &Session{+ SchemaVersion: SchemaVersion,+ BaseURL: baseURL,+ AccessToken: exchanged.AccessToken,+ TokenType: firstNonEmpty(exchanged.TokenType, "Bearer"),+ ExpiresAt: exchanged.ExpiresAt,+ CreatedAt: now().UTC(),+ User: exchanged.User,+ Organizations: exchanged.Organizations,+ ActiveOrganization: exchanged.ActiveOrganization,+ Scopes: exchanged.Scopes,+ }, nil+}++// Revoke asks beacon.sh to invalidate the CLI credential. Callers should remove+// the local session regardless of this result so logout still works offline.+func Revoke(ctx context.Context, session Session, client *http.Client) error {+ if !secureURL(session.BaseURL) {+ return errors.New("refusing to send the Beacon credential to an insecure URL")+ }+ if client == nil {+ client = &http.Client{Timeout: defaultTimeout}+ }+ body, _ := json.Marshal(map[string]string{"grant_version": CLIGrantVersion})+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(session.BaseURL, "/")+RevokePath, bytes.NewReader(body))+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", firstNonEmpty(session.TokenType, "Bearer")+" "+session.AccessToken)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", CLIClientName)+ resp, err := client.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode >= 200 && resp.StatusCode <= 299 {+ return nil+ }+ var payload struct {+ Detail string `json:"detail"`+ Error string `json:"error"`+ }+ _ = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&payload)+ detail := firstNonEmpty(payload.Detail, payload.Error)+ if detail != "" {+ return errors.New(detail)+ }+ return fmt.Errorf("revoke request returned HTTP %d", resp.StatusCode)+}++func ResolveBaseURL(flagValue string) string {+ value := strings.TrimSpace(flagValue)+ if value == "" {+ value = strings.TrimSpace(os.Getenv(BaseURLEnv))+ }+ if value == "" {+ value = DefaultBaseURL+ }+ return strings.TrimRight(value, "/")+}++func buildLoginURL(baseURL, state string, port int) string {+ u, err := url.Parse(baseURL + LoginPagePath)+ if err != nil {+ return baseURL + LoginPagePath+ }+ query := u.Query()+ query.Set("state", state)+ query.Set("port", fmt.Sprint(port))+ u.RawQuery = query.Encode()+ return u.String()+}++func secureURL(raw string) bool {+ u, err := url.Parse(strings.TrimSpace(raw))+ if err != nil || u.Host == "" {+ return false+ }+ if strings.EqualFold(u.Scheme, "https") {+ return true+ }+ if !strings.EqualFold(u.Scheme, "http") {+ return false+ }+ host := u.Hostname()+ return host == "localhost" || host == "127.0.0.1" || net.ParseIP(host) != nil && net.ParseIP(host).IsLoopback()+}++func validateExchange(result *exchangeResult, now time.Time) error {+ switch {+ case result.AccessToken == "":+ return errors.New("exchange response did not include an access token")+ case result.TokenType != "" && !strings.EqualFold(result.TokenType, "Bearer"):+ return fmt.Errorf("exchange response returned unsupported token type %q", result.TokenType)+ case result.User.ID == "" || result.User.Email == "":+ return errors.New("exchange response did not include the signed-in user")+ case result.ExpiresAt.IsZero():+ return errors.New("exchange response did not include token expiry")+ case !result.ExpiresAt.After(now):+ return errors.New("exchange response returned an expired token")+ }+ return nil+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return strings.TrimSpace(value)+ }+ }+ return ""+}diff --git a/cli/beacon/internal/account/login_test.go b/cli/beacon/internal/account/login_test.gonew file mode 100644index 00000000..94b0eb67--- /dev/null+++ b/cli/beacon/internal/account/login_test.go@@ -0,0 +1,183 @@+package account++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "testing"+ "time"+)++type fakeAuthService struct {+ mu sync.Mutex+ init map[string]any+ exchange map[string]any+ revoke bool+ server *httptest.Server+ expires time.Time+}++func newFakeAuthService(t *testing.T) *fakeAuthService {+ t.Helper()+ service := &fakeAuthService{expires: time.Now().Add(time.Hour).UTC()}+ service.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var payload map[string]any+ if r.Body != nil {+ body, _ := io.ReadAll(r.Body)+ _ = json.Unmarshal(body, &payload)+ }+ service.mu.Lock()+ defer service.mu.Unlock()+ switch r.URL.Path {+ case LoginInitPath:+ service.init = payload+ w.WriteHeader(http.StatusCreated)+ case ExchangePath:+ service.exchange = payload+ _ = json.NewEncoder(w).Encode(map[string]any{+ "access_token": "bcn_cli_test_secret",+ "token_type": "Bearer",+ "expires_at": service.expires.Format(time.RFC3339),+ "user": map[string]any{+ "id": "usr_1", "email": "[email protected]", "name": "Beacon User",+ },+ "organizations": []map[string]any{{+ "id": "org_1", "slug": "acme", "name": "Acme",+ }},+ "active_organization": map[string]any{+ "id": "org_1", "slug": "acme", "name": "Acme",+ },+ "scopes": []string{"profile:read", "device:enroll"},+ })+ case RevokePath:+ if r.Header.Get("Authorization") != "Bearer bcn_cli_test_secret" {+ http.Error(w, `{"detail":"missing token"}`, http.StatusUnauthorized)+ return+ }+ service.revoke = true+ w.WriteHeader(http.StatusNoContent)+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(service.server.Close)+ return service+}++func (s *fakeAuthService) approve(t *testing.T) func(string) error {+ t.Helper()+ return func(rawURL string) error {+ parsed, err := url.Parse(rawURL)+ if err != nil {+ return err+ }+ if parsed.Path != LoginPagePath {+ t.Errorf("login path = %s, want %s", parsed.Path, LoginPagePath)+ }+ if parsed.Query().Get("code_challenge") != "" {+ t.Errorf("login URL leaked code challenge: %s", rawURL)+ }+ state, port := parsed.Query().Get("state"), parsed.Query().Get("port")+ go func() {+ callbackURL := fmt.Sprintf("http://127.0.0.1:%s/callback?state=%s&exchange_code=code-123", port, state)+ resp, err := http.Get(callbackURL)+ if err == nil {+ resp.Body.Close()+ }+ }()+ return nil+ }+}++func TestLoginUsesPKCEAndReturnsPrivateSession(t *testing.T) {+ service := newFakeAuthService(t)+ now := time.Now().UTC().Truncate(time.Second)+ var out strings.Builder+ session, err := Login(context.Background(), LoginOptions{+ BaseURL: service.server.URL,+ Version: "v1.2.3",+ OpenBrowser: service.approve(t),+ HTTPClient: service.server.Client(),+ Out: &out,+ Timeout: 5 * time.Second,+ Now: func() time.Time { return now },+ })+ if err != nil {+ t.Fatalf("Login returned error: %v", err)+ }+ if session.AccessToken != "bcn_cli_test_secret" || session.User.Email != "[email protected]" {+ t.Fatalf("session = %#v", session)+ }+ if session.ActiveOrganization == nil || session.ActiveOrganization.ID != "org_1" {+ t.Fatalf("active organization = %#v", session.ActiveOrganization)+ }+ if !session.CreatedAt.Equal(now) || session.BaseURL != service.server.URL {+ t.Fatalf("session metadata = %#v", session)+ }++ service.mu.Lock()+ defer service.mu.Unlock()+ if service.init["code_challenge_method"] != "S256" || service.init["state"] == "" || service.init["redirect_port"] == nil {+ t.Fatalf("init payload = %#v", service.init)+ }+ client := service.init["client"].(map[string]any)+ if client["name"] != CLIClientName || client["version"] != "v1.2.3" || client["grant_version"] != CLIGrantVersion {+ t.Fatalf("client payload = %#v", client)+ }+ scopes := service.init["scopes"].([]any)+ if len(scopes) != 2 || scopes[0] != ScopeProfileRead || scopes[1] != ScopeDeviceEnroll {+ t.Fatalf("requested scopes = %#v", scopes)+ }+ if service.exchange["state"] != service.init["state"] || service.exchange["exchange_code"] != "code-123" || service.exchange["code_verifier"] == "" {+ t.Fatalf("exchange payload = %#v", service.exchange)+ }+ if !strings.Contains(out.String(), "Waiting for Beacon sign-in") {+ t.Fatalf("output = %q", out.String())+ }+}++func TestLoginRejectsInsecureAndExpiredSessions(t *testing.T) {+ if _, err := Login(context.Background(), LoginOptions{BaseURL: "http://beacon.example.com"}); err == nil {+ t.Fatal("expected insecure URL rejection")+ }+ service := newFakeAuthService(t)+ service.expires = time.Now().Add(-time.Minute)+ _, err := Login(context.Background(), LoginOptions{+ BaseURL: service.server.URL,+ OpenBrowser: service.approve(t),+ HTTPClient: service.server.Client(),+ Timeout: 5 * time.Second,+ })+ if err == nil || !strings.Contains(err.Error(), "expired token") {+ t.Fatalf("expected expired token error, got %v", err)+ }+}++func TestRevokeUsesBearerToken(t *testing.T) {+ service := newFakeAuthService(t)+ session := Session{BaseURL: service.server.URL, AccessToken: "bcn_cli_test_secret", TokenType: "Bearer"}+ if err := Revoke(context.Background(), session, service.server.Client()); err != nil {+ t.Fatalf("Revoke returned error: %v", err)+ }+ service.mu.Lock()+ defer service.mu.Unlock()+ if !service.revoke {+ t.Fatal("revoke endpoint was not called")+ }+}++func TestResolveBaseURLPrecedence(t *testing.T) {+ t.Setenv(BaseURLEnv, "https://env.example/")+ if got := ResolveBaseURL("https://flag.example/"); got != "https://flag.example" {+ t.Fatalf("flag URL = %q", got)+ }+ if got := ResolveBaseURL(""); got != "https://env.example" {+ t.Fatalf("env URL = %q", got)+ }+}diff --git a/cli/beacon/internal/account/store.go b/cli/beacon/internal/account/store.gonew file mode 100644index 00000000..254b709c--- /dev/null+++ b/cli/beacon/internal/account/store.go@@ -0,0 +1,199 @@+// Package account implements Beacon CLI account authentication and credential storage.+package account++import (+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "time"+)++const (+ SessionPath = ".beacon/auth/session.json"+ SchemaVersion = 1+)++var ErrNotSignedIn = errors.New("not signed in")++type User struct {+ ID string `json:"id"`+ Email string `json:"email"`+ Name string `json:"name,omitempty"`+}++type Organization struct {+ ID string `json:"id"`+ Slug string `json:"slug,omitempty"`+ Name string `json:"name"`+}++// Session is the private credential returned by the beacon.sh CLI exchange.+// AccessToken is deliberately omitted from all status/result types.+type Session struct {+ SchemaVersion int `json:"schema_version"`+ BaseURL string `json:"base_url"`+ AccessToken string `json:"access_token"`+ TokenType string `json:"token_type"`+ ExpiresAt time.Time `json:"expires_at"`+ CreatedAt time.Time `json:"created_at"`+ User User `json:"user"`+ Organizations []Organization `json:"organizations,omitempty"`+ ActiveOrganization *Organization `json:"active_organization,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+}++type Status struct {+ SignedIn bool `json:"signed_in"`+ Expired bool `json:"expired,omitempty"`+ BaseURL string `json:"base_url,omitempty"`+ ExpiresAt time.Time `json:"expires_at,omitempty"`+ User User `json:"user,omitempty"`+ Organizations []Organization `json:"organizations,omitempty"`+ ActiveOrganization *Organization `json:"active_organization,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+ SessionPath string `json:"session_path"`+}++func Path() string {+ home, err := os.UserHomeDir()+ if err != nil {+ return filepath.Join(".", SessionPath)+ }+ return filepath.Join(home, SessionPath)+}++func Load() (*Session, error) {+ path := Path()+ data, err := os.ReadFile(path)+ if errors.Is(err, os.ErrNotExist) {+ return nil, ErrNotSignedIn+ }+ if err != nil {+ return nil, fmt.Errorf("read Beacon session: %w", err)+ }+ var session Session+ if err := json.Unmarshal(data, &session); err != nil {+ return nil, fmt.Errorf("parse Beacon session: %w", err)+ }+ if err := validateSession(&session); err != nil {+ return nil, fmt.Errorf("invalid Beacon session: %w", err)+ }+ return &session, nil+}++func Save(session Session) error {+ if session.SchemaVersion == 0 {+ session.SchemaVersion = SchemaVersion+ }+ if session.CreatedAt.IsZero() {+ session.CreatedAt = time.Now().UTC()+ }+ if err := validateSession(&session); err != nil {+ return err+ }+ path := Path()+ dir := filepath.Dir(path)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return err+ }+ if runtime.GOOS != "windows" {+ if err := os.Chmod(dir, 0o700); err != nil {+ return err+ }+ }+ data, err := json.MarshalIndent(session, "", " ")+ if err != nil {+ return err+ }+ data = append(data, '\n')+ tmp, err := os.CreateTemp(dir, ".session-*.tmp")+ if err != nil {+ return err+ }+ tmpPath := tmp.Name()+ defer os.Remove(tmpPath)+ if err := tmp.Chmod(0o600); err != nil {+ tmp.Close()+ return err+ }+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Sync(); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ // Windows does not replace an existing destination with os.Rename.+ if runtime.GOOS == "windows" {+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {+ return err+ }+ }+ if err := os.Rename(tmpPath, path); err != nil {+ return err+ }+ if runtime.GOOS != "windows" {+ return os.Chmod(path, 0o600)+ }+ return nil+}++func Remove() error {+ err := os.Remove(Path())+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ return err+}++func Inspect(now time.Time) Status {+ status := Status{SessionPath: Path()}+ session, err := Load()+ if err != nil {+ return status+ }+ status.SignedIn = true+ status.Expired = session.Expired(now)+ status.BaseURL = session.BaseURL+ status.ExpiresAt = session.ExpiresAt+ status.User = session.User+ status.Organizations = append([]Organization(nil), session.Organizations...)+ status.ActiveOrganization = session.ActiveOrganization+ status.Scopes = append([]string(nil), session.Scopes...)+ return status+}++func (s Session) Expired(now time.Time) bool {+ return !s.ExpiresAt.IsZero() && !now.Before(s.ExpiresAt)+}++func validateSession(session *Session) error {+ switch {+ case session.SchemaVersion != 0 && session.SchemaVersion != SchemaVersion:+ return fmt.Errorf("unsupported schema version %d", session.SchemaVersion)+ case session.BaseURL == "":+ return errors.New("base URL is required")+ case !secureURL(session.BaseURL):+ return errors.New("base URL must use HTTPS or loopback HTTP")+ case session.AccessToken == "":+ return errors.New("access token is required")+ case session.User.ID == "" || session.User.Email == "":+ return errors.New("user id and email are required")+ }+ if session.TokenType == "" {+ session.TokenType = "Bearer"+ }+ if !strings.EqualFold(session.TokenType, "Bearer") {+ return fmt.Errorf("unsupported token type %q", session.TokenType)+ }+ session.TokenType = "Bearer"+ return nil+}diff --git a/cli/beacon/internal/account/store_test.go b/cli/beacon/internal/account/store_test.gonew file mode 100644index 00000000..7beee0fa--- /dev/null+++ b/cli/beacon/internal/account/store_test.go@@ -0,0 +1,110 @@+package account++import (+ "encoding/json"+ "errors"+ "os"+ "runtime"+ "strings"+ "testing"+ "time"+)++func testSession() Session {+ return Session{+ BaseURL: "https://beacon.sh",+ AccessToken: "bcn_cli_super_secret",+ TokenType: "Bearer",+ ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second),+ User: User{ID: "usr_1", Email: "[email protected]", Name: "Beacon User"},+ Organizations: []Organization{{+ ID: "org_1", Slug: "acme", Name: "Acme",+ }},+ Scopes: []string{"profile:read"},+ }+}++func TestSaveLoadInspectAndRemoveSession(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ session := testSession()+ if err := Save(session); err != nil {+ t.Fatalf("Save returned error: %v", err)+ }+ loaded, err := Load()+ if err != nil {+ t.Fatalf("Load returned error: %v", err)+ }+ if loaded.AccessToken != session.AccessToken || loaded.User.Email != session.User.Email {+ t.Fatalf("loaded session = %#v", loaded)+ }+ if loaded.SchemaVersion != SchemaVersion || loaded.CreatedAt.IsZero() {+ t.Fatalf("session metadata = %#v", loaded)+ }+ session.AccessToken = "bcn_cli_rotated_secret"+ if err := Save(session); err != nil {+ t.Fatalf("replace session: %v", err)+ }+ loaded, err = Load()+ if err != nil || loaded.AccessToken != session.AccessToken {+ t.Fatalf("replaced session = %#v, %v", loaded, err)+ }+ if runtime.GOOS != "windows" {+ info, err := os.Stat(Path())+ if err != nil {+ t.Fatal(err)+ }+ if info.Mode().Perm() != 0o600 {+ t.Fatalf("session mode = %o, want 600", info.Mode().Perm())+ }+ }++ status := Inspect(time.Now())+ if !status.SignedIn || status.User.Email != session.User.Email || status.SessionPath != Path() {+ t.Fatalf("status = %#v", status)+ }+ encoded, err := json.Marshal(status)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(encoded), session.AccessToken) || strings.Contains(string(encoded), "access_token") {+ t.Fatalf("status leaked access token: %s", encoded)+ }++ if err := Remove(); err != nil {+ t.Fatalf("Remove returned error: %v", err)+ }+ if _, err := Load(); !errors.Is(err, ErrNotSignedIn) {+ t.Fatalf("Load after remove = %v", err)+ }+}++func TestInspectMarksExpiredSession(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ session := testSession()+ session.ExpiresAt = time.Now().Add(-time.Minute)+ if err := Save(session); err != nil {+ t.Fatal(err)+ }+ status := Inspect(time.Now())+ if !status.SignedIn || !status.Expired {+ t.Fatalf("status = %#v", status)+ }+}++func TestSaveRejectsIncompleteSession(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ if err := Save(Session{BaseURL: "https://beacon.sh"}); err == nil {+ t.Fatal("expected missing token rejection")+ }+ session := testSession()+ session.BaseURL = "http://beacon.example.com"+ if err := Save(session); err == nil {+ t.Fatal("expected insecure base URL rejection")+ }+}diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdxnew file mode 100644index 00000000..0cb97f5f--- /dev/null+++ b/docs/cli/account-auth.mdx@@ -0,0 +1,60 @@+---+title: "Beacon account authentication"+description: "Sign the Beacon CLI in through beacon.sh without enabling managed telemetry forwarding"+---++Beacon account authentication is separate from endpoint forwarding. Signing in establishes your CLI identity, but it does not start Vector, register a managed endpoint, or send local telemetry anywhere.++```bash+beacon login+beacon whoami+beacon logout+```++## Sign in++`beacon login` starts a PKCE exchange and opens `https://beacon.sh/cli/auth`. After authentication, beacon.sh redirects a one-time exchange code to a temporary loopback listener. The PKCE verifier never leaves the CLI except during the HTTPS exchange.++```bash+beacon login+```++For SSH sessions or terminals that cannot open a browser:++```bash+beacon login --no-browser+```++The session is stored at `~/.beacon/auth/session.json` in a `0700` directory with file mode `0600`. Human and JSON command output never includes the access token. Tokens expire rather than refreshing indefinitely; run `beacon login` again after expiry.++Use `--auth-url` or `BEACON_AUTH_URL` only for a self-hosted or development authentication service. Non-loopback authentication URLs must use HTTPS.++## Inspect the account++`beacon whoami` reads the local session and displays the user, organization, expiry, authentication service, and session path. It does not contact beacon.sh.++```bash+beacon whoami+beacon whoami --json+```++## Sign out++`beacon logout` asks beacon.sh to revoke the CLI token and always removes the local session. If beacon.sh is unavailable, logout succeeds locally and warns that server revocation could not be confirmed.++```bash+beacon logout+```++Signing out does not stop an already configured managed forwarder. Use `beacon endpoint disconnect` for that separate device credential and service.++## beacon.sh server contract++The CLI uses the versioned `2026-09-01` grant contract:++- `POST /api/cli/auth/init` registers the PKCE challenge, state, loopback port, CLI version, operating system, and architecture.+- `GET /cli/auth?state=...&port=...` authenticates the person and redirects to the loopback callback with `state` and a one-time `exchange_code`.+- `POST /api/cli/auth/exchange` accepts the exchange code, state, and PKCE verifier. It returns a scoped access token, expiry, user identity, organization memberships, and optional active organization.+- `POST /api/cli/auth/revoke` accepts the access token as a Bearer credential and revokes it.++The intended initial scopes are `profile:read` and `device:enroll`. A later `beacon endpoint connect` can use `device:enroll` to mint a device-specific ingest key without treating the account token as an ingest credential.diff --git a/docs/cli/index.mdx b/docs/cli/index.mdxindex 4c3fa8d8..7e2b2705 100644--- a/docs/cli/index.mdx+++ b/docs/cli/index.mdx@@ -38,6 +38,8 @@ Top-level Agent Beacon CLI commands.| [`beacon doctor`](/cli/endpoint-doctor) | Alias for `beacon endpoint doctor`. || [`beacon endpoint`](/cli/endpoint) | Manage local endpoint telemetry, runtime logs, and integrations. || [`beacon inventory`](/cli/endpoint-inventory) | Alias for `beacon endpoint inventory`. |+| [`beacon login`](/cli/account-auth) | Sign in through beacon.sh without enabling telemetry forwarding. |+| [`beacon logout`](/cli/account-auth#sign-out) | Revoke and remove the local Beacon account session. || [`beacon memory`](/cli/memory) | Evaluate traces, review candidates, and install approved project memory. || [`beacon mcp`](/cli/mcp) | Expose local Beacon activity to MCP clients. || [`beacon rules`](/cli/rules) | Manage and author Beacon threat-detection rules. |@@ -45,6 +47,7 @@ Top-level Agent Beacon CLI commands.| [`beacon status`](/cli/endpoint-status) | Alias for `beacon endpoint status`. || [`beacon token-usage`](/cli/token-usage) | Report token usage and attribution from Beacon runtime logs. || [`beacon version`](/cli/version) | Display the installed Agent Beacon CLI version. |+| [`beacon whoami`](/cli/account-auth#inspect-the-account) | Show the current Beacon account and session expiry. |## beacon versiondiff --git a/docs/docs.json b/docs/docs.jsonindex 37734a69..e1abdebb 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -255,6 +255,7 @@"icon": "terminal","pages": ["cli/index",+ "cli/account-auth",{"group": "beacon ci","root": "cli/ci",