Skip to content
项目

关于

Install all your applications and configure everything the way you like it with one command

系统与基础设施

这些数字如何统计

实测星标增长

24小时
0
7天
-1
15天
0
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

macbook-playbook

Install all your applications and configure everything the way you like it with one command.

TODO:

  • add brew to path when installing. (/opt/homebrew/bin)
  • add GitHub to known hosts: ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
  • unencrypt and add SSH key to ssh session
  • figure out Emacs symbolic link internal directory
  • make caps lock -> ESC remapping work
  • install insta360 link ap
  • wait 1s after install spotify and steam
  • GraalVM on apple silicon?
  • kubectl-krew isn’t available right after installing
  • launch BTT on startup, load configuration and license
  • symlink id_rsa to mpereira@pluto SSH key
  • turn on dictation

Table of Contents

Tested on

I’ve been using macbook-playbook since 2013. I’ve used it on at least eight MacBook Pros with different macOS versions. As of May 2023 I use it on my personal 16” 2023 Macbook Pro with Ventura installed and on my work 16” 2019 Macbook Pro with Monterey installed.

Please open an issue if you’re trying this out and bump into anything.

Bootstrap machine (make bootstrap)

These are one-time steps that need to be done on machines that are running macbook-playbook for the first time.

Install Developer Tools (xcode-select)

Open the “Terminal” application, type git into the shell and follow the instructions to install the Apple Developer Tools.

Clone repository

Now your machine should have git and python3 installed.

git clone https://github.com/mpereira/macbook-playbook.git

Give Terminal/iTerm2/Emacs/etc. assistive access

Depending on your macOS version you will be queried or not for assistive access while make provision runs. This is required for example to remap caps lock to control.

In case that task fails, or if you want to do it beforehand just in case, go to “System Preferences > Security & Privacy > Privacy > Accessibility” and add the application running macbook-playbook (Terminal/iTerm2/Emacs/etc.) to the list.

Secrets

This repository is public, so its secrets are kept encrypted with Ansible Vault in a private repository outside of it. Each make provision reads them from a checkout of that repository and decrypts the values it uses, so there’s no plaintext file of all the secrets on disk. Roles still write the files they install, such as an SSH key.

make provision finds them through ~/.config/macbook-playbook/secrets.mk, which holds paths and no secrets. It sets ANSIBLE_SECRETS_ARGS to the Ansible arguments that name the vault password script and the variable files:

ANSIBLE_SECRETS_ARGS := \
    --vault-password-file /path/to/private-repo/bin/ansible-vault-password \
    --extra-vars @/path/to/private-repo/vars.yml \
    --extra-vars @/path/to/private-repo/vault.yml

The vault password script calls touch-id-secret, so a run prompts for Touch ID at most once, when it starts, and only while the keychain is locked. Ansible runs the script even if no role in that run uses a secret. A run from an agent’s Bash sandbox fails while the keychain is locked.

The values are read from whatever that checkout has at that moment, including a branch.

The variable files have to define the names in the table below. A role reads each value as the vault holds it, so renaming a value in the private repository breaks the role that reads it.

These are the roles that use secrets:

DescriptionSecret nameRole
AWS CLI credentialsaws_credentials_fileawscli
B2 application keyb2_application_keympereira-backup
B2 application keyIDb2_application_key_idmpereira-backup
Environment variables for dotfilesdotfiles_environment_yml_filedotfiles
gmailctl OAuth clientgmailctl_credentials_json_filegmailctl
gmailctl OAuth tokengmailctl_token_json_filegmailctl
restic mac passwordrestic_mac_passwordmpereira-backup
restic offsite passwordrestic_offsite_passwordmpereira-backup
restic tankette passwordrestic_tankette_passwordmpereira-backup
s3cmd configurations3cmd_cfg_files3cmd

The ssh-keys role reads its private keys from ssh_keys, whose entries take them from vault variables of any name.

The private vars file also holds settings that aren’t secret but belong to one person, such as repository URLs and SSH public keys. The roles’ defaults leave these empty, and a role skips what has nothing set. A value there can refer to a vault variable, as in private_key: "{{ my_ssh_private_key }}". These are the settings:

SettingRole
agent_skills_extra_monoreposskills
claude_sandbox_extra_excluded_commandsclaude
claude_sandbox_extra_writable_pathsclaude
claude_user_instructionsclaude
dotemacs_repositorydotemacs
dotfiles_repositorydotfiles
dotfiles_install_commanddotfiles
ssh_keysssh-keys
mpereira_backup_configmpereira-backup
mpereira_backup_secret_filesmpereira-backup

Each role’s defaults/main.yml describes its settings’ format.

Without secrets.mk, make provision prints a warning and runs with no vault password script, and the first role that needs a secret fails. You have two choices: skip these roles, or write your own secrets.mk and variable files.

To skip them, when you reach the provision machine step, use the command below. It needs neither touch-id-secret nor the private repository. You don’t need to run this now, the command below is just an example.

make provision ARGS='--skip-tags uses-secrets'

With secrets.mk in place, every run calls the password script. To run without it, and so without a Touch ID prompt, clear the setting for that run:

make provision ANSIBLE_SECRETS_ARGS= ARGS='--skip-tags uses-secrets'

On a new Mac, do these steps in this order:

  1. Run make bootstrap.
  2. Install touch-id-secret, which needs no secrets. The warning about secrets.mk is expected here:
    make provision ARGS='--tags touch-id-secret'
        
  3. Clone the private repository. The SSH key in the vault isn’t available yet, so use other GitHub access for this.
  4. Store the vault password from its recovery copy with touch-id-secret put.
  5. Write secrets.mk.
  6. Run make provision.

Keep a recovery copy of the vault password away from this Mac and outside its backups. It decrypts the restic passwords, so without it the backups can’t be read.

Prepare machine to run the Ansible playbooks

This will:

  1. Set up Touch ID sudo with password fallback (macOS 14 or later)
  2. Install a user Python3
  3. Install Ansible
make bootstrap

Your machine should now be ready to be provisioned! You won’t need to run the above steps again.

Configure machine (make provision)

Now that the machine is bootstrapped, we can provision it.

Provision machine

This runs all non-disabled roles in =main.yml=.
make provision ARGS='--skip-tags disabled'

ansible-playbook arguments can be passed via the ARGS environment variable. For example, --tags can be passed so that only matching roles are run.

make provision ARGS='--tags google-chrome'

--skip-tags can also be passed to avoid running certain roles.

make provision ARGS='--skip-tags disabled,unity'

All role tags can be seen in =main.yml=.

Tasks may fail due to intermittent reasons like temporary server unavailability. When a task fails you can either disable its role via --skip-tags or use --start-at-task with the name value of some task to cause Ansible to start the playbook exactly there.

For example, if the “Install Emacs” task from the “build-emacs” role fails for what seems to be an intermittent issue, you can pick up provisioning from there so that previous tasks don’t have to re-run.

make provision ARGS='--skip-tags disabled --start-at-task "Install Emacs"'

Check the official Ansible documentation for more details.

Manual steps post make provision

These are steps that are currently not automated because:

  • it would be difficult
  • it would be impossible
  • or I just didn’t have the time

Change keyboard layout to U.S. international

  1. System Preferences -> Keyboard -> Input Sources
  2. Click +
  3. Select “English” on left column
  4. Select “U.S. International - PC” on right column
  5. Click “Add”
  6. Remove other keyboard layouts from the left column

iStat Menus

  1. Import license from roles/istat-menus/files/iStat Menus Settings.ismp

PDF Expert

  1. Register license

BetterTouchTool

  1. Register license

Terminal

Preferences > Profiles > Pro > Font

Set to Hack Regular 18 pt.

System Preferences > Security & Privacy > Privacy > Accessibility

  • BetterTouchTool.app
  • Emacs-*.app
  • MacGPT
  • RescueTime
  • Terminal
  • VLC
  • WhatsApp

System Preferences > Keyboard > Shortcuts > Mission Control

Uncheck:

  • Mission Control
  • Move left a space
  • Move right a space
  • Switch to desktop 1

I use these keybindings on Emacs.

Roles

Installs

Desktop Applications

Agent skills

Managed by the skills role. The canonical copy of every skill lives under ~/.agents/skills (which Codex reads natively) and is symlinked into ~/.claude/skills, the only directory where Claude Code finds personal skills. Everything else, such as the commands the skills run, uses the ~/.agents/skills paths. No ~/.codex/skills symlinks are created, since that would double-list each skill in Codex. Codex’s own .system and codex-primary-runtime directories are left untouched.

make provision updates git-backed skills; add a version: to an entry in the defaults to pin it. Locally-maintained skills are copied from roles/skills/files and updated with the playbook. Sources (configured in roles/skills/defaults/main.yml):

  • Humanizer (standalone repo)
  • asd-ste100 (maintained here in roles/skills/files/asd-ste100/SKILL.md, with links to ASD’s official standard)
  • brief, build, converge and review (maintained here in roles/skills/files). A cross-model review loop across Claude Code, Codex, and Antigravity (Gemini): /brief plans, /build implements, /review reviews existing work, and all three run review rounds through converge’s bin/agent-review (defaulting review models via ~/.agents/converge.json)
  • HumanLayer skills (show-me)
  • anthropics/skills (frontend-design)
  • vercel-labs/skills (find-skills)

The clickup skill is the exception: it is generated by the cup CLI itself (cup skill --print) and provisioned by the clickup-cli role, so it always matches the installed CLI version.

agent_skills_extra_monorepos adds more monorepos in the same format, from the private vars file described under “Secrets”. An “all: true” entry there can list projects: its skills are then linked only into each project’s .claude/skills, so Claude Code sees them only there and Codex doesn’t see them.

Invoke these skills in Codex with $asd-ste100 or $show-me, and in Claude Code with /asd-ste100 or /show-me. Our ASD-STE100 skill defaults to an “80% STE” style for readable technical explanations, with stricter wording when requested. It does not certify compliance with the official dictionary. Both skills allow automatic selection when relevant. Show-me’s auto_invoke: true setting creates a configured copy with automatic selection enabled for Codex and Claude Code, keeping the upstream Git checkout clean.

Local skills are supported in the ChatGPT desktop app. This role provisions the local Codex discovery path; it does not publish a plugin for ChatGPT web or mobile. See OpenAI’s skill documentation.

Claude chat and Cowork require a separate upload. Enable code execution in Settings > Capabilities, then upload each skill folder as a ZIP in Customize > Skills and enable it. Use the resolved skill folder, including supporting scripts and references, rather than archiving only its symlink. See Claude’s skill setup instructions.

Text Editors

Configuration

  • macOS defaults in configure.sh
  • Emacs configuration, cloned from dotemacs_repository to ~/.emacs.d
  • dotfiles, cloned from dotfiles_repository to ~/.dotfiles and installed with dotfiles_install_command

Biome’s user-level config is provisioned directly by this playbook at ~/Library/Application Support/biome/biome.json.

The claude role installs ~/.claude/CLAUDE.md, Claude Code’s instructions for all projects, from claude_user_instructions. Edit that variable, not the installed copy, which make provision overwrites. When it’s empty, the role leaves ~/.claude/CLAUDE.md alone.

The dotemacs and dotfiles roles do nothing until the private vars file described under “Secrets” sets their repository.

The restic role installs only restic. The mpereira-backup role installs mpereira-backup, which backs up the Mac and its drives with restic on a schedule (hourly, from one launchd agent), reminds you when a backup is too old, and copies files from cards and folders without losing any (ingest, copy-media). Its settings are mpereira_backup_config in the private vars file; without them the role installs only the command. It writes the restic repository passwords and the B2 application key from vars.yml into ~/.config/restic, readable only by you (mpereira_backup_secret_files). Full Disk Access goes to its small launcher, /usr/local/bin/mpereira-backup-launch. Its README describes the backup strategy, every setting and command, restores, and what the file reorganization of 2026 taught.

The spotlight role limits Spotlight results to apps and System Settings. It writes the switches that System Settings › Spotlight turns off to EnabledPreferenceRules in com.apple.Spotlight. The list is spotlight_hidden_results in roles/spotlight/defaults/main.yml. To change it, set the switches in System Settings, then copy the new list from defaults read com.apple.Spotlight EnabledPreferenceRules.

The emacs-as-default-text-editor role makes Finder open text files, Markdown, Org and source code with Emacs. It sets the default app with duti for each type in emacs_as_default_text_editor_file_types in roles/emacs-as-default-text-editor/defaults/main.yml. Files without an extension, such as Makefile, aren’t covered. To check a type, run duti -x md.

Claude local settings are ignored through .gitignore.

Programming Languages

Multimedia

Fonts

Browser Plugins

Virtualization, Provisioning, Containers and System Tools

Package Managers and Build Tools

Shell

Programming Utilities

Data Systems

  • Apache Hadoop (disabled by default, it conflicts with the yarn JavaScript package manager)

Configuration, Monitoring and Debugging

Document Processors and Plotting

Markup Tools

  • Grip
  • Hugo
  • Markdown
  • Mermaid CLI Installed with npm, as upstream no longer supports the Homebrew formula. The role also installs the Chrome Headless Shell build that its Puppeteer pins into ~/.cache/puppeteer, owned by the user. make provision ARGS‘–tags markdown-preview’= installs Node.js, Pandoc and Mermaid CLI for Emacs’s Markdown previews.
  • Pandoc
  • wkhtmltopdf

Command line tools

Security

  • GnuPG
  • pinentry-mac
  • gpg-agent-config (configures gpg-agent.conf with pinentry-mac)
  • vault
  • age
  • age-plugin-se
  • touch-id-secret (keeps a secret in an auto-locking keychain that Touch ID unlocks)
  • touch-id-secret-lock-state (reports whether a keychain is locked without opening a dialog)

GNU Command Line Tools

  • binutils
  • coreutils
  • diffutils
  • ed
  • findutils
  • gawk
  • gnu-indent
  • gnu-sed
  • gnu-tar
  • gnu-which
  • gnutls
  • grep
  • gzip
  • screen
  • watch
  • wdiff
  • wget

Miscellaneous

Configures

Routes links with Finicky

The finicky role sets Finicky as the HTTP/HTTPS handler, routes app.clickup.com task and Doc links to the ClickUp desktop app, and uses Google Chrome for other links. It manages ~/.finicky.js and preserves the URL path, query, and anchor. Run it with make provision ARGS“–tags finicky”=. Accept macOS’s browser-change prompt if one appears. ClickUp’s desktop app must already be installed and signed in.

Links clicked inside Chrome normally stay in Chrome. With ClickUp running, open a ClickUp page in Chrome and select the notification checkbox to automatically open future links in the desktop app. This is ClickUp’s Detect Desktop App setting. Tracked notification URLs and public Doc URLs are left to Chrome to resolve.

Restricts Claude Code file writes

The claude role writes Claude Code managed settings to /Library/Application Support/ClaudeCode/managed-settings.json. The file is owned by root, so Claude can’t change it without sudo. Managed settings take precedence over every other settings file and apply to the Claude Code CLI and the Claude desktop app’s Code tab. ~/.claude/settings.json is left alone.

Claude can’t write to the paths in claude_write_protected_paths (~/.ssh, ~/.aws, ~/.gnupg, and ~/.config/gh by default). Each path is blocked twice:

  • An Edit deny rule stops Claude’s file tools.
  • The Bash sandbox stops shell commands and every process they start. It also limits writes to the working directory, a temporary directory, and the package caches in claude_sandbox_writable_paths (uv, Terraform and Cargo), plus the ones in claude_sandbox_extra_writable_paths from the private vars file. Claude can’t retry a blocked command outside the sandbox, and Claude Code refuses to start if the sandbox is unavailable.

Every pnpm that Claude runs, sandboxed or not, uses its own store, ~/.agents/pnpm-store (claude_pnpm_store_directory), instead of ~/Library/pnpm/store. pnpm clones packages from the store into each project, so a package changed in a store reaches every install from it. A sandboxed command can change Claude’s store, but not the store that installs in a terminal use. Without its own store, each sandboxed install downloads all packages into a .pnpm-store of its own at the top of the worktree.

Claude can’t read the paths in claude_read_protected_paths (~/.ssh by default), through a Read deny rule and the sandbox’s denyRead. Sandboxed commands can reach any host, so a private key they could read could leave this Mac. Commands excluded from the sandbox still read them, so git fetch and git push keep working.

Sandboxed commands can reach any host over HTTP and HTTPS. The commands in claude_sandbox_excluded_commands run outside the sandbox with full access: git network commands, because SSH remotes can’t connect from inside it, git commit, because lefthook needs a pseudo-terminal, git add, because the sandbox lets a session write the index only of the worktree the desktop app made for it, docker, because the sandbox blocks the Docker socket, codex exec, because macOS won’t start Codex’s own sandbox inside it (the codex role installs the Codex CLI), the converge skill’s agent-review, because the reviewer CLIs it starts write their sessions under the home directory, and a few others the sandbox breaks. claude_sandbox_extra_excluded_commands adds commands for your own projects, such as database tasks that can’t reach a database from inside the sandbox. Set it in the private vars file described under “Secrets”. Git hooks run with them, and Claude can edit hook configuration in the working directory, so the sandbox guards against accidents rather than acting as a security boundary. A command only runs outside the sandbox when the Bash call is the command alone, without cd, pipes or redirects, so the role also writes a managed CLAUDE.md next to the settings that lists the commands and tells Claude how to run them. Ansible writes its temporary files under /tmp/claude/ansible instead of ~/.ansible. Configure these lists in roles/claude/defaults/main.yml, then apply them with:

make provision ARGS='--tags claude'

Run /status in Claude Code and check that Setting sources lists Enterprise managed settings (file).

Upgrades OpenZFS without touching imported pools

The openzfs role installs the OpenZFS on OS X release set in openzfs_version in roles/openzfs/defaults/main.yml, using the Homebrew cask. If that version is already installed, it does nothing. It stops before upgrading when:

  • the cask offers a different version, so each new release gets reviewed and pinned first
  • a pool is imported or a dataset is mounted, because the upgrade exports every pool and unloads the running driver

To upgrade, close whatever uses the pools, then:

sudo zpool export -a
make provision ARGS='--tags openzfs'

If macOS asks, allow the extension in System Settings > Privacy & Security. Then reboot. Afterwards, zfs version should show the same version for zfs and zfs-kmod. Don’t run zpool upgrade until the new release has proven itself: older releases can’t import a pool with newer features enabled.

openzfs_arc_max limits the ARC (the ZFS read cache), in bytes. It’s 2 GiB, down from the driver’s own limit of 7.5 GiB on a 16 GiB Mac; 0 restores the driver’s limit. The role writes the limit to /etc/zfs/zsysctl.conf, which OpenZFS applies at boot, and leaves other lines there alone. --tags openzfs writes it too. Change it in roles/openzfs/defaults/main.yml rather than with --extra-vars, since the next make provision without it puts the default back. To write it and apply it without a reboot:

make provision ARGS='--tags openzfs-arc'
sudo sysctl -w kstat.zfs.darwin.tunable.zfs_arc.max=2147483648

Going back to 0 takes effect only after a reboot.

The ARC limit doesn’t cover the rest of the memory ZFS allocates, so compare before and after with roles/openzfs/files/zfs-memory-snapshot.sh <label>.

Passwordless sudo

The passwordless-sudo role enables Touch ID authentication through /etc/pam.d/sudo_local on macOS Sonoma 14 or later. This local PAM file survives macOS updates. Enroll a fingerprint in System Settings under Touch ID & Password before using it.

On a MacBook, keep the lid open unless you use a compatible external keyboard with Touch ID. Closing the lid makes the built-in sensor inaccessible, so sudo falls back to your login password.

sudo authenticates with Touch ID and falls back to your login password when Touch ID is unavailable. The role preserves local PAM customizations and leaves the system /etc/pam.d/sudo file intact.

Apply this configuration with:

make provision ARGS='--tags touch-id-sudo --ask-become-pass'

The first run needs --ask-become-pass because Touch ID isn’t enabled yet. After that, ansible.cfg leaves out sudo’s -n flag, so tasks that need administrator access ask for Touch ID instead of a password. When Touch ID is unavailable, add --ask-become-pass to ARGS. Without it, sudo waits for a password that Ansible can’t enter, and the run can hang. To check the fingerprint prompt from a local terminal, run:

sudo -k
sudo whoami

A successful authentication prints root. Canceling Touch ID allows password fallback. SSH and some terminal multiplexer sessions may need the password instead. See Apple’s macOS Sonoma enterprise release notes.

Touch ID for SSH

The secretive role installs Secretive and configures terra and luna to use its SSH agent. Run make provision ARGS‘–tags touch-id-ssh’= after creating a key named MacBook Touch ID in Secretive with Require Authentication selected. The role exports only its public key to ~/.ssh/secretive-macbook.pub and sets IdentityAgent, IdentityFile, IdentitiesOnly yes and ForwardAgent no for those hosts. Other SSH hosts continue to use their current agent.

Enroll that public key through the servers’ provisioning before connecting. In contextualize.ai, the operator-ssh-keys provisioning tag adds it to root’s authorized_keys without removing existing keys. A replacement Mac needs a new Secretive key and a corresponding public-key update in that provisioning. Secure Enclave private keys cannot be imported or exported. Keep a separately authorized recovery key outside this Mac, even after the new key works on every destination.

Secretive registers its background agent during first launch. Keep the MacBook lid open for Touch ID unless you have an external Touch ID keyboard. Its Require Authentication setting also permits macOS password or Apple Watch approval. The role discovers the named public identity through the agent, so it can rerun without a key’s device-specific identifier.

Private vars can add more keys with secretive_extra_keys, in the same format as secretive_keys, and give their aliases a HostName and User with secretive_host_entries. In ~/.ssh/config, such an alias’s block also matches its HostName, so an Ansible inventory that names the server by IP address uses the same key, whatever SSH_AUTH_SOCK says. The role tells you how to create each missing key and configures the keys it finds. A key created with Require Authentication cleared lets coding agents log in unattended as a confined, non-root user. Its private key still stays in the Secure Enclave, so it can’t be copied off this Mac. Keep root aliases on the Touch ID key.

Give such a key an ssh_config_file, such as ~/.ssh/agents.conf, and let Claude run only ssh -F ~/.ssh/agents.conf <alias> -- * outside its sandbox, through claude_sandbox_extra_excluded_commands. -F makes ssh read that file alone, which sandboxed commands can’t write, and -- stops ssh from reading options after the alias. Without both, a ProxyCommand added to ~/.ssh/config or to the command line would run on this Mac outside the sandbox.

Touch ID secrets

The touch-id-secret role installs a command that replaces a plaintext password file with a command printing the secret. Each secret lives in its own keychain, which locks when the Mac sleeps and after 60 seconds without a read. Its random password is encrypted with age to a Secure Enclave identity from age-plugin-se that only Touch ID can use. Install it with:

make provision ARGS='--tags touch-id-secret'

The role installs into /usr/local/bin and needs age-plugin-se, whose Homebrew formula requires macOS 26 on Apple silicon. touch_id_secret_idle_timeout_seconds in the role’s defaults sets the timeout. Commands that need a secret only need to know this:

CommandEffect
touch-id-secret put <name>Stores stdin; refuses an existing name
touch-id-secret put --force <name>Stores stdin; replaces an existing name
touch-id-secret get <name>Prints the secret to stdout

get prints exactly the bytes given to put, with nothing added, and diagnostics go to stderr. A trailing newline in the file stays in the secret. The exit status is 0 on success, 1 on any failure, including a cancelled Touch ID prompt, with nothing on stdout, and 2 on bad usage or an invalid name. Names use up to 64 of A-Z a-z 0-9 . _ -, starting with a letter or digit.

Each secret’s files are in ~/.local/share/touch-id-secret/<name>/, with that directory and its parent at mode 0700: identity.txt, keychain-password.age and <name>.keychain-db. The keychains stay off the search list. The item’s value is the secret in hex, which keeps every byte intact.

First setup

Store the secret from a file, confirm the Touch ID prompt, and check the result before removing the plaintext. put refuses to read from a terminal, where the secret would echo.

touch-id-secret put example < plaintext-file
touch-id-secret get example | cmp - plaintext-file

Keep a recovery copy off this Mac, for example in a password manager, then delete plaintext-file. A tool that wants a password file takes a small executable instead:

#!/bin/sh
exec touch-id-secret get example
Rotating a secret

Replace the secret, then update the recovery copy. put --force creates a new identity and keychain, and swaps them in only after the new ones work, so a failure or a cancelled prompt leaves the old secret in place.

touch-id-secret put --force example < new-plaintext-file

put writes the idle timeout into the keychain, so a changed timeout reaches an existing secret only when you store it again this way.

The swap is two moves, so a get during it can fail with “no secret named”. Run it again. A signal such as SIGTERM between the moves puts the old secret back. A SIGKILL or a power loss there leaves it in ~/.local/share/touch-id-secret/.<name>.XXXXXX.previous, and get fails until you move that directory back to <name> or store the secret again.

Recovery

The secret can’t be recovered without its Secure Enclave key. That key can’t be exported, and identity.txt is its only copy, so erasing the Mac erases the key too. Backups of ~/.local/share/touch-id-secret don’t help elsewhere, as no other Mac can use them. Restoring one to this Mac after an erase hasn’t been tested, so don’t rely on it. That is why the secret needs a recovery copy off this Mac. If get stops working, store the secret again from that copy:

touch-id-secret put --force example < recovered-plaintext-file
Replacing a Mac

Secure Enclave keys stay in the Mac that made them, so nothing here moves to the new one. Install the role on the new Mac and run put again from the recovery copy. Don’t copy ~/.local/share/touch-id-secret across.

Using it from several repositories

The command is installed for the whole machine, so repositories share it without a submodule or a shared library. Each repository only needs a small script that names its secret. For Ansible Vault, that secret is the vault password. The vaulted values stay encrypted in the repository, so adding one doesn’t add anything under ~/.local/share/touch-id-secret.

Give each repository its own vault password and its own name:

~/.local/share/touch-id-secret/
├── repo-a-ansible-vault/
└── repo-b-ansible-vault/

An agent working in one repository then can’t decrypt another’s vault without your Touch ID, unless that repository’s keychain is already unlocked. You can also rotate one password without touching the others. The cost is one Touch ID prompt per repository.

Put the script in the repository, as bin/ansible-vault-password with mode 0755. The full path means it also works where /usr/local/bin isn’t on PATH:

#!/bin/sh
exec /usr/local/bin/touch-id-secret get repo-a-ansible-vault

Then set vault_password_file = bin/ansible-vault-password in the repository’s ansible.cfg. Ansible only finds that file in the current directory, so to run from anywhere else, export ANSIBLE_VAULT_PASSWORD_FILE with the script’s full path instead. Ansible removes a trailing newline from what a password script prints. Other scripts can call touch-id-secret get <name> directly, and should pipe the value into the tool that needs it where they can.

To create a new vault password, generate it directly into the command, so it never reaches a file or your shell history. Then copy it to your recovery location and overwrite the clipboard. A clipboard manager may keep its own copy.

head -c 32 /dev/urandom | xxd -p | tr -d '\n' | touch-id-secret put repo-a-ansible-vault
touch-id-secret get repo-a-ansible-vault | pbcopy

To move an encrypted file to that password, run this in a terminal, because the Touch ID prompt can’t appear from an agent’s sandbox:

ansible-vault rekey --vault-password-file old-password-file --new-vault-password-file bin/ansible-vault-password secrets.yml

Keep these limits in mind. The Ansible behavior here was tested with dummy values on ansible-core 2.14.3:

  • ansible-vault rekey refuses a file whose values are inline encrypt_string blocks, and leaves it unchanged. Those values need a script that decrypts each one and encrypts it again.
  • Rekeying changes the current files only. Anyone with the old password can still decrypt the old commits, so if it may have leaked, rotate the secrets themselves too.
  • A branch that still has values encrypted with the old password can conflict with the rekey, or stop decrypting.
  • A machine without Touch ID, such as a server or a CI runner, can’t use this command. Give it the password another way, by pointing ANSIBLE_VAULT_PASSWORD_FILE at something else there.
  • The rekey and the script should land in one change, so a repository never has one without the other. Remove old plaintext copies last, including those in existing worktrees.

A playbook that installs this command can’t depend on it on a new Mac. Ansible runs a configured password script at the start of every run, and if the script fails or is missing, the run stops even when it uses no vaulted value. So such a playbook needs a way to run with no password configured, as make provision does here until secrets.mk exists. Its values also have to be inline. Ansible decrypts a fully encrypted variable file when it loads it, so --tags doesn’t help, and the run stops with “no vault secrets found”. An inline encrypt_string value is only decrypted when something uses it.

How it works

Two locks form a chain. Touch ID and the Secure Enclave protect a random password, and that password opens a keychain holding the secret. The password is the only link between them. The keychain has no tie to the enclave and doesn’t know about Touch ID: to macOS it’s an ordinary keychain with a password. The keychain provides the locking, and the enclave adds the Touch ID requirement.

Touch ID
   |  authorizes
   v
Secure Enclave + identity.txt       age-plugin-se
   |  decrypts
   v
keychain-password.age               age
   |  yields the keychain's password
   v
<name>.keychain-db                  security unlock-keychain
   |  stays unlocked until the timer runs out or the Mac sleeps
   v
the item, in hex                    security find-generic-password
   |  xxd -r -p
   v
stdout: the exact secret bytes
ComponentJob
touch-id-secretRuns all the others and keeps no state of its own
touch-id-secret-lock-stateReports locked or unlocked without opening a dialog
ageEncrypts and decrypts the keychain’s password file
age-plugin-seLets age use the Secure Enclave
Secure EnclaveDoes the private-key operation after Touch ID
securityCreates, unlocks, locks and reads the keychain

put generates these for each secret, so two secrets share nothing and each needs its own Touch ID approval:

FileContentsProtected by
identity.txtThe private key, wrappedThis Mac’s enclave, Touch ID
keychain-password.age32 random bytes as 64 hex charactersage, to that identity
<name>.keychain-dbOne generic password item: the secret in hexThe keychain’s password
The Secure Enclave key

“Wrapped” means encrypted with another key. The plain private key exists only inside the enclave, and everything outside it handles the wrapped copy:

  1. The enclave generates a P-256 private key inside itself, and hands out the wrapped copy and the public key. The copy goes in identity.txt, and the public key is the age1se1... recipient.
  2. To use the key, age-plugin-se loads the wrapped copy and asks for the key operation. After Touch ID, the enclave does the operation and returns only the result.

The enclave keeps no copy for this key that the file points to, so deleting identity.txt loses the key. A copy of the file is useless on another Mac, and on this one using it needs Touch ID.

age-plugin-se writes identity.txt, in the form age expects from a plugin:

# created: <time>
# access control: any biometry
# public key: age1se1...
AGE-PLUGIN-SE-1...

The last line is the wrapped copy, Bech32-encoded. Its prefix tells age which plugin to start, and age doesn’t look inside it. The public key comment is only for people: age-plugin-se recipients skips comments, and gets the public key by loading the wrapped copy.

Loading passes those bytes to PrivateKey(dataRepresentation:), which gives the program an object that refers to the key, not the plain key. Touch ID comes later, when the program asks for the key agreement. Apple doesn’t document what loading does inside, or the format of the wrapped copy.

Only this chip can unwrap the file because of its hardware key. Apple calls the root of these keys the UID: a random value fused into the chip when it is made, which Apple and its suppliers can’t access. Fused means burned in once, rather than kept in memory that software can read. Keys derived from it stay inside the chip’s crypto engines, hidden even from the enclave’s own operating system, and software can only ask for an operation with them. The enclave also has separate non-volatile storage, for entropy and attempt counters. See Apple’s guide to the Secure Enclave.

Apple says the UID protects device-specific secrets, but doesn’t document how a wrapped key is built. So the link from the UID to identity.txt is an inference. The plugin’s source does show that the file holds CryptoKit’s dataRepresentation of the key.

The same word applies to a second key, at a different layer:

What’s wrappedWrapped withStored inWho can unwrap it
Private keyThe enclave’s hardware keyidentity.txtOnly this Mac’s enclave
age’s file keyThe enclave key’s public halfkeychain-password.ageThe enclave, after Touch ID

That file key is how age uses the plugin. The identity and recipient strings name the plugin, so age starts age-plugin-se as a child process and talks to it over pipes.

  • Encrypting needs no Touch ID, because it only uses the public key. age makes a random file key and encrypts the data with it, and the plugin wraps the file key for the public key.
  • Decrypting needs Touch ID. age passes the wrapped file key to the plugin, the plugin asks the enclave for the private-key operation, which prompts, and the plugin returns the file key so that age can decrypt the data.

The file key crosses that connection in the clear, which is why the command clears AGEDEBUG.

The enclave doesn’t store and return secrets, which is why this chain exists. Its API has no call that takes your bytes and gives them back later. It only works with private keys it generated, and programs reach those keys through one of two frameworks. CryptoKit’s types are under SecureEnclave.P256.Signing and SecureEnclave.P256.KeyAgreement. The Security framework’s functions use the enclave when the key was made with kSecAttrTokenIDSecureEnclave.

OperationCryptoKitSecurity framework
Generate a keyPrivateKey(accessControl:)SecKeyCreateRandomKey
Get the public keypublicKeySecKeyCopyPublicKey
Save the keydataRepresentationkSecAttrIsPermanent
Load the keyPrivateKey(dataRepresentation:)SecItemCopyMatching
Signsignature(for:)SecKeyCreateSignature
Do a key agreementsharedSecretFromKeyAgreement(with:)SecKeyCopyKeyExchangeResult
DecryptBuilt on key agreementSecKeyCreateDecryptedData
Require a check for each useSecAccessControlSecAccessControl
  • Signing is how Secretive does SSH logins.
  • Key agreement is how this plugin decrypts. It also returns a secret to the caller, but one derived from the private key and the other side’s public key, not one that was stored.
  • The check is set when the key is made and can’t change. Touch ID here is kSecAccessControlBiometryAny, which the plugin’s any-biometry selects.
  • No call exports the plain key or imports one. To discard a key, delete its saved copy.
  • macOS 26 adds post-quantum keys: SecureEnclave.MLKEM768 and MLKEM1024 for key exchange, and MLDSA65 and MLDSA87 for signing. The plugin uses ML-KEM only with --pq, which this command doesn’t pass.

The plugin imports the CryptoKit calls for generating, saving, loading, the public key and key agreement. The rest of the table comes from the macOS 26.2 SDK and wasn’t run here.

macOS also has a command for these keys, sc_auth create-ctk-identity. It makes an identity for TLS, email and SSH, not a store for secrets. Only its key types ending in -ne stay in the enclave. Its man page says the others are exportable, encrypted with an enclave key rather than held by it.

How this relates to Secretive and sudo

Two other roles use Touch ID, and this command depends on neither of them:

RoleUsed forMechanismKey
passwordless-sudosudopam_tid.so in sudo_localNone, it only checks you
secretiveSSH to terra and lunaSecretive’s SSH agent signsSecretive’s own enclave key
touch-id-secretReading a secretage-plugin-se decryptsOne enclave key per secret

Secretive and this command use the same chip but share no key. A Secretive key signs SSH logins and can’t open a secret here, and an identity here can’t log in over SSH. Secretive’s Require Authentication also permits the macOS password or an Apple Watch, while this command’s keys accept only Touch ID.

A worked example

Say plaintext-file holds correct-horse with no trailing newline, and the name is demo. The password below is made up.

touch-id-secret put demo < plaintext-file
StepResult
Secret read as hex636f72726563742d686f727365
Identity createdidentity.txt, with public key age1se1...
Password generated9f3a...c71e, 64 hex characters
Password encryptedkeychain-password.age
Touch ID checkDecrypts the file and compares, to prove it works
Keychain createddemo.keychain-db, protected by 9f3a...c71e
Secret storedThe item’s value is 636f...7365
Keychain lockedEverything moves into ~/.local/share/touch-id-secret/demo/

After this, the password exists on disk only inside the encrypted file. The secret exists on disk only inside the keychain. Reading it while locked:

touch-id-secret get demo
  1. The helper reports locked.
  2. age -d prompts for Touch ID and returns 9f3a...c71e.
  3. security unlocks the keychain with that password.
  4. security reads 636f...7365, and xxd turns it back into correct-horse.

Within the next 60 seconds the helper reports unlocked, so age and the enclave aren’t involved and there’s no prompt. Only step 4 runs, and the read restarts the timer.

What it protects against

The goal is to remove a plaintext file from disk and to require a person after each lock. It doesn’t isolate the secret from other software running as you while the keychain is unlocked.

SituationResult
Someone copies the files, as from a backupThey can’t get the secret
The Mac slept, or no read for 60 secondsLocked, and the next read needs Touch ID
A process running as you, keychain lockedIt can start a prompt, but needs you to approve it
A process running as you, keychain unlockedNot protected: it reads with no prompt
A process that keeps readingNot protected: the keychain stays unlocked
Root, or malware replacing the commandOut of scope

A hostile process gains little by polling, because one read already gives it the secret. The cost is a longer window for everything else, for example when a harmless script polls.

None of this has been tested with a copy on another Mac, or after adding or removing a fingerprint. That securityd holds the unlock state and the timer is general macOS knowledge, also not tested here.

Limits
  • While the keychain is unlocked, any process running as you can read the secret, with no prompt.
  • A read restarts the timer, so the 60 seconds count from the last read. A process that keeps reading can keep the keychain unlocked until the Mac sleeps. The command has no lock subcommand, so to lock it sooner, run security lock-keychain ~/.local/share/touch-id-secret/<name>/<name>.keychain-db.
  • put refuses a secret above roughly 1,900 bytes, because security -i splits long lines. The exact limit depends on the name and the home directory’s path. That fits a password, but not a large PEM key.
  • Only one put can run per name, and a second one fails right away. A SIGKILL or a power loss leaves the lock behind, at ~/.local/share/touch-id-secret/.<name>.lock. put then names that directory, and you can remove it if no put is running. get ignores it. A signal in the instant put takes the lock can leave it behind too.
  • A SIGKILL or a power loss during put can leave a staging directory, at ~/.local/share/touch-id-secret/.<name>.XXXXXX. So can Ctrl-C in the instant put creates it, because it also stops mktemp. You can remove the directory if no put is running.
  • The command clears the caller’s environment apart from HOME, and sets its own PATH. This keeps AGEDEBUG=plugin from making age log its file key, but a setting you export doesn’t reach age, security or the plugin.
  • The timer can expire between get’s lock check and its read. macOS then opens its keychain password dialog. Cancel it and run get again.
  • Touch ID is the only way in: there’s no passcode fallback, so with the lid closed get needs an external Touch ID keyboard.
  • In Claude Code’s Bash sandbox, get exits 1 while the keychain is locked, because age-plugin-se can’t reach the helper it needs. While the keychain is unlocked, get works there too, so that sandbox doesn’t protect the secret during that window.
  • The lock check uses SecKeychainGetStatus through /usr/bin/python3. Apple has deprecated that API, and the interpreter comes with the Developer Tools.
Testing

roles/touch-id-secret/tests/test-touch-id-secret runs the command with a dummy secret and a throwaway name, then removes them. It needs you for Touch ID and for sleeping the Mac, so run it in a terminal. The sleep test passes only when pmset records a sleep during the test. Without one it reports SKIP, because a locked keychain alone doesn’t show that sleep locked it. Its timer mode checks that a read restarts the idle timer, and its rotation mode runs put --force on a locked and on an unlocked keychain.

roles/touch-id-secret/tests/test-touch-id-secret-logic tests the role’s template against the stubs in tests/stubs/, and checks what the script above reports for each result. It needs no Touch ID, Keychain or installed command, and it stores only dummy values in a temp directory, so it also works in an agent’s sandbox, where it skips the terminal stdin check. It doesn’t show that the real tools behave like the stubs.

Puts SSH keys in place

The ssh-keys role installs the keys in ssh_keys into ~/.ssh and adds the public keys of entries with authorized: true to ~/.ssh/authorized_keys. See roles/ssh-keys/defaults/main.yml.

Remaps Caps-Lock to Control

Uses an AppleScript helper for the current System Settings flow.

Sets a simple wallpaper and turns off the screen saver

The simple-wallpaper-screensaver role sets a static wallpaper of one solid color on every display and Space, and turns off the screen saver. This stops the animated wallpaper and screen saver processes, which use memory and CPU. Run it with:

make provision ARGS='--tags simple-wallpaper-screensaver'

The color is simple_wallpaper_screensaver_color in the role’s defaults, a muted slate blue. To try another color:

make provision ARGS='--tags simple-wallpaper-screensaver -e simple_wallpaper_screensaver_color=3b5578'

macOS has no built-in color like it, so the role writes a small PNG of the color to ~/Library/Application Support/simple-wallpaper-screensaver.

The screen saver setting is where an animated Ventura wallpaper can run: Ventura.appex is a screen saver, and no built-in screen saver is static. The role selects the small Shell.appex in its place, and sets “Start Screen Saver when inactive” to “Never”. The Mac still locks when the display sleeps, if “Require password” is set in System Settings > Lock Screen.

The role edits ~/Library/Application Support/com.apple.wallpaper/Store/Index.plist, because the public API and osascript reach only the current Space and desktoppicture.db no longer has an effect. The format of this file isn’t documented, so the role refuses a file with an unfamiliar shape, and fails if WallpaperAgent doesn’t keep the change. The display flashes while the agent restarts. A Space or display that macOS adds later can show a different wallpaper until the next make provision. The first run keeps the original file at ~/Library/Application Support/com.apple.wallpaper/Index.plist.before-simple-wallpaper-screensaver.

roles/simple-wallpaper-screensaver/tests/test-set-simple-wallpaper-screensaver tests the script against a temporary home and stubs.

Can restore the default wallpaper and screen saver

The default-wallpaper-screensaver role undoes simple-wallpaper-screensaver. It runs only when its tag is given:

make provision ARGS='--tags default-wallpaper-screensaver'

It selects the system’s default wallpaper on every display and Space, and the Ventura screen saver after 20 minutes. It replaces any wallpaper that you selected yourself. Ventura is the screen saver this Mac had before simple-wallpaper-screensaver, and it may not be the factory selection for a macOS version.

A full make provision runs simple-wallpaper-screensaver again. To stay on the defaults, remove simple-wallpaper-screensaver from main.yml.

roles/default-wallpaper-screensaver/tests/test-set-default-wallpaper-screensaver tests the script against a temporary home and stubs.

Restic repository passwords

The mac, offsite and tankette repositories each have their own password. It comes from vars.yml (see Secrets), and the mpereira-backup role writes it to ~/.config/restic/<repository>.password. Changing a password takes seconds, because it only replaces the small key file that unlocks the repository. No backup data is rewritten.

To change a password:

  1. Wait until no backup of that repository is running. restic needs the repository to itself for this, and stops with an “already locked” error otherwise. Don’t use restic unlock to get past that error while a backup is running.
  2. Save the new password in your password manager. Without its password, nobody can recover a repository’s backups.
  3. Change the password in the repository. Each command asks for the current password, then the new one twice.
    mpereira-backup restic mac key passwd
        
    mpereira-backup restic offsite key passwd
        
    mpereira-backup restic tankette key passwd
        
  4. Put the new password in your secrets project, and write group_vars/localhost/vars.yml from it.
  5. Install the new password file.
    make provision ARGS='--tags mpereira-backup'
        
  6. Check that the new password opens the repository.
    mpereira-backup restic mac snapshots --latest 1
        
    mpereira-backup restic offsite snapshots --latest 1
        
    mpereira-backup restic tankette snapshots --latest 1
        

Between steps 3 and 5, backups of that repository fail with a wrong-password error, because the password file still holds the old password. The same happens if you run make provision before updating vars.yml. No data is harmed, but do the steps together.

This doesn’t replace the repository’s encryption key:

  • Anyone with an older copy of the repository and the old password can still open that copy. That includes a ZFS snapshot of the dataset that holds the repository, until you destroy the snapshot.
  • If a password may have leaked, create a new repository and back up to it again. For offsite, that means uploading everything again.

Author

Murilo Pereira

License

MIT

探索相关项目

加载中…