CLI session (macOS)
The bw
CLI uses a separate session from the desktop app, and there's no easy programmatic way to set up and restore a session using it.
Pop the following in bw_session
on PATH
:
#!/bin/bash
# Ensure we have a Bitwarden session, and dump an export for it to STDOUT.
#
# Usage:
# eval "$(bw_session)"
# bw_session | source
set -eu -o pipefail
function bw_ensure_session() {
local service_name="family.carrier.luke.BW_SESSION"
BW_SESSION=$(security find-generic-password -a "$USER" -s "$service_name" -w || true)
export BW_SESSION
status=$(bw status | jq -r .status)
case "$status" in
"unauthenticated")
echo "Unauthenticated; clearing session token and logging in" >&2
unset BW_SESSION
export BW_SESSION=$(bw login --raw)
security add-generic-password -U -a "$USER" -s "$service_name" -w "$BW_SESSION"
;;
"locked")
echo "Locked; unlocking" >&2
unset BW_SESSION
export BW_SESSION=$(bw unlock --raw)
security add-generic-password -U -a "$USER" -s "$service_name" -w "$BW_SESSION"
;;
"unlocked")
echo "Unlocked; nothing to do" >&2
;;
*)
echo "Unknown status: $status" >&2
return 1
;;
esac
}
bw_ensure_session
printf "export BW_SESSION=%s\n" "$BW_SESSION"