diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index f971962..7708d96 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -366,6 +366,30 @@ nylas dashboard apps apikeys create --expires 30 # Expire in 30 days After creating a key, you choose: activate in CLI (recommended), copy to clipboard, or save to file. +### Structured output + +`status`, `apps list|create|use`, `apps apikeys list|create` and +`orgs list|switch` honour `--json`, `--format yaml` and `--quiet`, so scripts +and AI agents can read the result instead of the text: + +```bash +nylas dashboard status --json # {"logged_in": true, "organization_id": ..., "active_app": {...}} +nylas dashboard apps list --json # [] when there are none +nylas dashboard apps create --name "My App" --region us --secret-delivery file --json +nylas dashboard apps apikeys create --delivery activate --json +nylas dashboard apps apikeys create --delivery file -q # prints only the key ID +``` + +- A secret is never printed in any format. `apps create` and `apikeys create` + report how it was delivered (`method`, `delivered`, and `file` for a file), + never its value. A clipboard that is unavailable falls back to a file and + says so in `warning`. +- Signed out, `status --json` prints `{"logged_in": false, ...}` and exits 0, + like the text form. +- A structured run never prompts: pass `--delivery` / `--secret-delivery`, + the application ID to `apps use`, and `--org` to `orgs switch`. +- `apps list` partial-region warnings go to stderr, so stdout stays valid JSON. + ### Domains ```bash diff --git a/internal/cli/dashboard/apps.go b/internal/cli/dashboard/apps.go index daa5092..9b76253 100644 --- a/internal/cli/dashboard/apps.go +++ b/internal/cli/dashboard/apps.go @@ -76,10 +76,14 @@ Use --region to filter to a specific region.`, if !errors.As(err, &partialErr) || len(apps) == 0 { return wrapDashboardError(err) } - common.PrintWarning("%v", partialErr) + if structuredOutput(cmd) { + common.PrintWarningStderr("%v", partialErr) + } else { + common.PrintWarning("%v", partialErr) + } } - if len(apps) == 0 { + if len(apps) == 0 && !structuredOutput(cmd) { fmt.Println("No applications found.") fmt.Println("\nCreate one with: nylas dashboard apps create --name MyApp --region us") return nil @@ -127,7 +131,8 @@ func newAppsCreateCmd() *cobra.Command { if err := validateSecretDelivery(secretDelivery); err != nil { return err } - if !isInteractive() && secretDelivery == "" { + structured := structuredOutput(cmd) + if secretDelivery == "" && (structured || !isInteractive()) { return dashboardError( "client secret delivery requires an explicit choice in non-interactive runs", "Pass --secret-delivery clipboard or --secret-delivery file", @@ -152,6 +157,10 @@ func newAppsCreateCmd() *cobra.Command { return wrapDashboardError(err) } + if structured { + return writeAppCreated(cmd, app, secretDelivery) + } + _, _ = common.Green.Println("✓ Application created!") fmt.Printf(" Application ID: %s\n", app.ApplicationID) fmt.Printf(" Region: %s\n", app.Region) @@ -208,7 +217,7 @@ When called without arguments, lists your applications and lets you pick one int // If no app ID provided, show interactive selector if appID == "" { - if !isInteractive() { + if structuredOutput(cmd) || !isInteractive() { return dashboardError( "application selection requires an interactive terminal", "Pass the application ID and --region in non-interactive runs", @@ -234,6 +243,9 @@ When called without arguments, lists your applications and lets you pick one int return wrapDashboardError(err) } + if structuredOutput(cmd) { + return common.GetOutputWriter(cmd).Write(activeAppReport{ApplicationID: appID, Region: region}) + } _, _ = common.Green.Printf("✓ Active app: %s (%s)\n", appID, region) return nil }, @@ -244,6 +256,24 @@ When called without arguments, lists your applications and lets you pick one int return cmd } +// writeAppCreated delivers a new application's client secret and reports the +// application without the secret's value. +func writeAppCreated(cmd *cobra.Command, app *domain.GatewayCreatedApplication, secretDelivery string) error { + report := appCreatedReport{ + ApplicationID: app.ApplicationID, + Region: app.Region, + Environment: app.Environment, + } + if app.ClientSecret != "" { + delivered, err := deliverClientSecret(app.ClientSecret, secretDelivery) + if err != nil { + return err + } + report.ClientSecret = &delivered + } + return common.GetOutputWriter(cmd).Write(report) +} + // selectApp fetches apps and presents an interactive selector. // Returns the selected app ID and region. func selectApp(regionFilter string) (appID, region string, err error) { diff --git a/internal/cli/dashboard/helpers.go b/internal/cli/dashboard/helpers.go index b78543a..ca5524f 100644 --- a/internal/cli/dashboard/helpers.go +++ b/internal/cli/dashboard/helpers.go @@ -342,7 +342,9 @@ func chooseAuthMethod(action string) (string, error) { return common.Select(fmt.Sprintf("How would you like to %s?", action), opts) } -func isInteractive() bool { +// isInteractive reports whether stdin is a terminal. A variable so tests can +// stand in a terminal and prove --json alone is what stops a prompt. +var isInteractive = func() bool { return term.IsTerminal(int(os.Stdin.Fd())) } diff --git a/internal/cli/dashboard/keys.go b/internal/cli/dashboard/keys.go index 52646ac..f4f073d 100644 --- a/internal/cli/dashboard/keys.go +++ b/internal/cli/dashboard/keys.go @@ -88,7 +88,7 @@ Set an active app with: nylas dashboard apps use --region `, return wrapDashboardError(err) } - if len(keys) == 0 { + if len(keys) == 0 && !structuredOutput(cmd) { createCmd := "nylas dashboard apps " + "apikeys create --app " + appID + " --region " + region @@ -156,7 +156,8 @@ Set an active app with: nylas dashboard apps use --region `, if err := validateAPIKeyDelivery(delivery); err != nil { return err } - if !isInteractive() && delivery == "" { + structured := structuredOutput(cmd) + if delivery == "" && (structured || !isInteractive()) { return dashboardError( "API key delivery requires an explicit choice in non-interactive runs", "Pass --delivery activate, --delivery clipboard, or --delivery file", @@ -180,6 +181,10 @@ Set an active app with: nylas dashboard apps use --region `, return wrapDashboardError(err) } + if structured { + return writeAPIKeyCreated(cmd, key, appID, region, delivery) + } + _, _ = common.Green.Println("✓ API key created") fmt.Printf(" ID: %s\n", key.ID) fmt.Printf(" Name: %s\n", key.Name) @@ -197,6 +202,21 @@ Set an active app with: nylas dashboard apps use --region `, return cmd } +// writeAPIKeyCreated delivers a new key and reports it without its value. +func writeAPIKeyCreated(cmd *cobra.Command, key *domain.GatewayCreatedAPIKey, appID, region, delivery string) error { + report, err := deliverAPIKey(key.APIKey, appID, region, delivery) + if err != nil { + return err + } + return common.GetOutputWriter(cmd).Write(apiKeyCreatedReport{ + ID: key.ID, + Name: key.Name, + ApplicationID: appID, + Region: region, + Delivery: report, + }) +} + // handleAPIKeyDelivery prompts the user to choose how to handle the newly created key. // The API key is never printed to stdout to prevent leaking it in terminal history or logs. func handleAPIKeyDelivery(apiKey, appID, region, delivery string) error { @@ -219,33 +239,11 @@ func handleAPIKeyDelivery(apiKey, appID, region, delivery string) error { choice = selected } - switch choice { - case "activate": - if err := activateAPIKey(apiKey, appID, region, ""); err != nil { - _, _ = common.Yellow.Printf(" Could not activate: %v\n", err) - return nil - } - _, _ = common.Green.Println("✓ API key activated — CLI is ready to use") - _, _ = common.Dim.Println(" Try: nylas auth status") - - case "clipboard": - if err := common.CopyToClipboard(apiKey); err != nil { - _, _ = common.Yellow.Printf(" Clipboard unavailable: %v\n", err) - _, _ = common.Dim.Println(" Falling back to file save") - return saveSecretToFile(apiKey, "nylas-api-key.txt", "API key") - } - _, _ = common.Green.Println("✓ API key copied to clipboard") - - case "file": - return saveSecretToFile(apiKey, "nylas-api-key.txt", "API key") - - default: - return dashboardError( - "invalid API key delivery method", - "Use --delivery activate, --delivery clipboard, or --delivery file", - ) + report, err := deliverAPIKey(apiKey, appID, region, choice) + if err != nil { + return err } - + printDelivery("API key", report) return nil } @@ -270,25 +268,11 @@ func handleSecretDelivery(secret, label, delivery string) error { choice = selected } - switch choice { - case "clipboard": - if err := common.CopyToClipboard(secret); err != nil { - _, _ = common.Yellow.Printf(" Clipboard unavailable: %v\n", err) - _, _ = common.Dim.Println(" Falling back to file save") - return saveSecretToFile(secret, "nylas-client-secret.txt", label) - } - _, _ = common.Green.Printf("✓ %s copied to clipboard\n", label) - - case "file": - return saveSecretToFile(secret, "nylas-client-secret.txt", label) - - default: - return dashboardError( - "invalid secret delivery method", - "Use --secret-delivery clipboard or --secret-delivery file", - ) + report, err := deliverClientSecret(secret, choice) + if err != nil { + return err } - + printDelivery(label, report) return nil } @@ -316,17 +300,6 @@ func validateSecretDelivery(delivery string) error { } } -// saveSecretToFile writes a secret to a temp file with restrictive permissions. -func saveSecretToFile(secret, filename, label string) error { - keyFile, err := writeSecretTempFile(secret, filename) - if err != nil { - return wrapDashboardError(fmt.Errorf("failed to write file: %w", err)) - } - _, _ = common.Green.Printf("✓ %s saved to: %s\n", label, keyFile) - _, _ = common.Dim.Println(" Read it, then delete the file") - return nil -} - func writeSecretTempFile(secret, filename string) (string, error) { pattern := tempSecretPattern(filename) file, err := os.CreateTemp("", pattern) diff --git a/internal/cli/dashboard/orgs.go b/internal/cli/dashboard/orgs.go index c34246f..84a8bba 100644 --- a/internal/cli/dashboard/orgs.go +++ b/internal/cli/dashboard/orgs.go @@ -41,7 +41,7 @@ func newOrgsListCmd() *cobra.Command { return wrapDashboardError(err) } - if len(session.Relations) == 0 { + if len(session.Relations) == 0 && !structuredOutput(cmd) { fmt.Println("No organizations found.") return nil } diff --git a/internal/cli/dashboard/output.go b/internal/cli/dashboard/output.go new file mode 100644 index 0000000..e6eaa69 --- /dev/null +++ b/internal/cli/dashboard/output.go @@ -0,0 +1,178 @@ +package dashboard + +import ( + "fmt" + + "github.com/spf13/cobra" + + "github.com/nylas/cli/internal/cli/common" +) + +// The reports below are what --json and --format yaml print for the +// dashboard commands, so an agent or a script can read the result instead of +// scraping the human text. None of them ever carries a secret: a new API key +// or client secret is reported by HOW it was delivered, never by value. + +// statusReport is `nylas dashboard status` as structured output. A missing +// session is a report with logged_in false, not an error, matching the text +// form's exit code. +type statusReport struct { + LoggedIn bool `json:"logged_in" yaml:"logged_in"` + UserID string `json:"user_id,omitempty" yaml:"user_id,omitempty"` + OrganizationID string `json:"organization_id,omitempty" yaml:"organization_id,omitempty"` + OrganizationName string `json:"organization_name,omitempty" yaml:"organization_name,omitempty"` + OrganizationCount int `json:"organization_count,omitempty" yaml:"organization_count,omitempty"` + HasOrgToken bool `json:"has_org_token" yaml:"has_org_token"` + ActiveApp *activeAppReport `json:"active_app,omitempty" yaml:"active_app,omitempty"` + DPoPThumbprint string `json:"dpop_thumbprint,omitempty" yaml:"dpop_thumbprint,omitempty"` +} + +// QuietField is empty: like `nylas oauth status`, --quiet prints nothing. +func (statusReport) QuietField() string { return "" } + +// activeAppReport is the application the apikeys commands default to. +type activeAppReport struct { + ApplicationID string `json:"application_id" yaml:"application_id"` + Region string `json:"region" yaml:"region"` +} + +func (r activeAppReport) QuietField() string { return r.ApplicationID } + +// appCreatedReport is `nylas dashboard apps create` as structured output. +type appCreatedReport struct { + ApplicationID string `json:"application_id" yaml:"application_id"` + Region string `json:"region" yaml:"region"` + Environment string `json:"environment,omitempty" yaml:"environment,omitempty"` + ClientSecret *deliveryReport `json:"client_secret,omitempty" yaml:"client_secret,omitempty"` +} + +func (r appCreatedReport) QuietField() string { return r.ApplicationID } + +// apiKeyCreatedReport is `nylas dashboard apps apikeys create` as structured +// output. +type apiKeyCreatedReport struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + ApplicationID string `json:"application_id" yaml:"application_id"` + Region string `json:"region" yaml:"region"` + Delivery deliveryReport `json:"delivery" yaml:"delivery"` +} + +func (r apiKeyCreatedReport) QuietField() string { return r.ID } + +// orgSwitchReport is `nylas dashboard orgs switch` as structured output. +type orgSwitchReport struct { + OrganizationID string `json:"organization_id" yaml:"organization_id"` + OrganizationName string `json:"organization_name,omitempty" yaml:"organization_name,omitempty"` + Switched bool `json:"switched" yaml:"switched"` +} + +func (r orgSwitchReport) QuietField() string { return r.OrganizationID } + +// deliveryReport says where a secret went. Method is the one actually used: +// a clipboard that is unavailable falls back to a file, and says so in +// Warning. Delivered is false only when the secret reached nowhere, which +// today is an activation that failed. +type deliveryReport struct { + Method string `json:"method" yaml:"method"` + Delivered bool `json:"delivered" yaml:"delivered"` + File string `json:"file,omitempty" yaml:"file,omitempty"` + Warning string `json:"warning,omitempty" yaml:"warning,omitempty"` + + // fallbackFrom and cause keep the text form's wording; they are + // unexported so no encoder writes them. + fallbackFrom string + cause error +} + +// structuredOutput reports whether --json, --format json|yaml|quiet or +// --quiet was given. Structured runs never prompt: a prompt would write to +// the stream a reader is parsing. +func structuredOutput(cmd *cobra.Command) bool { + return common.IsStructuredOutput(cmd) +} + +// deliverAPIKey hands a new API key to method and reports what happened. It +// prints nothing, so it serves both the text and the structured forms. +func deliverAPIKey(apiKey, appID, region, method string) (deliveryReport, error) { + switch method { + case "activate": + if err := activateAPIKey(apiKey, appID, region, ""); err != nil { + return deliveryReport{ + Method: "activate", + Warning: "could not activate: " + err.Error(), + cause: err, + }, nil + } + return deliveryReport{Method: "activate", Delivered: true}, nil + case "clipboard": + return deliverToClipboard(apiKey, "nylas-api-key.txt") + case "file": + return deliverToFile(apiKey, "nylas-api-key.txt") + default: + return deliveryReport{}, dashboardError( + "invalid API key delivery method", + "Use --delivery activate, --delivery clipboard, or --delivery file", + ) + } +} + +// deliverClientSecret hands an application's client secret to method. +func deliverClientSecret(secret, method string) (deliveryReport, error) { + switch method { + case "clipboard": + return deliverToClipboard(secret, "nylas-client-secret.txt") + case "file": + return deliverToFile(secret, "nylas-client-secret.txt") + default: + return deliveryReport{}, dashboardError( + "invalid secret delivery method", + "Use --secret-delivery clipboard or --secret-delivery file", + ) + } +} + +func deliverToClipboard(secret, fallbackFile string) (deliveryReport, error) { + err := common.CopyToClipboard(secret) + if err == nil { + return deliveryReport{Method: "clipboard", Delivered: true}, nil + } + report, fileErr := deliverToFile(secret, fallbackFile) + if fileErr != nil { + return deliveryReport{}, fileErr + } + report.Warning = "clipboard unavailable, saved to a file instead: " + err.Error() + report.fallbackFrom = "clipboard" + report.cause = err + return report, nil +} + +func deliverToFile(secret, filename string) (deliveryReport, error) { + path, err := writeSecretTempFile(secret, filename) + if err != nil { + return deliveryReport{}, wrapDashboardError(fmt.Errorf("failed to write file: %w", err)) + } + return deliveryReport{Method: "file", Delivered: true, File: path}, nil +} + +// printDelivery is the text form of a delivery, worded as it always was. +func printDelivery(label string, report deliveryReport) { + if report.fallbackFrom == "clipboard" { + _, _ = common.Yellow.Printf(" Clipboard unavailable: %v\n", report.cause) + _, _ = common.Dim.Println(" Falling back to file save") + } + switch report.Method { + case "activate": + if !report.Delivered { + _, _ = common.Yellow.Printf(" Could not activate: %v\n", report.cause) + return + } + _, _ = common.Green.Println("✓ API key activated — CLI is ready to use") + _, _ = common.Dim.Println(" Try: nylas auth status") + case "clipboard": + _, _ = common.Green.Printf("✓ %s copied to clipboard\n", label) + case "file": + _, _ = common.Green.Printf("✓ %s saved to: %s\n", label, report.File) + _, _ = common.Dim.Println(" Read it, then delete the file") + } +} diff --git a/internal/cli/dashboard/output_test.go b/internal/cli/dashboard/output_test.go new file mode 100644 index 0000000..b4b77ae --- /dev/null +++ b/internal/cli/dashboard/output_test.go @@ -0,0 +1,237 @@ +package dashboard + +import ( + "bytes" + "context" + "encoding/json" + "os" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dashboardapp "github.com/nylas/cli/internal/app/dashboard" + "github.com/nylas/cli/internal/domain" + "github.com/nylas/cli/internal/ports" +) + +// The structured reports exist so an agent can drive the dashboard commands. +// An agent's stdout lands in its transcript, so the property these tests +// guard above all is that a secret never reaches stdout in any format. + +const testSecret = "nyk_v0_THIS-MUST-NEVER-BE-PRINTED" + +func structuredCmd(t *testing.T, flag string) (*cobra.Command, *bytes.Buffer) { + t.Helper() + // Secret files land in a directory the test removes, never the real temp dir. + t.Setenv("TMPDIR", t.TempDir()) + cmd := &cobra.Command{Use: "test"} + addTestOutputFlags(cmd) + var out bytes.Buffer + cmd.SetOut(&out) + if flag != "" { + require.NoError(t, cmd.Flags().Set(flag, "true")) + } + return cmd, &out +} + +func TestWriteAPIKeyCreated_ReportsWhereTheKeyWentAndNeverTheKey(t *testing.T) { + cmd, out := structuredCmd(t, "json") + key := &domain.GatewayCreatedAPIKey{ID: "key_1", Name: "agent key", APIKey: testSecret} + + require.NoError(t, writeAPIKeyCreated(cmd, key, "app_1", "us", "file")) + + assert.NotContains(t, out.String(), testSecret) + var report map[string]any + require.NoError(t, json.Unmarshal(out.Bytes(), &report)) + assert.Equal(t, "key_1", report["id"]) + assert.Equal(t, "agent key", report["name"]) + assert.Equal(t, "app_1", report["application_id"]) + assert.Equal(t, "us", report["region"]) + + delivery := report["delivery"].(map[string]any) + assert.Equal(t, "file", delivery["method"]) + assert.Equal(t, true, delivery["delivered"]) + path, _ := delivery["file"].(string) + + // The key is where the report says, and readable only by its owner. + contents, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, testSecret+"\n", string(contents)) + info, err := os.Stat(path) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + +func TestWriteAPIKeyCreated_QuietPrintsOnlyTheKeyID(t *testing.T) { + cmd, out := structuredCmd(t, "quiet") + key := &domain.GatewayCreatedAPIKey{ID: "key_1", Name: "agent key", APIKey: testSecret} + + require.NoError(t, writeAPIKeyCreated(cmd, key, "app_1", "us", "file")) + + assert.Equal(t, "key_1\n", out.String()) +} + +func TestWriteAPIKeyCreated_YAMLNeverCarriesTheKey(t *testing.T) { + cmd, out := structuredCmd(t, "") + require.NoError(t, cmd.Flags().Set("format", "yaml")) + key := &domain.GatewayCreatedAPIKey{ID: "key_1", Name: "agent key", APIKey: testSecret} + + require.NoError(t, writeAPIKeyCreated(cmd, key, "app_1", "us", "file")) + + assert.NotContains(t, out.String(), testSecret) + assert.Contains(t, out.String(), "id: key_1") + assert.Contains(t, out.String(), "method: file") +} + +func TestWriteAppCreated_ReportsTheClientSecretDeliveryAndNeverTheSecret(t *testing.T) { + cmd, out := structuredCmd(t, "json") + app := &domain.GatewayCreatedApplication{ + ApplicationID: "app_1", + Region: "eu", + Environment: "sandbox", + ClientSecret: testSecret, + } + + require.NoError(t, writeAppCreated(cmd, app, "file")) + + assert.NotContains(t, out.String(), testSecret) + var report appCreatedReport + require.NoError(t, json.Unmarshal(out.Bytes(), &report)) + assert.Equal(t, "app_1", report.ApplicationID) + assert.Equal(t, "eu", report.Region) + assert.Equal(t, "sandbox", report.Environment) + require.NotNil(t, report.ClientSecret) + assert.Equal(t, "file", report.ClientSecret.Method) + assert.True(t, report.ClientSecret.Delivered) +} + +func TestWriteAppCreated_WithoutAClientSecretSaysNothingAboutOne(t *testing.T) { + cmd, out := structuredCmd(t, "json") + app := &domain.GatewayCreatedApplication{ApplicationID: "app_1", Region: "us"} + + require.NoError(t, writeAppCreated(cmd, app, "file")) + + assert.JSONEq(t, `{"application_id":"app_1","region":"us"}`, out.String()) +} + +func TestDeliverAPIKey_RejectsAnUnknownMethodWithoutTouchingTheKey(t *testing.T) { + _, err := deliverAPIKey(testSecret, "app_1", "us", "print") + + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid API key delivery method") + assert.NotContains(t, err.Error(), testSecret) +} + +func TestDeliverClientSecret_RefusesActivate(t *testing.T) { + // A client secret is not an API key: it cannot configure the CLI. + _, err := deliverClientSecret(testSecret, "activate") + + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid secret delivery method") +} + +func TestStructuredRunsNeverPrompt(t *testing.T) { + // A prompt in a structured run would write into the stream being parsed, + // and in an agent's shell it would hang until the call times out. So each + // command that would prompt refuses instead, before calling any service. + tests := []struct { + name string + cmd func() *cobra.Command + args []string + want string + }{ + { + name: "apps use without an application", + cmd: newAppsUseCmd, + args: []string{"--json"}, + want: "application selection requires an interactive terminal", + }, + { + name: "apps create without a secret delivery", + cmd: newAppsCreateCmd, + args: []string{"--json", "--name", "agent app", "--region", "us"}, + want: "client secret delivery requires an explicit choice", + }, + { + name: "apikeys create without a delivery", + cmd: newAPIKeysCreateCmd, + args: []string{"--json", "--app", "app_1", "--region", "us"}, + want: "API key delivery requires an explicit choice", + }, + } + // Stand in a terminal: without --json each of these would prompt, so + // --json has to be what refuses. + orig := isInteractive + isInteractive = func() bool { return true } + t.Cleanup(func() { isInteractive = orig }) + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := tt.cmd() + addTestOutputFlags(cmd) + + out, err := executeTestCommand(cmd, tt.args...) + + require.Error(t, err) + assert.Contains(t, err.Error(), tt.want) + assert.NotContains(t, out, "{") + }) + } +} + +func TestNewStatusReport_CarriesWhatTheTextFormShows(t *testing.T) { + secrets := newMemSecretStore() + require.NoError(t, secrets.Set(ports.KeyDashboardAppID, "app_1")) + require.NoError(t, secrets.Set(ports.KeyDashboardAppRegion, "eu")) + session := &domain.DashboardSessionResponse{ + User: domain.DashboardUser{PublicID: "user_from_session"}, + CurrentOrg: "org_2", + Relations: []domain.DashboardSessionRelation{ + {OrgPublicID: "org_1", OrgName: "First"}, + {OrgPublicID: "org_2", OrgName: "Second"}, + }, + } + status := dashboardapp.Status{LoggedIn: true, OrgID: "org_1", HasOrgToken: true} + + report := newStatusReport(status, session, secrets, "thumb") + + assert.Equal(t, statusReport{ + LoggedIn: true, + UserID: "user_from_session", + OrganizationID: "org_2", + OrganizationName: "Second", + OrganizationCount: 2, + HasOrgToken: true, + ActiveApp: &activeAppReport{ApplicationID: "app_1", Region: "eu"}, + DPoPThumbprint: "thumb", + }, report) +} + +func TestStatusReport_SignedOutIsAnExplicitFalse(t *testing.T) { + // An agent reads logged_in to decide whether to sign in, so a signed-out + // report must say false rather than leave the field out. + b, err := json.Marshal(statusReport{}) + + require.NoError(t, err) + assert.JSONEq(t, `{"logged_in":false,"has_org_token":false}`, string(b)) +} + +func TestCaptureReloginOrg_ReportsTheOrganizationTheSignInChose(t *testing.T) { + calls := 0 + chosen, relogin := captureReloginOrg(reloginTo("org_9", &calls)) + + err := switchOAuthSessionOrg(context.Background(), &bytes.Buffer{}, "", relogin) + + require.NoError(t, err) + assert.Equal(t, 1, calls) + assert.Equal(t, "org_9", *chosen) +} + +func TestCaptureReloginOrg_KeepsAMissingReloginMissing(t *testing.T) { + chosen, relogin := captureReloginOrg(nil) + + assert.Nil(t, relogin) + assert.Empty(t, *chosen) +} diff --git a/internal/cli/dashboard/status.go b/internal/cli/dashboard/status.go index 9e17d47..2034bdd 100644 --- a/internal/cli/dashboard/status.go +++ b/internal/cli/dashboard/status.go @@ -5,7 +5,9 @@ import ( "github.com/spf13/cobra" + dashboardapp "github.com/nylas/cli/internal/app/dashboard" "github.com/nylas/cli/internal/cli/common" + "github.com/nylas/cli/internal/domain" "github.com/nylas/cli/internal/ports" ) @@ -21,7 +23,11 @@ func newStatusCmd() *cobra.Command { status := authSvc.GetStatus() + structured := structuredOutput(cmd) if !status.LoggedIn { + if structured { + return common.GetOutputWriter(cmd).Write(statusReport{}) + } _, _ = common.Yellow.Println("Not logged in") fmt.Println(" nylas dashboard login") return nil @@ -34,6 +40,14 @@ func newStatusCmd() *cobra.Command { return wrapDashboardError(err) } + if structured { + thumbprint := "" + if dpopSvc, _, err := createDPoPService(); err == nil { + thumbprint = dpopSvc.Thumbprint() + } + return common.GetOutputWriter(cmd).Write(newStatusReport(status, session, secrets, thumbprint)) + } + orgLabel := status.OrgID if session.CurrentOrg != "" { orgLabel = session.CurrentOrg @@ -84,3 +98,39 @@ func presentAbsent(present bool) string { } return "absent" } + +// newStatusReport collects what the text form prints into a statusReport. +func newStatusReport( + status dashboardapp.Status, + session *domain.DashboardSessionResponse, + secrets ports.SecretStore, + dpopThumbprint string, +) statusReport { + report := statusReport{ + LoggedIn: true, + UserID: status.UserID, + OrganizationID: status.OrgID, + OrganizationCount: len(session.Relations), + HasOrgToken: status.HasOrgToken, + DPoPThumbprint: dpopThumbprint, + } + if report.UserID == "" { + report.UserID = session.User.PublicID + } + if session.CurrentOrg != "" { + report.OrganizationID = session.CurrentOrg + for _, rel := range session.Relations { + if rel.OrgPublicID == session.CurrentOrg { + report.OrganizationName = rel.OrgName + break + } + } + } + + appID, _ := secrets.Get(ports.KeyDashboardAppID) + appRegion, _ := secrets.Get(ports.KeyDashboardAppRegion) + if appID != "" { + report.ActiveApp = &activeAppReport{ApplicationID: appID, Region: appRegion} + } + return report +} diff --git a/internal/cli/dashboard/switch_org.go b/internal/cli/dashboard/switch_org.go index bffd17d..2f13cae 100644 --- a/internal/cli/dashboard/switch_org.go +++ b/internal/cli/dashboard/switch_org.go @@ -40,12 +40,21 @@ organization there. --org then checks that the one chosen is the one named.`, if err != nil { return wrapDashboardError(err) } + structured := structuredOutput(cmd) if fromOAuth { ctx, cancel := common.CreateLongContext() defer cancel() - return switchOAuthSessionOrg(ctx, cmd.OutOrStdout(), orgFlag, OAuthRelogin) + if !structured { + return switchOAuthSessionOrg(ctx, cmd.OutOrStdout(), orgFlag, OAuthRelogin) + } + // The progress lines go to stderr so stdout is only the report. + chosen, relogin := captureReloginOrg(OAuthRelogin) + if err := switchOAuthSessionOrg(ctx, cmd.ErrOrStderr(), orgFlag, relogin); err != nil { + return err + } + return common.GetOutputWriter(cmd).Write(orgSwitchReport{OrganizationID: *chosen, Switched: true}) } - if orgFlag == "" && !isInteractive() { + if orgFlag == "" && (structured || !isInteractive()) { return dashboardError( "organization selection requires an interactive terminal", "Pass --org to choose the organization in non-interactive runs", @@ -66,6 +75,9 @@ organization there. --org then checks that the one chosen is the one named.`, } if len(session.Relations) == 0 { + if structured { + return dashboardError("no organizations found", "Run 'nylas dashboard orgs list' to check your memberships") + } fmt.Println("No organizations found.") return nil } @@ -79,6 +91,12 @@ organization there. --org then checks that the one chosen is the one named.`, } if targetOrgID == session.CurrentOrg { + if structured { + return common.GetOutputWriter(cmd).Write(orgSwitchReport{ + OrganizationID: targetOrgID, + OrganizationName: sessionOrgName(session, targetOrgID), + }) + } _, _ = common.Green.Printf("✓ Already on organization: %s\n", formatSessionOrg(session, session.CurrentOrg)) return nil } @@ -96,6 +114,13 @@ organization there. --org then checks that the one chosen is the one named.`, return wrapDashboardError(err) } + if structured { + return common.GetOutputWriter(cmd).Write(orgSwitchReport{ + OrganizationID: resp.Org.PublicID, + OrganizationName: resp.Org.Name, + Switched: true, + }) + } _, _ = common.Green.Printf("✓ Switched to organization: %s\n", formatOrgLabel(resp.Org.PublicID, resp.Org.Name)) return nil }, @@ -143,6 +168,35 @@ func switchOAuthSessionOrg( return nil } +// captureReloginOrg wraps relogin so the caller learns which organization the +// new sign-in chose. A nil relogin stays nil: switchOAuthSessionOrg reports +// that case itself. +func captureReloginOrg( + relogin func(context.Context) (*domain.DashboardOAuthExchangeResponse, error), +) (*string, func(context.Context) (*domain.DashboardOAuthExchangeResponse, error)) { + chosen := new(string) + if relogin == nil { + return chosen, nil + } + return chosen, func(ctx context.Context) (*domain.DashboardOAuthExchangeResponse, error) { + resp, err := relogin(ctx) + if resp != nil { + *chosen = resp.OrgPublicID + } + return resp, err + } +} + +// sessionOrgName returns an organization's name from the session's relations. +func sessionOrgName(session *domain.DashboardSessionResponse, orgPublicID string) string { + for _, rel := range session.Relations { + if rel.OrgPublicID == orgPublicID { + return rel.OrgName + } + } + return "" +} + // selectOrgFromSession prompts the user to select an org from the session's relations. func selectOrgFromSession(session *domain.DashboardSessionResponse) (string, error) { opts := make([]common.SelectOption[string], 0, len(session.Relations))