#!/usr/bin/env bash # # fido — autenticação SSH com duas YubiKeys, no GitHub e em servidores. # # Credenciais esperadas no token: # YUC (USB-C): comentário "github-yuc" ou "server-yuc" # YUA (USB-A): comentário "github-yua" ou "server-yua" # # Sem argumentos, pergunta no terminal com uma lista numerada. # Com --batch, executa o comando informado sem menu. Use --batch help. # set -Eeuo pipefail if [[ -z "${HOME:-}" ]]; then printf 'Erro: HOME não está definido.\n' >&2 exit 1 fi APP="fido" SSH_DIR="${HOME}/.ssh" CONFIG_FILE="${SSH_DIR}/fido.conf" MAIN_CONFIG="${SSH_DIR}/config" INCLUDE_LINE='Include ~/.ssh/fido.conf' LEGACY_CONFIG_FILE="${SSH_DIR}/yubikey-github.conf" LEGACY_INCLUDE_LINE='Include ~/.ssh/yubikey-github.conf' SERVER_HOSTS="${SSH_DIR}/fido-server.hosts" SERVER_FAVS="${SSH_DIR}/fido-server.favs" LEGACY_SERVER_HOSTS="${SSH_DIR}/yubikey-server.hosts" RECENT_LIMIT=6 YK_SERIAL="" YK_MULTI=0 CONNECTED_LABELS=() CONNECTED_MODELS=() CONNECTED_SERIALS=() CONNECTED_SCANNED=0 ACCOUNT="" ACCOUNTS_FILE="${SSH_DIR}/fido-github.accounts" SERVER_NAME="" SERVER_ACCOUNTS_FILE="${SSH_DIR}/fido-server.accounts" USE_COLOR=1 if [[ -n "${NO_COLOR:-}" || "${TERM:-}" == "dumb" ]]; then USE_COLOR=0 fi paint() { local code="$1" shift if (( USE_COLOR )); then printf '\033[%sm%s\033[0m' "$code" "$*" else printf '%s' "$*" fi } die() { printf '%s %s\n' "$(paint '1;31' 'Erro:')" "$*" >&2 exit 1 } info() { printf '%s %s\n' "$(paint '36' '➜')" "$*"; } ok() { printf '%s %s\n' "$(paint '1;32' '✓')" "$*"; } warn() { printf '%s %s\n' "$(paint '33' 'Aviso:')" "$*" >&2; } label_name() { case "$1" in yuc) printf 'YUC' ;; yua) printf 'YUA' ;; *) printf '%s' "$1" ;; esac } usage() { cat <<'EOF' fido — helper para autenticação SSH com duas YubiKeys Sem argumentos, pergunta no terminal o que fazer. Para executar direto, use a flag --batch: --batch create [conta] 1|2|yuc|yua [série] Cria a credencial da conta no token --batch add [conta] 1|2|yuc|yua Recupera a chave da conta no token conectado --batch use [conta] 1|2|yuc|yua Ativa essa conta em git@github.com --batch test Autentica em git@github.com com a chave ativa --batch pub [conta] Mostra as chaves públicas da conta --batch pub [conta] 1|2|yuc|yua Mostra e copia a chave escolhida --batch undo Remove só o que este helper gravou neste computador --batch status Mostra a configuração ativa --batch list Lista chaves recuperadas neste computador --batch server-create [nome] 1|2|yuc|yua [série] Cria a credencial residente para servidor --batch server-add [nome] 1|2|yuc|yua Recupera a credencial de servidor do token --batch server-install [nome] 1|2 user@ip Instala a chave pública no servidor --batch server-connect [nome] 1|2 user@ip Abre ssh com a chave do token --batch server-pub [nome] Mostra o comando para o authorized_keys --batch server-pub [nome] 1|2|yuc|yua Mostra e copia o comando da chave escolhida --batch server-undo Remove só as chaves de servidor deste computador --batch help Mostra esta ajuda Pela URL, no macOS ou Linux: curl -fsSL https://fido.polidev.cloud/script | bash curl -fsSL https://fido.polidev.cloud/script | bash -s -- --batch use yuc O nome escolhe a conta do GitHub. Cada YubiKey dessa conta precisa da própria chave pública cadastrada nela. Exemplo: --batch create trabalho 1 Sem nome, --batch create 1 grava a credencial github-yuc. Com mais de uma YubiKey no Criar, a série vai no fim. Exemplo: --batch create trabalho 1 12345678 A recuperação pede PIN e toque na YubiKey. O nome do servidor funciona como a conta do GitHub. Exemplo: --batch server-create casa 1 Sem nome, --batch server-create 1 grava a credencial server-yuc. O handle local fica em ~/.ssh. A credencial continua na YubiKey. EOF } require_tty() { # -r /dev/tty só olha a permissão do dispositivo. Sem terminal de controle, # a abertura falha com "No such device or address". if ! { : /dev/null 2>&1; then die "Terminal interativo não encontrado. Use --batch para executar sem perguntas." fi } tty_say() { require_tty printf '%s\n' "$1" >/dev/tty } tty_prompt() { local answer require_tty printf '%s' "$1" >/dev/tty IFS= read -r answer /dev/null 2>&1 || die "Comando necessário não encontrado: ${cmd}" done } require_openssh_sk() { local banner major minor banner="$(ssh -V 2>&1 || true)" major="$(printf '%s\n' "$banner" | sed -n 's/.*OpenSSH_\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\1/p')" minor="$(printf '%s\n' "$banner" | sed -n 's/.*OpenSSH_\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\2/p')" if [[ -z "$major" || -z "$minor" ]]; then warn "Não foi possível detectar a versão do OpenSSH. É necessário 8.2 ou mais recente para chaves FIDO." return 0 fi if (( major > 8 || (major == 8 && minor >= 2) )); then return 0 fi die "OpenSSH ${major}.${minor} não recupera credenciais residentes. É necessário OpenSSH 8.2 ou mais recente." } validate_label() { case "${1:-}" in 1|yuc) LABEL="yuc" ;; 2|yua) LABEL="yua" ;; *) die "Informe 1 (YUC, USB-C) ou 2 (YUA, USB-A). Exemplo: --batch add 1" ;; esac if [[ -n "${ACCOUNT:-}" ]]; then COMMENT="github-${ACCOUNT}-${LABEL}" else COMMENT="github-${LABEL}" fi } valid_account_name() { [[ "${1:-}" =~ ^[a-z0-9][a-z0-9-]{0,31}$ ]] } normalize_account_name() { printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' } set_account() { local name name="$(normalize_account_name "${1:-}")" if [[ -z "$name" ]]; then ACCOUNT="" return 0 fi valid_account_name "$name" || die "Nome de conta inválido: ${name}. Use letras minúsculas, números e hífen. Exemplo: trabalho" ACCOUNT="$name" } remember_account() { local line [[ -n "${ACCOUNT:-}" ]] || return 0 ensure_ssh_dir touch "$ACCOUNTS_FILE" chmod 600 "$ACCOUNTS_FILE" if [[ -f "$ACCOUNTS_FILE" ]]; then while IFS= read -r line || [[ -n "$line" ]]; do [[ "$line" == "$ACCOUNT" ]] && return 0 done < "$ACCOUNTS_FILE" fi printf '%s\n' "$ACCOUNT" >> "$ACCOUNTS_FILE" } remember_server_name() { local line [[ -n "${SERVER_NAME:-}" ]] || return 0 ensure_ssh_dir touch "$SERVER_ACCOUNTS_FILE" chmod 600 "$SERVER_ACCOUNTS_FILE" if [[ -f "$SERVER_ACCOUNTS_FILE" ]]; then while IFS= read -r line || [[ -n "$line" ]]; do [[ "$line" == "$SERVER_NAME" ]] && return 0 done < "$SERVER_ACCOUNTS_FILE" fi printf '%s\n' "$SERVER_NAME" >> "$SERVER_ACCOUNTS_FILE" } set_server_name() { local name name="$(normalize_account_name "${1:-}")" if [[ -z "$name" ]]; then SERVER_NAME="" return 0 fi valid_account_name "$name" || die "Nome inválido: ${name}. Use letras minúsculas, números e hífen. Exemplo: casa" SERVER_NAME="$name" remember_server_name } read_server_names() { local line SERVER_NAMES=() [[ -f "$SERVER_ACCOUNTS_FILE" ]] || return 0 while IFS= read -r line || [[ -n "$line" ]]; do line="$(normalize_account_name "$(trim "$line")")" valid_account_name "$line" || continue SERVER_NAMES+=("$line") done < "$SERVER_ACCOUNTS_FILE" } # O primeiro argumento é 1|2 ou o nome. A série ou user@ip fica depois da YubiKey. parse_server_args() { local require_label="${1:-required}" shift || true local first="${1:-}" second="${2:-}" third="${3:-}" SERVER_NAME="" SV_LABEL="" SV_SERIAL="" SV_TARGET="" if [[ -z "$first" ]]; then if [[ "$require_label" == required ]]; then die "Informe a YubiKey ou o nome. Exemplo: --batch server-create casa 1" fi return 0 fi if is_key_label "$first"; then SV_LABEL="$first" if valid_ssh_target "${second:-}"; then SV_TARGET="$second" else SV_SERIAL="${second:-}" fi return 0 fi set_server_name "$first" if [[ -z "$second" ]]; then if [[ "$require_label" == required ]]; then die "Informe a YubiKey depois do nome. Exemplo: --batch server-create ${SERVER_NAME} 1" fi return 0 fi if ! is_key_label "$second"; then die "Informe a YubiKey depois do nome. Exemplo: --batch server-create ${SERVER_NAME} 1" fi SV_LABEL="$second" if valid_ssh_target "${third:-}"; then SV_TARGET="$third" else SV_SERIAL="${third:-}" fi } is_key_label() { case "${1:-}" in 1|2|yuc|yua) return 0 ;; *) return 1 ;; esac } # O primeiro argumento é 1|2 ou o nome da conta. A série, se houver, fica por último. parse_github_args() { local first="${1:-}" second="${2:-}" third="${3:-}" GH_LABEL="" GH_SERIAL="" ACCOUNT="" if [[ -z "$first" ]]; then die "Informe a YubiKey ou o nome da conta. Exemplo: --batch create trabalho 1" fi if is_key_label "$first"; then GH_LABEL="$first" GH_SERIAL="$second" return 0 fi set_account "$first" is_key_label "$second" || die "Informe a YubiKey depois do nome. Exemplo: --batch create ${ACCOUNT} 1" GH_LABEL="$second" GH_SERIAL="$third" } parse_pub_args() { local first="${1:-}" second="${2:-}" GH_LABEL="" ACCOUNT="" if [[ -z "$first" ]]; then return 0 fi if is_key_label "$first"; then GH_LABEL="$first" return 0 fi set_account "$first" if [[ -n "$second" ]]; then is_key_label "$second" || die "Informe a YubiKey depois do nome. Exemplo: --batch pub ${ACCOUNT} 1" GH_LABEL="$second" fi } key_path() { local label="$1" local account="${2-${ACCOUNT:-}}" if [[ -n "$account" ]]; then printf '%s/%s_%s_github_id_ed25519_sk' "$SSH_DIR" "$account" "$label" else printf '%s/%s_github_id_ed25519_sk' "$SSH_DIR" "$label" fi } legacy_github_keys_present() { [[ -e "$(key_path yuc "")" || -e "$(key_path yuc "").pub" || -e "$(key_path yua "")" || -e "$(key_path yua "").pub" ]] } read_account_names() { local line ACCOUNT_NAMES=() [[ -f "$ACCOUNTS_FILE" ]] || return 0 while IFS= read -r line || [[ -n "$line" ]]; do line="$(normalize_account_name "$(trim "$line")")" valid_account_name "$line" || continue ACCOUNT_NAMES+=("$line") done < "$ACCOUNTS_FILE" } # Define ID_ACCOUNT e ID_LABEL a partir do arquivo da identidade. parse_identity_path() { local base ID_ACCOUNT="" ID_LABEL="" base="$(basename "${1:-}")" case "$base" in yuc_github_id_ed25519_sk) ID_LABEL="yuc"; return 0 ;; yua_github_id_ed25519_sk) ID_LABEL="yua"; return 0 ;; esac if [[ "$base" =~ ^([a-z0-9][a-z0-9-]{0,31})_(yuc|yua)_github_id_ed25519_sk$ ]]; then ID_ACCOUNT="${BASH_REMATCH[1]}" ID_LABEL="${BASH_REMATCH[2]}" fi } active_account_text() { local identity="$1" parse_identity_path "$identity" if [[ -z "$ID_LABEL" ]]; then printf 'Chave ativa: %s' "$identity" return 0 fi if [[ -n "$ID_ACCOUNT" ]]; then printf 'Conta ativa: %s (%s)' "$ID_ACCOUNT" "$(label_name "$ID_LABEL")" else printf 'Conta ativa: sem nome (%s)' "$(label_name "$ID_LABEL")" fi } read_identity() { local raw [[ -f "$CONFIG_FILE" ]] || return 0 raw="$(awk '$1 == "IdentityFile" { $1=""; sub(/^[[:space:]]+/, ""); print; exit }' "$CONFIG_FILE")" raw="${raw#\"}" raw="${raw%\"}" printf '%s' "$raw" } place_file() { local mode="$1" src="$2" dest="$3" if command -v install >/dev/null 2>&1; then install -m "$mode" "$src" "$dest" return 0 fi cp "$src" "$dest" chmod "$mode" "$dest" } ensure_ssh_dir() { mkdir -p "$SSH_DIR" chmod 700 "$SSH_DIR" } ensure_include() { touch "$MAIN_CONFIG" chmod 600 "$MAIN_CONFIG" # O Include no início faz a identidade selecionada prevalecer sobre # configurações Host github.com que apareçam depois no arquivo. if grep -Fqx "$INCLUDE_LINE" "$MAIN_CONFIG"; then return 0 fi local tmp tmp="$(mktemp "${TMPDIR:-/tmp}/fido.XXXXXX")" { printf '%s\n' "$INCLUDE_LINE" cat "$MAIN_CONFIG" } > "$tmp" cat "$tmp" > "$MAIN_CONFIG" rm -f "$tmp" } write_config() { local identity="$1" cat > "$CONFIG_FILE" </dev/null 2>&1; then pbcopy < "$file" || return 1 elif command -v wl-copy >/dev/null 2>&1; then wl-copy < "$file" || return 1 elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard < "$file" || return 1 elif command -v xsel >/dev/null 2>&1; then xsel --clipboard --input < "$file" || return 1 elif command -v clip.exe >/dev/null 2>&1; then clip.exe < "$file" || return 1 else return 1 fi } copy_text() { local text="$1" tmp status tmp="$(mktemp)" printf '%s\n' "$text" > "$tmp" copy_clipboard "$tmp" && status=0 || status=1 rm -f "$tmp" return "$status" } authorized_keys_install_command() { local pub="$1" key q IFS= read -r key < "$pub" || return 1 key="${key%$'\r'}" [[ -n "$key" ]] || return 1 q="${key//\'/\'\\\'\'}" printf '%s\n' "key='${q}' && { case \"\$key\" in sk-*|ssh-*|ecdsa-*) ;; COLE_A_CHAVE_PUBLICA) echo \"Substitua COLE_A_CHAVE_PUBLICA pela linha da chave pública.\"; exit 1 ;; *) echo \"A chave precisa ser a linha pública, começando com sk-, ssh- ou ecdsa-.\"; exit 1 ;; esac; } && mkdir -p -- \"\$HOME/.ssh\" && chmod 700 \"\$HOME/.ssh\" && touch \"\$HOME/.ssh/authorized_keys\" && chmod 600 \"\$HOME/.ssh/authorized_keys\" && { grep -qxF \"\$key\" \"\$HOME/.ssh/authorized_keys\" && echo \"A chave já estava em ~/.ssh/authorized_keys.\" || { printf '%s\\n' \"\$key\" >> \"\$HOME/.ssh/authorized_keys\" && echo \"Chave adicionada em ~/.ssh/authorized_keys.\"; }; }" } print_authorized_keys_command() { local pub="$1" cmd cmd="$(authorized_keys_install_command "$pub")" || die "Não foi possível ler a chave pública." printf '%s\n' "$cmd" } copy_authorized_keys_command() { local pub="$1" cmd cmd="$(authorized_keys_install_command "$pub")" || return 1 if copy_text "$cmd"; then ok "Comando copiado para a área de transferência." else info "Copie o comando acima e cole no servidor." fi } show_authorized_keys_command() { local pub="$1" info "No servidor, cole este comando. Ele grava a chave em ~/.ssh/authorized_keys:" printf '\n' print_authorized_keys_command "$pub" printf '\n' copy_authorized_keys_command "$pub" } # curl | bash deixa o stdin no fim do script. O OpenSSH lê o y/n da # sobrescrita nesse stdin. O PIN já abre /dev/tty. run_ssh_keygen() { if { : /dev/null 2>&1; then ssh-keygen "$@" _sk_rk__. resident_note() { local comment="$1" base="$2" prefix rest marker if [[ "$comment" == ssh:* && "$comment" != "ssh:" ]]; then rest="${comment#ssh:}" for prefix in id_ed25519_sk_rk_ id_ecdsa_sk_rk_; do marker="${prefix}${rest}_" if [[ "$base" == "$marker"* && "$base" != "$marker" ]]; then printf '%s' "${base#"$marker"}" return 0 fi done printf '%s' "$comment" return 0 fi if [[ "$comment" == "ssh:" ]]; then for prefix in id_ed25519_sk_rk_ id_ecdsa_sk_rk_; do if [[ "$base" == "$prefix"* && "$base" != "$prefix" ]]; then printf '%s' "${base#"$prefix"}" return 0 fi done fi printf '%s' "$comment" } resident_matches() { local expected="$1" comment="$2" base="$3" application [[ "$comment" == "$expected" ]] && return 0 if [[ "$comment" == "ssh:" ]]; then [[ "$base" == "id_ed25519_sk_rk_${expected}" || "$base" == "id_ecdsa_sk_rk_${expected}" ]] return fi application="$(credential_application "$expected")" [[ "$comment" == "$application" ]] || return 1 [[ "$base" == "id_ed25519_sk_rk_"*"_${expected}" || "$base" == "id_ecdsa_sk_rk_"*"_${expected}" ]] } normalize_recovered_comment() { local pub="$1" expected="$2" local key_type material comment [[ -f "$pub" ]] || return 0 key_type="$(awk '{print $1}' "$pub")" material="$(awk '{print $2}' "$pub")" comment="$(awk '{print $NF}' "$pub")" [[ "$comment" == ssh:* && "$comment" != "$expected" && "$key_type" == sk-* && -n "$material" && "$material" != "$comment" ]] || return 0 printf '%s %s %s\n' "$key_type" "$material" "$expected" > "$pub" chmod 644 "$pub" || true } # RESIDENT_STATUS: found, absent ou failed. # RESIDENT_NOTES: comentário do OpenSSH 9 ou user id lido no nome do arquivo. search_resident() { local expected_comment="$1" local dest_private="${2:-}" local previous status found pub key_type comment base note local -a pub_files=() local restore_nullglob=0 RESIDENT_STATUS="failed" RESIDENT_NOTES=() TMP_WORK="$(mktemp -d "${TMPDIR:-/tmp}/fido.XXXXXX")" || die "Não foi possível criar diretório temporário." # Sem subshell: o EXIT trap seria herdado e apagaria os arquivos antes da cópia. trap 'rm -rf "$TMP_WORK"' EXIT previous="$(pwd)" cd "$TMP_WORK" || die "Não foi possível entrar no diretório temporário." set +e run_ssh_keygen -K -N "" status=$? set -e cd "$previous" || true if (( status != 0 )); then rm -rf "$TMP_WORK" trap - EXIT unset TMP_WORK RESIDENT_STATUS="failed" return 0 fi if shopt -q nullglob; then restore_nullglob=1 else shopt -s nullglob fi pub_files=("$TMP_WORK"/*.pub) if (( restore_nullglob == 0 )); then shopt -u nullglob fi found="" if ((${#pub_files[@]} > 0)); then for pub in "${pub_files[@]}"; do key_type="$(awk '{print $1}' "$pub")" comment="$(awk '{print $NF}' "$pub")" base="$(basename "$pub" .pub)" note="$(resident_note "$comment" "$base")" RESIDENT_NOTES+=("$note") case "$key_type" in sk-*) ;; *) continue ;; esac if [[ -z "$found" ]] && resident_matches "$expected_comment" "$comment" "$base"; then found="${pub%.pub}" fi done fi if [[ -n "$found" ]]; then RESIDENT_STATUS="found" if [[ -n "$dest_private" ]]; then place_file 600 "$found" "$dest_private" place_file 644 "${found}.pub" "${dest_private}.pub" normalize_recovered_comment "${dest_private}.pub" "$expected_comment" fi else RESIDENT_STATUS="absent" fi rm -rf "$TMP_WORK" trap - EXIT unset TMP_WORK } report_missing_resident() { local expected_comment="$1" local note if ((${#RESIDENT_NOTES[@]} > 0)); then warn "Credenciais encontradas no token, mas nenhuma tem o comentário esperado: ${expected_comment}" warn "Comentários encontrados:" for note in "${RESIDENT_NOTES[@]}"; do printf ' - %s\n' "$note" >&2 done warn_legacy_ssh_comment else warn "Nenhuma credencial residente foi recuperada." fi die "Confirme se a chave foi criada com -C \"${expected_comment}\"." } # Credencial antiga, gravada sem -O user. No OpenSSH 10 o arquivo fica # id_ed25519_sk_rk, sem sufixo, e o comentário é a application "ssh:". warn_legacy_ssh_comment() { local note for note in "${RESIDENT_NOTES[@]}"; do [[ "$note" == "ssh:" ]] || return 0 done warn "O comentário ssh: é o identificador padrão do OpenSSH quando a credencial foi gravada sem nome de usuário. Crie a chave de novo. A credencial antiga continua no token até ser apagada." } recover_key() { local expected_comment="$1" local destination="$2" local audience="$3" local display display="$(label_name "$LABEL")" require_tools require_openssh_sk ensure_ssh_dir YK_SERIAL="" require_connected_label "$LABEL" info "Conecte somente a YubiKey ${display}." info "Será solicitado o PIN e, em seguida, o toque no dispositivo." printf '\n' search_resident "$expected_comment" "$destination" if [[ "$RESIDENT_STATUS" == failed ]]; then die "Não foi possível recuperar as credenciais residentes. Verifique a YubiKey, o PIN e se o OpenSSH tem suporte a FIDO (libfido2)." fi if [[ "$RESIDENT_STATUS" != found ]]; then report_missing_resident "$expected_comment" fi ok "Credencial ${display} recuperada em:" printf ' %s\n' "$destination" ssh-keygen -lf "${destination}.pub" || warn "Não foi possível calcular o fingerprint." printf '\n' if [[ "$audience" == github ]]; then info "Cadastre esta chave pública no GitHub, caso ainda não tenha feito:" printf '\n' cat "${destination}.pub" printf '\n' if copy_clipboard "${destination}.pub"; then ok "Chave pública copiada para a área de transferência." fi printf '\n' info "Ative-a em seguida pela opção de usar a YubiKey ${display}." else show_authorized_keys_command "${destination}.pub" info "Depois escolha Instalar ou Conectar." fi } add_key() { validate_label "${1:-}" remember_account recover_key "$COMMENT" "$(key_path "$LABEL")" github } add_server_key() { prepare_server_label "${1:-}" recover_key "$SERVER_COMMENT" "$(server_key_path "$LABEL")" server } refuse_existing_handle() { local destination="$1" display="$2" menu_name="$3" if [[ -e "$destination" || -e "${destination}.pub" ]]; then die "Já existe um handle local para ${display}. Use Desfazer no menu ${menu_name} antes de criar de novo." fi } accept_created_key() { local destination="$1" pub="$2" comment="$3" chmod 600 "$destination" 2>/dev/null || true if [[ ! -f "$pub" ]] || ! grep -q '^sk-ssh-ed25519@openssh.com ' "$pub"; then rm -f "$destination" "$pub" die "A chave criada não é uma credencial ed25519 residente. Nada foi mantido." fi search_resident "$comment" if [[ "$RESIDENT_STATUS" == failed ]]; then warn "A chave FIDO foi gravada, mas não foi possível confirmar a credencial no token. O handle local foi mantido." return 0 fi if [[ "$RESIDENT_STATUS" != found ]]; then if [[ "${YK_MULTI:-0}" == 1 ]]; then warn "A confirmação não encontrou o comentário. Com mais de uma YubiKey conectada, o handle local foi mantido." return 0 fi rm -f "$destination" "$pub" die "A credencial não está no token. O handle local foi removido." fi } use_key() { validate_label "${1:-}" require_tools require_openssh_sk ensure_ssh_dir remember_account local identity display who hint identity="$(key_path "$LABEL")" display="$(label_name "$LABEL")" who="$display" hint="--batch add ${LABEL}" if [[ -n "${ACCOUNT:-}" ]]; then who="${ACCOUNT} ${display}" hint="--batch add ${ACCOUNT} ${LABEL}" fi [[ -f "$identity" && -f "${identity}.pub" ]] || die "Chave ${who} não encontrada neste computador. Recupere-a antes com ${hint}." write_config "$identity" ok "$(active_account_text "$identity")" printf ' IdentityFile %s\n' "$identity" printf '\n' info "Para conferir, escolha Testar no menu ou rode --batch test." } status() { if [[ ! -f "$CONFIG_FILE" ]]; then printf 'Nenhuma YubiKey selecionada.\n' printf 'Recupere a chave e escolha Usar para ativá-la.\n' return 0 fi local identity identity="$(read_identity)" if [[ -z "$identity" ]]; then printf 'Arquivo de configuração existe, mas não contém IdentityFile.\n' return 1 fi printf '%s\n' "$(active_account_text "$identity")" if [[ -f "$identity" ]]; then printf 'Arquivo local: presente\n' else printf 'Arquivo local: ausente\n' fi } # YUC é a Security Key C NFC (USB-C). YUA é a Security Key NFC (USB-A). # O "5.8.0" é a versão do firmware, não a série YubiKey 5. classify_token_text() { local text="$1" if printf '%s\n' "$text" | grep -Eq 'USB-C'; then printf '%s' yuc return 0 fi if printf '%s\n' "$text" | grep -Eq 'USB-A'; then printf '%s' yua return 0 fi if printf '%s\n' "$text" | grep -Eq 'Security Key C([^[:alnum:]]|$)'; then printf '%s' yuc return 0 fi if printf '%s\n' "$text" | grep -Eq 'Security Key([^[:alnum:]]|$)'; then printf '%s' yua return 0 fi return 1 } device_model_name() { local line="$1" line="${line%% Serial:*}" line="${line%% (*}" trim "$line" } token_port() { case "$1" in yuc) printf 'USB-C' ;; yua) printf 'USB-A' ;; *) printf '%s' "$1" ;; esac } remember_connected_token() { local model="$1" serial="$2" text="$3" local classified="" classified="$(classify_token_text "$text" || true)" [[ -n "$classified" ]] || return 0 CONNECTED_LABELS+=("$classified") CONNECTED_MODELS+=("$model") CONNECTED_SERIALS+=("$serial") } load_connected_tokens() { local list_out err_file line model info text serial local -a device_lines=() models=() serials=() CONNECTED_LABELS=() CONNECTED_MODELS=() CONNECTED_SERIALS=() CONNECTED_SCANNED=0 command -v ykman >/dev/null 2>&1 || return 0 err_file="$(mktemp "${TMPDIR:-/tmp}/fido.XXXXXX")" list_out="$(ykman list 2>"$err_file" || true)" rm -f "$err_file" if printf '%s\n' "$list_out" | grep -q ''; then return 0 fi while IFS= read -r line; do [[ -z "${line//[[:space:]]/}" ]] && continue [[ "$line" =~ ^(Usage:|Error:|Failed ) ]] && continue [[ "$line" == *"No YubiKey"* ]] && continue device_lines+=("$line") models+=("$(device_model_name "$line")") if [[ "$line" =~ Serial:\ ([0-9]+) ]]; then serials+=("${BASH_REMATCH[1]}") else serials+=("") fi done <<< "$list_out" CONNECTED_SCANNED=1 if ((${#device_lines[@]} == 0)); then return 0 fi local i if ((${#device_lines[@]} == 1)); then info="$(ykman info 2>/dev/null || true)" text="${device_lines[0]}"$'\n'"${models[0]}"$'\n'"$info" remember_connected_token "${models[0]}" "${serials[0]}" "$text" return 0 fi for i in "${!device_lines[@]}"; do info="" serial="${serials[$i]}" if [[ -n "$serial" ]]; then info="$(ykman --device "$serial" info 2>/dev/null || true)" fi text="${device_lines[$i]}"$'\n'"${models[$i]}"$'\n'"$info" remember_connected_token "${models[$i]}" "$serial" "$text" done } connected_model_for() { local label="$1" i for i in "${!CONNECTED_LABELS[@]}"; do if [[ "${CONNECTED_LABELS[$i]}" == "$label" ]]; then printf '%s' "${CONNECTED_MODELS[$i]}" return 0 fi done return 1 } connected_summary() { local i port text="" for i in "${!CONNECTED_LABELS[@]}"; do port="$(token_port "${CONNECTED_LABELS[$i]}")" if [[ -n "$text" ]]; then text+=", " fi text+="$(label_name "${CONNECTED_LABELS[$i]}") (${CONNECTED_MODELS[$i]}, ${port})" done printf '%s' "$text" } label_matches_connected() { local label="$1" i saw=0 (( CONNECTED_SCANNED == 0 )) && return 0 ((${#CONNECTED_LABELS[@]} == 0)) && return 0 if [[ -n "${YK_SERIAL:-}" ]]; then for i in "${!CONNECTED_SERIALS[@]}"; do [[ "${CONNECTED_SERIALS[$i]}" == "$YK_SERIAL" ]] || continue saw=1 [[ "${CONNECTED_LABELS[$i]}" == "$label" ]] && return 0 done (( saw == 0 )) && return 0 return 1 fi for i in "${!CONNECTED_LABELS[@]}"; do [[ "${CONNECTED_LABELS[$i]}" == "$label" ]] && return 0 done return 1 } token_mismatch_message() { local label="$1" hint i port if [[ "$label" == yuc ]]; then hint="A YUC é a Security Key C NFC, com USB-C." else hint="A YUA é a Security Key NFC, com USB-A." fi if [[ -n "${YK_SERIAL:-}" ]]; then for i in "${!CONNECTED_SERIALS[@]}"; do if [[ "${CONNECTED_SERIALS[$i]}" == "$YK_SERIAL" ]]; then port="$(token_port "${CONNECTED_LABELS[$i]}")" printf 'A série %s é a %s (%s, %s). %s' \ "$YK_SERIAL" "$(label_name "${CONNECTED_LABELS[$i]}")" "${CONNECTED_MODELS[$i]}" "$port" "$hint" return 0 fi done fi printf 'Conectada agora: %s. %s' "$(connected_summary)" "$hint" } require_connected_label() { local label="$1" load_connected_tokens if label_matches_connected "$label"; then return 0 fi die "$(token_mismatch_message "$label")" } list_account_keys() { local account="$1" local label identity active marker display title model port suffix active="$(read_identity)" for label in yuc yua; do identity="$(key_path "$label" "$account")" display="$(label_name "$label")" if [[ -n "$account" ]]; then title="${account} ${display}" else title="$display" fi marker="·" if [[ -f "$identity" && -f "${identity}.pub" ]]; then marker="✓" suffix="presente neste computador" if [[ "$identity" == "$active" ]]; then suffix="presente neste computador, ativa" fi if connected_model_for "$label" >/dev/null; then suffix="${suffix}, token conectado" fi if [[ "$identity" == "$active" ]]; then printf '%s %s — %s\n' "$(paint '1;32' "$marker")" "$title" "$suffix" else printf '%s %s — %s\n' "$(paint '32' "$marker")" "$title" "$suffix" fi elif model="$(connected_model_for "$label")"; then port="$(token_port "$label")" printf '%s %s — conectada agora (%s, %s), chave ainda não recuperada neste computador\n' \ "$(paint '1;33' "$marker")" "$title" "$model" "$port" else printf '%s %s — ausente neste computador\n' "$(paint '2' "$marker")" "$title" fi done } list_keys() { local account ensure_ssh_dir load_connected_tokens read_account_names if legacy_github_keys_present || ((${#ACCOUNT_NAMES[@]} == 0)); then list_account_keys "" fi if ((${#ACCOUNT_NAMES[@]} > 0)); then for account in "${ACCOUNT_NAMES[@]}"; do list_account_keys "$account" done fi } menu_row() { local number="$1" title="$2" detail="$3" require_tty { printf ' %s ' "$(paint '1;36' "$number")" printf '%s' "$(paint '1' "$title")" printf ' %s\n' "$(paint '2' "$detail")" } >/dev/tty } active_summary() { local identity text identity="$(read_identity)" if [[ -z "$identity" ]]; then paint '33' 'Nenhuma chave ativa' return 0 fi text="$(active_account_text "$identity")" paint '1;32' "$text" } show_help() { tty_say "" tty_say "$(paint '1;36' 'Ajuda')" tty_say "O nome da conta escolhe qual GitHub está ativo. Cada YubiKey dessa conta tem a própria chave pública." tty_say "YUC é a Security Key C NFC, com USB-C. YUA é a Security Key NFC, com USB-A, a reserva da mesma conta." tty_say "O helper reconhece a conectada pelo nome Security Key que o ykman mostra. O 5.8.0 é só o firmware." tty_say "Uma conta sem nome usa os comentários github-yuc e github-yua." tty_say "" tty_say "1. Escolha o nome e Criar para gravar a credencial no token." tty_say "2. Ou recupere a credencial que já existe nesse token." tty_say "3. Usar define a conta e a YubiKey que git@github.com vai apresentar." tty_say "4. Testar mostra o usuário Hi do GitHub." tty_say "" tty_say "Sem menu: --batch create trabalho 1, --batch use trabalho 2, --batch pub trabalho 1" } show_token_help() { tty_say "" tty_say "$(paint '1;36' 'Qual número escolher')" tty_say "1 YUC USB-C Security Key C NFC" tty_say "2 YUA USB-A Security Key NFC" tty_say "O helper marca a que está conectada. Conecte o token correspondente antes de criar ou recuperar." } token_menu_detail() { local label="$1" port model port="$(token_port "$label")" if model="$(connected_model_for "$label")"; then printf '%s, conectada agora (%s)' "$port" "$model" else printf '%s' "$port" fi } prompt_label() { local choice label YK_SERIAL="" load_connected_tokens while true; do tty_say "" tty_say "$(paint '1' 'Qual YubiKey?')" menu_row 1 YUC "$(token_menu_detail yuc)" menu_row 2 YUA "$(token_menu_detail yua)" menu_row 3 Ajuda "o que significa cada uma" menu_row 4 Voltar "retorna ao menu" choice="$(tty_prompt "$(paint '1' 'Número: ')")" choice="$(trim "$choice")" choice="$(printf '%s' "$choice" | tr '[:upper:]' '[:lower:]')" label="" case "$choice" in 1|yuc) label=yuc ;; 2|yua) label=yua ;; 3|ajuda|help|\?) show_token_help; continue ;; 4|voltar|q) return 1 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')"; continue ;; esac if ! label_matches_connected "$label"; then tty_say "$(paint '33' "$(token_mismatch_message "$label")")" continue fi printf '%s' "$label" return 0 done } key_present() { [[ -f "$(key_path "$1")" && -f "$(key_path "$1").pub" ]] } print_public_key() { local label="$1" local pub display port pub="$(key_path "$label").pub" display="$(label_name "$label")" case "$label" in yuc) port="USB-C" ;; yua) port="USB-A" ;; esac printf '\n' if [[ -n "${ACCOUNT:-}" ]]; then info "${ACCOUNT} ${display} (${port})" else info "${display} (${port})" fi printf '\n' cat "$pub" printf '\n' } copy_one_public() { local pub="$1" if copy_clipboard "$pub"; then ok "Chave pública copiada para a área de transferência." else info "Copie o texto acima para cadastrar no GitHub." fi } show_public_keys() { local found=0 label choice local -a present=() for label in yuc yua; do if key_present "$label"; then print_public_key "$label" present+=("$label") found=1 fi done if (( found == 0 )); then warn "Nenhuma chave recuperada. Escolha Recuperar antes de cadastrar no GitHub." return 0 fi if ((${#present[@]} == 1)); then copy_one_public "$(key_path "${present[0]}").pub" return 0 fi while true; do tty_say "" tty_say "$(paint '1' 'Qual chave copiar para cadastrar no GitHub?')" menu_row 1 YUC "USB-C" menu_row 2 YUA "USB-A" menu_row 3 Voltar "retorna ao menu" choice="$(tty_prompt "$(paint '1' 'Número: ')")" choice="$(trim "$choice")" choice="$(printf '%s' "$choice" | tr '[:upper:]' '[:lower:]')" case "$choice" in 1|yuc) copy_one_public "$(key_path yuc).pub"; return 0 ;; 2|yua) copy_one_public "$(key_path yua).pub"; return 0 ;; 3|voltar|q) return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } show_public_batch() { local selector="${1:-}" if [[ -z "$selector" ]]; then local found=0 label for label in yuc yua; do if key_present "$label"; then print_public_key "$label" found=1 fi done if (( found == 0 )); then warn "Nenhuma chave recuperada. Escolha Recuperar antes de cadastrar no GitHub." return 1 fi return 0 fi validate_label "$selector" if ! key_present "$LABEL"; then warn "Chave $(label_name "$LABEL") não recuperada neste computador. Escolha Recuperar antes de cadastrar no GitHub." return 1 fi print_public_key "$LABEL" copy_one_public "$(key_path "$LABEL").pub" } test_github() { require_tools local identity output status name identity="$(read_identity)" if [[ -z "$identity" || ! -f "$identity" ]]; then warn "Nenhuma chave ativa. Escolha Usar antes de testar." return 1 fi info "Testando git@github.com. O PIN e o toque são os pedidos do SSH." set +e output="$(ssh -T -i "$identity" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new git@github.com 2>&1)" status=$? set -e printf '%s\n' "$output" if printf '%s\n' "$output" | grep -q 'successfully authenticated'; then name="$(printf '%s\n' "$output" | sed -n 's/^Hi \([^!]*\)!.*/\1/p' | head -n 1)" if [[ -n "$name" ]]; then ok "GitHub autenticou como ${name}." else ok "GitHub autenticou." fi return 0 fi if printf '%s\n' "$output" | grep -qi 'permission denied'; then warn "GitHub não autenticou. A chave ativa pode não estar cadastrada na conta." return 1 fi warn "Não foi possível confirmar a autenticação (código ${status})." return 1 } owned_paths() { local path restore_nullglob=0 printf '%s\n' \ "$CONFIG_FILE" \ "$LEGACY_CONFIG_FILE" \ "$ACCOUNTS_FILE" \ "$(key_path yuc "")" \ "$(key_path yuc "").pub" \ "$(key_path yua "")" \ "$(key_path yua "").pub" if shopt -q nullglob; then restore_nullglob=1 else shopt -s nullglob fi for path in "$SSH_DIR"/*_github_id_ed25519_sk "$SSH_DIR"/*_github_id_ed25519_sk.pub; do printf '%s\n' "$path" done if (( restore_nullglob == 0 )); then shopt -u nullglob fi } config_has_include() { [[ -f "$MAIN_CONFIG" && ! -L "$MAIN_CONFIG" ]] || return 1 if grep -Fqx "$INCLUDE_LINE" "$MAIN_CONFIG"; then return 0 fi if grep -Fqx "$LEGACY_INCLUDE_LINE" "$MAIN_CONFIG"; then return 0 fi return 1 } note_owned_symlinks() { local path while IFS= read -r path; do if [[ -L "$path" ]]; then warn "Atalho ignorado: $path" fi done < <(owned_paths) if [[ -L "$MAIN_CONFIG" ]]; then warn "Atalho ignorado: $MAIN_CONFIG" fi } strip_include_line() { local tmp line any=0 tmp="$(mktemp "${TMPDIR:-/tmp}/fido.XXXXXX")" while IFS= read -r line || [[ -n "$line" ]]; do if [[ "$line" == "$INCLUDE_LINE" || "$line" == "$LEGACY_INCLUDE_LINE" ]]; then continue fi printf '%s\n' "$line" >> "$tmp" if [[ -n "${line//[[:space:]]/}" ]]; then any=1 fi done < "$MAIN_CONFIG" if (( any == 0 )); then rm -f "$MAIN_CONFIG" ok "Removido: $MAIN_CONFIG" else cat "$tmp" > "$MAIN_CONFIG" ok "Removida a linha Include de $MAIN_CONFIG" fi rm -f "$tmp" } undo_apply() { local path removed=0 note_owned_symlinks while IFS= read -r path; do if [[ -L "$path" ]]; then continue fi if [[ -f "$path" ]]; then rm -f "$path" ok "Removido: $path" removed=1 fi done < <(owned_paths) if [[ -L "$MAIN_CONFIG" ]]; then : elif config_has_include; then strip_include_line removed=1 fi if (( removed == 0 )); then warn "Nada deste helper foi encontrado. O SSH não foi alterado." return 0 fi } undo_has_work() { local path while IFS= read -r path; do if [[ ! -L "$path" && -f "$path" ]]; then return 0 fi done < <(owned_paths) if config_has_include; then return 0 fi return 1 } undo_interactive() { local path choice tty_say "" if ! undo_has_work; then note_owned_symlinks warn "Nada deste helper foi encontrado. O SSH não foi alterado." return 0 fi tty_say "$(paint '1' 'Isto será removido:')" while IFS= read -r path; do if [[ ! -L "$path" && -f "$path" ]]; then tty_say " $path" fi done < <(owned_paths) if config_has_include; then tty_say " linha Include em $MAIN_CONFIG" fi while true; do tty_say "" menu_row 1 Confirmar "apaga só estes itens" menu_row 2 Voltar "não altera nada" choice="$(tty_prompt "$(paint '1' 'Número: ')")" choice="$(trim "$choice")" choice="$(printf '%s' "$choice" | tr '[:upper:]' '[:lower:]')" case "$choice" in 1|confirmar) undo_apply; return 0 ;; 2|voltar|q) info "Nada foi alterado." return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } YUBICO_YKMAN_URL='https://www.yubico.com/support/download/yubikey-manager/' ykman_package_manager() { local uname_s uname_s="$(uname -s 2>/dev/null || true)" case "$uname_s" in Darwin) command -v brew >/dev/null 2>&1 || return 1 printf '%s\n' brew ;; Linux) if command -v apt-get >/dev/null 2>&1; then printf '%s\n' apt elif command -v dnf >/dev/null 2>&1; then printf '%s\n' dnf else return 1 fi ;; MINGW*|MSYS*|CYGWIN*) command -v winget >/dev/null 2>&1 || return 1 printf '%s\n' winget ;; *) return 1 ;; esac } ykman_install_command() { case "$(ykman_package_manager 2>/dev/null || true)" in brew) printf '%s\n' 'brew install yubikey-manager' ;; apt) printf '%s\n' 'sudo apt-get install -y yubikey-manager' ;; dnf) printf '%s\n' 'sudo dnf install -y yubikey-manager' ;; winget) printf '%s\n' 'winget install --id Yubico.YubiKeyManagerCLI -e' ;; *) return 1 ;; esac } run_ykman_install() { case "$(ykman_package_manager 2>/dev/null || true)" in brew) brew install yubikey-manager ;; apt) sudo apt-get install -y yubikey-manager ;; dnf) sudo dnf install -y yubikey-manager ;; winget) winget install --id Yubico.YubiKeyManagerCLI -e ;; *) return 1 ;; esac } ensure_ykman() { local mode="$1" local cmd choice command -v ykman >/dev/null 2>&1 && return 0 if ! cmd="$(ykman_install_command)"; then die "ykman não encontrado. Baixe em ${YUBICO_YKMAN_URL}" fi if [[ "$mode" == "batch" ]]; then die "ykman não encontrado. Instale com: ${cmd}" fi tty_say "" tty_say "$(paint '1' 'O ykman não está instalado.')" tty_say " $cmd" while true; do tty_say "" menu_row 1 Instalar "executa o comando acima" menu_row 2 Voltar "não instala nada" choice="$(tty_prompt "$(paint '1' 'Número: ')")" choice="$(trim "$choice")" choice="$(printf '%s' "$choice" | tr '[:upper:]' '[:lower:]')" case "$choice" in 1|instalar) run_ykman_install || die "Não foi possível instalar o ykman." hash -r 2>/dev/null || true command -v ykman >/dev/null 2>&1 || die "O ykman foi instalado, mas não está no PATH deste terminal. Abra um novo terminal e rode o helper de novo." return 0 ;; 2|voltar|q) return 1 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } ykman_fido() { if [[ -n "${YK_SERIAL:-}" ]]; then ykman --device "$YK_SERIAL" "$@" else ykman "$@" fi } # Com uma YubiKey, YK_SERIAL fica vazio. Com várias, o usuário escolhe a série. # Retorna 1 se o menu interativo voltar. select_token() { local mode="$1" local requested="${2:-}" local command_name="${3:-create}" local list_out err_file line model serial choice n i known local -a device_lines=() serials=() models=() YK_SERIAL="" YK_MULTI=0 err_file="$(mktemp "${TMPDIR:-/tmp}/fido.XXXXXX")" list_out="$(ykman list 2>"$err_file" || true)" while IFS= read -r line; do [[ -z "${line//[[:space:]]/}" ]] && continue [[ "$line" =~ ^(Usage:|Error:|Failed ) ]] && continue [[ "$line" == *"No YubiKey"* ]] && continue device_lines+=("$line") if [[ "$line" =~ Serial:\ ([0-9]+) ]]; then serial="${BASH_REMATCH[1]}" model="${line%% Serial:*}" model="$(trim "$model")" serials+=("$serial") models+=("$model") fi done <<< "$list_out" if ((${#device_lines[@]} == 0)); then if [[ -s "$err_file" ]]; then cat "$err_file" >&2 fi rm -f "$err_file" die "Nenhuma YubiKey encontrada. Conecte um token e tente de novo." fi if printf '%s\n' "$list_out" | grep -q ''; then rm -f "$err_file" die "A YubiKey está conectada, mas o ykman não tem permissão para falar com ela. No Linux, seu usuário precisa do grupo plugdev ou da regra udev da Yubico." fi rm -f "$err_file" if ((${#device_lines[@]} <= 1)); then return 0 fi YK_MULTI=1 if ((${#serials[@]} == 0)); then die "Há mais de uma YubiKey conectada. Deixe somente a que vai receber a credencial." fi if [[ "$mode" == "batch" ]]; then if [[ -z "$requested" ]]; then printf 'Séries conectadas:\n' >&2 for i in "${!serials[@]}"; do printf ' %s %s\n' "${serials[$i]}" "${models[$i]}" >&2 done die "Há mais de uma YubiKey. Informe a série. Exemplo: --batch ${command_name} 1 ${serials[0]}" fi known=0 for serial in "${serials[@]}"; do if [[ "$serial" == "$requested" ]]; then known=1 break fi done if (( known == 0 )); then die "Série ${requested} não está conectada." fi YK_SERIAL="$requested" return 0 fi while true; do tty_say "" tty_say "$(paint '1' 'Qual YubiKey recebe a credencial?')" n=0 for i in "${!serials[@]}"; do n=$((n + 1)) menu_row "$n" "${serials[$i]}" "${models[$i]}" done menu_row "$((n + 1))" Voltar "retorna ao menu" choice="$(read_choice)" if [[ "$choice" == "$((n + 1))" || "$choice" == "voltar" || "$choice" == "q" ]]; then return 1 fi for serial in "${serials[@]}"; do if [[ "$choice" == "$serial" ]]; then YK_SERIAL="$serial" return 0 fi done if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= n )); then YK_SERIAL="${serials[choice-1]}" return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } ensure_fido_pin() { local info info="$(ykman_fido fido info 2>&1 || true)" if printf '%s\n' "$info" | grep -Eqi 'not set|not configured|no pin'; then if ! { : /dev/null 2>&1; then die "Terminal interativo não encontrado. Defina o PIN FIDO em um terminal e rode o helper de novo." fi info "Este token ainda não tem PIN FIDO. Você vai definir um agora." ykman_fido fido access change-pin = RECENT_LIMIT)); then break fi kept+=("$current") done < "$SERVER_HOSTS" fi printf '%s\n' "${kept[@]}" > "$SERVER_HOSTS" chmod 600 "$SERVER_HOSTS" } recent_menu_title() { local name="$1" label="$2" target="$3" who who="$(label_name "$label")" if [[ -n "$name" ]]; then printf 'Servidor > Conectar > %s > %s > %s' "$name" "$who" "$target" else printf 'Servidor > Conectar > %s > %s' "$who" "$target" fi } favorite_menu_detail() { local target="$1" label="$2" printf '%s · %s' "$target" "$(label_name "$label")" } load_recent_servers() { local line target rest name label RECENT_TARGETS=() RECENT_NAMES=() RECENT_LABELS=() [[ -f "$SERVER_HOSTS" ]] || return 0 while IFS= read -r line || [[ -n "$line" ]]; do target="${line%% *}" rest="${line#* }" name="" label="$rest" if [[ "$rest" == *" "* ]]; then name="${rest%% *}" label="${rest#* }" fi valid_ssh_target "$target" || continue [[ "$label" == "yuc" || "$label" == "yua" ]] || continue if [[ -n "$name" ]] && ! valid_account_name "$name"; then continue fi RECENT_TARGETS+=("$target") RECENT_NAMES+=("$name") RECENT_LABELS+=("$label") done < "$SERVER_HOSTS" } load_favorites() { local line alias target name label FAV_ALIASES=() FAV_TARGETS=() FAV_NAMES=() FAV_LABELS=() [[ -f "$SERVER_FAVS" ]] || return 0 while IFS= read -r line || [[ -n "$line" ]]; do [[ -z "$line" ]] && continue alias="" target="" name="" label="" read -r alias target name label <<<"$line" valid_account_name "$alias" || continue valid_ssh_target "$target" || continue [[ "$label" == "yuc" || "$label" == "yua" ]] || continue if [[ "$name" == "-" ]]; then name="" elif ! valid_account_name "$name"; then continue fi FAV_ALIASES+=("$alias") FAV_TARGETS+=("$target") FAV_NAMES+=("$name") FAV_LABELS+=("$label") done < "$SERVER_FAVS" } write_favorites() { local i stored local -a lines=() if ((${#FAV_ALIASES[@]} == 0)); then rm -f "$SERVER_FAVS" return 0 fi ensure_ssh_dir for i in "${!FAV_ALIASES[@]}"; do stored="-" if [[ -n "${FAV_NAMES[$i]}" ]]; then stored="${FAV_NAMES[$i]}" fi lines+=("${FAV_ALIASES[$i]} ${FAV_TARGETS[$i]} ${stored} ${FAV_LABELS[$i]}") done printf '%s\n' "${lines[@]}" > "$SERVER_FAVS" chmod 600 "$SERVER_FAVS" } save_favorite() { local alias="$1" target="$2" label="$3" local stored="-" line current current_alias found=0 local -a kept=() if [[ -n "${SERVER_NAME:-}" ]]; then stored="$SERVER_NAME" fi line="${alias} ${target} ${stored} ${label}" ensure_ssh_dir if [[ -f "$SERVER_FAVS" ]]; then while IFS= read -r current || [[ -n "$current" ]]; do [[ -z "$current" ]] && continue current_alias="${current%% *}" if [[ "$current_alias" == "$alias" ]]; then kept+=("$line") found=1 else kept+=("$current") fi done < "$SERVER_FAVS" fi if (( found == 0 )); then kept+=("$line") fi printf '%s\n' "${kept[@]}" > "$SERVER_FAVS" chmod 600 "$SERVER_FAVS" } remove_favorite_at() { local drop="$1" i local -a aliases=() targets=() names=() labels=() ((${#FAV_ALIASES[@]} > 0)) || return 0 for i in "${!FAV_ALIASES[@]}"; do if (( i == drop )); then continue fi aliases+=("${FAV_ALIASES[$i]}") targets+=("${FAV_TARGETS[$i]}") names+=("${FAV_NAMES[$i]}") labels+=("${FAV_LABELS[$i]}") done if ((${#aliases[@]} == 0)); then FAV_ALIASES=() FAV_TARGETS=() FAV_NAMES=() FAV_LABELS=() else FAV_ALIASES=("${aliases[@]}") FAV_TARGETS=("${targets[@]}") FAV_NAMES=("${names[@]}") FAV_LABELS=("${labels[@]}") fi write_favorites } recent_is_favorite() { local target="$1" name="$2" label="$3" i ((${#FAV_ALIASES[@]} > 0)) || return 1 for i in "${!FAV_ALIASES[@]}"; do if [[ "${FAV_TARGETS[$i]}" == "$target" && "${FAV_NAMES[$i]}" == "$name" && "${FAV_LABELS[$i]}" == "$label" ]]; then return 0 fi done return 1 } load_home_shortcuts() { local i added=0 HOME_TITLES=() HOME_DETAILS=() HOME_NAMES=() HOME_LABELS=() HOME_TARGETS=() load_favorites load_recent_servers if ((${#FAV_ALIASES[@]} > 0)); then for i in "${!FAV_ALIASES[@]}"; do HOME_TITLES+=("${FAV_ALIASES[$i]}") HOME_DETAILS+=("$(favorite_menu_detail "${FAV_TARGETS[$i]}" "${FAV_LABELS[$i]}")") HOME_NAMES+=("${FAV_NAMES[$i]}") HOME_LABELS+=("${FAV_LABELS[$i]}") HOME_TARGETS+=("${FAV_TARGETS[$i]}") done fi if ((${#RECENT_TARGETS[@]} > 0)); then for i in "${!RECENT_TARGETS[@]}"; do if (( added >= RECENT_LIMIT )); then break fi if recent_is_favorite "${RECENT_TARGETS[$i]}" "${RECENT_NAMES[$i]}" "${RECENT_LABELS[$i]}"; then continue fi HOME_TITLES+=("$(recent_menu_title "${RECENT_NAMES[$i]}" "${RECENT_LABELS[$i]}" "${RECENT_TARGETS[$i]}")") HOME_DETAILS+=("conecta agora") HOME_NAMES+=("${RECENT_NAMES[$i]}") HOME_LABELS+=("${RECENT_LABELS[$i]}") HOME_TARGETS+=("${RECENT_TARGETS[$i]}") added=$((added + 1)) done fi } prompt_favorite_alias() { local alias while true; do alias="$(tty_prompt "Nome do servidor: ")" alias="$(normalize_account_name "$(trim "$alias")")" if [[ -z "$alias" ]]; then return 1 fi if valid_account_name "$alias"; then printf '%s' "$alias" return 0 fi tty_say "$(paint '33' 'Use letras minúsculas, números e hífen. Exemplo: casa')" done } create_server_key() { local mode="${2:-interactive}" local serial="${3:-}" prepare_server_label "${1:-}" require_tools require_openssh_sk if ! ensure_ykman "$mode"; then return 0 fi if ! select_token "$mode" "$serial" server-create; then return 0 fi require_connected_label "$LABEL" ensure_fido_pin ensure_ssh_dir local destination display pub who destination="$(server_key_path "$LABEL")" display="$(label_name "$LABEL")" who="$display" if [[ -n "${SERVER_NAME:-}" ]]; then who="${SERVER_NAME} ${display}" fi pub="${destination}.pub" refuse_existing_handle "$destination" "$who" "Servidor" announce_create_target "$display" info "A credencial será residente no token." info "Digite o PIN quando aparecer Enter PIN. Toque na YubiKey quando ela piscar, depois do PIN." info "Se aparecer Overwrite key in token, responda y para substituir a credencial desse nome." if ! run_ssh_keygen -q -t ed25519-sk -O resident -O verify-required \ -O "application=$(credential_application "$SERVER_COMMENT")" -O "user=$SERVER_COMMENT" \ -C "$SERVER_COMMENT" -N "" -f "$destination"; then rm -f "$destination" "$pub" die "Não foi possível criar a credencial residente. Se aparecer Overwrite key in token, responda y. Confira o PIN, o toque e se há somente uma YubiKey conectada." fi accept_created_key "$destination" "$pub" "$SERVER_COMMENT" if [[ "$RESIDENT_STATUS" == found ]]; then ok "Credencial residente ${display} criada em:" else ok "Handle local gravado em:" fi printf ' %s\n' "$destination" printf '\n' show_authorized_keys_command "$pub" info "Depois escolha Conectar." } show_server_install_help() { local pub="$1" tty_say "" show_authorized_keys_command "$pub" info "Ou, neste computador, com a senha do servidor uma vez:" printf ' ssh-copy-id -i %s user@ip\n' "$pub" } install_server_key() { local mode="${2:-interactive}" target pub choice prepare_server_label "${1:-}" require_tools pub="$(server_key_path "$LABEL").pub" if ! server_key_present "$LABEL"; then die "Chave $(label_name "$LABEL") do servidor não existe neste computador. Escolha Criar ou Recuperar antes." fi show_server_install_help "$pub" if [[ "$mode" == "batch" ]]; then target="${3:-}" valid_ssh_target "$target" || die "Informe user@ip. Exemplo: --batch server-install 1 user@10.0.0.8" if ! command -v ssh-copy-id >/dev/null 2>&1; then warn "ssh-copy-id não encontrado. Use o comando acima no servidor." return 0 fi copy_server_key "$pub" "$target" return 0 fi while true; do tty_say "" menu_row 1 Enviar "roda ssh-copy-id com a senha do servidor" menu_row 2 Voltar "deixa só o texto na tela" choice="$(read_choice)" case "$choice" in 1|enviar) if ! command -v ssh-copy-id >/dev/null 2>&1; then warn "ssh-copy-id não encontrado. Use o comando acima no servidor." return 0 fi target="$(prompt_target)" copy_server_key "$pub" "$target" return 0 ;; 2|voltar|q) return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } copy_server_key() { local pub="$1" target="$2" info "Enviando a chave pública para ${target}." # curl | bash deixa o stdin no fim do script. A senha do servidor lê /dev/tty. if { : /dev/null 2>&1; then ssh-copy-id -i "$pub" -o IdentitiesOnly=yes -o IdentityAgent=none "$target" /dev/null 2>&1; then die "Terminal interativo não encontrado. Conectar precisa de um terminal." fi local status=0 set +e ssh -t -i "$identity" -o IdentitiesOnly=yes -o IdentityAgent=none -- "$target" = 1 && choice <= n )); then SERVER_NAME="${RECENT_NAMES[choice-1]}" connect_server "${RECENT_LABELS[choice-1]}" interactive "${RECENT_TARGETS[choice-1]}" || true return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } remove_favorite_prompt() { local choice n=0 i load_favorites if ((${#FAV_ALIASES[@]} == 0)); then return 0 fi tty_say "" tty_say "$(paint '1' 'Qual favorito remover?')" for i in "${!FAV_ALIASES[@]}"; do n=$((n + 1)) menu_row "$n" "${FAV_ALIASES[$i]}" "$(favorite_menu_detail "${FAV_TARGETS[$i]}" "${FAV_LABELS[$i]}")" done menu_row "$((n + 1))" Voltar "não apaga nada" while true; do choice="$(read_choice)" if [[ "$choice" == "$((n + 1))" || "$choice" == "voltar" || "$choice" == "q" ]]; then return 0 fi if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= n )); then remove_favorite_at "$((choice - 1))" ok "Favorito removido." return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } show_favorites() { local choice n remover voltar i while true; do load_favorites if ((${#FAV_ALIASES[@]} == 0)); then warn "Nenhum favorito neste computador." return 0 fi tty_say "" tty_say "$(paint '1' 'Favoritos')" n=0 for i in "${!FAV_ALIASES[@]}"; do n=$((n + 1)) menu_row "$n" "${FAV_ALIASES[$i]}" "$(favorite_menu_detail "${FAV_TARGETS[$i]}" "${FAV_LABELS[$i]}")" done remover=$((n + 1)) voltar=$((n + 2)) menu_row "$remover" Remover "apaga um favorito" menu_row "$voltar" Voltar "retorna ao menu" choice="$(read_choice)" if [[ "$choice" == "$voltar" || "$choice" == "voltar" || "$choice" == "q" ]]; then return 0 fi if [[ "$choice" == "$remover" || "$choice" == "remover" ]]; then remove_favorite_prompt || true continue fi if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= n )); then SERVER_NAME="${FAV_NAMES[choice-1]}" connect_server "${FAV_LABELS[choice-1]}" interactive "${FAV_TARGETS[choice-1]}" || true return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } show_server_public_keys() { local found=0 label pub local -a present=() for label in yuc yua; do if server_key_present "$label"; then present+=("$label") found=1 fi done if (( found == 0 )); then warn "Nenhuma chave de servidor recuperada. Escolha Criar ou Recuperar antes." return 0 fi info "No servidor, cole o comando da chave. Ele grava a linha em ~/.ssh/authorized_keys:" for label in "${present[@]}"; do pub="$(server_key_path "$label").pub" printf '\n' info "$(label_name "$label") ($( [[ "$label" == yuc ]] && printf 'USB-C' || printf 'USB-A' ))" printf '\n' print_authorized_keys_command "$pub" printf '\n' done if ((${#present[@]} == 1)); then copy_authorized_keys_command "$(server_key_path "${present[0]}").pub" fi } show_server_public_batch() { local selector="${1:-}" if [[ -z "$selector" ]]; then local found=0 label for label in yuc yua; do if server_key_present "$label"; then if (( found == 0 )); then info "No servidor, cole o comando da chave. Ele grava a linha em ~/.ssh/authorized_keys:" fi printf '\n%s\n\n' "$(label_name "$label")" print_authorized_keys_command "$(server_key_path "$label").pub" printf '\n' found=1 fi done if (( found == 0 )); then warn "Nenhuma chave de servidor neste computador." return 1 fi return 0 fi prepare_server_label "$selector" server_key_present "$LABEL" || die "Chave $(label_name "$LABEL") do servidor não existe neste computador." info "No servidor, cole este comando. Ele grava a chave em ~/.ssh/authorized_keys:" printf '\n' info "$(label_name "$LABEL") ($( [[ "$LABEL" == yuc ]] && printf 'USB-C' || printf 'USB-A' ))" printf '\n' print_authorized_keys_command "$(server_key_path "$LABEL").pub" printf '\n' copy_authorized_keys_command "$(server_key_path "$LABEL").pub" } server_owned_paths() { local restore_nullglob=0 path printf '%s\n' "$SERVER_HOSTS" "$LEGACY_SERVER_HOSTS" "$SERVER_ACCOUNTS_FILE" "$SERVER_FAVS" if shopt -q nullglob; then restore_nullglob=1 else shopt -s nullglob fi for path in "$SSH_DIR"/*_server_id_ed25519_sk "$SSH_DIR"/*_server_id_ed25519_sk.pub; do printf '%s\n' "$path" done if (( restore_nullglob == 0 )); then shopt -u nullglob fi } undo_server_apply() { local path removed=0 while IFS= read -r path; do if [[ -L "$path" ]]; then warn "Atalho ignorado: $path" continue fi if [[ -f "$path" ]]; then rm -f "$path" ok "Removido: $path" removed=1 fi done < <(server_owned_paths) if (( removed == 0 )); then warn "Nada do helper de servidor foi encontrado. O SSH não foi alterado." fi } undo_server_has_work() { local path while IFS= read -r path; do if [[ ! -L "$path" && -f "$path" ]]; then return 0 fi done < <(server_owned_paths) return 1 } undo_server_interactive() { local path choice if ! undo_server_has_work; then warn "Nada do helper de servidor foi encontrado. O SSH não foi alterado." return 0 fi tty_say "" tty_say "$(paint '1' 'Isto será removido:')" while IFS= read -r path; do if [[ ! -L "$path" && -f "$path" ]]; then tty_say " $path" fi done < <(server_owned_paths) while true; do tty_say "" menu_row 1 Confirmar "apaga só as chaves de servidor" menu_row 2 Voltar "não altera nada" choice="$(read_choice)" case "$choice" in 1|confirmar) undo_server_apply; return 0 ;; 2|voltar|q) info "Nada foi alterado." return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } show_server_help() { tty_say "" tty_say "$(paint '1;36' 'Servidor')" tty_say "A chave fica dentro da YubiKey. O arquivo local só aponta para ela." tty_say "O nome separa as credenciais. Sem nome usa server-yuc e server-yua." tty_say "1. Crie a credencial residente no token." tty_say "2. Ou recupere a credencial, se ela já estiver no token." tty_say "3. Cole no servidor o comando que o script mostra para o authorized_keys." tty_say "4. Conecte com user@ip. O token pede PIN e toque." tty_say "No Conectar, Salvar favorito grava um nome para esse user@ip." tty_say "O menu inicial mostra os favoritos e as 6 últimas conexões. Um número conecta." tty_say "Sem este script, o comando é o que Conectar imprime. A forma é:" tty_say " ssh -i ARQUIVO -o IdentitiesOnly=yes -o IdentityAgent=none -- user@ip" tty_say "Desfazer apaga só esses arquivos, não as chaves do GitHub." } prompt_server_name() { local choice name n i nova voltar local -a names=() slots=() read_server_names if ((${#SERVER_NAMES[@]} > 0)); then names=("${SERVER_NAMES[@]}") fi while true; do tty_say "" tty_say "$(paint '1' 'Qual nome?')" n=0 slots=() n=$((n + 1)) slots+=("") menu_row "$n" "sem nome" "chaves server-yuc e server-yua" if ((${#names[@]} > 0)); then for i in "${!names[@]}"; do n=$((n + 1)) slots+=("${names[$i]}") menu_row "$n" "${names[$i]}" "credencial de servidor" done fi nova=$((n + 1)) voltar=$((n + 2)) menu_row "$nova" Nova "grava um nome novo" menu_row "$voltar" Voltar "retorna ao menu" choice="$(read_choice)" if [[ "$choice" == "$voltar" || "$choice" == "voltar" || "$choice" == "q" ]]; then return 1 fi for i in "${!slots[@]}"; do if [[ -n "${slots[$i]}" && "$choice" == "${slots[$i]}" ]]; then printf '%s' "${slots[$i]}" return 0 fi done if [[ "$choice" == "$nova" || "$choice" == "nova" ]]; then name="$(tty_prompt "$(paint '1' 'Nome: ')")" name="$(normalize_account_name "$(trim "$name")")" if ! valid_account_name "$name"; then tty_say "$(paint '33' 'Use letras minúsculas, números e hífen. Exemplo: casa')" continue fi SERVER_NAME="$name" remember_server_name names+=("$name") printf '%s' "$name" return 0 fi if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= n )); then printf '%s' "${slots[choice-1]}" return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } server_with_name() { local action="$1" name label name="$(prompt_server_name)" || return 0 SERVER_NAME="$name" if [[ "$action" == pub ]]; then show_server_public_keys || true return 0 fi label="$(prompt_label)" || return 0 case "$action" in create) create_server_key "$label" interactive || true ;; add) add_server_key "$label" || true ;; install) install_server_key "$label" interactive || true ;; connect) connect_server "$label" interactive || true ;; esac } server_menu() { local choice while true; do tty_say "" tty_say "$(paint '1;36' 'Servidor')" tty_say "" menu_row 1 Criar "grava a credencial residente no token" menu_row 2 Recuperar "lê a chave do token conectado agora" menu_row 3 Instalar "envia a chave pública para o servidor" menu_row 4 Conectar "abre ssh em user@ip com essa chave" menu_row 5 Recentes "entra de novo em um servidor já usado" menu_row 6 Favoritos "conecta ou remove um user@ip salvo" menu_row 7 Públicas "mostra o comando para o authorized_keys" menu_row 8 Ajuda "explica criar, instalar e conectar" menu_row 9 Desfazer "remove só as chaves de servidor deste computador" menu_row 10 Voltar "retorna ao menu inicial" choice="$(read_choice)" case "$choice" in 1|criar|create) server_with_name create ;; 2|recuperar|add) server_with_name add ;; 3|instalar|install) server_with_name install ;; 4|conectar|connect) server_with_name connect ;; 5|recentes) show_recent_servers || true ;; 6|favoritos) show_favorites || true ;; 7|publicas|pub) server_with_name pub ;; 8|ajuda|help|\?) show_server_help ;; 9|desfazer|undo) undo_server_interactive ;; 10|voltar|q) return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } run_command() { local command="$1" shift || true case "$command" in create) parse_github_args "$@" create_key "$GH_LABEL" batch "$GH_SERIAL" ;; add) parse_github_args "$@" add_key "$GH_LABEL" ;; use) parse_github_args "$@" use_key "$GH_LABEL" ;; test) test_github ;; pub) parse_pub_args "$@" show_public_batch "$GH_LABEL" ;; status) status ;; list) list_keys ;; undo) undo_apply ;; server-create) parse_server_args required "$@" create_server_key "$SV_LABEL" batch "$SV_SERIAL" ;; server-add) parse_server_args required "$@" add_server_key "$SV_LABEL" ;; server-install) parse_server_args required "$@" install_server_key "$SV_LABEL" batch "$SV_TARGET" ;; server-connect) parse_server_args required "$@" connect_server "$SV_LABEL" batch "$SV_TARGET" ;; server-pub) parse_server_args optional "$@" show_server_public_batch "$SV_LABEL" ;; server-undo) undo_server_apply ;; help|-h|--help) usage ;; *) usage; die "Comando desconhecido: ${command}" ;; esac } read_choice() { local choice choice="$(tty_prompt "$(paint '1' 'Número: ')")" choice="$(trim "$choice")" printf '%s' "$choice" | tr '[:upper:]' '[:lower:]' } prompt_account() { local choice name n i nova voltar local -a names=() slots=() read_account_names if ((${#ACCOUNT_NAMES[@]} > 0)); then names=("${ACCOUNT_NAMES[@]}") fi while true; do tty_say "" tty_say "$(paint '1' 'Qual conta?')" n=0 slots=() if legacy_github_keys_present || ((${#names[@]} == 0)); then n=$((n + 1)) slots+=("") menu_row "$n" "sem nome" "chaves github-yuc e github-yua" fi if ((${#names[@]} > 0)); then for i in "${!names[@]}"; do n=$((n + 1)) slots+=("${names[$i]}") menu_row "$n" "${names[$i]}" "conta do GitHub" done fi nova=$((n + 1)) voltar=$((n + 2)) menu_row "$nova" Nova "grava um nome novo" menu_row "$voltar" Voltar "retorna ao menu" choice="$(read_choice)" if [[ "$choice" == "$voltar" || "$choice" == "voltar" || "$choice" == "q" ]]; then return 1 fi if ((${#slots[@]} > 0)); then for i in "${!slots[@]}"; do if [[ -n "${slots[$i]}" && "$choice" == "${slots[$i]}" ]]; then printf '%s' "${slots[$i]}" return 0 fi done fi if [[ "$choice" == "$nova" || "$choice" == "nova" ]]; then name="$(tty_prompt "$(paint '1' 'Nome: ')")" name="$(normalize_account_name "$(trim "$name")")" if ! valid_account_name "$name"; then tty_say "$(paint '33' 'Use letras minúsculas, números e hífen. Exemplo: trabalho')" continue fi ACCOUNT="$name" remember_account names+=("$name") printf '%s' "$name" return 0 fi if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= n )); then printf '%s' "${slots[choice-1]}" return 0 fi tty_say "$(paint '33' 'Escolha um número da lista.')" done } github_with_account() { local account label action action="$1" account="$(prompt_account)" || return 0 ACCOUNT="$account" case "$action" in pub) show_public_keys || true return 0 ;; esac label="$(prompt_label)" || return 0 case "$action" in create) create_key "$label" interactive || true ;; add) add_key "$label" || true ;; use) use_key "$label" || true ;; esac } github_menu() { local choice while true; do tty_say "" tty_say "$(paint '1;36' 'GitHub')" tty_say "$(active_summary)" tty_say "" menu_row 1 Criar "grava a credencial da conta no token" menu_row 2 Recuperar "lê a chave dessa conta no token" menu_row 3 Usar "ativa a conta em git@github.com" menu_row 4 Testar "autentica em git@github.com" menu_row 5 Status "mostra a conta ativa" menu_row 6 Listar "mostra a YubiKey conectada e as chaves recuperadas" menu_row 7 Públicas "mostra a chave para cadastrar nessa conta" menu_row 8 Ajuda "explica o nome, YUC, YUA e o fluxo" menu_row 9 Desfazer "remove o que este helper gravou neste computador" menu_row 10 Voltar "retorna ao menu inicial" choice="$(read_choice)" case "$choice" in 1|criar|create) github_with_account create ;; 2|recuperar|add) github_with_account add ;; 3|usar|use) github_with_account use ;; 4|testar|test) test_github || true ;; 5|status) status || true ;; 6|listar|list) list_keys || true ;; 7|publicas|pub) github_with_account pub ;; 8|ajuda|help|\?) show_help ;; 9|desfazer|undo) undo_interactive ;; 10|voltar|q) return 0 ;; *) tty_say "$(paint '33' 'Escolha um número da lista.')" ;; esac done } interactive() { local choice n sair i require_tty while true; do tty_say "" tty_say "$(paint '1;36' 'fido')" tty_say "" menu_row 1 GitHub "alterna as YubiKeys na conta do GitHub" menu_row 2 Servidor "entra em um servidor com a YubiKey" load_home_shortcuts n=2 if ((${#HOME_TITLES[@]} > 0)); then for i in "${!HOME_TITLES[@]}"; do n=$((n + 1)) menu_row "$n" "${HOME_TITLES[$i]}" "${HOME_DETAILS[$i]}" done fi sair=$((n + 1)) menu_row "$sair" Sair "encerra" choice="$(read_choice)" case "$choice" in 1|github) github_menu ;; 2|servidor|ssh) server_menu ;; q|sair) return 0 ;; *) if [[ "$choice" == "$sair" ]]; then return 0 fi if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 3 && choice < sair )); then i=$((choice - 3)) SERVER_NAME="${HOME_NAMES[$i]}" connect_server "${HOME_LABELS[$i]}" interactive "${HOME_TARGETS[$i]}" || true else tty_say "$(paint '33' 'Escolha um número da lista.')" fi ;; esac done } migrate_legacy_names() { if [[ -f "$LEGACY_CONFIG_FILE" && ! -e "$CONFIG_FILE" && ! -L "$LEGACY_CONFIG_FILE" ]]; then mv "$LEGACY_CONFIG_FILE" "$CONFIG_FILE" fi if [[ -f "$LEGACY_SERVER_HOSTS" && ! -e "$SERVER_HOSTS" && ! -L "$LEGACY_SERVER_HOSTS" ]]; then mv "$LEGACY_SERVER_HOSTS" "$SERVER_HOSTS" fi [[ -f "$MAIN_CONFIG" && ! -L "$MAIN_CONFIG" ]] || return 0 if ! grep -Fqx "$LEGACY_INCLUDE_LINE" "$MAIN_CONFIG"; then return 0 fi local tmp line has_new=0 wrote_new=0 if grep -Fqx "$INCLUDE_LINE" "$MAIN_CONFIG"; then has_new=1 fi tmp="$(mktemp "${TMPDIR:-/tmp}/fido.XXXXXX")" while IFS= read -r line || [[ -n "$line" ]]; do if [[ "$line" == "$LEGACY_INCLUDE_LINE" ]]; then if (( has_new == 0 && wrote_new == 0 )); then printf '%s\n' "$INCLUDE_LINE" >> "$tmp" wrote_new=1 fi continue fi printf '%s\n' "$line" >> "$tmp" done < "$MAIN_CONFIG" cat "$tmp" > "$MAIN_CONFIG" rm -f "$tmp" } main() { umask 077 migrate_legacy_names case "${1:-}" in help|-h|--help) usage return 0 ;; esac local batch=0 if [[ "${1:-}" == "--batch" ]]; then batch=1 shift || true fi if (( batch == 0 )); then if [[ $# -gt 0 ]]; then die "Este helper pergunta no terminal. Para um comando direto, use --batch. Exemplo: --batch add 1" fi interactive return 0 fi local command="${1:-}" if [[ -z "$command" ]]; then die "No modo --batch informe o comando. Exemplo: --batch add 1" fi shift || true run_command "$command" "$@" } # curl | bash deixa BASH_SOURCE vazio. source nos testes preenche BASH_SOURCE # com o caminho deste arquivo, diferente de $0. if [[ -z "${BASH_SOURCE[0]:-}" || "${BASH_SOURCE[0]:-}" == "$0" ]]; then main "$@" fi