This repository has no description
3.2 kB
102 lines
1{ ... }:
2{
3 perSystem =
4 { pkgs, ... }:
5 {
6 packages.pass-otp = pkgs.writeShellApplication {
7 name = "pass-otp";
8 runtimeInputs = [
9 pkgs.oath-toolkit
10 pkgs.xclip
11 pkgs.wl-clipboard
12 ];
13 text = ''
14 set -euo pipefail
15 # Tool-agnostic OTP generator that accepts secret via stdin or args
16
17 show_usage() {
18 echo "Usage: pass-otp [--clip,-c] <secret>"
19 echo " echo <secret> | pass-otp [--clip,-c]"
20 echo ""
21 echo "Accepts OTP secret as argument or via stdin"
22 echo "Secret can be:"
23 echo " - Raw base32 secret"
24 echo " - otpauth:// URL"
25 echo " - Multi-line text with secret on line 2+"
26 }
27
28 clip=false
29 secret_input=""
30
31 # Parse arguments
32 while [[ $# -gt 0 ]]; do
33 case "$1" in
34 "--clip"|"-c")
35 clip=true
36 shift
37 ;;
38 "--help"|"-h")
39 show_usage
40 exit 0
41 ;;
42 *)
43 secret_input="$1"
44 shift
45 ;;
46 esac
47 done
48
49 # If no argument provided, read from stdin
50 if [[ -z "$secret_input" ]]; then
51 secret_input=$(cat)
52 fi
53
54 if [[ -z "$secret_input" ]]; then
55 echo "Error: No OTP secret provided"
56 show_usage
57 exit 1
58 fi
59
60 # Extract TOTP secret from input
61 if echo "$secret_input" | grep -q "^otpauth://"; then
62 # Extract secret from otpauth URL
63 secret_key=$(echo "$secret_input" | sed -n 's/.*secret=\([^&]*\).*/\1/p')
64 elif echo "$secret_input" | wc -l | grep -q "^1$"; then
65 # Single line - assume it's the raw secret
66 secret_key=$(echo "$secret_input" | tr -d ' ')
67 else
68 # Multi-line - assume secret is on line 2 or later
69 secret_key=$(echo "$secret_input" | tail -n +2 | head -n 1 | tr -d ' ')
70 fi
71
72 if [[ -z "$secret_key" ]]; then
73 echo "Error: Could not extract OTP secret from input"
74 exit 1
75 fi
76
77 # Generate OTP code
78 otp_code=$(oathtool --totp --base32 "$secret_key")
79
80 # Output or copy to clipboard
81 if [[ "$clip" == "true" ]]; then
82 if [[ "$(uname)" == "Darwin" ]]; then
83 echo -n "$otp_code" | pbcopy
84 echo "Copied OTP code to clipboard."
85 elif [[ -n "''${WAYLAND_DISPLAY:-}" ]] && command -v wl-copy >/dev/null 2>&1; then
86 echo -n "$otp_code" | wl-copy
87 echo "Copied OTP code to clipboard (Wayland)."
88 elif [[ -n "''${DISPLAY:-}" ]] && command -v xclip >/dev/null 2>&1; then
89 echo -n "$otp_code" | xclip -selection clipboard
90 echo "Copied OTP code to clipboard (X11)."
91 else
92 echo "Error: No clipboard tool found (tried pbcopy, wl-copy, xclip)"
93 echo "$otp_code"
94 exit 1
95 fi
96 else
97 echo "$otp_code"
98 fi
99 '';
100 };
101 };
102}