-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeygen.sh
More file actions
executable file
·1709 lines (1462 loc) · 47.2 KB
/
Copy pathkeygen.sh
File metadata and controls
executable file
·1709 lines (1462 loc) · 47.2 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
# keygen.sh
# Secure password/key generator with polished terminal output.
# Requires: bash, od, tr. Optional: uuidgen, curl or wget, ssh-keygen, xclip/wl-copy/xsel/pbcopy.
#
# Wordlist resolution order (memorable mode):
# 1. URL ($REMOTE_WORDLIST_URL), cached on first download
# 2. Local file ($LOCAL_WORDLIST_PATH, installed share, bundled wordlist, or XDG cache)
# 3. Built-in fallback list
#
# Delete the cache file to force a fresh download on next run.
set -Eeuo pipefail
IFS=$'\n\t'
if ((BASH_VERSINFO[0] < 4)); then
printf 'error: %s requires Bash 4 or newer\n' "${0##*/}" >&2
exit 1
fi
APP_NAME="keygen"
SCRIPT_PATH="${BASH_SOURCE[0]}"
SCRIPT_DIR="$(cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd -P)"
APP_VERSION="1.0.1"
LOCAL_META_PATH="$SCRIPT_DIR/.meta"
REMOTE_META_URL="${KEYGEN_META_URL:-https://raw.githubusercontent.com/yonasuriv/${APP_NAME}/refs/heads/main/.meta}"
REMOTE_SCRIPT_URL="${KEYGEN_SCRIPT_URL:-https://raw.githubusercontent.com/yonasuriv/${APP_NAME}/refs/heads/main/${APP_NAME}.sh}"
REMOTE_WORDLIST_URL="${REMOTE_WORDLIST_URL:-https://raw.githubusercontent.com/yonasuriv/${APP_NAME}/refs/heads/main/wordlist/en-memorable.txt}"
INSTALL_TARGET_CUSTOM="false"
if [[ -n "${PREFIX:-}" ]]; then
INSTALL_PREFIX="$PREFIX"
INSTALL_TARGET_CUSTOM="true"
elif (( EUID == 0 )); then
INSTALL_PREFIX="/usr"
else
INSTALL_PREFIX="${HOME}/.local"
fi
[[ -n "${KEYGEN_BIN_DIR:-}" || -n "${KEYGEN_SHARE_DIR:-}" ]] && INSTALL_TARGET_CUSTOM="true"
INSTALL_BIN_DIR="${KEYGEN_BIN_DIR:-$INSTALL_PREFIX/bin}"
INSTALL_SHARE_DIR="${KEYGEN_SHARE_DIR:-$INSTALL_PREFIX/share/$APP_NAME}"
INSTALL_CONFIG_DIR="$INSTALL_SHARE_DIR/config"
INSTALL_WORDLIST_DIR="$INSTALL_SHARE_DIR/wordlist"
INSTALLED_META_PATH="$INSTALL_SHARE_DIR/.meta"
DEFAULT_CONFIG_PATH="$SCRIPT_DIR/config/default.conf"
# Configurable defaults are loaded from the default conf file.
# These initializations satisfy set -u while preserving environment variables.
# Emergency fallbacks are applied by set_config_defaults() only if the configs
# do not set a value.
TYPE="${TYPE:-}"
LENGTH="${LENGTH:-}"
MEMO_WORDS="${MEMO_WORDS:-}"
CASE="${CASE:-}"
ALLOW="${ALLOW:-}"
MEMO_SEPARATOR="${MEMO_SEPARATOR:-}"
COUNT="${COUNT:-}"
PLAIN="${PLAIN:-}"
SPINNER="${SPINNER:-}"
ACTION="${ACTION:-generate}"
MEMO_CAPITALIZE="${MEMO_CAPITALIZE:-}"
MEMO_NUM_PER_WORD="${MEMO_NUM_PER_WORD:-}"
SAFE_MODE="${SAFE_MODE:-}"
ASSUME_YES="${ASSUME_YES:-}"
SSH_FORCE="${SSH_FORCE:-}"
SSH_ACTION="${SSH_ACTION:-}"
REMOTE_WORDLIST_MIN_LEN="${REMOTE_WORDLIST_MIN_LEN:-}"
REMOTE_WORDLIST_TIMEOUT="${REMOTE_WORDLIST_TIMEOUT:-}"
set_config_defaults() {
[[ -z "$TYPE" ]] && TYPE="random"
[[ -z "$LENGTH" ]] && LENGTH=16
[[ -z "$MEMO_WORDS" ]] && MEMO_WORDS=3
[[ -z "$CASE" ]] && CASE="default"
[[ -z "$ALLOW" ]] && ALLOW="letters,numbers"
[[ -z "$MEMO_SEPARATOR" ]] && MEMO_SEPARATOR="hyphen"
[[ -z "$COUNT" ]] && COUNT=1
[[ -z "$PLAIN" ]] && PLAIN="false"
[[ -z "$SPINNER" ]] && SPINNER="true"
[[ -z "$MEMO_CAPITALIZE" ]] && MEMO_CAPITALIZE="true"
[[ -z "$MEMO_NUM_PER_WORD" ]] && MEMO_NUM_PER_WORD="true"
[[ -z "$SAFE_MODE" ]] && SAFE_MODE="false"
[[ -z "$SSH_FORCE" ]] && SSH_FORCE="false"
[[ -z "$SSH_ACTION" ]] && SSH_ACTION="generate"
[[ -z "${REMOTE_WORDLIST_MIN_LEN:-}" ]] && REMOTE_WORDLIST_MIN_LEN=4
[[ -z "${REMOTE_WORDLIST_TIMEOUT:-}" ]] && REMOTE_WORDLIST_TIMEOUT=5
return 0
}
SPINNER_PID=""
DEFAULT_WORDLIST_URL="$REMOTE_WORDLIST_URL"
DEFAULT_WORDLIST_PATH="${XDG_CACHE_HOME:-${HOME}/.cache}/keygen/wordlist.txt"
WORDS_LIST=()
WORDS_LOADED="false"
# Last-resort fallback. Only used when URL fetch and local path both fail.
HARDCODED_WORDS=(
amber anchor apple arctic atlas autumn beacon binary blossom border canyon
carbon cedar cipher cobalt comet copper coral cosmos crystal delta desert
dragon ember engine falcon fiber forest galaxy garden glacier harbor hazel
horizon ivory jasmine kernel ladder lagoon lantern lunar magnet marble matrix
meadow meteor mirror nebula neon nickel ocean olive orbit orchid panda pebble
pepper photon pine pixel plasma prairie quartz radar raven river rocket
saffron salmon satin shadow signal silver solar sphere spiral summit syntax
timber token tundra velvet vector violet willow winter zephyr acorn alpine
azure basil breezy brick bronze canvas charm chrome circuit cloud clover
crown fabric field flint frost golden grove island jade jungle kite lemon
lotus maple mint moss noble nova pearl prism quiet ruby sable sage slate
storm swift tiger tulip vapor vivid wave whale zenith
)
# Color Variables
BOLD=$'\033[1m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[0;33m'
RED=$'\033[0;31m'
BLUE=$'\033[0;34m'
CYAN=$'\033[1;36m'
RESET=$'\033[0m'
usage() {
local cmd="${0##*/}"
cmd="${cmd%.sh}"
cat <<EOF
Usage:
$cmd [type] [options]
$cmd --safe
Options:
--safe Generate a .env-friendly and URL-safe value using the A-Za-z0-9._~- charset.
-t, --type VALUE Output mode.
Values: memorable, random, basic, uuid, hex, base32, base58, base64, base64url, nanoid, token, {special types}
Default: random
-c, --case VALUE Letter casing for generated output.
Values: default, lower, upper, capitalize
Default: default
-l, --length N Length for random and key-based formats.
Range: 8-64
Default: 16
-w, --words N Number of words for memorable passwords.
Range: 1-10
Default: 3
-s, --separator VALUE Word separator for memorable mode.
Values: hyphen, space, period, comma, underscore, none
Default: hyphen
-a, --allow VALUE Comma-separated character classes to include.
Values: letters,numbers,symbols,hyphen,space,period,comma,underscore,all
Default: letters,numbers
-n, --count N Number of values to generate.
Default: 1
-v, --version Print the current version and check for updates.
-u, --update Update the installed or local script from GitHub.
-i, --install Install keygen. Uses /usr when run as root, otherwise ~/.local.
-y, --yes Skip installation confirmation prompts.
-p, --plain Print generated values only. Disables colors, boxes, and labels.
--no-spinner Disable the progress spinner.
--force Regenerate an existing SSH key pair (ssh mode only).
-h, --help Show this help message.
Special types:
secret,jwt Generate a JWT/general-purpose secret.
basic,flag Generate a MD5 flag-style secret.
general Generate a general-purpose secret key for apps, APIs, and services.
token Generate a URL-safe 32-byte Base64 secret without padding.
django Generate a Django-style secret key.
ssh Create an Ed25519 SSH key pair in ~/.ssh/ if missing.
Subcommands: pub (copy public key), priv (copy private key).
Environment (memorable mode):
LOCAL_WORDLIST_PATH Local cache/fallback. Default: installed/bundled wordlist, then XDG cache
REMOTE_WORDLIST_URL Source URL. Default: project wordlist on GitHub
REMOTE_WORDLIST_MIN_LEN Minimum word length. Default: 4
REMOTE_WORDLIST_TIMEOUT Download timeout (seconds). Default: 5
Install/update environment:
PREFIX Install prefix. Default: /usr as root, otherwise ~/.local
KEYGEN_BIN_DIR Override binary directory.
KEYGEN_SHARE_DIR Override shared data directory.
Examples:
$cmd
$cmd jwt
$cmd base64
$cmd --safe --plain
$cmd --length 24 --allow letters,numbers,symbols
$cmd --type memorable --words 4 --case capitalize --separator hyphen
$cmd --type uuid --count 3
$cmd --type base64url --length 32 --plain
$cmd ssh
$cmd ssh --force
$cmd ssh pub
$cmd ssh priv
EOF
}
has_command() {
command -v "$1" >/dev/null 2>&1
}
fatal() {
printf '%bERROR%b: %s\n' "$RED" "$RESET" "$1" >&2
exit 1
}
is_integer() {
[[ "${1:-}" =~ ^[0-9]+$ ]]
}
read_meta_version() {
local file="$1"
[[ -r "$file" ]] || return 1
local line version
line="$(awk -F= '$1 == "APP_VERSION" { print $2; exit }' "$file" 2>/dev/null)" || return 1
version="${line%\"}"
version="${version#\"}"
[[ -n "$version" ]] || return 1
printf '%s' "$version"
}
init_app_version() {
local version
if version="$(read_meta_version "$LOCAL_META_PATH")"; then
APP_VERSION="$version"
elif version="$(read_meta_version "$INSTALLED_META_PATH")"; then
APP_VERSION="$version"
elif version="$(read_meta_version "$SCRIPT_DIR/../share/$APP_NAME/.meta")"; then
APP_VERSION="$version"
elif version="$(read_meta_version "/usr/share/$APP_NAME/.meta")"; then
APP_VERSION="$version"
elif version="$(read_meta_version "${HOME}/.local/share/$APP_NAME/.meta")"; then
APP_VERSION="$version"
fi
}
script_target_path() {
if [[ "$SCRIPT_PATH" == /* ]]; then
printf '%s' "$SCRIPT_PATH"
else
printf '%s/%s' "$SCRIPT_DIR" "${SCRIPT_PATH##*/}"
fi
}
download_to_file() {
local url="$1"
local dest="$2"
local timeout="${3:-15}"
if has_command curl; then
curl -fsSL --max-time "$timeout" "$url" -o "$dest"
elif has_command wget; then
wget -q --timeout="$timeout" "$url" -O "$dest"
else
return 1
fi
}
fetch_remote_version() {
local tmp
tmp="$(mktemp "${TMPDIR:-/tmp}/keygen-meta.XXXXXX")" || return 1
if download_to_file "$REMOTE_META_URL" "$tmp" 10; then
read_meta_version "$tmp"
local rc=$?
rm -f "$tmp" 2>/dev/null || true
return "$rc"
fi
rm -f "$tmp" 2>/dev/null || true
return 1
}
version_is_newer() {
local remote="$1"
local current="$2"
[[ "$remote" != "$current" ]] || return 1
if has_command sort; then
[[ "$(printf '%s\n%s\n' "$current" "$remote" | sort -V | tail -n 1)" == "$remote" ]]
else
[[ "$remote" > "$current" ]]
fi
}
print_version() {
init_app_version
printf '%s %s\n' "$APP_NAME" "$APP_VERSION"
local remote
if remote="$(fetch_remote_version)"; then
if version_is_newer "$remote" "$APP_VERSION"; then
printf 'update available: %s\n' "$remote"
else
printf 'up to date\n'
fi
else
printf 'update check unavailable\n' >&2
fi
}
load_user_config() {
local default_config="" user_config=""
# Snapshot environment variables before config files can overwrite them
local _TYPE _LENGTH _MEMO_WORDS _CASE _ALLOW _MEMO_SEPARATOR _COUNT _PLAIN _SPINNER
local _MEMO_CAPITALIZE _MEMO_NUM_PER_WORD _SAFE_MODE _REMOTE_WORDLIST_MIN_LEN
local _REMOTE_WORDLIST_URL _LOCAL_WORDLIST_PATH _REMOTE_WORDLIST_TIMEOUT
[[ ${TYPE+x} ]] && _TYPE="$TYPE"
[[ ${LENGTH+x} ]] && _LENGTH="$LENGTH"
[[ ${MEMO_WORDS+x} ]] && _MEMO_WORDS="$MEMO_WORDS"
[[ ${CASE+x} ]] && _CASE="$CASE"
[[ ${ALLOW+x} ]] && _ALLOW="$ALLOW"
[[ ${MEMO_SEPARATOR+x} ]] && _MEMO_SEPARATOR="$MEMO_SEPARATOR"
[[ ${COUNT+x} ]] && _COUNT="$COUNT"
[[ ${PLAIN+x} ]] && _PLAIN="$PLAIN"
[[ ${SPINNER+x} ]] && _SPINNER="$SPINNER"
[[ ${MEMO_CAPITALIZE+x} ]] && _MEMO_CAPITALIZE="$MEMO_CAPITALIZE"
[[ ${MEMO_NUM_PER_WORD+x} ]] && _MEMO_NUM_PER_WORD="$MEMO_NUM_PER_WORD"
[[ ${SAFE_MODE+x} ]] && _SAFE_MODE="$SAFE_MODE"
[[ ${REMOTE_WORDLIST_MIN_LEN+x} ]] && _REMOTE_WORDLIST_MIN_LEN="$REMOTE_WORDLIST_MIN_LEN"
[[ ${REMOTE_WORDLIST_URL+x} ]] && _REMOTE_WORDLIST_URL="$REMOTE_WORDLIST_URL"
[[ ${LOCAL_WORDLIST_PATH+x} ]] && _LOCAL_WORDLIST_PATH="$LOCAL_WORDLIST_PATH"
[[ ${REMOTE_WORDLIST_TIMEOUT+x} ]] && _REMOTE_WORDLIST_TIMEOUT="$REMOTE_WORDLIST_TIMEOUT"
# Search for default.conf
for config in \
"$INSTALL_CONFIG_DIR/default.conf" \
"$SCRIPT_DIR/config/default.conf" \
"$SCRIPT_DIR/../share/$APP_NAME/config/default.conf" \
"/usr/share/$APP_NAME/config/default.conf" \
"/usr/local/share/$APP_NAME/config/default.conf" \
"${HOME}/.local/share/$APP_NAME/config/default.conf"
do
[[ -r "$config" ]] || continue
default_config="$config"
break
done
# Search for user.conf
for config in \
"$INSTALL_CONFIG_DIR/user.conf" \
"$SCRIPT_DIR/config/user.conf" \
"$SCRIPT_DIR/../share/$APP_NAME/config/user.conf" \
"/usr/share/$APP_NAME/config/user.conf" \
"/usr/local/share/$APP_NAME/config/user.conf" \
"${HOME}/.local/share/$APP_NAME/config/user.conf"
do
[[ -r "$config" ]] || continue
user_config="$config"
break
done
# Load default.conf first
if [[ -n "$default_config" ]]; then
# shellcheck source=/dev/null
source "$default_config"
fi
# Load user.conf second (overrides defaults)
if [[ -n "$user_config" ]]; then
# shellcheck source=/dev/null
source "$user_config"
fi
# Strip CRLF from loaded config values
TYPE="${TYPE//$'\r'/}"
LENGTH="${LENGTH//$'\r'/}"
MEMO_WORDS="${MEMO_WORDS//$'\r'/}"
CASE="${CASE//$'\r'/}"
ALLOW="${ALLOW//$'\r'/}"
MEMO_SEPARATOR="${MEMO_SEPARATOR//$'\r'/}"
COUNT="${COUNT//$'\r'/}"
PLAIN="${PLAIN//$'\r'/}"
SPINNER="${SPINNER//$'\r'/}"
MEMO_CAPITALIZE="${MEMO_CAPITALIZE//$'\r'/}"
MEMO_NUM_PER_WORD="${MEMO_NUM_PER_WORD//$'\r'/}"
SAFE_MODE="${SAFE_MODE//$'\r'/}"
REMOTE_WORDLIST_MIN_LEN="${REMOTE_WORDLIST_MIN_LEN//$'\r'/}"
REMOTE_WORDLIST_TIMEOUT="${REMOTE_WORDLIST_TIMEOUT//$'\r'/}"
# Restore environment variables (env vars override config files)
[[ ${_TYPE+x} ]] && TYPE="$_TYPE"
[[ ${_LENGTH+x} ]] && LENGTH="$_LENGTH"
[[ ${_MEMO_WORDS+x} ]] && MEMO_WORDS="$_MEMO_WORDS"
[[ ${_CASE+x} ]] && CASE="$_CASE"
[[ ${_ALLOW+x} ]] && ALLOW="$_ALLOW"
[[ ${_MEMO_SEPARATOR+x} ]] && MEMO_SEPARATOR="$_MEMO_SEPARATOR"
[[ ${_COUNT+x} ]] && COUNT="$_COUNT"
[[ ${_PLAIN+x} ]] && PLAIN="$_PLAIN"
[[ ${_SPINNER+x} ]] && SPINNER="$_SPINNER"
[[ ${_MEMO_CAPITALIZE+x} ]] && MEMO_CAPITALIZE="$_MEMO_CAPITALIZE"
[[ ${_MEMO_NUM_PER_WORD+x} ]] && MEMO_NUM_PER_WORD="$_MEMO_NUM_PER_WORD"
[[ ${_SAFE_MODE+x} ]] && SAFE_MODE="$_SAFE_MODE"
[[ ${_REMOTE_WORDLIST_MIN_LEN+x} ]] && REMOTE_WORDLIST_MIN_LEN="$_REMOTE_WORDLIST_MIN_LEN"
[[ ${_REMOTE_WORDLIST_URL+x} ]] && REMOTE_WORDLIST_URL="$_REMOTE_WORDLIST_URL"
[[ ${_LOCAL_WORDLIST_PATH+x} ]] && LOCAL_WORDLIST_PATH="$_LOCAL_WORDLIST_PATH"
[[ ${_REMOTE_WORDLIST_TIMEOUT+x} ]] && REMOTE_WORDLIST_TIMEOUT="$_REMOTE_WORDLIST_TIMEOUT"
return 0
}
config_bool() {
local name="$1"
local value="${2,,}"
case "$value" in
true|1|yes|on) printf 'true' ;;
false|0|no|off) printf 'false' ;;
*) fatal "$name must be true or false" ;;
esac
}
normalize_config() {
# Normalize values loaded from config files
[[ -n "${TYPE:-}" ]] && TYPE="${TYPE,,}"
[[ -n "${CASE:-}" ]] && CASE="${CASE,,}"
[[ -n "${MEMO_SEPARATOR:-}" ]] && MEMO_SEPARATOR="${MEMO_SEPARATOR,,}"
[[ -n "${PLAIN:-}" ]] && PLAIN="$(config_bool PLAIN "$PLAIN")"
[[ -n "${SPINNER:-}" ]] && SPINNER="$(config_bool SPINNER "$SPINNER")"
[[ -n "${MEMO_CAPITALIZE:-}" ]] && MEMO_CAPITALIZE="$(config_bool MEMO_CAPITALIZE "$MEMO_CAPITALIZE")"
[[ -n "${MEMO_NUM_PER_WORD:-}" ]] && MEMO_NUM_PER_WORD="$(config_bool MEMO_NUM_PER_WORD "$MEMO_NUM_PER_WORD")"
[[ -n "${SAFE_MODE:-}" ]] && SAFE_MODE="$(config_bool SAFE_MODE "$SAFE_MODE")"
[[ -n "${SSH_FORCE:-}" ]] && SSH_FORCE="$(config_bool SSH_FORCE "$SSH_FORCE")"
# Lowercase environment fallbacks
[[ ${type+x} ]] && TYPE="${type,,}"
[[ ${length+x} ]] && LENGTH="$length"
[[ ${memo_words+x} ]] && MEMO_WORDS="$memo_words"
[[ ${CASE+x} ]] && CASE="${CASE,,}"
[[ ${allow+x} ]] && ALLOW="$allow"
[[ ${memo_separator+x} ]] && MEMO_SEPARATOR="${memo_separator,,}"
[[ ${count+x} ]] && COUNT="$count"
[[ ${plain+x} ]] && PLAIN="$(config_bool plain "$plain")"
[[ ${spinner+x} ]] && SPINNER="$(config_bool spinner "$spinner")"
[[ ${memo_capitalize+x} ]] && MEMO_CAPITALIZE="$(config_bool memo_capitalize "$memo_capitalize")"
[[ ${memo_num_per_word+x} ]] && MEMO_NUM_PER_WORD="$(config_bool memo_num_per_word "$memo_num_per_word")"
[[ ${REMOTE_WORDLIST_MIN_LEN+x} ]] && REMOTE_WORDLIST_MIN_LEN="$REMOTE_WORDLIST_MIN_LEN"
[[ ${remote_wordlist_url+x} ]] && REMOTE_WORDLIST_URL="$remote_wordlist_url"
[[ ${local_wordlist_path+x} ]] && LOCAL_WORDLIST_PATH="$local_wordlist_path"
[[ ${remote_wordlist_timeout+x} ]] && REMOTE_WORDLIST_TIMEOUT="$remote_wordlist_timeout"
return 0
}
install_scope() {
if (( EUID == 0 )); then
printf 'sudo'
else
printf 'normal user'
fi
}
print_install_info() {
local scope
scope="$(install_scope)"
printf '\nYou are running this command as %s.\n' "$scope"
printf '\nThis will install %s to:\n' "$APP_NAME"
printf '\n Binary: %s/keygen\n' "$INSTALL_BIN_DIR"
printf ' Shared data: %s\n\n' "$INSTALL_SHARE_DIR"
}
prompt_yes_no() {
local prompt_text="$1"
local default_yes="$2"
if [[ "$ASSUME_YES" == "true" ]]; then
return 0
fi
if [[ ! -t 0 ]]; then
printf '\n'
fatal "Installation requires confirmation from an interactive shell"
fi
local answer
printf '%s ' "$prompt_text"
IFS= read -r answer
if [[ "$default_yes" == "true" ]]; then
case "${answer,,}" in
n|no) fatal "Installation cancelled" ;;
*) ;;
esac
else
case "${answer,,}" in
y|yes) ;;
*) fatal "Installation cancelled" ;;
esac
fi
}
installation_candidates() {
printf '%s\n' \
"/usr/bin/keygen|system binary" \
"/usr/share/keygen|system shared data" \
"/usr/local/bin/keygen|legacy system binary" \
"/usr/local/share/keygen|legacy system shared data" \
"${HOME}/.local/bin/keygen|user binary" \
"${HOME}/.local/share/keygen|user shared data"
}
check_existing_installations() {
[[ "$INSTALL_TARGET_CUSTOM" == "true" ]] && return 0
local target_bin="$INSTALL_BIN_DIR/keygen"
local existing=()
local candidate path label
while IFS= read -r candidate; do
path="${candidate%%|*}"
label="${candidate#*|}"
[[ "$path" == "$target_bin" || "$path" == "$INSTALL_SHARE_DIR" ]] && continue
[[ -e "$path" ]] && existing+=("$label: $path")
done < <(installation_candidates)
if ((${#existing[@]} > 0)); then
printf 'Existing installation found outside the selected target:\n' >&2
for candidate in "${existing[@]}"; do
printf ' %s\n' "$candidate" >&2
done
fatal "Remove the existing installation or set PREFIX/KEYGEN_BIN_DIR/KEYGEN_SHARE_DIR intentionally"
fi
}
install_default_config() {
local dest_default="$INSTALL_CONFIG_DIR/default.conf"
local dest_user="$INSTALL_CONFIG_DIR/user.conf"
# Install default.conf if not present
if [[ ! -f "$dest_default" ]]; then
local source=""
local candidate
for candidate in \
"$DEFAULT_CONFIG_PATH" \
"$INSTALL_SHARE_DIR/default.conf" \
"$SCRIPT_DIR/../share/$APP_NAME/default.conf"
do
if [[ -f "$candidate" ]]; then
source="$candidate"
break
fi
done
[[ -n "$source" ]] || fatal "default config not found"
install -m 0644 "$source" "$dest_default"
fi
# Install user.conf if not present
if [[ ! -f "$dest_user" ]]; then
local user_source=""
local user_candidate
for user_candidate in \
"$SCRIPT_DIR/config/user.conf" \
"$SCRIPT_DIR/../share/$APP_NAME/config/user.conf" \
"$INSTALL_SHARE_DIR/config/user.conf"
do
if [[ -f "$user_candidate" ]]; then
user_source="$user_candidate"
break
fi
done
if [[ -n "$user_source" ]]; then
install -m 0644 "$user_source" "$dest_user"
fi
fi
}
install_keygen() {
init_app_version
check_existing_installations
print_install_info
if [[ -e "$INSTALL_BIN_DIR/keygen" ]]; then
prompt_yes_no "Reinstall? [y/N]:" "false"
else
prompt_yes_no "Continue? [Y/n]:" "true"
fi
mkdir -p "$INSTALL_BIN_DIR" "$INSTALL_CONFIG_DIR" "$INSTALL_WORDLIST_DIR"
install -m 0755 "$(script_target_path)" "$INSTALL_BIN_DIR/keygen"
if [[ -f "$DEFAULT_CONFIG_PATH" ]]; then
install -m 0644 "$DEFAULT_CONFIG_PATH" "$INSTALL_SHARE_DIR/default.conf"
elif [[ -f "$SCRIPT_DIR/../share/$APP_NAME/default.conf" ]]; then
install -m 0644 "$SCRIPT_DIR/../share/$APP_NAME/default.conf" "$INSTALL_SHARE_DIR/default.conf"
fi
install_default_config
if [[ -f "$SCRIPT_DIR/wordlist/en-memorable.txt" && ! -f "$INSTALL_WORDLIST_DIR/en-memorable.txt" ]]; then
install -m 0644 "$SCRIPT_DIR/wordlist/en-memorable.txt" "$INSTALL_WORDLIST_DIR/en-memorable.txt"
fi
if [[ -f "$LOCAL_META_PATH" ]]; then
install -m 0644 "$LOCAL_META_PATH" "$INSTALLED_META_PATH"
else
printf 'APP_VERSION="%s"\n' "$APP_VERSION" > "$INSTALLED_META_PATH"
fi
printf 'Done.'
}
update_keygen() {
init_app_version
local remote
if ! remote="$(fetch_remote_version)"; then
fatal "Could not check remote version"
fi
if ! version_is_newer "$remote" "$APP_VERSION"; then
printf '%s %s is already up to date\n' "$APP_NAME" "$APP_VERSION"
return 0
fi
local tmp_script tmp_meta target meta_target
tmp_script="$(mktemp "${TMPDIR:-/tmp}/keygen-script.XXXXXX")" || fatal "Could not create temporary file"
tmp_meta="$(mktemp "${TMPDIR:-/tmp}/keygen-meta.XXXXXX")" || {
rm -f "$tmp_script" 2>/dev/null || true
fatal "Could not create temporary file"
}
if ! download_to_file "$REMOTE_SCRIPT_URL" "$tmp_script" 30; then
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
fatal "Could not download update"
fi
if ! download_to_file "$REMOTE_META_URL" "$tmp_meta" 30; then
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
fatal "Could not download update metadata"
fi
if [[ ! -s "$tmp_script" ]]; then
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
fatal "Downloaded script is empty"
fi
if ! bash -n "$tmp_script"; then
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
fatal "Downloaded script failed syntax check"
fi
local shebang
shebang="$(head -n 1 "$tmp_script")"
if [[ "$shebang" != "#!/usr/bin/env bash"* && "$shebang" != "#!/bin/bash"* ]]; then
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
fatal "Downloaded script does not have a valid bash shebang"
fi
target="$(script_target_path)"
meta_target="$LOCAL_META_PATH"
if [[ "$target" == "$INSTALL_BIN_DIR/keygen" || -f "$INSTALLED_META_PATH" ]]; then
meta_target="$INSTALLED_META_PATH"
fi
install -m 0755 "$tmp_script" "$target"
mkdir -p "$(dirname "$meta_target")"
install -m 0644 "$tmp_meta" "$meta_target"
rm -f "$tmp_script" "$tmp_meta" 2>/dev/null || true
printf 'Updated %s from %s to %s\n' "$APP_NAME" "$APP_VERSION" "$remote"
}
contains_allow() {
local needle=","$1","
local normalized=",${ALLOW// /},"
[[ "$normalized" == *"$needle"* ]]
}
normalize_allow() {
local raw="$1"
raw="${raw// /}"
raw="${raw,,}"
local out=()
local item
IFS=',' read -r -a parts <<< "$raw"
for item in "${parts[@]}"; do
case "$item" in
letter|letters|alpha) out+=("letters") ;;
number|numbers|digit|digits) out+=("numbers") ;;
symbol|symbols|special|specials) out+=("symbols") ;;
hyphen|hyphens|dash|dashes) out+=("hyphen") ;;
space|spaces) out+=("space") ;;
period|periods|dot|dots) out+=("period") ;;
comma|commas) out+=("comma") ;;
underscore|underscores) out+=("underscore") ;;
alnum) out+=("letters" "numbers") ;;
all) out+=("letters" "numbers" "symbols" "hyphen" "space" "period" "comma" "underscore") ;;
"") ;;
*) fatal "Unsupported allow token: $item" ;;
esac
done
if ((${#out[@]} == 0)); then
fatal "--allow cannot be empty"
fi
local joined=""
local seen=","
for item in "${out[@]}"; do
if [[ "$seen" != *",$item,"* ]]; then
joined+="${joined:+,}$item"
seen+="$item,"
fi
done
printf '%s' "$joined"
}
validate_args() {
# --safe short-circuits type-specific validation
if [[ "$SAFE_MODE" == "true" ]]; then
is_integer "$LENGTH" || fatal "--length must be an integer"
is_integer "$COUNT" || fatal "--count must be an integer"
(( LENGTH >= 8 && LENGTH <= 64 )) || fatal "--length must be between 8 and 64"
(( COUNT >= 1 && COUNT <= 100 )) || fatal "--count must be between 1 and 100"
return 0
fi
case "$TYPE" in
random|memorable|passphrase|basic|flag|uuid|hex|base64|base64url|base32|base58|nanoid|jwt|secret|general|django|token|ssh) ;;
*) fatal "Unsupported type: $TYPE" ;;
esac
if [[ "$TYPE" == "ssh" ]]; then
case "$SSH_ACTION" in
generate|pub|priv) ;;
*) fatal "Unsupported ssh subcommand: $SSH_ACTION" ;;
esac
if [[ "$SSH_FORCE" == "true" && "$SSH_ACTION" != "generate" ]]; then
fatal "--force is only supported with ssh generate"
fi
is_integer "$COUNT" || fatal "--count must be an integer"
(( COUNT == 1 )) || fatal "ssh mode only supports --count 1"
return 0
fi
if [[ "$SSH_FORCE" == "true" ]]; then
fatal "--force is only supported with ssh mode"
fi
case "$CASE" in
default|lower|upper|capitalize) ;;
*) fatal "Unsupported case mode: $CASE" ;;
esac
case "$MEMO_SEPARATOR" in
hyphen|space|period|comma|underscore|none) ;;
*) fatal "Unsupported separator: $MEMO_SEPARATOR" ;;
esac
is_integer "$LENGTH" || fatal "--length must be an integer"
is_integer "$MEMO_WORDS" || fatal "--words must be an integer"
is_integer "$COUNT" || fatal "--count must be an integer"
(( LENGTH >= 8 && LENGTH <= 64 )) || fatal "--length must be between 8 and 64"
(( MEMO_WORDS >= 1 && MEMO_WORDS <= 10 )) || fatal "--words must be between 1 and 10"
(( COUNT >= 1 && COUNT <= 100 )) || fatal "--count must be between 1 and 100"
ALLOW="$(normalize_allow "$ALLOW")"
if [[ "$TYPE" == "memorable" && "$MEMO_CAPITALIZE" == "true" && "$CASE" == "default" ]]; then
CASE="capitalize"
fi
}
parse_args() {
local type_set="false"
while (($#)); do
case "$1" in
random|memorable|passphrase|basic|flag|uuid|hex|base64|base64url|base32|base58|nanoid|jwt|secret|general|django|token|ssh)
[[ "$type_set" == "false" ]] || fatal "Multiple output types provided"
TYPE="$1"
type_set="true"
;;
-t|--type)
shift || fatal "Missing value for --type"
TYPE="${1,,}"
type_set="true"
;;
--type=*) TYPE="${1#*=}"; TYPE="${TYPE,,}"; type_set="true" ;;
-l|--length)
shift || fatal "Missing value for --length"
LENGTH="$1"
;;
--length=*) LENGTH="${1#*=}" ;;
-w|--words)
shift || fatal "Missing value for --words"
MEMO_WORDS="$1"
;;
--words=*) MEMO_WORDS="${1#*=}" ;;
-c|--case)
shift || fatal "missing value for --case"
CASE="${1,,}"
;;
--case=*) CASE="${1#*=}"; CASE="${CASE,,}" ;;
-a|--allow)
shift || fatal "Missing value for --allow"
ALLOW="$1"
;;
--allow=*) ALLOW="${1#*=}" ;;
-s|--separator|--sep)
shift || fatal "Missing value for --separator"
MEMO_SEPARATOR="${1,,}"
;;
--separator=*|--sep=*) MEMO_SEPARATOR="${1#*=}"; MEMO_SEPARATOR="${MEMO_SEPARATOR,,}" ;;
-n|--count)
shift || fatal "Missing value for --count"
COUNT="$1"
;;
--count=*) COUNT="${1#*=}" ;;
--safe)
SAFE_MODE="true"
;;
-p|--plain)
PLAIN="true"
SPINNER="false"
;;
--no-spinner)
SPINNER="false"
;;
--force)
SSH_FORCE="true"
;;
-v|--version)
ACTION="version"
;;
-u|--update)
ACTION="update"
;;
-i|--install)
ACTION="install"
;;
--uninstall)
ACTION="uninstall"
;;
-y|--yes)
ASSUME_YES="true"
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
*)
if [[ "$1" == -* ]]; then
fatal "Unknown option: $1"
fi
if [[ "$type_set" == "false" ]]; then
TYPE="${1,,}"
type_set="true"
elif [[ "$TYPE" == "ssh" && "$SSH_ACTION" == "generate" ]]; then
case "${1,,}" in
pub|public) SSH_ACTION="pub" ;;
priv|private) SSH_ACTION="priv" ;;
*) fatal "Unexpected argument: $1" ;;
esac
else
fatal "Unexpected argument: $1"
fi
;;
esac
shift
done
}
color_init() {
if [[ "$PLAIN" == "true" || -n "${NO_COLOR:-}" || ! -t 1 ]]; then
BOLD="" DIM="" RESET="" ACCENT="" MUTED="" OK="" WARN="" LINE=""
return
fi
BOLD=$'\033[1m'
DIM=$'\033[2m'
RESET=$'\033[0m'
if [[ "${COLORTERM:-}" == "truecolor" || "${COLORTERM:-}" == "24bit" ]]; then
ACCENT=$'\033[38;2;124;156;255m'
MUTED=$'\033[38;2;148;163;184m'
OK=$'\033[38;2;52;211;153m'
WARN=$'\033[38;2;251;191;36m'
LINE=$'\033[38;2;71;85;105m'
else
ACCENT=$'\033[38;5;111m'
MUTED=$'\033[38;5;245m'
OK=$'\033[38;5;120m'
WARN=$'\033[38;5;220m'
LINE=$'\033[38;5;240m'
fi
}
spinner_start() {
[[ "$SPINNER" == "true" && "$PLAIN" != "true" && -t 2 ]] || return 0
local msg="$1"
(
local frames=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
local frame
while true; do
for frame in "${frames[@]}"; do
printf '\r%b%s%b %s' "$ACCENT" "$frame" "$RESET" "$msg" >&2
sleep 0.06
done
done
) &
SPINNER_PID="$!"
}
spinner_stop() {
[[ -n "${SPINNER_PID:-}" ]] || return 0
kill "$SPINNER_PID" >/dev/null 2>&1 || true
wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
printf '\r\033[K' >&2
}
cleanup() {
spinner_stop
}
trap cleanup EXIT INT TERM
random_byte() {
od -An -N1 -tu1 /dev/urandom | tr -d ' '
}
# Uniform random integer in [0, max) via rejection sampling.
# Reads as many random bytes as needed to cover max (supports up to ~2^32).
pick_index() {
local max="$1"
(( max >= 1 )) || fatal "Internal random bound out of range: $max"
local cap byte_count
if (( max <= 256 )); then
cap=256; byte_count=1
elif (( max <= 65536 )); then
cap=65536; byte_count=2
elif (( max <= 16777216 )); then
cap=16777216; byte_count=3
else
cap=4294967296; byte_count=4
fi
local limit=$(( (cap / max) * max ))
local n i
while true; do
n=0
for ((i = 0; i < byte_count; i++)); do
n=$(( n * 256 + $(random_byte) ))
done
if (( n < limit )); then
printf '%d' $(( n % max ))
return 0
fi
done
}
pick_char() {
local alphabet="$1"
local max="${#alphabet}"
local idx
idx="$(pick_index "$max")"
printf '%s' "${alphabet:idx:1}"
}
random_token() {
local length="$1"
local alphabet="$2"
local out=""
local i
((${#alphabet} > 0)) || fatal "Generated charset is empty"
for ((i = 0; i < length; i++)); do
out+="$(pick_char "$alphabet")"
done
printf '%s' "$out"
}