An open-source, faster Devin alternative
TypeScript
Polish CLI authentication output
Igor Zalutskib60bae22f8c5
diff --git a/cmd/oc/internal/commands/auth.go b/cmd/oc/internal/commands/auth.goindex 3d18be1d..34580125 100644--- a/cmd/oc/internal/commands/auth.go+++ b/cmd/oc/internal/commands/auth.go@@ -342,17 +342,59 @@ func printLoginResult(cmd *cobra.Command, result loginResult, already bool) erroif jsonOutput {return json.NewEncoder(cmd.OutOrStdout()).Encode(result)}- prefix := "✓ Logged in as "+ renderLoginResult(+ cmd.OutOrStdout(),+ result,+ already,+ deployStyleFor(cmd.OutOrStdout()),+ )+ return nil+}++func renderLoginResult(w io.Writer, result loginResult, already bool, style deployOutputStyle) {+ action := "Logged in as"if already {- prefix = "Already logged in as "+ action = "Already logged in as"}- fmt.Fprintf(cmd.OutOrStdout(), "%s%s\n", prefix, oneLine(result.Email))- fmt.Fprintf(cmd.OutOrStdout(), " %-11s %s\n", "Workspace", oneLine(result.OrgName))- fmt.Fprintf(cmd.OutOrStdout(), " %-11s %s\n", "API", oneLine(result.APIURL))+ mark := ansiText("✓", "32", style.color)+ email := ansiText(oneLine(result.Email), "1", style.color)+ fmt.Fprintf(w, "%s %s %s\n", mark, action, email)+ fmt.Fprintf(w, "\n %-11s %s\n", "Workspace", oneLine(result.OrgName))+ fmt.Fprintf(w, " %-11s %s\n", "API", terminalLink(result.APIURL, style))if !already {- fmt.Fprintln(cmd.OutOrStdout(), "\nNext: oc agent init")+ fmt.Fprintf(w, "\n %s\n", ansiText("Next", "1", style.color))+ fmt.Fprintf(w, " %s oc agent init\n", ansiText("$", "2", style.color))}- return nil+}++func renderLoginInstructions(w io.Writer, receipt deviceAuthorization, style deployOutputStyle) {+ fmt.Fprintln(w, "Open this page to sign in:")+ fmt.Fprintf(w, " %s\n", terminalLink(receipt.VerificationURIComplete, style))+ fmt.Fprintf(+ w,+ "\n %-11s %s\n",+ "Code",+ ansiText(oneLine(receipt.UserCode), "1", style.color),+ )+}++type loginCanceledError struct {+ cause error+}++func (e *loginCanceledError) Error() string {+ return "login canceled; no credentials were changed"+}++func (e *loginCanceledError) Unwrap() error {+ return e.cause+}++func canceledLoginError(err error) error {+ if errors.Is(err, context.Canceled) {+ return &loginCanceledError{cause: err}+ }+ return err}func identityAsLoginResult(identity loginIdentity, metadata *config.LoginMetadata) loginResult {@@ -458,18 +500,20 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {receipt, err := authClient.start(cmd.Context())if err != nil {+ if errors.Is(err, context.Canceled) {+ return canceledLoginError(err)+ }return fmt.Errorf("starting login: %w", err)}style := deployStyleFor(errOut)- fmt.Fprintln(errOut, "Open this page to sign in:")- fmt.Fprintf(errOut, " %s\n\n", terminalLink(receipt.VerificationURIComplete, style))- fmt.Fprintf(errOut, "Confirm code: %s\n", oneLine(receipt.UserCode))- fmt.Fprintln(errOut, "Waiting for confirmation…")+ renderLoginInstructions(errOut, receipt, style)if !noBrowser {if err := openAuthBrowser(receipt.VerificationURIComplete); err != nil {- fmt.Fprintf(errOut, "Could not open a browser automatically: %s\n", oneLine(err.Error()))+ fmt.Fprintln(errOut, "Could not open a browser automatically. Open the URL above.")}}+ fmt.Fprintln(errOut, "\nWaiting for confirmation…")+ fmt.Fprintln(errOut)interval := time.Duration(receipt.Interval) * time.Seconddeadline := time.Now().Add(time.Duration(receipt.ExpiresIn) * time.Second)@@ -480,10 +524,13 @@ func runLogin(cmd *cobra.Command, force, noBrowser bool) error {return authAPIError(http.StatusGone, "authorization_expired")}if err := authSleep(cmd.Context(), interval); err != nil {- return err+ return canceledLoginError(err)}exchange, err = authClient.exchange(cmd.Context(), receipt.DeviceCode, credentialName())if err != nil {+ if errors.Is(err, context.Canceled) {+ return canceledLoginError(err)+ }var authErr *cliAuthAPIErrorif errors.As(err, &authErr) &&authErr.Code == "auth_provider_unavailable" &&@@ -595,6 +642,10 @@ func runLogout(cmd *cobra.Command, localOnly bool) error {if jsonOutput {return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]string{"status": "logged_out"})}+ if localOnly {+ fmt.Fprintln(cmd.OutOrStdout(), "Local login cleared. The remote credential was not revoked.")+ return nil+ }fmt.Fprintln(cmd.OutOrStdout(), "Logged out.")return nil}diff --git a/cmd/oc/internal/commands/auth_test.go b/cmd/oc/internal/commands/auth_test.goindex 5f426b70..96ff5bec 100644--- a/cmd/oc/internal/commands/auth_test.go+++ b/cmd/oc/internal/commands/auth_test.go@@ -103,6 +103,61 @@ func whoamiResponse() map[string]any {}}+func TestLoginHumanOutputMatchesDeployPresentation(t *testing.T) {+ result := loginResult{+ loginIdentity: loginIdentity{+ Email: "[email protected]",+ OrgName: "Igor's workspace",+ APIURL: "https://app.opencomputer.dev",+ },+ }+ var out bytes.Buffer+ renderLoginResult(&out, result, false, deployOutputStyle{})+ want := "✓ Logged in as [email protected]\n\n" ++ " Workspace Igor's workspace\n" ++ " API https://app.opencomputer.dev\n\n" ++ " Next\n" ++ " $ oc agent init\n"+ if out.String() != want {+ t.Fatalf("login output:\n%q\nwant:\n%q", out.String(), want)+ }++ out.Reset()+ renderLoginResult(&out, result, true, deployOutputStyle{})+ if strings.Contains(out.String(), "Next") ||+ !strings.HasPrefix(out.String(), "✓ Already logged in as [email protected]\n") {+ t.Fatalf("existing-login output:\n%q", out.String())+ }++ out.Reset()+ renderLoginResult(&out, result, false, deployOutputStyle{color: true, hyperlinks: true})+ for _, want := range []string{+ "\x1b[32m✓\x1b[0m",+ "\x1b[[email protected]\x1b[0m",+ "\x1b]8;;https://app.opencomputer.dev\x1b\\",+ "\x1b[1mNext\x1b[0m",+ } {+ if !strings.Contains(out.String(), want) {+ t.Fatalf("styled login output missing %q:\n%q", want, out.String())+ }+ }+}++func TestLoginInstructionsAreCompactAndCopyable(t *testing.T) {+ receipt := deviceAuthorization{+ UserCode: testUserCode,+ VerificationURIComplete: "https://auth.example.test/device?user_code=" + testUserCode,+ }+ var out bytes.Buffer+ renderLoginInstructions(&out, receipt, deployOutputStyle{})+ want := "Open this page to sign in:\n" ++ " https://auth.example.test/device?user_code=ABCD-EFGH\n\n" ++ " Code ABCD-EFGH\n"+ if out.String() != want {+ t.Fatalf("login instructions:\n%q\nwant:\n%q", out.String(), want)+ }+}+func TestLoginPollsSavesVerifiesAndNeverPrintsCredential(t *testing.T) {var mu sync.Mutexvar exchanges int@@ -180,7 +235,8 @@ func TestLoginPollsSavesVerifiesAndNeverPrintsCredential(t *testing.T) {t.Fatalf("secret leaked to output: %q", combined)}if !strings.Contains(stdout.String(), "Logged in as [email protected]") ||- !strings.Contains(stdout.String(), "Igor's workspace") {+ !strings.Contains(stdout.String(), "Igor's workspace") ||+ !strings.Contains(stdout.String(), "$ oc agent init") {t.Fatalf("unexpected success output:\n%s", stdout.String())}@@ -199,6 +255,36 @@ func TestLoginPollsSavesVerifiesAndNeverPrintsCredential(t *testing.T) {}}+func TestLoginBrowserFailurePointsBackToPrintedURLBeforeWaiting(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/auth/cli/device":+ writeJSONResponse(w, 200, deviceReceipt())+ case "/auth/cli/device/exchange":+ writeJSONResponse(w, 200, authorizedExchange())+ case "/api/whoami":+ writeJSONResponse(w, 200, whoamiResponse())+ default:+ http.NotFound(w, r)+ }+ }))+ defer server.Close()+ cmd, _, stderr := authTestCommand(t, server.URL)+ openAuthBrowser = func(string) error {+ return errors.New("no browser opener at /private/path")+ }+ if err := runLogin(cmd, false, false); err != nil {+ t.Fatalf("runLogin: %v", err)+ }+ got := stderr.String()+ failure := "Could not open a browser automatically. Open the URL above."+ if !strings.Contains(got, failure) ||+ strings.Contains(got, "/private/path") ||+ strings.Index(got, failure) > strings.Index(got, "Waiting for confirmation…") {+ t.Fatalf("browser-failure output:\n%s", got)+ }+}+func TestLoginNoBrowserAndJSONContainNoKeyOrDeviceCode(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -603,7 +689,7 @@ func TestLogoutLocalDoesNotCallRemote(t *testing.T) {http.Error(w, "unexpected", 500)}))defer server.Close()- cmd, _, _ := authTestCommand(t, server.URL)+ cmd, stdout, _ := authTestCommand(t, server.URL)if err := config.Save(config.Config{APIURL: server.URL,APIKey: testKey,@@ -625,6 +711,9 @@ func TestLogoutLocalDoesNotCallRemote(t *testing.T) {if got := config.LoadFile(); got.APIKey != "" || got.Login != nil {t.Fatalf("local login remains: %#v", got)}+ if strings.TrimSpace(stdout.String()) != "Local login cleared. The remote credential was not revoked." {+ t.Fatalf("stdout = %q", stdout.String())+ }}func TestLogoutLocalIgnoresEffectiveCredentialOverride(t *testing.T) {@@ -665,6 +754,9 @@ func TestLoginCancellationDoesNotSaveCredential(t *testing.T) {if !errors.Is(err, context.Canceled) {t.Fatalf("error = %v, want context.Canceled", err)}+ if err.Error() != "login canceled; no credentials were changed" {+ t.Fatalf("cancellation error = %v", err)+ }if _, err := os.Stat(filepath.Join(os.Getenv("HOME"), ".oc", "config.json")); !os.IsNotExist(err) {t.Fatalf("config unexpectedly created: %v", err)}