This repository has no description
3.2 kB
95 lines
1#!/usr/bin/env bash
2set -euo pipefail
3
4# age-detect: Detects connected age-compatible security keys
5# Returns identity file path and detected key information
6
7# Function to detect connected security keys and their age identities
8detect_age_keys() {
9 local temp_identities
10 temp_identities=$(mktemp)
11
12 # Check for Secure Enclave on macOS (highest priority)
13 if [[ "$(uname)" == "Darwin" ]] && command -v age-plugin-se >/dev/null 2>&1; then
14 rm -f "$temp_identities"
15 echo "DETECTED_KEY=se"
16 echo "KEY_TYPE=se"
17 return
18 fi
19
20 # Check for TPM on Linux (second priority - built-in, no USB needed)
21 # Requires: TPM device, hostname.age with age1tpm1 recipient, and identity in ~/.config/age/
22 if [[ -c /dev/tpmrm0 ]] && [[ -f ~/.config/age/tpm-identity.txt ]]; then
23 local hostname_key
24 hostname_key="${AGE_DETECT_KEYS_DIR:-}/age/$(hostname).age"
25 if [[ -f "$hostname_key" ]] && grep -q "^age1tpm1" "$hostname_key" 2>/dev/null; then
26 rm -f "$temp_identities"
27 echo "DETECTED_KEY=tpm"
28 echo "KEY_TYPE=tpm"
29 return
30 fi
31 fi
32
33 # Check for YubiKeys (third priority)
34 if command -v ykman >/dev/null 2>&1; then
35 local yubikey_serial
36 yubikey_serial=$(ykman info 2>/dev/null | grep "Serial number:" | cut -d: -f2 | tr -d ' ' || true)
37 if [[ -n "$yubikey_serial" ]]; then
38 echo "AGE-PLUGIN-YUBIKEY-1M2PLUQYZ242EPUSSHDFWJ" > "$temp_identities"
39 echo "IDENTITY_FILE=$temp_identities"
40 case "$yubikey_serial" in
41 "16679898")
42 echo "DETECTED_KEY=yubi1"
43 ;;
44 "11342136")
45 echo "DETECTED_KEY=yubi2"
46 ;;
47 *)
48 echo "DETECTED_KEY=yubikey-${yubikey_serial}"
49 ;;
50 esac
51 echo "KEY_TYPE=yubikey"
52 return
53 fi
54 fi
55
56 # Check for Solo2 (lowest priority)
57 if command -v fido2-token >/dev/null 2>&1; then
58 if fido2-token -L 2>/dev/null | grep -q "Solo 2"; then
59 # FIDO2-HMAC doesn't use identity file
60 rm -f "$temp_identities"
61 echo "IDENTITY_FILE="
62 echo "DETECTED_KEY=solo2"
63 echo "KEY_TYPE=solo2"
64 return
65 fi
66 fi
67
68 # No keys detected
69 rm -f "$temp_identities"
70 echo "IDENTITY_FILE="
71 echo "DETECTED_KEY="
72 echo "KEY_TYPE="
73}
74
75# Parse command line arguments
76case "${1:-detect}" in
77 detect)
78 detect_age_keys
79 ;;
80 --help|-h)
81 echo "Usage: age-detect [detect]"
82 echo ""
83 echo "Detects the first available age-compatible security key and outputs:"
84 echo " IDENTITY_FILE=<path> - Path to temporary identity file for age (empty for Solo2)"
85 echo " DETECTED_KEY=<name> - Name of the detected key (e.g., yubi1, solo2, se)"
86 echo " KEY_TYPE=<type> - Type of key (yubikey, solo2, se)"
87 echo ""
88 echo "Priority order: se > tpm > yubikey > solo2"
89 ;;
90 *)
91 echo "Unknown command: $1" >&2
92 echo "Use --help for usage information" >&2
93 exit 1
94 ;;
95esac