-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup
More file actions
executable file
·1996 lines (1719 loc) · 71.2 KB
/
Copy pathsetup
File metadata and controls
executable file
·1996 lines (1719 loc) · 71.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -Eeuo pipefail
# Keep setup usable after nix-darwin removes /run/current-system from a shell
# whose command cache and PATH still reference that generation.
export PATH="${PATH:-}:/usr/bin:/bin:/usr/sbin:/sbin"
# Every Nix operation in this script is flake-based. Do not inherit an older
# nix-darwin generation's channel-backed NIX_PATH during the switch that
# replaces it.
export NIX_PATH="nixpkgs=flake:nixpkgs"
hash -r
resolve_script_path() {
local source="${BASH_SOURCE[0]}"
local directory target
if [[ "${source}" != */* ]]; then
source="$(command -v -- "${source}")"
fi
while [[ -L "${source}" ]]; do
directory="$(cd -P -- "$(dirname -- "${source}")" && pwd)"
target="$(readlink "${source}")"
if [[ "${target}" == /* ]]; then
source="${target}"
else
source="${directory}/${target}"
fi
done
directory="$(cd -P -- "$(dirname -- "${source}")" && pwd)"
printf '%s/%s\n' "${directory}" "$(basename -- "${source}")"
}
SETUP_PATH="$(resolve_script_path)"
readonly SETUP_PATH
REPO_ROOT="$(dirname -- "${SETUP_PATH}")"
readonly REPO_ROOT
readonly FLAKE_DIR="${REPO_ROOT}/nix"
readonly NIX_INSTALL_URL="https://nixos.org/nix/install"
readonly HOMEBREW_INSTALL_URL="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"
readonly SECRETS_REMOTE="ssh://git@github.com/randy1burrell/secrets.git"
readonly OPENPGP_ENCRYPTION_RECIPIENTS_FILE="${GNUPGHOME:-${HOME}/.gnupg}/openpgp-encryption-recipients"
readonly YUBIKEY_STATE_ROOT="${XDG_STATE_HOME:-${HOME}/.local/state}/dotfiles/yubikeys"
info() {
printf '\033[1;34m==>\033[0m %s\n' "$*"
}
fail() {
printf '\033[1;31merror:\033[0m %s\n' "$*" >&2
exit 1
}
warn() {
printf '\033[1;33mwarning:\033[0m %s\n' "$*" >&2
}
usage() {
printf 'Usage: %s [action] [-- app-arguments...]\n\n' "${BASH_SOURCE[0]}"
cat <<'EOF'
Run without an action to open the interactive menu.
The repository may live anywhere. Setup resolves the flake relative to this
script, regardless of the current working directory or a symlink used to run it.
System actions:
switch Build and activate this machine's configuration
build Build without activating the configuration
check Evaluate without building the configuration
apply Personalize the configuration for a machine
apt Install and upgrade declared Ubuntu APT packages
snaps Install and refresh declared Ubuntu Snap packages
github-user Show or change the saved GitHub username
github-ssh-key
Register the connected YubiKey's OpenPGP SSH key with GitHub
doctor Validate scripts, Nix, Emacs, GnuPG, and GitHub SSH readiness
clean Remove old system generations and reclaim space
install-nix Install upstream Nix, or replace an installer-managed Nix
update-secrets Encrypt and push local secrets plus a durable ~/.ssh archive
pull-secrets Pull, validate, back up, and restore encrypted SSH secrets
refresh-secrets-lock
Refresh only the private secrets input in flake.lock
Key and GPG actions:
gpg Start and verify the GPG-backed SSH agent
cache-gpg-pin
Let one connected YubiKey retain its signature PIN until removal
check-keys Verify the SSH/Agenix files and GPG agent
copy-keys Copy keys from a mounted drive after starting GPG
create-keys Create SSH/Agenix keys after starting GPG
yubikey-login
Enable local computer login with a YubiKey PIN
yubikey-agenix
Provision a YubiKey for hardware-backed Agenix encryption
yubikey-setup
Provision one YubiKey for PINs, keys, login, SSH, and Agenix
Environment:
GITHUB_USER Supply the GitHub username for an unattended first run.
SYSTEM_CONFIG Override the flake configuration name selected from the
current CPU architecture.
DOTFILES_NIXOS_HOSTNAME
Override the detected NixOS hostname.
DOTFILES_NIXOS_DISK
Override the detected NixOS root disk (for example /dev/nvme0n1).
KEYS_MOUNT_PATH Select the mounted key directory for copy-keys.
SECRETS_UPDATE_IDENTITY
Use a specific SSH private key while refreshing secrets.
SECRETS_SSH_IDENTITY
Use a specific SSH private key for secrets push or pull.
AGENIX_IDENTITY_PATH
Override ~/.ssh/id_ed25519_agenix for encryption/decryption.
AGE_YUBIKEY_IDENTITY_PATH
Override ~/.config/age/yubikey-identities.txt.
AGE_YUBIKEY_RECIPIENTS_PATH
Override ~/.config/age/yubikey-recipients.txt.
SECRETS_CONFIRM=yes
Allow a non-interactive secrets push.
GPG_PIN_CACHE_CONFIRM=yes
Confirm a non-interactive YubiKey signature-policy change.
EOF
}
github_username_path() {
printf '%s/dotfiles/github-user\n' "${XDG_CONFIG_HOME:-${HOME}/.config}"
}
validate_github_username() {
local username="$1"
[[ ${#username} -ge 1 && ${#username} -le 39 ]] || return 1
[[ "${username}" =~ ^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$ ]]
}
save_github_username() {
local username="$1" destination directory temporary
validate_github_username "${username}" || \
fail "GitHub usernames must be 1-39 characters and contain only letters, numbers, or single hyphens that are not first or last."
destination="$(github_username_path)"
directory="$(dirname -- "${destination}")"
(
umask 077
mkdir -p -- "${directory}"
temporary="$(mktemp "${directory}/github-user.XXXXXX")"
printf '%s\n' "${username}" > "${temporary}"
mv -f -- "${temporary}" "${destination}"
) || fail "Could not save the GitHub username to ${destination}."
}
read_saved_github_username() {
local destination username
destination="$(github_username_path)"
[[ -r "${destination}" ]] || return 1
IFS= read -r username < "${destination}" || true
[[ -n "${username}" ]] || return 1
printf '%s\n' "${username}"
}
configure_github_username() {
local username="" saved_username=""
saved_username="$(read_saved_github_username || true)"
username="${saved_username:-${GITHUB_USER:-}}"
if [[ -z "${username}" ]]; then
[[ -t 0 ]] || \
fail "No GitHub username is saved. Run ${SETUP_PATH} github-user USERNAME, or set GITHUB_USER for this run."
IFS= read -r -p "GitHub username (saved for future setup runs): " username
fi
validate_github_username "${username}" || \
fail "Invalid GitHub username '${username}'. Run ${SETUP_PATH} github-user to replace it."
if [[ "${saved_username}" != "${username}" ]]; then
save_github_username "${username}"
info "Saved GitHub username ${username}"
fi
export GITHUB_USER="${username}"
export DOTFILES_GITHUB_USER="${username}"
}
change_github_username() {
local username="${1:-}" current=""
[[ $# -le 1 ]] || fail "Usage: ${SETUP_PATH} github-user [USERNAME]"
current="$(read_saved_github_username || true)"
if [[ -z "${username}" ]]; then
[[ -t 0 ]] || fail "Usage: ${SETUP_PATH} github-user USERNAME"
if [[ -n "${current}" ]]; then
IFS= read -r -p "GitHub username [${current}]: " username
username="${username:-${current}}"
else
IFS= read -r -p "GitHub username: " username
fi
fi
save_github_username "${username}"
export GITHUB_USER="${username}"
export DOTFILES_GITHUB_USER="${username}"
info "GitHub username saved as ${username}"
info "Run ${SETUP_PATH} switch to apply it to your shell and Git configuration"
}
load_nix() {
hash -r
if command -v nix >/dev/null 2>&1 && nix --version >/dev/null 2>&1; then
return 0
fi
if [[ -x /nix/var/nix/profiles/default/bin/nix ]]; then
export PATH="/nix/var/nix/profiles/default/bin:${PATH}"
hash -r
if nix --version >/dev/null 2>&1; then
return 0
fi
fi
local profile
for profile in \
/nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh \
"${HOME}/.nix-profile/etc/profile.d/nix.sh"
do
if [[ -r "${profile}" ]]; then
# shellcheck disable=SC1090
source "${profile}"
if command -v nix >/dev/null 2>&1 && nix --version >/dev/null 2>&1; then
return 0
fi
fi
done
return 1
}
GPG_PINENTRY_REPAIRED=0
GPG_SUITE_BIN_DIR=""
GPG_BIN=""
GPGCONF_BIN=""
GPG_AGENT_BIN=""
GPG_CONNECT_AGENT_BIN=""
select_managed_gnupg_suite() {
local candidate fallback="" bin_directory
local -a candidates=()
# Home Manager owns GnuPG and its socket-activated agent. Prefer that
# profile over Linuxbrew or the host distribution so clients, daemons, and
# sockets always come from one release.
if [[ "$(uname -s)" == "Darwin" ]]; then
candidates+=(
/run/current-system/sw/bin/gpgconf
"${HOME}/.nix-profile/bin/gpgconf"
)
else
candidates+=(
"${HOME}/.nix-profile/bin/gpgconf"
/run/current-system/sw/bin/gpgconf
)
fi
fallback="$(command -v gpgconf 2>/dev/null || true)"
[[ -z "${fallback}" ]] || candidates+=("${fallback}")
for candidate in "${candidates[@]}"; do
[[ -x "${candidate}" ]] || continue
bin_directory="$(dirname -- "${candidate}")"
if [[ -x "${bin_directory}/gpg" && \
-x "${bin_directory}/gpg-agent" && \
-x "${bin_directory}/gpg-connect-agent" ]]; then
GPG_SUITE_BIN_DIR="${bin_directory}"
GPG_BIN="${bin_directory}/gpg"
GPGCONF_BIN="${candidate}"
GPG_AGENT_BIN="${bin_directory}/gpg-agent"
GPG_CONNECT_AGENT_BIN="${bin_directory}/gpg-connect-agent"
# Shared setup actions are repository scripts rather than Nix app
# wrappers, so give them the same coherent suite selected here.
export PATH="${GPG_SUITE_BIN_DIR}:${PATH}"
export DOTFILES_GPG="${GPG_BIN}"
export DOTFILES_GPGCONF="${GPGCONF_BIN}"
export DOTFILES_GPG_AGENT="${GPG_AGENT_BIN}"
export DOTFILES_GPG_CONNECT_AGENT="${GPG_CONNECT_AGENT_BIN}"
hash -r
return 0
fi
done
return 1
}
openpgp_encryption_fingerprints_from_colons() {
awk -F: '
function emit() {
if (primary != "" && usable && encryption) print toupper(primary)
}
$1 == "pub" || $1 == "sec" {
emit()
primary = ""
usable = ($2 !~ /[der]/)
encryption = (usable && $12 ~ /e/)
candidate = 0
next
}
$1 == "fpr" && primary == "" {
primary = $10
next
}
$1 == "sub" || $1 == "ssb" {
candidate = (usable && $2 !~ /[der]/ && $12 ~ /e/)
next
}
$1 == "fpr" && candidate {
encryption = 1
candidate = 0
}
END { emit() }
'
}
refresh_openpgp_encryption_recipients() {
local public_key_bundle="${1:-}" directory temporary discovered=""
local local_secret_recipients="" fingerprint_file
directory="$(dirname -- "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}")"
install -d -m 700 "${directory}"
temporary="$(mktemp "${directory}/openpgp-encryption-recipients.XXXXXX")"
if [[ -n "${public_key_bundle}" && -r "${public_key_bundle}" ]]; then
discovered="$({
LC_ALL=C "${GPG_BIN}" --batch --with-colons \
--import-options show-only --dry-run --import "${public_key_bundle}" 2>/dev/null
} | openpgp_encryption_fingerprints_from_colons)" || discovered=""
fi
# Include active encryption keys backed by secret-key stubs already known to
# this machine. This covers a newly inserted card before its public
# certificate has been uploaded to GitHub.
if [[ -n "${GPG_BIN:-}" && -x "${GPG_BIN}" ]]; then
local_secret_recipients="$({
LC_ALL=C "${GPG_BIN}" --batch --with-colons --list-secret-keys 2>/dev/null
} | openpgp_encryption_fingerprints_from_colons)" || local_secret_recipients=""
fi
{
if [[ -r "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}" ]]; then
cat -- "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}"
fi
for fingerprint_file in "${YUBIKEY_STATE_ROOT}"/*/openpgp-fingerprint.txt; do
[[ -r "${fingerprint_file}" ]] || continue
cat -- "${fingerprint_file}"
done
printf '%s\n' "${discovered}"
printf '%s\n' "${local_secret_recipients}"
} | awk '
(length($0) == 40 || length($0) == 64) && $0 ~ /^[[:xdigit:]]+$/ {
print toupper($0)
}
' | sort -u > "${temporary}"
if [[ ! -s "${temporary}" ]]; then
rm -f -- "${temporary}"
return 0
fi
if [[ -r "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}" ]] && \
cmp -s "${temporary}" "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}"; then
rm -f -- "${temporary}"
else
mv -- "${temporary}" "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}"
info "Updated the OpenPGP encryption recipients used by Emacs"
fi
chmod 600 "${OPENPGP_ENCRYPTION_RECIPIENTS_FILE}"
}
sync_github_gpg_public_keys() {
local curl_bin key_file
# Preserve fingerprints exported by local card provisioning even when the
# network is unavailable or a new public certificate has not been uploaded
# to GitHub yet.
refresh_openpgp_encryption_recipients
[[ -n "${GITHUB_USER:-}" && -n "${GPG_BIN}" ]] || return 0
curl_bin="$(command -v curl 2>/dev/null || true)"
[[ -n "${curl_bin}" ]] || {
warn "curl is unavailable; skipping GitHub OpenPGP public-key synchronization."
return 0
}
key_file="$(mktemp "${TMPDIR:-/tmp}/dotfiles-github-gpg.XXXXXX")"
if ! "${curl_bin}" --fail --silent --show-error --location \
--proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 30 \
"https://github.com/${GITHUB_USER}.gpg" --output "${key_file}"; then
rm -f -- "${key_file}"
warn "Could not download ${GITHUB_USER}'s public OpenPGP certificates from GitHub; continuing with the local keyring."
return 0
fi
if [[ ! -s "${key_file}" ]] || \
! "${GPG_BIN}" --batch --show-keys "${key_file}" >/dev/null 2>&1; then
rm -f -- "${key_file}"
warn "GitHub did not return a usable OpenPGP certificate for ${GITHUB_USER}."
return 0
fi
if "${GPG_BIN}" --batch --import-options import-minimal \
--import "${key_file}" >/dev/null 2>&1; then
info "Synchronized ${GITHUB_USER}'s public OpenPGP certificates from GitHub"
refresh_openpgp_encryption_recipients "${key_file}"
# Importing the public certificate first lets GnuPG associate any
# connected OpenPGP card with its non-exportable secret keys.
"${GPG_BIN}" --batch --card-status >/dev/null 2>&1 || true
else
warn "Could not import ${GITHUB_USER}'s public OpenPGP certificates into the local keyring."
fi
rm -f -- "${key_file}"
}
ensure_linux_gpg_pinentry() {
local gpg_directory agent_config configured_pinentry pinentry_program
local temporary backup=""
[[ "$(uname -s)" == "Linux" ]] || return 0
gpg_directory="${GNUPGHOME:-${HOME}/.gnupg}"
agent_config="${gpg_directory}/gpg-agent.conf"
configured_pinentry="$(
awk '$1 == "pinentry-program" { print $2; exit }' "${agent_config}" 2>/dev/null || true
)"
if [[ -n "${configured_pinentry}" && -x "${configured_pinentry}" ]]; then
return 0
fi
if [[ -x /usr/bin/pinentry-curses ]]; then
pinentry_program=/usr/bin/pinentry-curses
elif pinentry_program="$(command -v pinentry-curses 2>/dev/null)" && \
[[ -n "${pinentry_program}" ]]; then
:
elif pinentry_program="$(command -v pinentry 2>/dev/null)" && \
[[ -n "${pinentry_program}" ]]; then
:
else
fail "No usable Pinentry was found. Install pinentry-curses before using the YubiKey."
fi
mkdir -p -- "${gpg_directory}"
chmod 700 "${gpg_directory}"
temporary="$(mktemp "${gpg_directory}/gpg-agent.conf.XXXXXX")"
if [[ -r "${agent_config}" ]]; then
awk '$1 != "pinentry-program"' "${agent_config}" > "${temporary}"
fi
printf 'pinentry-program %s\n' "${pinentry_program}" >> "${temporary}"
chmod 600 "${temporary}"
if [[ -e "${agent_config}" || -L "${agent_config}" ]]; then
backup="${agent_config}.setup-backup.$(date +%Y%m%d%H%M%S).$$"
mv -- "${agent_config}" "${backup}" || \
fail "Could not back up ${agent_config}."
fi
if ! mv -- "${temporary}" "${agent_config}"; then
[[ -z "${backup}" ]] || mv -- "${backup}" "${agent_config}" || true
fail "Could not install the temporary Linux Pinentry configuration."
fi
[[ -z "${backup}" ]] || warn "Saved the previous GPG agent configuration at ${backup}"
info "Configured Linux Pinentry at ${pinentry_program}"
GPG_PINENTRY_REPAIRED=1
}
prepare_gpg_ssh_agent() {
local expected_version running_version running_dirmngr_version socket
local ssh_executable setup_git_ssh_command
select_managed_gnupg_suite || return 0
ensure_linux_gpg_pinentry
if (( GPG_PINENTRY_REPAIRED )); then
"${GPGCONF_BIN}" --kill all >/dev/null 2>&1 || true
fi
"${GPGCONF_BIN}" --launch gpg-agent >/dev/null 2>&1 || return 0
if [[ -x "${GPG_AGENT_BIN}" && -x "${GPG_CONNECT_AGENT_BIN}" ]]; then
expected_version="$("${GPG_AGENT_BIN}" --version 2>/dev/null | awk 'NR == 1 { print $3; exit }')"
running_version="$(
"${GPG_CONNECT_AGENT_BIN}" 'GETINFO version' /bye 2>/dev/null |
awk '$1 == "D" { print $2; exit }' || true
)"
if [[ -n "${expected_version}" && -n "${running_version}" && "${running_version}" != "${expected_version}" ]]; then
warn "Restarting stale gpg-agent ${running_version} with managed version ${expected_version}."
"${GPGCONF_BIN}" --kill all >/dev/null 2>&1 || true
if [[ "$(uname -s)" == "Linux" ]] && command -v systemctl >/dev/null 2>&1; then
# Ubuntu commonly socket-activates gpg-agent. Reload the user units
# after a Home Manager upgrade so the next socket connection starts
# the managed binary rather than the distribution's older service.
systemctl --user daemon-reload >/dev/null 2>&1 || true
fi
"${GPGCONF_BIN}" --launch gpg-agent >/dev/null 2>&1 || \
fail "Could not launch the managed gpg-agent ${expected_version}."
running_version="$(
"${GPG_CONNECT_AGENT_BIN}" 'GETINFO version' /bye 2>/dev/null |
awk '$1 == "D" { print $2; exit }' || true
)"
[[ "${running_version}" == "${expected_version}" ]] || \
fail "Expected gpg-agent ${expected_version}, but socket reports ${running_version:-unknown}."
fi
running_dirmngr_version="$(
"${GPG_CONNECT_AGENT_BIN}" --dirmngr 'GETINFO version' /bye 2>/dev/null |
awk '$1 == "D" { print $2; exit }' || true
)"
if [[ -n "${expected_version}" && -n "${running_dirmngr_version}" && \
"${running_dirmngr_version}" != "${expected_version}" ]]; then
warn "Replacing stale dirmngr ${running_dirmngr_version} with managed version ${expected_version}."
if [[ "$(uname -s)" == "Linux" ]] && command -v systemctl >/dev/null 2>&1; then
# Stop the distribution socket before killing the daemon. Otherwise
# Ubuntu immediately starts /usr/bin/dirmngr again when gpgconf checks
# the standard socket. The next Home Manager switch installs a unit
# override that permanently points this socket at managed GnuPG.
systemctl --user stop dirmngr.socket dirmngr.service >/dev/null 2>&1 || true
fi
"${GPGCONF_BIN}" --kill dirmngr >/dev/null 2>&1 || true
"${GPGCONF_BIN}" --launch dirmngr >/dev/null 2>&1 || \
fail "Could not launch the managed dirmngr ${expected_version}."
running_dirmngr_version="$(
"${GPG_CONNECT_AGENT_BIN}" --dirmngr 'GETINFO version' /bye 2>/dev/null |
awk '$1 == "D" { print $2; exit }' || true
)"
[[ "${running_dirmngr_version}" == "${expected_version}" ]] || \
fail "Expected dirmngr ${expected_version}, but socket reports ${running_dirmngr_version:-unknown}."
fi
fi
sync_github_gpg_public_keys
# Refresh the smart-card inventory before SSH asks the agent for keys. This
# is important after changing applets or swapping among several YubiKeys.
"${GPG_CONNECT_AGENT_BIN}" 'SCD SERIALNO --all' /bye >/dev/null 2>&1 || true
socket="$("${GPGCONF_BIN}" --list-dirs agent-ssh-socket 2>/dev/null || true)"
[[ -n "${socket}" ]] || return 0
export SSH_AUTH_SOCK="${socket}"
# Point setup's Git and Nix input fetches at gpg-agent even before the
# generated SSH config is active. Conventional default identity files remain
# available as migration fallbacks because IdentitiesOnly is disabled.
if [[ -z "${GIT_SSH_COMMAND:-}" ]]; then
ssh_executable="$(command -v ssh)"
if [[ "$(uname -s)" == "Linux" && -x /usr/bin/ssh ]]; then
# Ubuntu's client supports the GSSAPI options in /etc/ssh/ssh_config;
# the standard Nixpkgs build does not.
ssh_executable=/usr/bin/ssh
fi
printf -v setup_git_ssh_command \
'%q -o IdentityAgent=%q -o IdentitiesOnly=no' \
"${ssh_executable}" "${socket}"
export GIT_SSH_COMMAND="${setup_git_ssh_command}"
fi
if [[ -t 0 ]]; then
export GPG_TTY
GPG_TTY="$(tty)"
"${GPG_CONNECT_AGENT_BIN}" --quiet updatestartuptty /bye >/dev/null 2>&1 || true
fi
}
register_github_ssh_key() (
local authenticated_user auth_fingerprint card_status gh_bin gh_root github_keys
local delay key_file public_key serial ssh_key title
download_github_ssh_keys() {
curl --fail --silent --show-error --location \
--header 'Cache-Control: no-cache' \
--proto '=https' --tlsv1.2 --connect-timeout 10 --max-time 30 \
"https://github.com/${GITHUB_USER}.keys" --output "${github_keys}"
}
github_ssh_key_is_registered() {
download_github_ssh_keys && \
awk 'NF >= 2 { print $1 " " $2 }' "${github_keys}" |
grep -Fqx -- "${ssh_key}"
}
command -v curl >/dev/null 2>&1 || fail "curl is required to inspect GitHub SSH keys."
prepare_gpg_ssh_agent
card_status="$("${GPG_BIN}" --with-colons --card-status 2>/dev/null)" || \
fail "GnuPG could not read an OpenPGP card. Insert exactly one configured YubiKey and retry."
serial="$(awk -F: '$1 == "serial" { print $2; exit }' <<< "${card_status}")"
auth_fingerprint="$(awk -F: '$1 == "fpr" && NF >= 4 { print $4; exit }' <<< "${card_status}")"
[[ -n "${serial}" && -n "${auth_fingerprint}" ]] || \
fail "The connected YubiKey does not report an OpenPGP authentication key. Run ${SETUP_PATH} yubikey-setup first."
public_key="$("${GPG_BIN}" --export-ssh-key "${auth_fingerprint}!" 2>/dev/null)" || \
fail "Could not convert OpenPGP authentication key ${auth_fingerprint} to an SSH public key."
ssh_key="$(awk 'NF >= 2 { print $1 " " $2; exit }' <<< "${public_key}")"
[[ -n "${ssh_key}" ]] || fail "GnuPG returned an empty SSH public key."
github_keys="$(mktemp "${TMPDIR:-/tmp}/dotfiles-github-keys.XXXXXX")"
key_file="$(mktemp "${TMPDIR:-/tmp}/dotfiles-yubikey-ssh.XXXXXX")"
trap 'rm -f -- "${github_keys:-}" "${key_file:-}"' EXIT
printf '%s\n' "${public_key}" > "${key_file}"
if github_ssh_key_is_registered; then
info "YubiKey ${serial}'s OpenPGP authentication key is already registered with GitHub user ${GITHUB_USER}"
return 0
fi
gh_bin="$(command -v gh 2>/dev/null || true)"
if [[ -z "${gh_bin}" ]]; then
load_nix || fail "GitHub CLI is not installed and Nix is unavailable to load it. Install gh, then retry."
info "Loading GitHub CLI from Nix for this registration"
gh_root="$(
nix --extra-experimental-features 'nix-command flakes' build \
--no-link --print-out-paths 'github:NixOS/nixpkgs/nixos-26.05#gh'
)" || fail "Nix could not provide GitHub CLI. Check network access and retry."
gh_bin="${gh_root}/bin/gh"
fi
if ! "${gh_bin}" auth status --hostname github.com >/dev/null 2>&1; then
[[ -t 0 ]] || \
fail "GitHub CLI is not authenticated. Run gh auth login --hostname github.com, then retry."
info "Opening GitHub CLI authentication; sign in as ${GITHUB_USER}"
"${gh_bin}" auth login --hostname github.com --web --skip-ssh-key \
--scopes admin:public_key || \
fail "GitHub CLI authentication did not complete."
fi
authenticated_user="$("${gh_bin}" api user --jq .login 2>/dev/null || true)"
[[ "${authenticated_user}" == "${GITHUB_USER}" ]] || \
fail "GitHub CLI is authenticated as ${authenticated_user:-unknown}, but setup is configured for ${GITHUB_USER}. Run gh auth switch --hostname github.com --user ${GITHUB_USER}, then retry."
title="YubiKey ${serial} OpenPGP ($(hostname -s 2>/dev/null || hostname))"
info "Registering YubiKey ${serial}'s OpenPGP authentication key with GitHub user ${GITHUB_USER}"
if ! "${gh_bin}" ssh-key add "${key_file}" --type authentication --title "${title}"; then
fail "GitHub rejected the key registration. Run gh auth refresh --hostname github.com --scopes admin:public_key, then retry."
fi
# Public key endpoints can lag briefly behind a successful API write. Retry
# for a few seconds so normal propagation is not reported as a failure.
for delay in 0 1 2 3 4; do
(( delay == 0 )) || sleep "${delay}"
github_ssh_key_is_registered && break
done
github_ssh_key_is_registered || \
fail "GitHub accepted the request but did not publish the key for ${GITHUB_USER}. Check gh ssh-key list before retrying secrets access."
info "GitHub SSH registration succeeded; ${SETUP_PATH} pull-secrets can now authenticate with this YubiKey"
)
prepare_darwin_nix_mountpoint() {
local backup_path="" synthetic_tmp
[[ "$(uname -s)" == "Darwin" ]] || return 0
if [[ -L /nix ]]; then
fail "/nix is a symlink to $(/usr/bin/readlink /nix). Remove the conflicting synthetic link and reboot before installing Nix."
fi
synthetic_tmp="$(/usr/bin/mktemp "${TMPDIR:-/tmp}/synthetic-conf.XXXXXX")"
if [[ -e /etc/synthetic.conf ]]; then
/usr/bin/awk '
BEGIN { print "nix" }
{
normalized = $0
sub(/\r$/, "", normalized)
if (normalized == "nix" || normalized ~ /^nix[[:space:]]/) next
print $0
}
' /etc/synthetic.conf > "${synthetic_tmp}"
else
printf 'nix\n' > "${synthetic_tmp}"
fi
if [[ -e /etc/synthetic.conf ]] \
&& /usr/bin/cmp -s "${synthetic_tmp}" /etc/synthetic.conf
then
/bin/rm -f "${synthetic_tmp}"
return 0
fi
info "Repairing the macOS /nix synthetic mount-point declaration"
sudo -v || {
/bin/rm -f "${synthetic_tmp}"
fail "Administrator authentication failed; synthetic.conf was not changed."
}
sudo /bin/mkdir -p /var/backups
if [[ -e /etc/synthetic.conf ]]; then
backup_path="/var/backups/dotfiles-synthetic.conf-$(/bin/date +%Y%m%d-%H%M%S)-$$"
sudo /bin/cp -p /etc/synthetic.conf "${backup_path}"
fi
sudo /usr/bin/install -o root -g wheel -m 0644 \
"${synthetic_tmp}" /etc/synthetic.conf
/bin/rm -f "${synthetic_tmp}"
{
/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -t || true
/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs.util -B || true
} >/dev/null 2>&1
/usr/bin/grep -q '^nix$' /etc/synthetic.conf || \
fail "Could not create an exact nix entry in /etc/synthetic.conf."
if [[ -n "${backup_path}" ]]; then
info "Previous synthetic.conf saved at ${backup_path}"
fi
}
install_upstream_nix() {
local installer="$1" install_log install_mode status
case "$(uname -s)" in
Darwin)
install_mode="--daemon"
prepare_darwin_nix_mountpoint
;;
Linux)
if [[ -d /run/systemd/system ]]; then
install_mode="--daemon"
else
install_mode="--no-daemon"
fi
;;
*)
fail "The upstream Nix installer is unsupported on $(uname -s)."
;;
esac
if [[ "$(uname -s)" != "Darwin" ]]; then
NIX_INSTALLER_NO_CHANNEL_ADD=1 NIX_INSTALLER_YES=1 \
/bin/sh "${installer}" "${install_mode}"
return $?
fi
install_log="$(/usr/bin/mktemp "${TMPDIR:-/tmp}/upstream-nix-install.XXXXXX")"
if NIX_INSTALLER_NO_CHANNEL_ADD=1 NIX_INSTALLER_YES=1 \
/bin/sh "${installer}" "${install_mode}" \
2> >(/usr/bin/tee "${install_log}" >&2)
then
/bin/rm -f "${install_log}"
return 0
else
status=$?
fi
if ! /usr/bin/grep -Fq 'failed to configure synthetic.conf' "${install_log}"; then
/bin/rm -f "${install_log}"
return "${status}"
fi
warn "The Nix installer removed the repaired synthetic entry during cleanup; restoring it and retrying once."
/bin/rm -f "${install_log}"
prepare_darwin_nix_mountpoint
NIX_INSTALLER_NO_CHANNEL_ADD=1 NIX_INSTALLER_YES=1 \
/bin/sh "${installer}" "${install_mode}"
}
install_nix() {
command -v curl >/dev/null 2>&1 || fail "curl is required to install Nix."
local installer
installer="$(mktemp)"
info "Nix is not installed; downloading the official upstream Nix installer"
if ! curl --fail --silent --show-error --location \
--proto '=https' --tlsv1.2 "${NIX_INSTALL_URL}" --output "${installer}"
then
rm -f -- "${installer}"
fail "Could not download the Nix installer."
fi
if ! install_upstream_nix "${installer}"; then
rm -f -- "${installer}"
fail "Nix installation failed."
fi
rm -f -- "${installer}"
load_nix || fail "Nix installed, but this shell could not load it. Open a new terminal and verify it with nix --version."
}
system_curl() {
local candidate resolved
for candidate in /usr/bin/curl /bin/curl; do
[[ -x "${candidate}" ]] && { printf '%s\n' "${candidate}"; return 0; }
done
candidate="$(command -v curl 2>/dev/null || true)"
[[ -n "${candidate}" ]] || return 1
resolved="$(readlink -f "${candidate}" 2>/dev/null || printf '%s' "${candidate}")"
[[ "${resolved}" != /nix/* ]] || return 1
printf '%s\n' "${candidate}"
}
nix_darwin_remnants_present() {
[[ -L /etc/static || -L /run/current-system \
|| -e /Library/LaunchDaemons/org.nixos.activate-system.plist \
|| -e /Library/LaunchDaemons/org.nixos.activate-agenix.plist \
|| -e /Library/LaunchDaemons/org.nixos.nix-gc.plist ]]
}
recover_upstream_nix() {
local backup_root confirmation current_uid current_user daemon_plist profile_root
local config_tmp synthetic_tmp target path backup_source label
profile_root="/nix/var/nix/profiles/default"
daemon_plist="${profile_root}/Library/LaunchDaemons/org.nixos.nix-daemon.plist"
current_uid="$(/usr/bin/id -u)"
current_user="$(/usr/bin/id -un)"
[[ "$(uname -s)" == "Darwin" ]] || \
fail "The nix-darwin recovery is available only on macOS."
[[ -x "${profile_root}/bin/nix" \
&& -r "${profile_root}/etc/profile.d/nix-daemon.sh" \
&& -r "${daemon_plist}" ]] || \
fail "The installer-owned upstream Nix profile is incomplete; automatic recovery was stopped."
for path in /etc/bashrc /etc/zshenv /etc/zprofile /etc/zshrc; do
if [[ -L "${path}" ]]; then
target="$(/usr/bin/readlink "${path}")"
[[ "${target}" == /etc/static/* ]] || \
fail "Refusing to replace unexpected symlink ${path} -> ${target}."
backup_source="${path}.before-nix-darwin"
[[ -r "${backup_source}" ]] || \
fail "Cannot recover ${path}; expected backup ${backup_source} is missing."
fi
done
if [[ -L /etc/static ]]; then
target="$(/usr/bin/readlink /etc/static)"
[[ "${target}" == /nix/store/*-etc/etc ]] || \
fail "Refusing to remove unexpected /etc/static symlink target ${target}."
fi
if [[ -L /run/current-system ]]; then
target="$(/usr/bin/readlink /run/current-system)"
[[ "${target}" == /nix/store/*-darwin-system-* ]] || \
fail "Refusing to remove unexpected /run/current-system target ${target}."
fi
printf 'A usable upstream Nix profile already exists in the current store.\n'
printf 'This recovery preserves /nix, removes verified nix-darwin services and links,\n'
printf 'and switches the daemon and shell startup files to upstream Nix.\n'
IFS= read -r -p "Type 'recover' to continue, or press Enter to cancel: " confirmation || true
if [[ "${confirmation}" != "recover" ]]; then
info "Upstream Nix recovery cancelled"
return 0
fi
sudo -v || fail "Administrator authentication failed; recovery was not started."
backup_root="/var/backups/dotfiles-upstream-nix-$(/bin/date +%Y%m%d-%H%M%S)"
sudo /bin/mkdir -p "${backup_root}"
backup_path() {
local source="$1" destination="${backup_root}$1"
if [[ -e "${source}" || -L "${source}" ]]; then
sudo /bin/mkdir -p "$(/usr/bin/dirname "${destination}")"
sudo /bin/mv "${source}" "${destination}"
fi
}
copy_to_backup() {
local source="$1" destination="${backup_root}$1"
if [[ -e "${source}" || -L "${source}" ]]; then
sudo /bin/mkdir -p "$(/usr/bin/dirname "${destination}")"
sudo /bin/cp -pPR "${source}" "${destination}"
fi
}
info "Stopping nix-darwin user services"
for label in org.nixos.emacs org.nixos.skhd; do
path="${HOME}/Library/LaunchAgents/${label}.plist"
/bin/launchctl bootout "gui/${current_uid}/${label}" >/dev/null 2>&1 || true
backup_path "${path}"
done
info "Removing nix-darwin system services"
for label in org.nixos.activate-agenix org.nixos.activate-system org.nixos.nix-gc; do
sudo /bin/launchctl bootout "system/${label}" >/dev/null 2>&1 || true
backup_path "/Library/LaunchDaemons/${label}.plist"
done
if [[ -e /Library/LaunchDaemons/systems.determinate.nix-installer.nix-hook.plist ]]; then
sudo /bin/launchctl bootout system/systems.determinate.nix-installer.nix-hook \
>/dev/null 2>&1 || true
backup_path /Library/LaunchDaemons/systems.determinate.nix-installer.nix-hook.plist
fi
info "Restoring installer-owned shell startup files"
for path in /etc/bashrc /etc/zshenv /etc/zprofile /etc/zshrc; do
if [[ -L "${path}" ]]; then
backup_source="${path}.before-nix-darwin"
backup_path "${path}"
sudo /bin/cp -p "${backup_source}" "${path}"
fi
done
for path in /etc/skhdrc /etc/terminfo /etc/pam.d/sudo_local; do
if [[ -L "${path}" ]]; then
target="$(/usr/bin/readlink "${path}")"
if [[ "${target}" == /etc/static/* ]]; then
backup_path "${path}"
else
fail "Refusing to remove unexpected symlink ${path} -> ${target}."
fi
fi
done
info "Installing a standalone upstream Nix configuration"
config_tmp="$(/usr/bin/mktemp "${TMPDIR:-/tmp}/upstream-nix-conf.XXXXXX")"
{
printf 'build-users-group = nixbld\n'
printf 'experimental-features = nix-command flakes\n'
printf 'ssl-cert-file = %s/etc/ssl/certs/ca-bundle.crt\n' "${profile_root}"
printf 'trusted-users = root @admin %s\n' "${current_user}"
} > "${config_tmp}"
backup_path /etc/nix/nix.conf
sudo /bin/mkdir -p /etc/nix
sudo /usr/bin/install -o root -g wheel -m 0644 "${config_tmp}" /etc/nix/nix.conf
/bin/rm -f "${config_tmp}"
if [[ -L /etc/ssl/certs/ca-certificates.crt ]]; then
target="$(/usr/bin/readlink /etc/ssl/certs/ca-certificates.crt)"
if [[ "${target}" == /etc/static/* ]]; then
backup_path /etc/ssl/certs/ca-certificates.crt
sudo /bin/ln -s \
"${profile_root}/etc/ssl/certs/ca-bundle.crt" \
/etc/ssl/certs/ca-certificates.crt
fi
fi
if [[ -e /etc/synthetic.conf ]]; then
synthetic_tmp="$(/usr/bin/mktemp "${TMPDIR:-/tmp}/synthetic-conf.XXXXXX")"
/usr/bin/awk 'BEGIN { print "nix" } $0 == "nix" { next } $1 == "run" && $2 == "private/var/run" { next } { print }' \
/etc/synthetic.conf > "${synthetic_tmp}"
if ! /usr/bin/cmp -s "${synthetic_tmp}" /etc/synthetic.conf; then
copy_to_backup /etc/synthetic.conf
sudo /usr/bin/install -o root -g wheel -m 0644 \
"${synthetic_tmp}" /etc/synthetic.conf
fi
/bin/rm -f "${synthetic_tmp}"
fi
info "Switching to the upstream Nix daemon"
sudo /bin/launchctl bootout system/org.nixos.nix-daemon >/dev/null 2>&1 || true
copy_to_backup /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo /bin/cp "${daemon_plist}" /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo /usr/sbin/chown root:wheel /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo /bin/chmod 0644 /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo /bin/launchctl bootstrap system /Library/LaunchDaemons/org.nixos.nix-daemon.plist
sudo /bin/launchctl kickstart -k system/org.nixos.nix-daemon
backup_path /Applications/Nix\ Apps
backup_path /run/current-system
backup_path /etc/static
backup_path /nix/receipt.json
backup_path /nix/nix-installer
export PATH="${profile_root}/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH}"
unset __NIX_DARWIN_SET_ENVIRONMENT_DONE __ETC_PROFILE_NIX_SOURCED || true
hash -r
nix --version >/dev/null 2>&1 || \
fail "Recovery completed, but the upstream Nix client did not start. Backup: ${backup_root}"
nix store info >/dev/null 2>&1 || \
fail "Recovery completed, but the upstream Nix daemon did not respond. Backup: ${backup_root}"
info "Upstream Nix recovery completed; backup saved at ${backup_root}"
warn "Open a new terminal so it no longer inherits nix-darwin environment variables."
warn "Reboot macOS when convenient to remove the obsolete /run synthetic link."
}
reinstall_nix() {
local current_version installer curl_command confirmation darwin_uninstaller=""
current_version="$(nix --version 2>/dev/null || printf 'an unknown Nix version')"
printf 'Nix is already installed: %s\n' "${current_version}"
printf '\033[1;33mA full reinstall removes the Nix store, installed packages, and system generations.\033[0m\n'
printf 'Your dotfiles repository is outside the Nix store and will not be removed.\n'
printf 'nix-darwin will remain uninstalled; only upstream Nix will be installed.\n'
IFS= read -r -p "Type 'reinstall' to continue, or press Enter to cancel: " confirmation || true
if [[ "${confirmation}" != "reinstall" ]]; then
info "Nix reinstall cancelled"
return 0
fi
[[ -x /nix/nix-installer && -f /nix/receipt.json ]] || \
fail "This Nix installation has no Determinate installer receipt, so setup will not remove it automatically. Follow the installer-specific uninstall instructions instead."
curl_command="$(system_curl)" || \
fail "A curl executable outside /nix is required before the Nix store can be removed."
installer="$(mktemp)"