summaryrefslogtreecommitdiff
path: root/zsh/functions/op-ssh-add
blob: 6bbdd13697674d357b36515429d64c2ecb71bd8e (plain)
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
# -*- mode: sh -*-

# op-ssh-add will add SSH keys to the agent, but will fetch the
# passphrase in 1Password rather than prompt you for it.
#
# To be found, keys must have the following three things:
#
#   1. Have the password field set to the passphrase of the key,
#   2. Have an ‘SSH’ tag set, and
#   3. Have a ‘fingerprint’ field set to the fingerprint of the key.
#
# You must also have the 1Password CLI 2 installed.

if [[ ${@[1]} =~ '-[DdKLlTXx]' ]]; then
  command ssh-add $@
  return $?
fi

local args=$@ fp prv pub
for prv (${@[-1]} ~/.ssh/id_{ecdsa,ed25519}{_sk,}); do
  if [[ -f ${prv}.pub ]]; then
    pub=${prv}.pub
    fp=$(cut -d' ' -f2 <<< $(ssh-keygen -f ${pub} -l))
    if [[ ${prv} != ${@[-1]} ]]; then
      args+=(${prv})
    fi
    break
  fi
done

if [[ -z ${pub} ]]; then
  command ssh-add $@
  return $?
fi

local session=$(op signin --raw)
if [[ -z ${session} ]]; then
  return 1
fi

zmodload zsh/zpty
zpty ssh command ssh-add ${args}

_cleanup() {
  zpty -d ssh
  op signout --session $1
  trap -
  unfunction _cleanup
}
trap "_cleanup ${session}" EXIT HUP INT TERM

zpty -w ssh $(trap -
              op item list --format json --session ${session} --tags SSH \
                | op item get                                            \
                     --fields fingerprint,password                       \
                     --session ${session} -                              \
                | grep ${fp} | cut -d, -f2)
zpty -r ssh