-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzsh-bitwarden.zsh
1233 lines (1039 loc) · 31.7 KB
/
zsh-bitwarden.zsh
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# zsh-bitwarden -- A Bitwarden CLI wrapper for Zsh
# https://github.com/Game4Move78/zsh-bitwarden
# Copyright (c) 2021 Patrick Lenihan
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
_bw_pipefail() {
# Usage _bw_pipefail ${pipestatus[@]}
for st in "$@"; do
if [[ "$st" -ne 0 ]]; then
return $st
fi
done
}
_bw_get_alias() {
local found_alias=$(alias | grep -E "=\W*$1\W*$" | cut -d'=' -f1)
if [ -z "$found_alias" ]; then
echo "$1"
else
echo "$found_alias"
fi
}
_bw_test_subshell() {
local pid=$(exec sh -c 'echo $PPID')
if [[ "$$" == "$pid" ]]; then
return 0
else
return 1
fi
}
bw_escape_jq() {
sed -e 's/\t/\\t/g' -e 's/\n/\\n/g' -e 's/\r/\\r/g'
}
bw_raw_jq() {
sed -e 's/\\t/\t/g' -e 's/\\n/\n/g' -e 's/\\r/\r/g' -e 's/\\\\/\\/g'
}
export BW_DEFAULT_HEADERS="${0:h}/default-headers.csv"
bw_default_header() {
while IFS=$'\n' read -r line; do
local key=$(printf "%s" "$line" | awk -F, '{print $1}' | sed 's/^"//; s/"$//')
local value=$(printf "%s" "$line" | awk -F, '{print $2}' | sed 's/^"//; s/"$//')
if [[ "$key" == "$1" ]]; then
printf "%s" "$value"
return
fi
done < "$BW_DEFAULT_HEADERS"
printf "%s" "$1"
# case "$1" in
# ".id") printf "%s" "Item ID" ;;
# ".login.username"|".username") printf "%s" "Username" ;;
# ".login.password"|".password") printf "%s" "Password" ;;
# ".name") printf "%s" "Name" ;;
# *) printf "%s" "$1"
# esac
}
# Takes JSON as stdin and jq paths to extract into tsv as args
bw_table() {
local -a nskiparg harg Harg
zparseopts -D -K -E -- \
-nskip:=nskiparg \
{h,-headers}+:=harg \
{H,-rev-headers}+:=Harg \
|| return
if [[ "$#" == 0 ]]; then
echo "Usage: $0 [PATH]..."
return 1
fi
local headers=()
local nskip=0
if (( $#nskiparg )); then
nskip="${nskiparg[-1]}"
fi
for (( i = 1; i <= $#; i++)); do
local header=""
if [[ "$i" -le "$nskip" ]]; then
header=$(bw_default_header "${(P)i}")
elif [[ "$#harg" -ge "$(( (i - nskip) * 2 ))" ]]; then
header="${harg[$(( (i - nskip) * 2 ))]}"
elif [[ "1" -le "$(( (i + nskip - $#) * 2 + $#Harg ))" ]]; then
header="${Harg[$(( (i + nskip - $#) * 2 + $#Harg ))]}"
else
header=$(bw_default_header "${(P)i}")
fi
if [[ "$header" == $'\t' ]]; then
header=$(bw_default_header "${(P)i}")
fi
headers+=("$header")
done
local json=$(</dev/stdin)
# Comma-join arguments
local width=$#
local keys="($1)? // null"
for key in "${@:2}"; do
keys="$keys, ($key)? // null"
done
local jq_output
# Construct tsv with values selected using args
jq_output=$(
printf "%s" "$json" \
| jq -rceM "to_entries | .[] | [.key] + [.value|($keys)] | select(all(.[]; . != null) and length == $width + 1) | map(tostring) | @tsv" 2> /dev/null
) || return $?
if [[ -z "$jq_output" ]]; then
echo "Error: No results." >&2
return 1
fi
# Output arguments as tsv header
printf "%s" "idx"
for arg in "${headers[@]}"; do
printf "\t%s" "$arg"
done
printf "\n"
printf "%s\n" "$jq_output"
}
#NOTE: bw escapes \t\n
# Takes tsv as stdin and columns to show in fzf as args
_bw_select() {
# Read input from stdin
local tsv=$(</dev/stdin)
# Validate that the input TSV is not empty
if [[ -z "$tsv" ]]; then
echo "Error: No input provided. Please provide a valid TSV input." >&2
return 1
fi
# Construct a formatted table with row indices
# local tbl=$( \
# printf "%s" "$tsv" \
# | cut -f2-
# | column -t -s $'\t'
# )
# local ids=$(
# printf "%s" "$tsv" | cut -f1
# )
local tbl=$(paste \
<(printf "%s" "$tsv" | cut -f1) \
<(printf "%s" "$tsv" | cut -f2- | column -t -s $'\t') \
)
_bw_pipefail ${pipestatus[@]}
# Check if the table was generated correctly
if [[ "$?" -ne 0 || -z "$tbl" ]]; then
echo "Error: Unable to generate table. Please check the column indices." >&2
return 1
fi
local row
row=$( \
printf "%s" "$tbl" \
| fzf -d $'\t' --with-nth=2 --select-1 --header-lines=1 \
| awk '{print $1}' \
)
_bw_pipefail ${pipestatus[@]}
if [[ "$?" -ne 0 || -z "$row" ]]; then
echo "Couldn't return value from fzf. Is the header line missing?" >&2
return 2
fi
# Output the corresponding row from the original tsv
printf "%s" "$row"
}
DEBUG_ARRAY_FLAG=1
debug_array() {
(( DEBUG_ARRAY_FLAG )) || return 0
for arg in "$@"; do
printf "%s\n" "$arg" >&2
done
}
bw_search() {
local -a header_queue header_args raw_queue raw_list jqout jqtbl
local i=1
local -a carg=("$@")
local curr next isout istbl
while (( i <= $#carg )); do
#TODO: Ordered header arguments
curr="${carg[$i]}"
isout=0 istbl=0
i=$(( i + 1 ))
if [[ "$curr" == ("-h"|"-o"|"-c"|"-O") && $#carg -ge $i ]]; then
next="${carg[$i]}"
i=$(( i + 1 ))
if [[ "$curr" == "-h" ]]; then
header_queue+=("$next")
continue
else
[[ "$curr" != "-c" ]] && isout=1
[[ "$curr" != "-O" ]] && istbl=1
fi
elif [[ "$curr" == "-r" ]]; then
raw_queue+=(1)
continue
else
next="$curr"
isout=0
istbl=1
fi
if (( isout )); then
jqout+=("$next")
if [[ "$#raw_queue" -eq 0 ]]; then
raw_list+=(0)
else
raw_list+=(1)
raw_queue=("${raw_queue[@]:1}")
fi
fi
if (( istbl )); then
jqtbl+=("$next")
if [[ "$#header_queue" -eq 0 ]]; then
next=$(bw_default_header "$next")
header_args+=("-h" "$next")
else
header_args+=("-h" "${header_queue[1]}")
header_queue=("${header_queue[@]:1}")
fi
fi
done
if [[ $#raw_list != $#jqout ]]; then
echo "raw list error $#raw_list $#jqout" >&2
return 1
fi
if [[ $#header_args != $(( $#jqtbl * 2)) ]]; then
echo "ERROR" >&2
return 1
fi
# Ensure there are visible and output fields
if [[ "${#jqtbl}" == 0 ]]; then
echo "No visible fields entered" >&2
return 1
fi
if [[ "${#jqout}" == 0 ]]; then
jqout=(".")
raw_queue+=(1)
# echo "No output fields entered" >&2
# return 2
fi
# Search using bitwarden
local items=$(</dev/stdin)
local noitems tsv row
noitems=$(printf "%s" "$items" | jq '. | length')
if [ $? -ne 0 ] || [ -z "$items" ] \
|| [ "$noitems" -eq "0" ]; then
echo "No results found. Try '' to search all items." >&2
return 4
fi
local -a bw_table_args
bw_table_args+=("${header_args[@]}")
(( $#nskiparg )) && bw_table_args+=("${nskiparg[@]}")
bw_table_args+=("${jqtbl[@]}")
tsv=$(printf "%s" "$items" | bw_table "${bw_table_args[@]}")
if [ $? -ne 0 ]; then
echo "Failed to construct tsv" >&2
return 4
fi
local -a bw_select_args
bw_select_args+=("${jqout[@]}")
row=$(printf "%s" "$tsv" | _bw_select)
if [ $? -ne 0 ]; then
echo "Failed to select row" >&2
return 4
fi
local item key raw entry
local -a jq_args
item=$(printf "%s" "$items" | jq "${jq_args[@]}" -ceM ".[$row]")
for (( i=1; i <= $#jqout; i++ )); do
key="($jqout[$i])?"
jq_args=()
(( raw_list[$i] )) && jq_args=() || jq_args=("-r")
# strip trailing newline
entry=$(printf "%s" "$item" | jq "${jq_args[@]}" -ceM "$key")
printf "%s" "$entry"
if [[ $i -ne $#jqout ]]; then
printf "\x1F"
fi
done
}
bw_request_params() {
if [[ $# -eq 0 ]]; then
return
fi
printf "?%s=%s" "$1" "$2"
local j
for (( i=3, j=4; i <= $#; i += 2, j += 2)); do
printf "&%s=%s" "${(P)i}" "${(P)j}"
done
}
bw_request() {
local method=$1 endpoint=$2 res
local -a data_args
local params=$(bw_request_params "${@:3}")
if ! [[ -t 0 ]]; then
data_args+=("-d" "$(</dev/stdin)")
fi
# local res=$(wget --method="$method" --header="accept: application/json" --header="Content-Type: application/json" --body-data="${data_args[@]}" -qO- "http://localhost:8087$endpoint$params") || return $?
res=$(curl -sX "$method" "http://localhost:8087$endpoint$params" -H 'accept: application/json' -H 'Content-Type: application/json' "${data_args[@]}") || return $?
if ! printf "%s" "$res" | jq empty > /dev/null 2>&1; then
printf "%s\n" "$res" >&2
return 1
fi
local success=$(printf "%s" "$res" | jq -rceM .success)
if [[ "$success" == "false" ]]; then
printf "%s" "$res" | jq -rceM .message >&2
return 1
fi
local jq_cond=$(printf "%s" "$res" | jq -ceM 'has("data")')
if [[ "$jq_cond" == "true" ]]; then
res=$(printf "%s" "$res" | jq -ceM .data)
fi
printf "%s" "$res"
}
bw_request_path() {
local -a rarg narg
zparseopts -D -K -E -- \
r=rarg \
n=narg || return
local method="$1" endpoint="$2" jqpath="$3" res exitcode
local params_list=("${@:4}")
res=$(bw_request "$method" "$endpoint" "${params_list[@]}"| jq "${rarg[@]}" -ceM "$jqpath")
_bw_pipefail ${pipestatus[@]} || return $?
printf "%s" "$res"
if (( !$#narg )); then
echo
fi
}
bw_status() {
local res
res=$(bw_request_path -rn GET '/status' '.template.status') || return $?
printf "%s\n" "$res" >&2
if [[ "$res" == "unlocked" ]]; then
return 0
else
return 1
fi
}
bw_sync() {
local res
bw_request_path -r POST '/sync' '.title' || return $?
}
bw_serve() {
if ! pgrep -f "bw serve" > /dev/null 2>&1; then
nohup bw serve > /dev/null 2> /dev/null &
sleep 2
fi
}
bw_unlock() {
bw_serve
local st
if st=$(bw_status) 2> /dev/null; then
return
fi
local pass
echo -n "Enter your master password: " >&2
if ! read -s pass; then
echo
return 1
fi
echo
local res exitcode
printf "%s" "$pass" | awk '{print "{\"password\":\"" $0 "\"}"}' | bw_request_path -r POST /unlock .title >&2
}
bw_lock() {
bw_serve
local st res
if ! st=$(bw_status) 2> /dev/null; then
return
fi
bw_request_path -r POST /lock .title
}
bw_generate() {
local -a larg uarg sarg narg lengtharg
zparseopts -D -F -K -- \
{l,-lowercase}=larg \
{u,-uppercase}=uarg \
{s,-special}=sarg \
{n,-number}=narg \
-length:=lengtharg || return
bw_unlock || return $?
local -a param_list
(( $#larg)) && param_list+=( "lowercase" "true" )
(( $#uarg)) && param_list+=( "uppercase" "true" )
(( $#sarg)) && param_list+=( "special" "true" )
(( $#narg)) && param_list+=( "number" "true" )
(( $#lengtharg)) && param_list+=( "length" "${lengtharg[-1]}" )
bw_request_path -rn GET "/generate$params" .data "${param_list[@]}"
}
bw_template() {
bw_request_path -n GET /object/template/item .template
}
bw_list_cache() {
bw_unlock || return $?
local res
bw_request_path -n GET /list/object/items .data
}
bw_simplify() {
jq -ceM "[.[] | {
id: .id,
name: .name,
notes: .notes,
username: .login.username,
password: .login.password,
fields: ((.fields | group_by(.name) | map({(.[0].name): map(.value)}) | add )? // {})
}]"
}
bw_unsimplify() {
local uuid item old_item
item=$(jq -ceM '{
id: .id,
name: .name,
notes: .notes,
fields: [
.fields | to_entries[] |
.value[] as $v |
{name: .key, value: $v, type: 0, linkedId: null}
],
login: {
username: .username,
password: .password
}
}') || return $?
uuid=$(printf "%s" "$item" | jq -rceM ".id") || return $?
if [[ "$uuid" == "null" ]]; then
old_item=$(bw_template) || return $?
else
old_item=$(bw_list_cache | bw_get_item "$uuid") || return $?
fi
printf "%s" "$old_item $item" | jq -ceMs ".[0] * .[1]" || return $?
}
bw_list() {
local -a sarg sxarg jarg garg simplifyarg larg narg
zparseopts -D -F -K -- \
{s,-search-all}+:=sarg \
{-search-name,-search-user,-search-pass,-search-note}+:=sxarg \
{j,-search-jq}:=jarg \
{g,-group-fields}=garg \
-simplify=simplifyarg \
{l,-login}=larg \
{n,-note}=narg || return
local items
items=$(bw_list_cache) || return $?
for (( i = 2; i <= $#sarg; i+=2)); do
items=$(printf "%s" "$items" | jq -ceM "[.[] | select(
reduce [ .id, .name, .notes, .login.username, .login.password, (.fields[]?.value) ][] as \$field
(false; . or (\$field // \"\" | test(\"${sarg[$i]}\";\"i\")))
)]") || return $?
done
for (( i = 1; i <= $#sxarg; i+=2)); do
local jqpath=""
case "${sxarg[$i]}" in
"--search-name")
jqpath=".name"
;;
"--search-user")
jqpath=".login.username"
;;
"--search-pass")
jqpath=".login.password"
;;
"--search-notes")
jqpath=".login.notes"
;;
esac
items=$(printf "%s" "$items" | jq -ceM "[.[] | select($jqpath | test(\"${sxarg[(( $i + 1 ))]}\";\"i\")?)]") || return $?
done
# local items=$(bw list items --search "${sarg[-1]}")
if (( $#larg || $#narg)); then
local item_type
if (( $#larg)); then
item_type=1
elif (( $#narg )); then
item_type=2
fi
items=$(printf "%s" "$items" | jq -ceM "[.[] | select(.type == $item_type)]") || return $?
fi
if (( $#simplifyarg )); then
items=$(printf "%s" "$items" | bw_simplify) || return $?
elif (( $#garg )); then
items=$(printf "%s" "$items" | bw_group_fields) || return $?
fi
for (( i = 2; i <= $#jarg; i+=2)); do
items=$(printf "%s" "$items" | jq -ceM "[.[] | select((${jarg[$i]})? // false)]") || return $?
done
# Command substitution removes newline
printf "%s\n" "$items"
}
bw_copy() {
clipcopy
}
bw_tsv() {
local -a \
itemsonlyarg \
sarg \
sxarg \
jarg \
garg \
simplifyarg \
larg \
narg \
parg \
carg \
targ
zparseopts -D -K -E -- \
-items-only=itemsonlyarg \
{s,-search-all}+:=sarg \
{-search-name,-search-user,-search-pass,-search-note}+:=sxarg \
{j,-search-jq}:=jarg \
{g,-group-fields}=garg \
-simplify=simplifyarg \
{l,-login}=larg \
{n,-note}=narg \
{p,-clipboard}=parg \
{t,-table}=targ || return
if (( !$#parg )) && { (( $#targ )) || ! [[ -t 1 ]]; }; then
parg+=("-p")
fi
local res
local -a bw_table_args
(( $#nskiparg )) && bw_table_args+=("${nskiparg[@]}")
local items
if [[ -t 0 ]]; then
local -a bw_list_args
(( $#sarg )) && bw_list_args+=("${sarg[@]}")
(( $#sxarg )) && bw_list_args+=("${sxarg[@]}")
(( $#jarg )) && bw_list_args+=("${jarg[@]}")
(( $#garg )) && bw_list_args+=("${garg[@]}")
(( $#simplifyarg )) && bw_list_args+=("${simplifyarg[@]}")
(( $#larg )) && bw_list_args+=("${larg[@]}")
(( $#narg )) && bw_list_args+=("${narg[@]}")
items=$(bw_list "${bw_list_args[@]}")
if (( $#itemsonlyarg )); then
printf "%s" "$items"
return
fi
else
items=$(</dev/stdin)
fi
if (( $#targ )); then
IFS='' res=$(printf "%s" "$items" | bw_table "${bw_table_args[@]}" "$@") || return $?
else
local -a bw_search_args
IFS='' res=$(printf "%s" "$items" | bw_search "${bw_table_args[@]}" "${bw_search_args[@]}" "$@") || return $?
fi
if (( $#parg )); then
printf "%s" "$res"
else
printf "%s" "$res" | bw_copy
fi
}
# bw_read_results() {
# local res=$(</dev/stdin)
# local -a values
# IFS=$'\x1F' values=($(printf "%s" "$res"))
# for (( i=1; i<=$#; i++)); do
# var="${(P)i}"
# val="${values[$i]}"
# # echo eval "$var='$val'" | cat -A
# eval "$var='$val'"
# done
# }
bw_connect_wifi() {
bw_unlock || return $?
local -a res
local ssids jqfilter
ssids=$(nmcli device wifi list | grep -v 'SSID' | grep -v '|' | awk '{print $2}' | paste -sd'|')
items=$(bw_list -l "$@" | jq -ceM "[.[] | select((.login.username | test(\"^($ssids)\$\"))?)]")
IFS=$'\x1F' res=($(printf "%s" "$items" | bw_search -c .name -o .login.username -O .login.password))
_bw_pipefail ${pipestatus[@]} || return $?
user="${res[1]}" pass="${res[2]}"
printf "%s" "$pass" | nmcli --ask c up "$user"
}
bw_user_pass() {
local -a sarg
bw_unlock || return $?
local user pass
local -a res
IFS=$'\x1F' res=($(bw_list -l "$@" | bw_search -c .name -o .login.username -O .login.password))
_bw_pipefail ${pipestatus[@]}
user="${res[1]}" pass="${res[2]}"
if [[ "$?" -ne 0 ]]; then
return 2
fi
echo -n "Hit enter to copy username..."
read _ && printf "%s" "$user" | clipcopy
echo -n "Hit enter to copy password..."
read _ && printf "%s" "$pass" | clipcopy
}
bw_select_values() {
jq -rceM "[.[] | $1] | unique | .[]" \
| fzf --header="$2" --print-query \
| awk 'NR == 1 && $0 != "" { print $0; exit } NR == 2 { print $0; exit }'
_bw_pipefail ${pipestatus[@]}
}
bw_select_field() {
bw_select_values '.fields[]?.name?' "field"
}
bw_group_fields() {
jq -ceM '[.[] | . as $item | .fields? | to_entries? | .[] as $field | $item | .fields=$field]'
}
# bw_field_old() {
# local -a sarg farg
# zparseopts -D -K -E -- \
# {p,-clipboard}=parg \
# {f,-field}:=farg || return
# local items=$(bw_list -g "$@")
# local name
# if (( $#farg)); then
# name="${farg[-1]}"
# else
# name=$(printf "%s" "$items" | bw_select_field)
# fi
# #local fieldpath="[.fields[] | select(.name == \"$name\") | .value] | first"
# local fieldpath=".fields.value | select(.name == \"$name\") | .value"
# local res=$(printf "%s" "$items" | bw_search \
# -c .name \
# -H "$name" -o "$fieldpath")
# if (( $#parg )); then
# printf "%s" "$res"
# else
# printf "%s" "$items" | bw_copy
# fi
# }
bw_field() {
local -a rarg parg farg choosearg
zparseopts -D -K -E -- \
{p,-clipboard}=parg \
{f,-field}:=farg \
-choose=choosearg || return
local items
items=$(bw_tsv -p --items-only --simplify "$@") || return $?
local res item name
if (( $#farg || $#choosearg )); then
if (( $#farg )); then
name="${farg[-1]}"
elif (( $#choosearg)); then
name=$(printf "%s" "$items" | bw_select_values '.fields | keys_unsorted | .[]' "field") || return $?
fi
item=$(printf "%s" "$items" | bw_tsv \
-r -O . \
-c .name \
-h "$name" -c ".fields[\"$name\"] | select(length > 0) | join(\", \")" "$@") || return $?
else
item=$(printf "%s" "$items" | bw_tsv \
-r -O . \
-c .name \
-h fields -c ".fields | keys_unsorted | select(length > 0) | join(\", \")" "$@" \
) || return $?
name=$(printf "%s" "$item" | jq -ceM ".fields | to_entries" | bw_search \
-h field -o '.key' \
-h value -c '.value | join(", ")') || return $?
fi
res=$(printf "%s" "$item" | jq -ceM ".fields[\"$name\"]" | bw_search -h "$name" -o .)
_bw_pipefail ${pipestatus[@]}
if (( $#parg )); then
printf "%s" "$res"
else
printf "%s" "$res" | bw_copy
fi
}
bw_get_item() {
jq -ceM ".[] | select(.id == \"$1\")$2"
}
bw_edit_json() {
local item=$(</dev/stdin)
local uuid
uuid=$(printf "%s" "$item" | jq -rceM ".id") || return $?
if [[ "$uuid" == "null" ]]; then
printf "%s" "$item" | bw_request POST /object/item
else
printf "%s" "$item" | bw_request PUT "/object/item/$uuid"
fi
}
bw_edit_item() {
# bw_reset_cache_list
jq -ceM "$2" | bw_request PUT "/object/item/$1"
}
bw_edit_item_assign() {
bw_edit_item "$1" "$2 = \"$3\""
}
bw_edit_item_append() {
bw_edit_item "$1" "$2 += [$3]"
}
bw_edit_field() {
local -a narg rarg darg farg
zparseopts -D -K -E -- \
{n,-new}=narg \
{r,-rename}=rarg \
{d,-delete}=darg \
{f,-field}:=farg || return
bw_unlock || return $?
local items
items=$(bw_tsv -p --items-only --simplify "$@") || return $?
local -a res
local item
local name
if (( $#farg || $#choosearg )); then
if (( $#farg )); then
name="${farg[-1]}"
elif (( $#choosearg)); then
name=$(printf "%s" "$items" | bw_select_values '.fields | keys_unsorted | .[]' "field") || return $?
fi
item=$(printf "%s" "$items" | bw_tsv \
-r -O . \
-c .name \
-h "$name" -c ".fields[\"$name\"] | select(length > 0) | join(\", \")" "$@") || return $?
else
item=$(printf "%s" "$items" | bw_tsv \
-r -O . \
-c .name \
-h fields -c ".fields | keys_unsorted | select(length > 0) | join(\", \")" "$@" \
) || return $?
name=$(printf "%s" "$item" | jq -ceM ".fields | to_entries" | bw_search \
-h field -o '.key' \
-h value -c '.value | join(", ")') || return $?
fi
local item uuid idx value
uuid=$(printf "%s" "$item" | jq -rceM ".id")
IFS=$'\x1F' res=($(printf "%s" "$item" | jq -ceM ".fields[\"$name\"] | to_entries" | bw_search -O .key -h "$name" -o .value))
_bw_pipefail ${pipestatus[@]}
# printf "%s" "$res" | bw_read_results idx val || return $?
idx="${res[1]}" val="${res[2]}"
item=$(printf "%s" "$item" | jq -ceM ". | del(.fields.${name}[$idx])")
if (( $#darg)); then
printf "%s" "$item" | bw_edit_item "$uuid" "del(.fields[$idx])"
_bw_pipefail ${pipestatus[@]}
return $?
fi
if (( $#rarg)); then
if [[ -t 0 ]]; then
vared -p "Edit field name: " name
else
name=$(</dev/stdin)
fi
else
if [[ -t 0 ]]; then
vared -p "Edit field $name: " val
else
val=$(</dev/stdin)
fi
fi
printf "%s" "$item" | jq -ceM ". | .fields.${name}+=[\"$val\"]" | bw_unsimplify | bw_edit_json
_bw_pipefail ${pipestatus[@]}
}
bw_add_field() {
local -a farg
zparseopts -D -K -E -- \
{f,-field}:=farg || return
bw_unlock || return $?
local -a res
local items item name val
items=$(bw_list "$@") || return $?
if (( $#farg)); then
name="${farg[-1]}"
else
name=$(printf "%s" "$items" | bw_select_field) || return $?
fi
local path_val="[(.fields[] | select(.name == \"$name\") | .value) // \"\"] | first"
IFS=$'\x1F' res=($(printf "%s" "$items" | bw_search \
-r -O . \
-O .id -c .name \
-h "$name" -o "$path_val")) || return $?
if [[ $? -ne 0 ]]; then
echo "Couldn't find items with search args $@" >&2
return 1
fi
# printf "%s" "$res" | bw_read_results item uuid val || return $?
item="${res[1]}" uuid="${res[2]}" val="${res[3]}"
if [[ -t 0 ]]; then
vared -p "Field value: " val
else
val=$(</dev/stdin)
fi
local field_json="{\"name\": \"$name\", \"value\": \"$val\"}"
printf "%s" "$item" | bw_edit_item_append "$uuid" ".fields" "$field_json"
}
bw_edit_name() {
bw_unlock || return $?
local items item uuid val res
items=$(bw_list -l "$@") || return $?
IFS=$'\x1F' res=($(printf "%s" "$items" | bw_search \
-r -O . \
-o .name \
-c .login.username \
-O .id)) || return $?
if [[ $? -ne 0 ]]; then
echo "Couldn't find items with search strings $@" >&2
return 1
fi
local -a values
item="${res[1]}" val="${res[2]}" uuid="${res[3]}"
# printf "%s" "$res" | bw_read_results item val uuid || return $?
if [[ -t 0 ]]; then
val=$(printf "%s" "$val" | bw_raw_jq)
vared -p "Edit name: " val
else
val=$(</dev/stdin)
fi
val=$(printf "%s" "$val" | bw_escape_jq)
printf "%s" "$item" | bw_edit_item_assign "$uuid" ".name" "$val"
_bw_pipefail ${pipestatus[@]}
}
bw_filter_type() {
local -a larg narg
zparseopts -D -F -K -- \
{l,-login}=larg \
{n,-note}=narg || return
local item_type
if (( $#larg)); then
item_type=1
elif (( $#narg )); then
item_type=2
else
return 1
fi
jq -ceM "[.[] | select(.type == $item_type)]"
}
bw_edit_username() {
bw_unlock || return $?
local -a res
local items item uuid val
items=$(bw_list -l "$@") || return $?
IFS=$'\x1F' res=($(printf "%s" "$items" | bw_search \
-r -O . \
-c .name \
-o .login.username \
-O .id)) || return $?