aboutsummaryrefslogtreecommitdiff
path: root/scripts/bokftui-bw
blob: a067581a7c630e003265ba891f70c0befeff4f5c (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/bin/sh
# Start bokftui with a credential fetched from a Bitwarden/Vaultwarden item.
# Runs entirely as the invoking user — no root, no sudo.
#
#   BOKF_BW_ITEM   item name (default: bokf)
#   BOKF_BW_FIELD  custom field that holds the secret (default: the password)
#   BOKF_BW_KIND   password (default) exports BOKFD_PASSWORD;
#                  token exports BOKFD_TOKEN
#
# Works with the official Bitwarden CLI (bw) or with rbw. With bw the session
# key is cached in ~/.cache/bokf/bw-session (mode 0600) so the master password
# is only asked when the session expires or after a logout.
set -eu

item="${BOKF_BW_ITEM:-bokf}"
field="${BOKF_BW_FIELD:-}"
kind="${BOKF_BW_KIND:-password}"
BOKFTUI="${BOKFTUI:-bokftui}"

if command -v rbw >/dev/null 2>&1; then
    if ! rbw unlocked >/dev/null 2>&1; then
        rbw unlock
    fi
    if [ -n "$field" ]; then
        secret=$(rbw get --field "$field" "$item")
    else
        secret=$(rbw get "$item")
    fi
elif command -v bw >/dev/null 2>&1; then
    # The SDK's WASM crypto needs the Web Crypto global; Node < 19 only has
    # it with this flag. Probe with a local command instead of guessing.
    if ! bw generate -uln --length 1 >/dev/null 2>&1; then
        NODE_OPTIONS="${NODE_OPTIONS:-} --experimental-global-webcrypto"
        export NODE_OPTIONS
    fi
    umask 077
    cache="${XDG_CACHE_HOME:-$HOME/.cache}/bokf/bw-session"
    if [ -f "$cache" ]; then
        BW_SESSION=$(cat "$cache")
        export BW_SESSION
    fi
    if ! bw status 2>/dev/null | jq -e '.status == "unlocked"' >/dev/null 2>&1
    then
        mkdir -p "$(dirname "$cache")"
        BW_SESSION=$(bw unlock --raw)
        export BW_SESSION
        printf '%s\n' "$BW_SESSION" > "$cache"
    fi
    if [ -n "$field" ]; then
        secret=$(bw get item "$item" | jq -r --arg f "$field" \
            '.fields[]? | select(.name == $f) | .value' | head -n 1)
    else
        secret=$(bw get password "$item")
    fi
else
    echo "bokftui-bw: install rbw or the Bitwarden CLI (bw)" >&2
    exit 1
fi

if [ -z "$secret" ] || [ "$secret" = "null" ]; then
    echo "bokftui-bw: no secret named '$field' in item '$item'" >&2
    exit 1
fi

case "$kind" in
    token)
        BOKFD_TOKEN="$secret"
        export BOKFD_TOKEN
        ;;
    password)
        BOKFD_PASSWORD="$secret"
        export BOKFD_PASSWORD
        ;;
    *)
        echo "bokftui-bw: BOKF_BW_KIND must be password or token" >&2
        exit 1
        ;;
esac

exec "$BOKFTUI" "$@"