Files
omarchy_setup/modules/ssh-keyring.sh
google-labs-jules[bot] f91ab3bd6e Fix: Improve GNOME Keyring Socket Detection (#9)
* feat: add dev tools, AI aliases, and improve zshrc documentation

This commit introduces several new features and improvements:

- **Adds Development Tools to `apps.sh`:** The `apps.sh` module now installs essential development tools, including `python`, `pip`, `nodejs`, `npm`, `uv`, and `nvm`.

- **Implements `.zshrc.local` for Private Variables:**
  - A `.zshrc.local.example` file has been added to serve as a template for users to securely store their private environment variables, such as API keys.
  - The main `.zshrc` file now sources `.zshrc.local` if it exists.

- **Adds AI Aliases to `.zshrc`:** A new section has been added to `.zshrc` with example aliases for interacting with command-line AI tools.

- **Improves `.zshrc` Documentation:** The `.zshrc` file has been thoroughly documented with comments in Spanish, explaining the purpose of each section. The title has also been updated and professionalized.

- **Fixes a Regression:** This commit restores the `ytm`, `ytv`, `ytls`, and SSH agent functions in `.zshrc` that were accidentally removed in a previous step.

* feat: improve keyring UX and icon manager flow

This commit introduces two main improvements to the user experience:

1.  **Refactors the Icon Manager for Non-Interactive Installation:**
    - The `icon_manager.sh` module can now be run in a non-interactive mode.
    - The "Install All" process has been updated to use this non-interactive mode, which installs the default icon theme without pausing the script or requiring user input.

2.  **Improves the GNOME Keyring Workflow:**
    - The script no longer errors out if the GNOME Keyring agent is not immediately available after installation.
    - Instead, a clear summary message is now displayed at the end of the "Install All" process, instructing the user to log out and back in, and then run the SSH key synchronization module separately. This provides a much smoother and more intuitive user experience.

* fix: improve GNOME Keyring socket detection

This commit fixes a bug in the `ssh-keyring.sh` module where the GNOME Keyring socket could not be found after a system reboot.

The script now explicitly determines the user's UID to construct the correct path to the socket, instead of relying on the potentially unreliable `$UID` environment variable. This makes the socket detection more robust, especially when the script is run with `sudo`.

* fix: improve GNOME Keyring socket detection

This commit fixes a bug in the `ssh-keyring.sh` module where the GNOME Keyring socket could not be found after a system reboot.

The script now uses the `logname` command to reliably determine the user's UID and construct the correct path to the socket, instead of relying on environment variables that can be unreliable when the script is run with `sudo`. This makes the socket detection more robust.

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: Marco Gallegos <marco.gallegos@outlook.com>
2025-11-19 09:18:14 -06:00

136 lines
4.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# ===============================================================
# ssh-keyring.sh - Sincronizar claves SSH con GNOME Keyring
# ===============================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/common.sh"
_derive_fingerprint() {
local key_path="$1"
local pub_path="${key_path}.pub"
local fingerprint=""
if [[ -f "$pub_path" ]]; then
fingerprint="$(ssh-keygen -lf "$pub_path" 2>/dev/null | awk '{print $2}')"
else
fingerprint="$(ssh-keygen -lf <(ssh-keygen -y -f "$key_path" 2>/dev/null) 2>/dev/null | awk '{print $2}')"
fi
echo "$fingerprint"
}
sync_ssh_keyring() {
log_step "Sincronizar claves SSH con GNOME Keyring"
if ! command_exists gnome-keyring-daemon; then
log_error "gnome-keyring-daemon no está instalado. Ejecuta primero el módulo de aplicaciones."
return 1
fi
if ! command_exists ssh-add; then
log_error "ssh-add no está disponible (openssh). Instala el módulo de aplicaciones antes."
return 1
fi
mkdir -p "${HOME}/.config/environment.d"
cat <<'EOF' > "${HOME}/.config/environment.d/10-gnome-keyring.conf"
SSH_AUTH_SOCK=/run/user/$UID/keyring/ssh
EOF
local keyring_eval=""
if keyring_eval="$(gnome-keyring-daemon --start --components=ssh,secrets 2>/dev/null)"; then
eval "$keyring_eval"
log_success "GNOME Keyring iniciado."
else
log_info "GNOME Keyring ya estaba en ejecución."
fi
local target_uid
target_uid=$(id -u "$(logname)")
local keyring_socket="${SSH_AUTH_SOCK:-/run/user/${target_uid}/keyring/ssh}"
if [[ ! -S "$keyring_socket" ]]; then
log_warning "No se encontró el socket de GNOME Keyring en la ruta esperada."
# Como fallback, intentamos la ruta con el UID del proceso actual.
local fallback_socket="/run/user/$(id -u)/keyring/ssh"
if [[ -S "$fallback_socket" ]]; then
keyring_socket="$fallback_socket"
log_info "Se encontró un socket válido en la ruta de fallback: ${keyring_socket}"
else
log_error "GNOME Keyring no parece estar exponiendo el socket SSH. Asegúrate de haber reiniciado la sesión."
return 1
fi
fi
export SSH_AUTH_SOCK="$keyring_socket"
local ssh_dir="${HOME}/.ssh"
if [[ ! -d "$ssh_dir" ]]; then
log_warning "No existe el directorio ${ssh_dir}. No hay claves para agregar."
return 0
fi
mapfile -t ssh_private_keys < <(
find "$ssh_dir" -maxdepth 1 -type f -perm -u=r \
! -name "*.pub" \
! -name "*-cert.pub" \
! -name "known_hosts" \
! -name "known_hosts.*" \
! -name "authorized_keys" \
! -name "config" \
! -name "*.old" \
! -name "agent" \
! -name "*.bak" \
2>/dev/null | sort
)
if [[ ${#ssh_private_keys[@]} -eq 0 ]]; then
log_warning "No se encontraron claves privadas SSH en ${ssh_dir}."
return 0
fi
local existing_fingerprints=""
if output=$(SSH_AUTH_SOCK="$SSH_AUTH_SOCK" ssh-add -l 2>/dev/null); then
existing_fingerprints="$(awk '{print $2}' <<<"$output")"
else
existing_fingerprints=""
fi
local added=0
for key_path in "${ssh_private_keys[@]}"; do
local fingerprint
fingerprint="$(_derive_fingerprint "$key_path")"
if [[ -z "$fingerprint" ]] && ! ssh-keygen -y -f "$key_path" >/dev/null 2>&1; then
log_warning "El archivo $(basename "$key_path") no parece una clave privada válida. Se omite."
continue
fi
if [[ -n "$fingerprint" ]] && grep -Fq "$fingerprint" <<<"$existing_fingerprints"; then
log_info "Clave $(basename "$key_path") ya está registrada en el keyring."
continue
fi
log_info "Añadiendo clave $(basename "$key_path") al keyring..."
if SSH_AUTH_SOCK="$SSH_AUTH_SOCK" ssh-add "$key_path"; then
log_success "Clave $(basename "$key_path") añadida correctamente."
added=$((added + 1))
if [[ -n "$fingerprint" ]]; then
existing_fingerprints+=$'\n'"$fingerprint"
fi
else
log_warning "No se pudo añadir la clave $(basename "$key_path")."
fi
done
if [[ $added -gt 0 ]]; then
log_success "Claves SSH sincronizadas con GNOME Keyring."
else
log_info "No se añadieron nuevas claves SSH."
fi
log_info "Para verificar, ejecuta: ssh-add -l"
return 0
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
sync_ssh_keyring "$@"
fi