switch-profile 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,163 +1,246 @@
1
1
  # switch-profile
2
2
 
3
- An interactive CLI tool for switching between AWS profiles directly from your terminal. No more manually editing `~/.aws/credentials` or juggling environment variables.
3
+ Switch between AWS profiles from your terminal. Type a few letters, press enter, and every AWS tool uses that account. SSO logins work on remote machines too (device code, clipboard over SSH, QR code), and each terminal can stay on its own account.
4
+
5
+ ```
6
+ ┌ switch-profile 2.0.0
7
+ │
8
+ │ ● acme-prod · Admin · 111111111111 · ap-southeast-2 · PROD · SSO ✓ auto-refresh · logged in 3h ago
9
+ │
10
+ ◆ Switch to · type a name, account, role or client
11
+ │ Search: dev▌
12
+ │ ● acme-dev Admin 222222222222 ap-southeast-2 (used 2d ago)
13
+ │ ○ globex-dev ReadOnly 333333333333 us-east-1
14
+ │ ○ initech-dev Admin 444444444444 eu-west-1
15
+ └
16
+ ```
17
+
18
+ - **Fast picker.** Fuzzy search across profile name, account id, account name, role, SSO session (client) and region. The profiles you use most come first.
19
+ - **One identity check per switch.** `switch-profile` calls `aws sts get-caller-identity` once, logs in if needed, then makes the profile the default.
20
+ - **Auto-refresh.** It writes the profile's *settings* into `[default]`, never temporary credentials, so the AWS CLI, SDKs and Terraform refresh credentials on their own.
21
+ - **Per-terminal.** With the `sp` shortcut, the current terminal also gets `AWS_PROFILE`, so different terminals can use different accounts. `sp` also adds tab-completion.
22
+ - **Remote-friendly.** Over SSH, logins use a device code: the code is copied to your laptop's clipboard and the URL can be shown as a QR code.
23
+ - **Import a whole portal.** `sp add` creates one profile per account and role of an IAM Identity Center portal.
24
+ - **Script and agent friendly.** Never prompts when there is no terminal, `--json` output, stable exit codes.
25
+
26
+ ## Table of Contents
27
+
28
+ <!-- BEGIN toc -->
29
+ - [Quick start](#quick-start)
30
+ - [Commands](#commands)
31
+ - [Working on remote machines (SSH)](#working-on-remote-machines-ssh)
32
+ - [Importing a client's accounts](#importing-a-clients-accounts)
33
+ - [Scripts and AI agents](#scripts-and-ai-agents)
34
+ - [Settings](#settings)
35
+ - [The `sp` shortcut](#the-sp-shortcut)
36
+ - [Upgrading from 1.x](#upgrading-from-1x)
37
+ - [Requirements](#requirements)
38
+ - [Troubleshooting](#troubleshooting)
39
+ - [`invalid_grant` during an SSO login](#invalid_grant-during-an-sso-login)
40
+ - [`Error loading SSO Token` or "session has expired"](#error-loading-sso-token-or-session-has-expired)
41
+ - [SSO login hangs on a remote machine](#sso-login-hangs-on-a-remote-machine)
42
+ - [The code is not in my clipboard over SSH](#the-code-is-not-in-my-clipboard-over-ssh)
43
+ - [`sp: command not found`](#sp-command-not-found)
44
+ - [Tab-completion does not work in zsh](#tab-completion-does-not-work-in-zsh)
45
+ - [Commands still use the wrong account](#commands-still-use-the-wrong-account)
46
+ - [AWS CLI not found](#aws-cli-not-found)
47
+ - [Documentation](#documentation)
48
+ - [License](#license)
49
+ <!-- END toc -->
50
+
51
+ ## Quick start
4
52
 
5
53
  ```shell
6
54
  npx switch-profile
7
55
  ```
8
56
 
9
- ## Why?
57
+ On the first switch, `switch-profile` offers to set up the `sp` shortcut (a small function in your shell startup file). Say yes, open a new terminal, and from then on:
10
58
 
11
- AWS SSO credentials expire every hour. Without `switch-profile`, refreshing them means either:
59
+ ```shell
60
+ sp # pick a profile
61
+ sp acme-prod # switch straight to a profile
62
+ sp acme prod # fuzzy match: switches if exactly one profile matches
63
+ ```
64
+
65
+ For speed, install it globally. `npx` checks the npm registry on every run, which adds a noticeable delay; `sp` uses the global command when it exists and falls back to `npx` otherwise.
66
+
67
+ ```shell
68
+ npm install -g switch-profile
69
+ ```
12
70
 
13
- 1. **Manual copy-paste** - Browse to the SSO portal, log in, reveal credentials, paste them into your terminal or `~/.aws/credentials` file. Repeat every hour.
14
- 2. **Per-command `--profile` flag** - Use `aws sso login --profile <name>`, but then every command (and every tool like Terraform) needs `--profile`. Not always possible or practical.
71
+ No profiles yet? `switch-profile` starts the **Add profiles** flow. To import every account of your company's or client's SSO portal, see [Importing a client's accounts](#importing-a-clients-accounts).
15
72
 
16
- `switch-profile` makes setting any AWS profile as `default` trivial - one command, pick from a list, done. It handles SSO session refresh automatically, including opening the browser for re-authentication when sessions expire.
73
+ ## Commands
17
74
 
18
- ## Prerequisites
75
+ | Command | What it does |
76
+ |---------|--------------|
77
+ | `switch-profile [profile...]` | Opens the picker. With words: an exact name or a unique fuzzy match switches directly; otherwise the picker opens pre-filtered (or exits 3 when non-interactive). |
78
+ | `use <profile>` | Switches to a profile by its exact name (no fuzzy matching). |
79
+ | `status [--json]` | Shows the default profile, its login state, and what this terminal uses. |
80
+ | `login [profile] [--device\|--browser]` | Starts a fresh login now, even if the session is still valid. Defaults to this terminal's `AWS_PROFILE`, then the default profile. |
81
+ | `logout [--yes]` | Ends every SSO session on this machine (`aws sso logout`, plus `aws logout --all` on AWS CLI 2.32+). |
82
+ | `add` | Adds profiles: import accounts from an SSO portal (recommended), a single SSO profile, a console sign-in profile, or access keys. |
83
+ | `add --from-sso [session]` | Imports or re-syncs every account and role of an `[sso-session]`. Options: `--region`, `--prefix`, `--prune`, `--yes`. |
84
+ | `remove [profiles...] [--yes]` | Removes profiles (alias `rm`). The current default cannot be removed. |
85
+ | `settings` | Per-terminal switching, SSO login mode, legacy SSO upgrade. |
19
86
 
20
- - **[AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)** - Version 2 or later is required.
21
- - **Node.js** - Any recent version that supports `npx`.
87
+ Global options: `--json`, `--no-input` (never prompt), `--debug` (show stack traces), `-v, --version`. In examples, `sp` and `switch-profile` are interchangeable; only `sp` changes the current terminal.
22
88
 
23
- > **Important:** Remove these environment variables from your shell if they are set, as they override the default profile and will conflict with `switch-profile`:
24
- > - `AWS_ACCESS_KEY_ID`
25
- > - `AWS_SECRET_ACCESS_KEY`
26
- > - `AWS_SESSION_TOKEN`
89
+ See [CLI Interface](docs/cli-interface.md) for every screen.
27
90
 
28
- ## Installation
91
+ ## Working on remote machines (SSH)
29
92
 
30
- No installation needed. Run directly with npx:
93
+ Since AWS CLI 2.22, `aws sso login` opens a browser on the machine running the CLI. Over SSH there is none, so the login hangs. `switch-profile` detects remote sessions (`SSH_CONNECTION`, `SSH_CLIENT` or `SSH_TTY` set, or Linux without `DISPLAY`/`WAYLAND_DISPLAY`) and uses a device code instead:
31
94
 
32
- ```shell
33
- npx switch-profile
34
95
  ```
96
+ ◇ Approve the login for acme
35
97
 
36
- Or install globally:
98
+ Open https://device.sso.us-east-1.amazonaws.com/?user_code=WXYZ-ABCD
99
+ Code WXYZ-ABCD 📋 sent to your clipboard
37
100
 
38
- ```shell
39
- npm install -g switch-profile
40
- switch-profile
101
+ 🔒 Only approve if the page shows exactly this code.
102
+ q QR code · c copy again · ctrl+c cancel
103
+ ◒ Waiting for approval 0:12
41
104
  ```
42
105
 
43
- ## Quick Start
106
+ - **Clipboard over SSH.** The code is sent to your local clipboard with the OSC 52 terminal escape sequence. iTerm2, Ghostty, kitty, WezTerm and Windows Terminal support it; tmux needs `set -g set-clipboard on` (or `allow-passthrough on`). If your terminal ignores it, copy the code by hand.
107
+ - **QR code.** Press `q` to show the URL as a QR code and approve from your phone.
108
+ - **Log in any time.** `sp login` starts a fresh session now, for example before a long task. `--device` and `--browser` override the automatic choice; Settings can make either permanent.
109
+ - **Log out.** `sp logout` ends every SSO session on the machine, so a shared or rented server keeps no AWS access.
110
+
111
+ How often you log in is set by IAM Identity Center, not by `switch-profile`:
44
112
 
45
- ### Switch between existing profiles
113
+ - The **user interactive session** duration decides when you must log in again. The default is 8 hours, up to 90 days. Your administrator sets it once for the whole Identity Center instance (Settings > Authentication).
114
+ - The **permission set** session duration (1 to 12 hours) matters less: role credentials refresh automatically while the SSO session is valid, as long as the profile uses an `[sso-session]` (the format `switch-profile` writes).
115
+
116
+ ## Importing a client's accounts
46
117
 
47
118
  ```shell
48
- npx switch-profile
119
+ sp add # then choose "Accounts from an SSO portal"
49
120
  ```
50
121
 
51
- This will:
52
- 1. Show your current default profile with its expiry status.
53
- 2. List all available profiles.
54
- 3. Let you pick one to set as the new `default`.
55
- 4. Display an `export AWS_PROFILE=<name>` command you can run to lock that profile to your current terminal session.
122
+ 1. Pick an existing `[sso-session]` or create one: start URL (e.g. `https://acme.awsapps.com/start`), SSO region (where Identity Center lives, not where you deploy), and a short name, usually the client.
123
+ 2. Log in if needed.
124
+ 3. `switch-profile` lists every account and role you can access, then asks for a default region and a name prefix. Profiles are named `<prefix>-<account-name>-<role>`, for example `acme-prod-workloads-admin`.
125
+ 4. A preview shows the new profiles, the ones already set up, and the ones that no longer exist. Confirm to write them.
56
126
 
57
- For SSO profiles, if the session has expired, it automatically opens your browser for re-authentication.
127
+ Run it again later to pick up new accounts. Account/role pairs that already have a profile are never duplicated, whatever its name. Generated profiles that no longer exist can be pruned (after a backup); profiles you wrote by hand are never pruned.
58
128
 
59
- ### Create a new profile
129
+ Non-interactive (after `aws sso login --sso-session acme` or `sp login`):
60
130
 
61
131
  ```shell
62
- npx switch-profile
63
- # Select "More options" > "Create profile"
132
+ switch-profile add --from-sso acme --region eu-west-1 --prefix acme --yes --json
64
133
  ```
65
134
 
66
- You can create:
67
- - **Standard profiles** - Access key + secret key pair.
68
- - **SSO profiles** - Launches the interactive `aws configure sso` flow.
135
+ ## Scripts and AI agents
136
+
137
+ `switch-profile` never prompts when stdin or stdout is not a terminal, when `CI` is set, or with `--no-input`. It fails with a hint and an exit code instead.
138
+
139
+ | Exit code | Meaning |
140
+ |-----------|---------|
141
+ | 0 | OK |
142
+ | 1 | Error |
143
+ | 2 | Login required (run `switch-profile login <profile>` in a terminal) |
144
+ | 3 | Bad input: unknown or ambiguous profile, missing argument or `--yes` |
145
+ | 130 | Cancelled |
69
146
 
70
- ### Delete profiles
147
+ - `--json` prints machine-readable results on stdout. Expected errors are printed as JSON on stderr: `{"error": "...", "hint": "...", "code": 3}`.
148
+ - `switch-profile status --json` lists every profile with its kind, account, role, region and whether it is production.
149
+ - Non-interactive logins still work: `switch-profile login acme-dev --device` prints the AWS CLI's URL and code on stderr and waits for approval.
150
+ - A shell tool's environment does not survive between commands, so `sp` and `export AWS_PROFILE` do not help an agent. Prefix each AWS command instead:
71
151
 
72
152
  ```shell
73
- npx switch-profile
74
- # Select "More options" > "Delete profiles"
153
+ AWS_PROFILE=acme-dev aws s3 ls
154
+ AWS_PROFILE=acme-dev terraform plan
75
155
  ```
76
156
 
77
- Select one or more profiles to remove. The current default profile cannot be deleted (switch to another one first).
78
-
79
- ### Refresh an expired profile
157
+ ## Settings
80
158
 
81
159
  ```shell
82
- npx switch-profile
83
- # Select "More options" > "Refresh default profile"
160
+ sp settings
84
161
  ```
85
162
 
86
- This option only appears when the current default profile has expired. It forces a new SSO login and refreshes the credentials.
163
+ - **Per-terminal switching**: turns the `sp` shortcut (and tab-completion) on or off.
164
+ - **SSO login**: `auto` (device code over SSH, browser otherwise), always device code, or always browser.
165
+ - **Legacy SSO profiles**: upgrades SSO profiles that have no `[sso-session]` (no auto-refresh).
166
+
167
+ The tool's own state lives in `~/.switch-profile/settings.json`. See [Configuration Files](docs/configuration-files.md).
87
168
 
88
- ## How It Works
169
+ ### The `sp` shortcut
89
170
 
90
- `switch-profile` manages two AWS configuration files:
171
+ `sp` is a shell function added to your startup file inside a `# >>> switch-profile ... >>>` block. It runs `switch-profile`, then sets `AWS_PROFILE` in the current terminal and clears `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` and `AWS_DEFAULT_PROFILE`, which would otherwise override the profile. It also completes profile names and subcommands with Tab. Do not edit the block: `switch-profile` rewrites it when a new version changes it.
91
172
 
92
- | File | Purpose |
93
- |------|---------|
94
- | `~/.aws/config` | Stores profile settings (region, output format, SSO metadata) |
95
- | `~/.aws/credentials` | Stores access keys, secret keys, and session tokens |
173
+ | Shell | Startup file |
174
+ |-------|--------------|
175
+ | zsh | `${ZDOTDIR:-~}/.zshrc` |
176
+ | bash | `~/.bashrc` (Linux), `~/.bash_profile` (macOS) |
177
+ | fish | `~/.config/fish/config.fish` |
178
+ | PowerShell | `$PROFILE.CurrentUserAllHosts` (for `pwsh` and/or Windows PowerShell) |
96
179
 
97
- When you select a profile, `switch-profile`:
98
- 1. Retrieves the credentials for that profile (from cache or via SSO login).
99
- 2. Writes them into the `[default]` section of both files.
100
- 3. Records the profile name and expiry date for status display.
101
- 4. Shows an `export AWS_PROFILE=<name>` command to optionally lock the profile to your terminal session.
180
+ ## Upgrading from 1.x
102
181
 
103
- ### Per-terminal profile isolation
182
+ Version 1.x copied temporary credentials into `[default]` of `~/.aws/credentials`, which expired after about an hour. Version 2 upgrades your setup automatically on its first run:
104
183
 
105
- By default, switching profiles updates the global `[default]` section, which affects all terminals. If you need different AWS profiles in different terminals simultaneously, copy and run the command shown after each switch (`export AWS_PROFILE=<name>` on Linux/macOS, or the PowerShell/CMD equivalent on Windows). This sets an environment variable scoped to that terminal only, so other terminals remain unaffected.
184
+ - `~/.aws/config` and `~/.aws/credentials` are backed up next to themselves (e.g. `~/.aws/config.bak-2026-10-01T10-12-00Z`).
185
+ - `[default]` is rewritten with the settings of the profile you last selected, and the 1.x `profile` and `expiry_date` keys are removed.
186
+ - If some SSO profiles use the legacy format (no `sso_session`), you are asked once whether to upgrade them. Profiles of the same portal share one session, so one login covers them all.
106
187
 
107
- For SSO profiles specifically, it leverages two additional AWS CLI cache directories:
108
- - `~/.aws/sso/cache/` - SSO session tokens (long-lived, ~24 hours)
109
- - `~/.aws/cli/cache/` - Temporary AWS credentials (short-lived, ~1 hour)
188
+ The old `switch-profile switch` command still works. If you run 1.x again later (e.g. `npx switch-profile@1`), the next 2.x run repairs `[default]` (with backups).
110
189
 
111
- ## Detailed Documentation
190
+ ## Requirements
112
191
 
113
- For deeper technical details, see the docs below:
192
+ - **Node.js 20.12 or later.** Older versions get a clear message.
193
+ - **[AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).** 2.22 or later is recommended (choice between device code and browser login); console sign-in (`aws login`) needs 2.32+.
194
+ - **macOS and Linux** are first-class (zsh, bash, fish). **Windows PowerShell** is supported. **CMD** is limited: no `sp`, so run the `set AWS_PROFILE=<name>` command shown after each switch.
114
195
 
115
- | Document | Description |
116
- |----------|-------------|
117
- | [Architecture](docs/architecture.md) | Project structure, source files, and how the components fit together |
118
- | [AWS Profile Management](docs/aws-profile-management.md) | How AWS profiles, SSO sessions, and credentials are managed internally |
119
- | [CLI Interface](docs/cli-interface.md) | Detailed walkthrough of every menu, prompt, and user flow |
120
- | [Configuration Files](docs/configuration-files.md) | Exact formats of all AWS and internal configuration files |
121
- | [Development Guide](docs/development-guide.md) | How to set up, develop, test, lint, and release |
122
- | [Gotchas](docs/gotchas.md) | Critical pitfalls — global profile switching, per-terminal isolation limits, and LLM agent constraints |
196
+ The published package has no runtime dependencies: everything is bundled into one file.
123
197
 
124
198
  ## Troubleshooting
125
199
 
126
- ### `invalid_grant: Invalid grant provided`
200
+ ### `invalid_grant` during an SSO login
201
+
202
+ The SSO region is wrong. It must be the region of your IAM Identity Center instance, not the region you deploy to. Fix `sso_region` in the `[sso-session]` section of `~/.aws/config` (or remove the portal and add it again).
203
+
204
+ ### `Error loading SSO Token` or "session has expired"
127
205
 
128
- This error occurs during SSO profile creation when the **wrong SSO region** is specified. AWS SSO is region-specific - you must use the region where your SSO instance is configured, not the region you want to deploy resources to.
206
+ The SSO login is missing or expired. Run `sp login` (or just switch to the profile again: `switch-profile` logs in when needed). There is no need to recreate the profile.
129
207
 
130
- **Fix:** Delete the profile and recreate it with the correct SSO region.
208
+ ### SSO login hangs on a remote machine
131
209
 
132
- ### `Error: Fail to get credentials for profile ... Error loading SSO Token...`
210
+ The AWS CLI is waiting for a browser on the remote machine. Run `sp login --device`, or set **Settings > SSO login** to always use a device code.
133
211
 
134
- This typically happens after the `~/.aws/sso/cache` folder has been deleted or corrupted. This folder tracks SSO sessions and cannot be reconstructed automatically.
212
+ ### The code is not in my clipboard over SSH
135
213
 
136
- **Fix:** Delete the affected SSO profiles and recreate them:
214
+ Your terminal does not accept OSC 52, or tmux blocks it. In tmux, add `set -g set-clipboard on` to `~/.tmux.conf`. Otherwise copy the code from the screen (press `c` to try again).
137
215
 
138
- 1. Run `npx switch-profile`
139
- 2. Select **More options** > **Delete profiles**
140
- 3. Remove the broken SSO profiles
141
- 4. Recreate them via **More options** > **Create profile**
216
+ ### `sp: command not found`
217
+
218
+ The terminal was opened before `sp` was set up. Open a new terminal or run `source ~/.zshrc` (or your shell's equivalent). `sp settings` shows whether it is on.
219
+
220
+ ### Tab-completion does not work in zsh
221
+
222
+ The completion registers only if `compinit` ran before the `switch-profile` block. Move the block below `compinit` (or below the line that loads oh-my-zsh) in `~/.zshrc`.
223
+
224
+ ### Commands still use the wrong account
225
+
226
+ `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` in the environment override every profile, and `AWS_REGION` overrides the profile's region. The picker warns about them; switching with `sp` clears the credential variables (not the region).
142
227
 
143
228
  ### AWS CLI not found
144
229
 
145
- `switch-profile` requires AWS CLI v2. Install it for your platform:
230
+ **macOS:** `brew install awscli`
146
231
 
147
- **macOS:**
148
- ```shell
149
- brew install awscli
150
- brew link --overwrite awscli
151
- ```
232
+ **Linux and Windows:** follow the [AWS CLI install guide](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
152
233
 
153
- **Linux:**
154
- ```shell
155
- curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
156
- unzip awscliv2.zip
157
- sudo ./aws/install
158
- ```
234
+ ## Documentation
159
235
 
160
- **Windows:** Download and run the [AWS CLI MSI installer](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
236
+ <!-- BEGIN doc-index -->
237
+ - [Architecture](docs/architecture.md) — Module map, data flow and bundling of the switch-profile CLI.
238
+ - [AWS Profile Management](docs/aws-profile-management.md) — Profile kinds, switching, SSO logins, SSO import, migrations and the sp shell function.
239
+ - [CLI Interface](docs/cli-interface.md) — Walkthrough of every command and screen of the CLI.
240
+ - [Configuration Files](docs/configuration-files.md) — Exact formats of the AWS files, the settings file and the shell block written by switch-profile.
241
+ - [Development Guide](docs/development-guide.md) — Build, lint, tests, manual testing and releases.
242
+ - [Gotchas](docs/gotchas.md) — Non-obvious pitfalls for users and maintainers.
243
+ <!-- END doc-index -->
161
244
 
162
245
  ## License
163
246