Identity and local trust
Store a local secret in Keychain
Use macOS Keychain for a developer secret while keeping retrieval narrow and preventing accidental command output.
10 minute lesson
Keychain stores passwords, keys, and certificates behind macOS access controls: encrypted at rest, unlocked with your login, with per-item prompts when an unfamiliar process asks. It is a better home for a local credential than .zshrc or a committed configuration file, because nothing inherits it and no dotfiles repository can accidentally publish it.
The command-line interface is the security tool.
Store a secret
Add a generic password item:
security add-generic-password -a "$USER" -s dev.example.token -w
# password data for new item: ********
# retype password for new item: ********
-a sets the account, -s sets the service name — the label you will query by. Leaving -w bare makes security prompt for the value interactively. That is deliberate: typing the token after -w on the command line would land it in your shell history, which defeats the purpose.
Give the item a specific service name. dev.example.token says which system it belongs to; a generic name like token guarantees confusion once you have five of them.
Retrieve it exactly when needed
A script can request one named value when it needs it:
security find-generic-password -a "$USER" -s dev.example.token -w
The -w flag prints only the secret value, so command substitution stays clean:
export EXAMPLE_TOKEN="$(security find-generic-password -a "$USER" -s dev.example.token -w)"
Run that line inside the script that needs the token, at the moment it needs it — not in .zprofile. Retrieval at use time keeps the secret out of every unrelated process, which is the “narrow” part of this lesson’s promise.
The output leak
The realistic failure is not theft, it’s echo. Run a script with zsh -x for debugging and every expanded command — token included — lands in the trace. Do not run the retrieval command in shared logs or tracing mode, and review captured output before pasting it anywhere.
Two closing pieces of hygiene. Document how to recreate the item: the service name, the account, and where the value comes from, so a new Mac is a five-minute task. And keep a separate account-recovery path — the Keychain copy is a convenience, not the only copy of your ability to log in.
Lesson completed