-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0xchat-cli
More file actions
executable file
·4488 lines (4079 loc) · 176 KB
/
Copy path0xchat-cli
File metadata and controls
executable file
·4488 lines (4079 loc) · 176 KB
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
#!/usr/bin/env bash
set -u
set -o pipefail
readonly SCRIPT_NAME="0xchat-cli"
readonly SCRIPT_VERSION="0.37.0"
readonly DEFAULT_CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/0xchat-cli"
# Centralized limits and defaults per Specification
readonly DEFAULT_GET_LIMIT=20
readonly MAX_GET_LIMIT=200
readonly MAX_CONTACT_RECIPIENTS=20
readonly MAX_GROUP_MEMBERS=20
readonly MAX_TEXT_MESSAGES=20
readonly MAX_RELAYS=20
readonly EXIT_OK=0
readonly EXIT_ERROR=1
readonly EXIT_USAGE=2
readonly EXIT_NOT_IMPLEMENTED=69
# Global state flags
DEBUG=0
QUIET=0
NO_COLOR=0
JSON=0
SHOW_HELP=0
SHOW_VERSION=0
# Command routing
TOP_COMMAND=""
VERB=""
HELP_FUNC=""
HELP_LEVEL=""
# Config paths (CLI overrides)
CONFIG_IDENTITIES_PATH=""
CONFIG_CONTACTS_PATH=""
CONFIG_RELAYS_PATH=""
CONFIG_PRIVATE_GROUPS_PATH=""
CONFIG_CHANNELS_PATH=""
CONFIG_OPEN_CLOSED_GROUPS_PATH=""
# Config variables (loaded from files)
# Multi-identity support
declare -A CONFIG_IDENTITIES_MAP=()
CONFIG_IDENTITIES_LIST=()
DEFAULT_IDENTITY=""
# Consolidated private groups support
declare -A CONFIG_PRIVATE_GROUPS=()
# Legacy/Other configs
CONFIG_RELAYS=()
CONFIG_CONTACTS=()
CONFIG_CHANNELS=()
CONFIG_NIP29_GROUPS=()
# CLI Override trackers (for replace-on-presence behavior)
CLI_HAS_NPUBS=0
CLI_HAS_RELAYS=0
CLI_HAS_NSEC=0
CLI_HAS_LIMIT=0
CLI_HAS_SINCE=0
CLI_HAS_UNTIL=0
CLI_HAS_HEX=0
CLI_HAS_PRIVATE_GROUP_NAME=0
CLI_HAS_CHANNEL_IDS=0
CLI_HAS_NIP29_GROUPS=0
CLI_HAS_EXEC_CMD=0
# Common arguments
NSEC=""
PRIVATE_GROUP_NAME=""
LIMIT=""
SINCE=""
UNTIL=""
HEX_VALUE=""
NPUBS=()
RELAYS=()
TEXTS=()
TEXT_FILES=()
TIMESTAMP_VALUE=""
NEVENTS=()
CHANNEL_IDS=()
NIP29_GROUP_IDS=()
NIP29_RELAY=""
EXEC_CMD=""
# Profile specific arguments
PROFILE_NAME=""
PROFILE_ABOUT=""
PROFILE_PICTURE=""
PROFILE_NIP05=""
PROFILE_LUD16=""
PROFILE_DISPLAY_NAME=""
PROFILE_WEBSITE=""
PROFILE_BANNER=""
# NIP-29 Listen state
NIP29_RESOLVED_GID=""
NIP29_RESOLVED_RELAY=""
NIP29_RESOLVED_TYPE=""
COMMAND_REST=()
# Colors
COLOR_RED=""
COLOR_GREEN=""
COLOR_YELLOW=""
COLOR_RESET=""
# Global fetch counter for listen loops
LAST_FETCH_COUNT=0
# Global deduplication tracker for listen loops (prevents NIP-17 randomization duplicates)
declare -A SEEN_IDS=()
# ==============================================================================
# Core Utilities & Error Handling
# ==============================================================================
setup_colors() {
if [[ -t 2 && "$NO_COLOR" != "1" ]] && command -v tput > /dev/null 2>&1 && [[ -n "${TERM:-}" && "${TERM}" != "dumb" ]]; then
COLOR_RED="$(tput setaf 1)"
COLOR_GREEN="$(tput setaf 2)"
COLOR_YELLOW="$(tput setaf 3)"
COLOR_RESET="$(tput sgr0)"
fi
}
log_debug() {
if [[ $DEBUG -eq 1 ]]; then
printf '[DEBUG] %s\n' "$*" >&2
fi
}
log_err() {
printf '%b[ERROR] %s%b\n' "$COLOR_RED" "$*" "$COLOR_RESET" >&2
}
trim() {
local var="$*"
var="${var#"${var%%[![:space:]]*}"}"
var="${var%"${var##*[![:space:]]}"}"
printf '%s' "$var"
}
nsec_short() {
local value="${1:-}"
local len=${#value}
if [[ $len -le 11 ]]; then
printf '%s' "$value"
return 0
fi
printf '%s...%s' "${value:0:8}" "${value: -3}"
}
sanitize_args_for_log() {
local sanitized=()
for arg in "$@"; do
if [[ "$arg" == nsec1* || "$arg" == ncryptsec1* ]]; then
sanitized+=("$(nsec_short "$arg")")
else
sanitized+=("$arg")
fi
done
IFS=' '; printf '%s' "${sanitized[*]}" # separate by spaces, default is |
}
require_bash4_if_needed() {
log_debug "Checking Bash version"
local major="${BASH_VERSINFO[0]}"
local minor="${BASH_VERSINFO[1]}"
if (( major < 4 )) || { (( major == 4 )) && (( minor < 0 )); }; then
printf '%s: This script requires Bash 4.0+ because it uses associative arrays and modern array features.\n' "$SCRIPT_NAME" >&2
printf '%s: Detected Bash %s.%s.\n' "$SCRIPT_NAME" "$major" "$minor" >&2
exit "$EXIT_ERROR"
fi
log_debug "Bash version check passed: $major.$minor"
}
usage_error() {
log_err "$1"
printf 'Try "%s --help" for more information.\n' "$SCRIPT_NAME" >&2
exit "$EXIT_USAGE"
}
fail() {
log_err "$1"
exit "$EXIT_ERROR"
}
check_dependencies() {
log_debug "Checking dependencies"
local missing=0
for cmd in nak jq awk; do
if ! command -v "$cmd" > /dev/null 2>&1; then
if [[ "$cmd" == "nak" ]]; then
log_err "Required command not found: nak"
log_err "Please install nak. See: https://github.com/fiatjaf/nak"
else
log_err "Required command not found: $cmd"
fi
missing=1
else
log_debug "$cmd found: $(command -v "$cmd")"
fi
done
if [[ $missing -eq 1 ]]; then
fail "Missing required dependencies. Please install them and try again."
fi
}
run_nak() {
local stderr_file
stderr_file=$(mktemp)
log_debug "Running nak: $(sanitize_args_for_log "$@")"
local output
local status=0
output=$("$@" 2>"$stderr_file") || status=$?
local err_output
err_output=$(<"$stderr_file")
rm -f "$stderr_file"
if [[ $status -ne 0 ]]; then
log_err "nak command failed (exit $status): $(sanitize_args_for_log "$@")"
if [[ -n "$err_output" ]]; then
printf '%b[ERROR] nak stderr: %s%b\n' "$COLOR_RED" "$err_output" "$COLOR_RESET" >&2
else
printf '%b[ERROR] nak stderr: <empty>%b\n' "$COLOR_RED" "$COLOR_RESET" >&2
fi
if [[ -n "$output" ]]; then
printf '%b[ERROR] nak stdout: %s%b\n' "$COLOR_RED" "$output" "$COLOR_RESET" >&2
fi
return 1
fi
if [[ -n "$err_output" ]]; then
log_err "nak command produced stderr (exit $status): $(sanitize_args_for_log "$@")"
printf '%b[ERROR] nak stderr: %s%b\n' "$COLOR_RED" "$err_output" "$COLOR_RESET" >&2
if [[ -z "$output" ]]; then
return 1
fi
fi
local result
result=$(printf '%s\n' "$output" | awk 'NF {print $1; exit}')
result="$(trim "$result")"
if [[ -z "$result" ]]; then
log_err "nak command produced empty output: $(sanitize_args_for_log "$@")"
return 1
fi
printf '%s' "$result"
return 0
}
run_nak_full() {
local stderr_file
stderr_file=$(mktemp)
log_debug "Running nak (full): $(sanitize_args_for_log "$@")"
local output
local status=0
output=$("$@" 2>"$stderr_file") || status=$?
local err_output
err_output=$(<"$stderr_file")
rm -f "$stderr_file"
# err_output always contains something, even on success it contains: ...connecting ... ok.
if [[ "$err_output" == *"failed"* ]] || [[ "$err_output" == *"blocked"* ]] || \
[[ "$err_output" == *"restricted"* ]] || [[ "$err_output" == *"unknown member"* ]] || \
[[ "$err_output" == *"not a member"* ]]; then
log_err "nak command failed (exit $status): $(sanitize_args_for_log "$@")"
# log_err "nak command failed (exit $status): stderr: $err_output"
printf '%b[ERROR] nak stderr: %s%b\n' "$COLOR_RED" "$err_output" "$COLOR_RESET" >&2
return 1
fi
if [[ $status -ne 0 ]]; then
log_err "nak command failed (exit $status): $(sanitize_args_for_log "$@")"
if [[ -n "$err_output" ]]; then
printf '%b[ERROR] nak stderr: %s%b\n' "$COLOR_RED" "$err_output" "$COLOR_RESET" >&2
fi
return 1
fi
printf '%s' "$output"
return 0
}
print_debug_args() {
if [[ $DEBUG -eq 1 ]]; then
log_debug "--- Parsed State Dump ---"
log_debug "TOP_COMMAND: ${TOP_COMMAND:-<unset>}"
log_debug "VERB: ${VERB:-<unset>}"
log_debug "JSON: $JSON | QUIET: $QUIET | NO_COLOR: $NO_COLOR"
log_debug "CONFIG_IDENTITIES_PATH: ${CONFIG_IDENTITIES_PATH:-<unset>}"
log_debug "CONFIG_CONTACTS_PATH: ${CONFIG_CONTACTS_PATH:-<unset>}"
log_debug "CONFIG_RELAYS_PATH: ${CONFIG_RELAYS_PATH:-<unset>}"
log_debug "CONFIG_PRIVATE_GROUPS_PATH: ${CONFIG_PRIVATE_GROUPS_PATH:-<unset>}"
log_debug "CONFIG_CHANNELS_PATH: ${CONFIG_CHANNELS_PATH:-<unset>}"
log_debug "CONFIG_OPEN_CLOSED_GROUPS_PATH: ${CONFIG_OPEN_CLOSED_GROUPS_PATH:-<unset>}"
if [[ -n "$NSEC" ]]; then
log_debug "NSEC: $(nsec_short "$NSEC")"
else
log_debug "NSEC: <unset>"
fi
log_debug "PRIVATE_GROUP_NAME: ${PRIVATE_GROUP_NAME:-<unset>}"
log_debug "LIMIT: ${LIMIT:-<unset>}"
log_debug "SINCE: ${SINCE:-<unset>}"
log_debug "UNTIL: ${UNTIL:-<unset>}"
log_debug "HEX_VALUE: ${HEX_VALUE:-<unset>}"
if [[ ${#NPUBS[@]} -gt 0 ]]; then log_debug "NPUBS: ${NPUBS[*]}"; fi
if [[ ${#RELAYS[@]} -gt 0 ]]; then log_debug "RELAYS: ${RELAYS[*]}"; fi
if [[ ${#TEXTS[@]} -gt 0 ]]; then log_debug "TEXTS: ${TEXTS[*]}"; fi
if [[ ${#TEXT_FILES[@]} -gt 0 ]]; then log_debug "TEXT_FILES: ${TEXT_FILES[*]}"; fi
if [[ ${#NEVENTS[@]} -gt 0 ]]; then log_debug "NEVENTS: ${NEVENTS[*]}"; fi
if [[ ${#CHANNEL_IDS[@]} -gt 0 ]]; then log_debug "CHANNEL_IDS: ${CHANNEL_IDS[*]}"; fi
if [[ ${#NIP29_GROUP_IDS[@]} -gt 0 ]]; then log_debug "NIP29_GROUP_IDS: ${NIP29_GROUP_IDS[*]}"; fi
if [[ -n "$NIP29_RELAY" ]]; then log_debug "NIP29_RELAY: $NIP29_RELAY"; fi
if [[ -n "$EXEC_CMD" ]]; then log_debug "EXEC_CMD: $EXEC_CMD"; fi
if [[ ${#CONFIG_CONTACTS[@]} -gt 0 ]]; then log_debug "CONFIG_CONTACTS: ${#CONFIG_CONTACTS[@]} entries"; fi
if [[ ${#CONFIG_CHANNELS[@]} -gt 0 ]]; then log_debug "CONFIG_CHANNELS: ${#CONFIG_CHANNELS[@]} entries"; fi
if [[ ${#CONFIG_NIP29_GROUPS[@]} -gt 0 ]]; then log_debug "CONFIG_NIP29_GROUPS: ${#CONFIG_NIP29_GROUPS[@]} entries"; fi
log_debug "-------------------------"
fi
}
not_implemented() {
print_debug_args
log_err "This command is not yet implemented."
printf '%s: Contributions are welcome: please open a PR.\n' "$SCRIPT_NAME" >&2
exit "$EXIT_NOT_IMPLEMENTED"
}
# ==============================================================================
# Timestamp Resolution (Auto-detect Unix vs Human/Relative via GNU date)
# ==============================================================================
resolve_timestamp_to_unix() {
local input="$1"
input="$(trim "$input")"
# Pure digits -> Unix timestamp
if [[ "$input" =~ ^[0-9]+$ ]]; then
local len=${#input}
if [[ $len -ge 13 ]]; then
# Milliseconds (or higher precision) to seconds
printf '%s' "${input:0:10}"
return 0
else
# Seconds (handles 0, short timestamps, and standard 10-digit)
printf '%s' "$input"
return 0
fi
fi
# Human/Relative string -> GNU date
local unix_ts
if unix_ts=$(date -d "$input" +%s 2>/dev/null); then
printf '%s' "$unix_ts"
return 0
fi
log_err "Failed to parse timestamp (requires GNU date for relative strings): $input"
return 1
}
resolve_timestamp_to_human() {
local unix_ts="$1"
local human
if human=$(date -d "@$unix_ts" "+%Y-%m-%d %H:%M:%S %Z" 2>/dev/null); then
printf '%s' "$human"
return 0
fi
printf '%s' "$unix_ts"
return 1
}
# ==============================================================================
# Identity & Key Resolution (v0.31.0+ Multi-Identity Support)
# ==============================================================================
# Resolves an identity token (alias, nsec1..., or 64-char hex) to a valid nsec1...
# Checks CONFIG_IDENTITIES_MAP first, then attempts direct conversion.
resolve_identity_token() {
local token="$1"
local trimmed
trimmed="$(trim "$token")"
# 1. Check alias in loaded identities map
if [[ ${#CONFIG_IDENTITIES_MAP[@]} -gt 0 ]]; then
local mapped_val="${CONFIG_IDENTITIES_MAP[$trimmed]:-}"
if [[ -n "$mapped_val" ]]; then
log_debug "Resolved identity alias '$trimmed' -> $(nsec_short "$mapped_val")"
# Recursively resolve in case map points to hex or another format
resolve_identity_token "$mapped_val"
return $?
fi
fi
# 2. Literal nsec
if [[ "$trimmed" == nsec1* ]]; then
log_debug "Using literal nsec: $(nsec_short "$trimmed")"
printf '%s' "$trimmed"
return 0
fi
# 3. 64-char private hex
if [[ ${#trimmed} -eq 64 && "$trimmed" =~ ^[0-9a-fA-F]{64}$ ]]; then
log_debug "Encoding private hex to nsec"
local encoded
if encoded=$(run_nak nak encode nsec "$trimmed"); then
log_debug "Encoded private hex -> $(nsec_short "$encoded")"
printf '%s' "$encoded"
return 0
fi
log_err "Failed to encode private hex to nsec"
return 1
fi
log_err "Unrecognized identity format: '$trimmed'. Not a known alias, nsec1..., or 64-char hex."
return 1
}
resolve_and_set_nsec() {
local token="$1"
local resolved
if ! resolved=$(resolve_identity_token "$token"); then
usage_error "Failed to resolve --nsec value: $token"
fi
NSEC="$resolved"
}
# Determines the active NSEC based on precedence:
# 1. CLI --nsec (already set in NSEC if provided)
# 2. DEFAULT_IDENTITY from identities.sh
# 3. First entry in CONFIG_IDENTITIES_LIST
resolve_active_nsec_from_config() {
# If CLI already set it, do nothing
if [[ -n "$NSEC" ]]; then
return 0
fi
# Try DEFAULT_IDENTITY
if [[ -n "$DEFAULT_IDENTITY" ]]; then
log_debug "Resolving DEFAULT_IDENTITY: $DEFAULT_IDENTITY"
local resolved
if resolved=$(resolve_identity_token "$DEFAULT_IDENTITY"); then
NSEC="$resolved"
log_debug "Active NSEC set from DEFAULT_IDENTITY: $(nsec_short "$NSEC")"
return 0
else
log_err "Failed to resolve DEFAULT_IDENTITY '$DEFAULT_IDENTITY'"
return 1
fi
fi
# Fallback to first identity in list
if [[ ${#CONFIG_IDENTITIES_LIST[@]} -gt 0 ]]; then
local first_entry="${CONFIG_IDENTITIES_LIST[0]}"
local first_key="${first_entry#*|}"
log_debug "Falling back to first identity in list: $(nsec_short "$first_key")"
local resolved
if resolved=$(resolve_identity_token "$first_key"); then
NSEC="$resolved"
return 0
fi
fi
# No identity found at all - this is OK at load time; require_nsec will catch it later
log_debug "No active NSEC determined from config"
return 0
}
# ==============================================================================
# NPUB Resolution (alias → NIP-05 → hex → npub)
# ==============================================================================
resolve_npub_token() {
local token="$1"
local trimmed
trimmed="$(trim "$token")"
# 1. Alias lookup
for entry in "${CONFIG_CONTACTS[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias_name="${entry%%|*}"
local contact_npub="${entry#*|}"
if [[ "$alias_name" == "$trimmed" ]]; then
log_debug "Resolved alias '$trimmed' -> $contact_npub"
printf '%s' "$contact_npub"
return 0
fi
fi
done
# 2. NIP-05
if [[ "$trimmed" == *@*.* ]]; then
log_debug "Resolving NIP-05: $trimmed"
local nip_hex nip_npub
if nip_hex=$(run_nak nak decode "$trimmed" 2>/dev/null) && nip_npub=$(run_nak nak encode npub "$nip_hex"); then
log_debug "Resolved NIP-05 '$trimmed' -> $nip_npub"
printf '%s' "$nip_npub"
return 0
fi
log_err "Failed to resolve NIP-05: $trimmed"
return 1
fi
# 3. Public hex
if [[ ${#trimmed} -eq 64 && "$trimmed" =~ ^[0-9a-fA-F]{64}$ ]]; then
local hex_npub
if hex_npub=$(run_nak nak encode npub "$trimmed"); then
log_debug "Encoded public hex -> $hex_npub"
printf '%s' "$hex_npub"
return 0
fi
log_err "Failed to encode public hex: $trimmed"
return 1
fi
log_debug "Using npub token: $trimmed"
printf '%s' "$trimmed"
}
resolve_and_append_npub() {
local token="$1"
local resolved
if ! resolved=$(resolve_npub_token "$token"); then
usage_error "Failed to resolve --npub value: $token"
fi
NPUBS+=("$resolved")
}
resolve_token_to_hex() {
local token="$1"
local resolved_npub hex
resolved_npub=$(resolve_npub_token "$token") || return 1
hex=$(run_nak nak decode "$resolved_npub") || return 1
printf '%s' "$hex"
}
resolve_all_contacts_to_hex() {
local hexes=()
for entry in "${CONFIG_CONTACTS[@]}"; do
local npub_val
if [[ "$entry" == *"|"* ]]; then
npub_val="${entry#*|}"
else
npub_val="$entry"
fi
local hex
if hex=$(run_nak nak decode "$npub_val" 2>/dev/null); then
hexes+=("$hex")
else
log_debug "Failed to decode contact npub: $npub_val"
fi
done
printf '%s\n' "${hexes[@]}"
}
lookup_alias_for_hex() {
local target_hex="$1"
for entry in "${CONFIG_CONTACTS[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias_name="${entry%%|*}"
local contact_npub="${entry#*|}"
local contact_hex
contact_hex=$(run_nak nak decode "$contact_npub" 2>/dev/null) || continue
if [[ "$contact_hex" == "$target_hex" ]]; then
printf '%s' "$alias_name"
return 0
fi
fi
done
return 1
}
format_sender_label() {
local pubkey="$1"
local label=""
if [[ -n "$pubkey" ]]; then
label=$(lookup_alias_for_hex "$pubkey" 2>/dev/null) || label=""
fi
if [[ -n "$label" ]]; then
# Alias available: truncate to 10 + "..." if > 13 chars
if [[ ${#label} -gt 13 ]]; then
label="${label:0:10}..."
fi
else
# No alias: use shortened npub (e.g., npub1ab...xyz) to exactly 13 chars
local npub
npub=$(run_nak nak encode npub "$pubkey" 2>/dev/null) || npub="$pubkey"
if [[ "$npub" == npub1* && ${#npub} -ge 13 ]]; then
label="${npub:0:7}...${npub: -3}"
else
label="${npub:0:10}..."
fi
fi
# Pad or truncate to exactly 13 characters
printf '%-13.13s' "$label"
}
# ==============================================================================
# Channel Resolution (alias → nevent → hex)
# ==============================================================================
resolve_channel_token() {
local token="$1"
local trimmed
trimmed="$(trim "$token")"
# 1. Alias lookup
for entry in "${CONFIG_CHANNELS[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias_name="${entry%%|*}"
local channel_val="${entry#*|}"
if [[ "$alias_name" == "$trimmed" ]]; then
log_debug "Resolved channel alias '$trimmed' -> $channel_val"
trimmed="$channel_val"
break
fi
fi
done
# 2. NIP-19 nevent
if [[ "$trimmed" == nostr:nevent1* || "$trimmed" == nevent1* ]]; then
log_debug "Decoding nevent: $trimmed"
local decoded
if decoded=$(run_nak_full nak decode "$trimmed"); then
local id
id=$(printf '%s' "$decoded" | jq -r '.id // empty')
if [[ -n "$id" ]]; then
printf '%s' "$id"
return 0
fi
fi
log_err "Failed to decode nevent: $trimmed"
return 1
fi
# 3. Raw hex
if [[ ${#trimmed} -eq 64 && "$trimmed" =~ ^[0-9a-fA-F]{64}$ ]]; then
printf '%s' "$trimmed"
return 0
fi
log_err "Unrecognized channel-id format: $trimmed"
return 1
}
# ==============================================================================
# NIP-29 Group Resolution (alias → group-id + relay)
# ==============================================================================
resolve_nip29_group() {
local token="$1" # alias or group-id or nostr:naddr1... or addr1...
local fallback_type="$2"
local trimmed
trimmed="$(trim "$token")"
log_debug "resolve_nip29_group: check first if $trimmed is an naddr1 object."
if [[ "$trimmed" == nostr:naddr* || "$trimmed" == naddr* ]]; then
if ! output=$(_event_decode "$trimmed"); then
log_debug "Could not decode naddr1. This is probably going to fail."
else
local type="" gid="" relay=""
# identifier and first relay
gid=$(jq -r '.identifier' <<<"$output")
relay=$(jq -r '.relays[0]' <<<"$output")
type="$fallback_type"
printf '%s|%s|%s' "$type" "$gid" "$relay"
return 0
fi
fi
log_debug "resolve_nip29_group: trying to look up id or alias $trimmed in CONFIG_NIP29_GROUPS array."
# Lookup in config
# The user can either give ALIAS of group or GROUP-ID (which is the gid in the array)
# One has to go through the array and try to find this alias or this gid.
# If found extract the other values: type, relay.
# The return all 3: type, gid, relay.
for entry in "${CONFIG_NIP29_GROUPS[@]}"; do
local IFS='|'
read -ra parts <<< "$entry"
local alias="" type="" gid="" relay=""
if [[ ${#parts[@]} -eq 4 ]]; then
alias="${parts[0]}"
type="${parts[1]}"
gid="${parts[2]}"
relay="${parts[3]}"
elif [[ ${#parts[@]} -eq 3 ]]; then
type="${parts[0]}"
gid="${parts[1]}"
relay="${parts[2]}"
fi
if [[ -n "$alias" && "$alias" == "$trimmed" ]] || [[ "$gid" == "$trimmed" ]]; then
printf '%s|%s|%s' "$type" "$gid" "$relay"
return 0
fi
done
log_err "Unrecognized NIP-29 group: must be Alias, hex Group-Id, nostr:naddr1 object: found $trimmed"
return 1
}
# ==============================================================================
# Validation Requirements
# ==============================================================================
require_nsec() {
log_debug "Checking requirement: nsec"
if [[ -z "$NSEC" ]]; then
usage_error "nsec not set. Provide --nsec, set DEFAULT_IDENTITY in identities.sh, or add identities to CONFIG_IDENTITIES."
fi
}
require_npub() {
log_debug "Checking requirement: npub"
if [[ ${#NPUBS[@]} -eq 0 ]]; then
if [[ "$TOP_COMMAND" == "key" ]]; then
usage_error "npub not set, provide option --npub"
else
usage_error "recipient/member not set, provide --npub or configure private-groups.sh"
fi
fi
}
require_text() {
log_debug "Checking requirement: text"
if [[ ${#TEXTS[@]} -eq 0 && ${#TEXT_FILES[@]} -eq 0 ]]; then
usage_error "message not set, provide --text or --text-file"
fi
}
require_hex() {
log_debug "Checking requirement: hex"
if [[ -z "$HEX_VALUE" ]]; then
usage_error "hex not set, provide option --hex"
fi
}
require_private_group_name() {
log_debug "Checking requirement: group-name"
if [[ -z "$PRIVATE_GROUP_NAME" ]]; then
usage_error "group-name not set, provide option --group-name"
fi
}
require_npub_or_nsec() {
log_debug "Checking requirement: npub or nsec"
if [[ ${#NPUBS[@]} -eq 0 && -z "$NSEC" ]]; then
usage_error "identity not set, provide --npub, --nsec, or configure identities.sh"
fi
}
require_relays() {
log_debug "Checking requirement: relays"
if [[ ${#RELAYS[@]} -eq 0 ]]; then
usage_error "no relays configured, provide --relay (1 or more times) or configure relays.sh"
fi
}
# ==============================================================================
# Configuration Loading (Multi-Layer System v0.31.0+)
# ==============================================================================
validate_explicit_configs() {
log_debug "Entering validate_explicit_configs"
if [[ -n "$CONFIG_IDENTITIES_PATH" && ! -f "$CONFIG_IDENTITIES_PATH" ]]; then
usage_error "Identities config file not found: $CONFIG_IDENTITIES_PATH"
fi
if [[ -n "$CONFIG_CONTACTS_PATH" && ! -f "$CONFIG_CONTACTS_PATH" ]]; then
usage_error "Contacts config file not found: $CONFIG_CONTACTS_PATH"
fi
if [[ -n "$CONFIG_RELAYS_PATH" && ! -f "$CONFIG_RELAYS_PATH" ]]; then
usage_error "Relays config file not found: $CONFIG_RELAYS_PATH"
fi
if [[ -n "$CONFIG_PRIVATE_GROUPS_PATH" && ! -f "$CONFIG_PRIVATE_GROUPS_PATH" ]]; then
usage_error "Private groups config file not found: $CONFIG_PRIVATE_GROUPS_PATH"
fi
if [[ -n "$CONFIG_CHANNELS_PATH" && ! -f "$CONFIG_CHANNELS_PATH" ]]; then
usage_error "Channels config file not found: $CONFIG_CHANNELS_PATH"
fi
if [[ -n "$CONFIG_OPEN_CLOSED_GROUPS_PATH" && ! -f "$CONFIG_OPEN_CLOSED_GROUPS_PATH" ]]; then
usage_error "NIP-29 groups config file not found: $CONFIG_OPEN_CLOSED_GROUPS_PATH"
fi
log_debug "Exiting validate_explicit_configs"
}
load_configs() {
log_debug "Entering load_configs"
# 1. Identities (NEW v0.31.0)
local identities_file="${CONFIG_IDENTITIES_PATH:-$DEFAULT_CONFIG_DIR/identities.sh}"
if [[ -f "$identities_file" ]]; then
log_debug "Sourcing identities config: $identities_file"
source "$identities_file"
# Populate map and list from CONFIG_IDENTITIES array defined in file
if [[ ${#CONFIG_IDENTITIES[@]} -gt 0 ]]; then
for entry in "${CONFIG_IDENTITIES[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias="${entry%%|*}"
local key="${entry#*|}"
CONFIG_IDENTITIES_MAP["$alias"]="$key"
CONFIG_IDENTITIES_LIST+=("$entry")
log_debug " Identity: $alias -> $(nsec_short "$key")"
else
log_debug " Identity (no alias): $(nsec_short "$entry")"
CONFIG_IDENTITIES_LIST+=("$entry")
fi
done
fi
if [[ -n "${DEFAULT_IDENTITY:-}" ]]; then
log_debug "DEFAULT_IDENTITY: $DEFAULT_IDENTITY"
fi
# Resolve active NSEC from config if CLI hasn't set it
resolve_active_nsec_from_config
else
log_debug "Identities config not found: $identities_file"
fi
# 2. Contacts
local contacts_file="${CONFIG_CONTACTS_PATH:-$DEFAULT_CONFIG_DIR/contacts.sh}"
if [[ -f "$contacts_file" ]]; then
log_debug "Sourcing contacts config: $contacts_file"
source "$contacts_file"
local contact_count=${#CONFIG_CONTACTS[@]}
log_debug "Contacts loaded: $contact_count entries"
if [[ $contact_count -gt 0 ]]; then
for entry in "${CONFIG_CONTACTS[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias_name="${entry%%|*}"
local contact_npub="${entry#*|}"
log_debug " Contact: $alias_name -> $contact_npub"
else
log_debug " Contact: $entry (no alias)"
fi
done
fi
else
log_debug "Contacts config not found: $contacts_file"
fi
# 3. Relays
local relays_file="${CONFIG_RELAYS_PATH:-$DEFAULT_CONFIG_DIR/relays.sh}"
if [[ -f "$relays_file" ]]; then
log_debug "Sourcing relays config: $relays_file"
source "$relays_file"
local relay_count=${#CONFIG_RELAYS[@]}
log_debug "Relays loaded: $relay_count entries"
if [[ $relay_count -gt 0 && ${#RELAYS[@]} -eq 0 ]]; then
for r in "${CONFIG_RELAYS[@]}"; do
r="$(trim "$r")"
RELAYS+=("$r")
log_debug " Relay: $r"
done
fi
else
log_debug "Relays config not found: $relays_file"
fi
# 4. Private Groups (NEW v0.31.0 - Consolidated)
local private_groups_file="${CONFIG_PRIVATE_GROUPS_PATH:-$DEFAULT_CONFIG_DIR/private-groups.sh}"
if [[ -f "$private_groups_file" ]]; then
log_debug "Sourcing private-groups config: $private_groups_file"
source "$private_groups_file"
# CONFIG_PRIVATE_GROUPS associative array is now populated from file
if [[ ${#CONFIG_PRIVATE_GROUPS[@]} -gt 0 ]]; then
log_debug "Private groups loaded: ${#CONFIG_PRIVATE_GROUPS[@]} groups"
for gname in "${!CONFIG_PRIVATE_GROUPS[@]}"; do
local var_name="${CONFIG_PRIVATE_GROUPS[$gname]}"
log_debug " Group: '$gname' -> \$$var_name"
done
fi
else
log_debug "Private groups config not found: $private_groups_file"
fi
# 5. Channels (NIP-28)
local channels_file="${CONFIG_CHANNELS_PATH:-$DEFAULT_CONFIG_DIR/channels.sh}"
if [[ -f "$channels_file" ]]; then
log_debug "Sourcing channels config: $channels_file"
source "$channels_file"
local channel_count=${#CONFIG_CHANNELS[@]}
log_debug "Channels loaded: $channel_count entries"
if [[ $channel_count -gt 0 ]]; then
for entry in "${CONFIG_CHANNELS[@]}"; do
if [[ "$entry" == *"|"* ]]; then
local alias_name="${entry%%|*}"
local channel_val="${entry#*|}"
log_debug " Channel: $alias_name -> $channel_val"
else
log_debug " Channel: $entry (no alias)"
fi
done
fi
else
log_debug "Channels config not found: $channels_file"
fi
# 6. NIP-29 Groups (Open/Closed)
local nip29_file="${CONFIG_OPEN_CLOSED_GROUPS_PATH:-$DEFAULT_CONFIG_DIR/open-closed-groups.sh}"
if [[ -f "$nip29_file" ]]; then
log_debug "Sourcing NIP-29 groups config: $nip29_file"
source "$nip29_file"
local group_count=${#CONFIG_NIP29_GROUPS[@]}
log_debug "NIP-29 groups loaded: $group_count entries"
if [[ $group_count -gt 0 ]]; then
for entry in "${CONFIG_NIP29_GROUPS[@]}"; do
local IFS='|'
read -ra parts <<< "$entry"
if [[ ${#parts[@]} -eq 4 ]]; then
log_debug " Group: ${parts[0]} (${parts[1]}) -> ${parts[2]} @ ${parts[3]}"
elif [[ ${#parts[@]} -eq 3 ]]; then
log_debug " Group: (${parts[0]}) -> ${parts[1]} @ ${parts[2]}"
fi
done
fi
else
log_debug "NIP-29 groups config not found: $nip29_file"
fi
log_debug "Exiting load_configs"
}
# ==============================================================================
# Help Functions (Full Versions with --exec documentation)
# ==============================================================================
print_help_top() {
cat <<EOF
${SCRIPT_NAME} ${SCRIPT_VERSION}
Usage: ${SCRIPT_NAME} [global-options] <command> [<verb>] [options]
Top-level commands:
help Show this help
version Print version
timestamp Convert between Unix and human-readable timestamps
key Key management (generate, convert, derive)
event Decode NIP-19 nevent entities
profile Profile metadata (get, set)
contact Direct messages (send, get, listen)
private-group NIP-17 encrypted groups (send, get, listen)
open-group NIP-29 open groups (send, get, listen)
closed-group NIP-29 closed groups (send, get, listen)
public-channel NIP-28 public channels (send, get, listen)
post Public notes (send, get, listen)
self-test Run automated self-tests
Global Options:
-h, --help Show help
-v, --version Print version
-d, --debug Enable debug output
-q, --quiet Suppress informational output
--no-color Disable colors
--json Output JSON
--config-identities PATH Identities config file (multi-user)
--config-contacts PATH Contacts config file
--config-relays PATH Relays config file
--config-private-groups PATH Private groups config file (NIP-17)
--config-channels PATH Channels config file (NIP-28)
--config-open-closed-groups PATH NIP-29 groups config file
Identity Resolution:
--nsec VALUE Accepts alias, nsec1..., OR 64-char private hex.
Aliases are resolved from identities.sh.
Private hex is automatically encoded to nsec.
--npub VALUE Accepts any of:
- npub1... (literal bech32)
- 64-char public hex (auto-encoded to npub)
- NIP-05 identifier (e.g. user@example.com)
- Alias name from contacts.sh
Requirements:
- nak (https://github.com/fiatjaf/nak) [This is also the only connection to the Internet.]
- jq
- awk
- GNU date (for relative time parsing like "1 hour ago")
Run '${SCRIPT_NAME} <command> --help' for more information on a command.
Run '${SCRIPT_NAME} <command> <verb> --help' for more information on a verb.
Notes:
- This tool is intended to be used as a companion CLI, admin app, bot tool,
or AI access to the lovely 0xchat app, see
https://www.0xchat.com/ and https://github.com/0xchat-app.
- This tool is purposefully only one file, one Bash v4+ script to be exact, for
simplicity of installation and portability.
- This tool does not connect to the internet ever, except for the needed
invocations of the "nak" tool to contact the user provided Nostr relays.
- This tool is incomplete. The full CLI has not been implemented. Therefore,
contributions are welcome. But there is enough functionality there to run a
trivial bot on a home server for a few friends.
EOF
}