-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfmanager.sh
More file actions
executable file
·10417 lines (9452 loc) · 412 KB
/
Copy pathcfmanager.sh
File metadata and controls
executable file
·10417 lines (9452 loc) · 412 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
#!/bin/bash
# ╔══════════════════════════════════════════════════════════════════╗
# ║ CF-MANAGER v3.0 — Cloudflare CLI Dashboard ║
# ║ Designed for Termux | github-sync | multi-account ║
# ╚══════════════════════════════════════════════════════════════════╝
#
# Features: Workers · KV · D1 · R2 · Durable Objects · GitHub Sync
# Rollback · Encrypted token storage · Multi-account
#
# Install deps (Termux):
# pkg install curl jq openssl git nano
#
# For real-time worker logs (`wrangler tail`), also needs Node + wrangler:
# pkg install nodejs
# npm install -g wrangler
# (cf-manager will offer to install these for you the first time you tail.)
#
# Usage: bash cf-manager.sh
set -euo pipefail
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# USER-TUNABLE SETTINGS (edit these to customise behaviour)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# ── Storage location ──────────────────────────────────────────────
CONFIG_DIR="$HOME/script/cfmanager/.cfmanager"
# ── Caching ───────────────────────────────────────────────────────
# Set CACHE_ENABLED=false to bypass all read/write cache calls and
# always hit the Cloudflare API directly. Invalidation and warm-up
# functions become no-ops; the cache directory is never written to.
CACHE_ENABLED=true
# How many seconds a cache entry stays fresh before being considered
# stale and re-fetched from the API. Only used when CACHE_ENABLED=true.
CACHE_TTL=600
# ── Editor ────────────────────────────────────────────────────────
# Preferred editor for inline worker editing and pre-deploy review.
# Falls back to vi if the chosen binary is not found.
PREFERRED_EDITOR="${EDITOR:-nano}"
# ── Backup retention ──────────────────────────────────────────────
# Maximum number of local worker backups to keep per worker name.
# Oldest backups beyond this count are deleted automatically.
BACKUP_MAX_COUNT=10
# ── API page sizes ────────────────────────────────────────────────
# Maximum items fetched in a single list call for each resource type.
# Raise if you have more resources than the default; lower to reduce
# response size on slow connections.
API_PAGE_KV=100 # KV namespaces
API_PAGE_D1=100 # D1 databases
API_PAGE_R2=1000 # R2 object listings
API_PAGE_KV_KEYS=1000 # KV key listings
API_PAGE_LIST=100 # interactive list display (KV keys browser, R2 object browser)
API_PAGE_ACCOUNTS=50 # account / membership lookups
# ── D1 copy batch size ────────────────────────────────────────────
# Number of rows fetched per page when copying D1 table data during
# sync / rename operations. Reduce if you hit API payload limits.
D1_COPY_PAGE_SIZE=500
# ── Live TUI refresh rate ─────────────────────────────────────────
# Seconds between progress-table redraws during parallel deploys.
# Lower = smoother, Higher = less CPU on slow devices.
TUI_POLL_INTERVAL=0.12
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# INTERNAL CONSTANTS (do not edit below this line)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VERSION="3.0.0"
CF_API="https://api.cloudflare.com/client/v4"
# Linux distro (via proot-distro) used to run wrangler/workerd, since workerd
# ships no native binary for Android/Bionic — only glibc Linux, macOS, Windows.
WRANGLER_DISTRO="ubuntu"
ACCOUNTS_ENC="$CONFIG_DIR/accounts.enc"
MASTER_HASH="$CONFIG_DIR/.mhash"
SALT_FILE="$CONFIG_DIR/.salt"
SESSION_FILE="$CONFIG_DIR/.session"
CURRENT_ACCOUNT="$CONFIG_DIR/.current_account"
LOG_FILE="$CONFIG_DIR/cfmanager.log"
WORKERS_DIR="$CONFIG_DIR/workers"
REPOS_DIR="$CONFIG_DIR/repos"
BACKUPS_DIR="$CONFIG_DIR/backups"
DEPLOY_HOOKS="$CONFIG_DIR/hooks"
FLOWS_DIR="$CONFIG_DIR/flows"
CFWORKER_DIR="$CONFIG_DIR/workers"
NA_LAST_SRC_FILE="$CONFIG_DIR/.na_last_src"
CACHE_DIR="$CONFIG_DIR/cache"
PANEL_PASS_FILE="$CONFIG_DIR/.panel_passwords"
ANALYTICS_TOKEN_FILE="$CONFIG_DIR/.analytics_tokens"
# Manager targets (manager.js admin URL + admin secret), used by flow
# post_deploy.webhook steps to auto-register a freshly-deployed worker
# (e.g. a nexus instance) with a manager.js panel. Deliberately stored
# PLAINTEXT (not in the encrypted $ACCOUNTS_ENC vault) — explicit user
# choice, since these are re-enterable manager admin secrets rather than
# Cloudflare account credentials. File is still created with mode 600.
MANAGER_TARGETS_FILE="$CONFIG_DIR/manager_targets.json"
# MASTER_HASH / SALT_FILE / SESSION_FILE are only referenced by
# maybe_migrate_legacy_vault() to detect and clean up an old
# master-password vault from previous versions.
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# COLORS & UI SYMBOLS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
R='\033[0;31m' # Red
G='\033[0;32m' # Green
Y='\033[1;33m' # Yellow
B='\033[0;34m' # Blue
C='\033[0;36m' # Cyan
M='\033[0;35m' # Magenta
W='\033[1;37m' # White bold
O='\033[0;33m' # Orange
DM='\033[2m' # Dim
BLD='\033[1m' # Bold
NC='\033[0m' # Reset
BG_B='\033[44m' # Blue background
BG_G='\033[42m' # Green background
SYM_OK="${G}✓${NC}"
SYM_ERR="${R}✗${NC}"
SYM_WARN="${Y}⚠${NC}"
SYM_INFO="${C}ℹ${NC}"
SYM_ARR="${B}▶${NC}"
SYM_DOT="${W}•${NC}"
SYM_STAR="${Y}★${NC}"
SYM_GEAR="${C}⚙${NC}"
SYM_CLOUD="${B}☁${NC}"
# Runtime globals
CF_TOKEN=""
CF_ACCOUNT_ID=""
CF_ZONE_ID=""
ACTIVE_ACCOUNT_NAME=""
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# UTILITY FUNCTIONS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE" 2>/dev/null || true
}
die() {
echo -e "${R}${BLD}FATAL:${NC} $*" >&2
log "FATAL: $*"
exit 1
}
info() { echo -e "${SYM_INFO} $*"; }
success() { echo -e "${SYM_OK} $*"; }
warn() { echo -e "${SYM_WARN} $*"; }
error() { echo -e "${SYM_ERR} ${R}$*${NC}"; log "ERROR: $*"; }
press_enter() {
echo -e "\n${DM}Press Enter to continue...${NC}"
read -r
}
# Generate a random worker name in Cloudflare dashboard style: adjective-noun-NNN
gen_worker_name() {
local -a _ADJS=(
aged ancient autumn billowing bitter black blue bold broken calm
cold crimson damp dark dawn divine dry empty falling fancy
flat floral fragrant frosty gentle hidden holy icy jolly late
lingering little lively long lucky misty morning muddy mute
nameless noisy odd old orange patient plain polished proud
purple quiet rapid red restless rough rustic shrill silent
small snowy solitary sparkling spring still summer sweet
twilight wandering weathered white wild winter wispy young
)
local -a _NOUNS=(
bird breeze brook bush butterfly cherry cloud dawn dew dream
dust feather field fire firefly flower fog forest frog gale
glitter grass haze hill lake leaf meadow moon morning mountain
night paper pine pond rain resonance river sea shadow shape
silence sky smoke snow snowflake sound star sun sunset surf
thunder tree truth union violet voice water waterfall wave
wildflower wind winter wood
)
local adj noun suffix
adj="${_ADJS[$((RANDOM % ${#_ADJS[@]}))]}"
noun="${_NOUNS[$((RANDOM % ${#_NOUNS[@]}))]}"
suffix=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom 2>/dev/null | head -c4)
if [[ -z "$suffix" ]]; then
local chars='abcdefghijklmnopqrstuvwxyz0123456789'
suffix=""
for _ in 1 2 3 4; do
suffix+="${chars:$((RANDOM % ${#chars})):1}"
done
fi
echo "${adj}-${noun}-${suffix}"
}
# Prompt for a worker name with a generated suggestion.
# Stores the result in the nameref variable. Never returns empty.
# prompt_worker_name result_var
prompt_worker_name() {
local -n _pwn_result="$1"
local random_name
random_name=$(gen_worker_name)
echo -e "${DM}Suggested name: ${C}${random_name}${NC}"
echo -ne "${W}Worker name${NC} ${DM}[Enter for '${random_name}']:${NC} "
read -r _pwn_result
if [[ -z "$_pwn_result" ]]; then
_pwn_result="$random_name"
fi
return 0
}
# Write the standard CF-Manager worker template to FILEPATH, substituting
# WORKER_NAME for the given name. Used by create_worker and new_to_all.
# write_worker_template filepath worker_name
write_worker_template() {
local filepath="$1" worker_name="$2"
cat > "$filepath" <<'WORKERTEMPLATE'
// CF-Manager generated worker
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const { method } = request;
// Router
if (url.pathname === '/') {
return new Response(JSON.stringify({
status: 'ok',
worker: 'WORKER_NAME',
timestamp: new Date().toISOString(),
}), {
headers: { 'Content-Type': 'application/json' },
});
}
return new Response('Not Found', { status: 404 });
},
};
WORKERTEMPLATE
sed -i "s/WORKER_NAME/${worker_name}/" "$filepath"
}
# Write the minimal fallback template used by edit_worker when the live
# source cannot be fetched. Interpolates worker_name into the response text.
# write_fallback_template filepath worker_name
write_fallback_template() {
local filepath="$1" worker_name="$2"
cat > "$filepath" <<WORKERTEMPLATE
// Could not fetch source for: ${worker_name}
// Edit this template and deploy to overwrite
export default {
async fetch(request, env, ctx) {
return new Response('Hello from ${worker_name}!', {
headers: { 'Content-Type': 'text/plain' },
});
},
};
WORKERTEMPLATE
}
# Read JS code from stdin until a line containing only "EOF", write to FILEPATH.
# Prints the save path on success.
# paste_code_to_file filepath
paste_code_to_file() {
local filepath="$1"
echo -e "${DM}Paste JS code. End with a line containing only EOF:${NC}"
local _code=""
while IFS= read -r _line; do
[[ "$_line" == "EOF" ]] && break
_code+="$_line"$'\n'
done
printf '%s' "$_code" > "$filepath"
}
# Unified directory file picker.
# Pick a .js or .gs file from DIR interactively.
# Prints the chosen path to stdout; returns 1 on cancel/empty.
# pick_js_file_from_dir DIR
pick_js_file_from_dir() {
local dir="$1"
if [[ ! -d "$dir" ]]; then
warn "Directory not found: $dir" >&2
warn "Create it or place .js/.gs files there first." >&2
return 1
fi
local -a files
mapfile -t files < <(find "$dir" -maxdepth 1 \( -name "*.js" -o -name "*.gs" \) -type f 2>/dev/null | sort)
if [[ ${#files[@]} -eq 0 ]]; then
warn "No .js or .gs files found in $dir" >&2
return 1
fi
echo -e "${W}Files in ${C}${dir}${W}:${NC}\n" >&2
for i in "${!files[@]}"; do
local fname size
fname=$(basename "${files[$i]}")
size=$(wc -c < "${files[$i]}" 2>/dev/null || echo "?")
printf " ${C}%d${NC}. %-40s ${DM}%s bytes${NC}\n" "$((i+1))" "$fname" "$size" >&2
done
echo -ne "\n${W}Select file (0=cancel):${NC} " >&2
local sel
read -r sel
[[ "$sel" == "0" || -z "$sel" ]] && return 1
local idx=$((sel-1))
if [[ $idx -lt 0 || $idx -ge ${#files[@]} ]]; then
error "Invalid selection." >&2
return 1
fi
printf '%s' "${files[$idx]}"
}
# Pick a .js or .gs file from $CFWORKER_DIR interactively.
# Prints the chosen path to stdout; returns 1 on cancel/empty.
pick_cfworker_file() {
pick_js_file_from_dir "$CFWORKER_DIR"
}
# Pick a .js or .gs file from ~/shared/Download interactively.
# Prints the chosen path to stdout; returns 1 on cancel/empty.
pick_downloads_file() {
pick_js_file_from_dir "$HOME/shared/Download"
}
confirm() {
local msg="${1:-Are you sure?}"
echo -ne "${Y}${msg} [y/N]:${NC} "
read -r ans
[[ "$ans" =~ ^[Yy]$ ]]
}
require_cmd() {
for cmd in "$@"; do
command -v "$cmd" &>/dev/null || die "Required command not found: $cmd\n Install with: pkg install $cmd"
done
}
check_deps() {
local missing=()
for cmd in curl jq openssl git; do
command -v "$cmd" &>/dev/null || missing+=("$cmd")
done
if [[ ${#missing[@]} -gt 0 ]]; then
echo -e "${R}Missing dependencies:${NC} ${missing[*]}"
echo -e "${Y}Install with:${NC} pkg install ${missing[*]}"
exit 1
fi
}
# Make sure wrangler is available and runnable (needed for `wrangler tail`).
#
# wrangler bundles workerd, which only ships native binaries for glibc Linux,
# macOS, and Windows — there is no Android/Bionic build, so it cannot run
# directly under Termux (fails with "Unsupported platform: android arm64").
# The fix is to run it inside a proot-distro Linux container, which presents
# as ordinary glibc Linux. This installs proot-distro + Ubuntu + node +
# wrangler on first use, all inside that container, and is a no-op after that.
#
# Returns 1 (without dying) if the user declines or a step fails, so callers
# can bail out gracefully.
#
# All logins use --isolated: by default proot-distro binds Termux's own app
# paths into the container for convenience, which meant the container could
# see and execute the host's (broken, non-Linux) wrangler/workerd binaries
# instead of ones installed inside it. --isolated skips that binding so the
# container only ever uses its own, real Linux copies.
ensure_wrangler() {
if ! command -v proot-distro &>/dev/null; then
warn "proot-distro is required to run wrangler on Termux (workerd has no Android build)."
if confirm "Install proot-distro now via 'pkg install proot-distro'?"; then
pkg install -y proot-distro || { error "proot-distro install failed."; return 1; }
else
info "Install manually with: pkg install proot-distro"
return 1
fi
fi
# Probing by attempting a real login is more robust than parsing
# `proot-distro list -i` output, whose format has changed across versions
# and was causing this check to always report "not installed".
if ! proot-distro login "$WRANGLER_DISTRO" --isolated -- true &>/dev/null; then
warn "No '${WRANGLER_DISTRO}' container found."
if confirm "Install it now via 'proot-distro install ${WRANGLER_DISTRO}'? (one-time, ~500MB)"; then
proot-distro install "$WRANGLER_DISTRO" || { error "${WRANGLER_DISTRO} install failed."; return 1; }
else
info "Install manually with: proot-distro install ${WRANGLER_DISTRO}"
return 1
fi
fi
# Check node AND that npm actually runs — Ubuntu/Debian's apt-packaged
# npm ships with broken/mismatched dependencies (commonly fails with
# "Cannot find module '.../glob/...'"), so command -v alone isn't enough.
if ! proot-distro login "$WRANGLER_DISTRO" --isolated -- bash -lc 'command -v node &>/dev/null && npm --version' &>/dev/null; then
warn "node/npm inside the ${WRANGLER_DISTRO} container is missing or broken."
if confirm "Install a working Node.js now via NodeSource?"; then
# apt's own nodejs/npm packages are broken on Debian/Ubuntu, so purge
# them first and install from NodeSource instead, which bundles a
# matching, working npm with the node binary.
proot-distro login "$WRANGLER_DISTRO" --isolated -- bash -lc '
set -e
apt purge -y nodejs npm >/dev/null 2>&1 || true
apt update -qq
apt install -y -qq ca-certificates curl gnupg
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt install -y nodejs
' || { error "node install failed inside ${WRANGLER_DISTRO}."; return 1; }
else
info "Install manually inside the container via NodeSource: https://github.com/nodesource/distributions"
return 1
fi
fi
if ! proot-distro login "$WRANGLER_DISTRO" --isolated -- bash -lc 'command -v wrangler' &>/dev/null; then
warn "wrangler is not installed inside the ${WRANGLER_DISTRO} container."
if confirm "Install it now via 'npm install -g wrangler'?"; then
proot-distro login "$WRANGLER_DISTRO" --isolated -- bash -lc 'npm install -g wrangler' \
|| { error "wrangler install failed inside ${WRANGLER_DISTRO}."; return 1; }
else
info "Install manually inside the container with: npm install -g wrangler"
return 1
fi
fi
return 0
}
divider() {
local char="${1:-─}"
local cols
cols=$(tput cols 2>/dev/null || echo 60)
printf "${DM}%${cols}s${NC}\n" | tr ' ' "$char"
}
header() {
local title="$1"
local cols
cols=$(tput cols 2>/dev/null || echo 60)
clear
echo -e "${BLD}${C}"
divider "═"
printf "%*s\n" $(( (${#title} + cols) / 2 )) "$title"
divider "═"
echo -e "${NC}"
if [[ -n "$ACTIVE_ACCOUNT_NAME" ]]; then
echo -e " ${SYM_CLOUD} Account: ${BLD}${G}${ACTIVE_ACCOUNT_NAME}${NC} ${DM}| CF-Manager v${VERSION}${NC}"
divider
echo ""
fi
}
spinner() {
local pid=$1
local msg="${2:-Working...}"
local frames=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
local i=0
tput civis 2>/dev/null || true
while kill -0 "$pid" 2>/dev/null; do
printf "\r${C}${frames[$i]}${NC} %s" "$msg"
i=$(( (i+1) % ${#frames[@]} ))
sleep 0.1
done
printf "\r%${#msg}s\r" " "
tput cnorm 2>/dev/null || true
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# SAFE ARITHMETIC HELPERS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# WHY THESE EXIST:
# The script runs under `set -e` (errexit). The bash arithmetic
# compound command (( expr )) exits with status 1 whenever the
# expression evaluates to zero — which is the normal "falsy" result
# for a post-increment on a zero-valued counter:
#
# local ok=0
# ((ok++)) # post-increment returns OLD value (0) → exit 1 → script dies
#
# This silently kills the script after the first successful iteration
# of any batch loop. The helpers below use the `var=$(( ))` expansion
# form, which is always a string assignment and never triggers errexit,
# making them safe to call in any context.
#
# Usage:
# inc var_name # var_name += 1
# dec var_name # var_name -= 1 (never goes below 0)
inc() {
# Increment a named variable by 1, safe under set -e.
local -n _inc_ref="$1"
_inc_ref=$(( _inc_ref + 1 ))
}
dec() {
# Decrement a named variable by 1, clamped at 0, safe under set -e.
local -n _dec_ref="$1"
_dec_ref=$(( _dec_ref > 0 ? _dec_ref - 1 : 0 ))
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# SHARED HELPER FUNCTIONS
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# cf_curl_delete ENDPOINT
# Run a curl DELETE with http_code capture; echoes raw response JSON.
# Returns 0 always — callers check cf_check on the returned JSON.
cf_curl_delete() {
local endpoint="$1"
local token="${CF_TOKEN//[[:space:]]/}"
local account_id="${CF_ACCOUNT_ID//[[:space:]]/}"
local tmpfile
tmpfile=$(mktemp)
local http_code
http_code=$(curl -s -w "%{http_code}" -o "$tmpfile" \
-X DELETE "${CF_API}${endpoint}" \
-H "Authorization: Bearer ${token}" \
-H "Content-Type: application/json" 2>/dev/null)
local resp
resp=$(cat "$tmpfile" 2>/dev/null || echo "")
rm -f "$tmpfile"
# Surface http_code in the fake error JSON so callers can log it
if ! cf_check "$resp" && [[ -z "$resp" ]]; then
resp="{\"success\":false,\"errors\":[{\"message\":\"HTTP ${http_code}\"}]}"
fi
printf '%s' "$resp"
}
# cf_curl_post_raw ENDPOINT DATA
# Same pattern as cf_curl_delete but for POST; returns resp + http_code.
# Prints JSON response to stdout. Sets _CF_LAST_HTTP_CODE in caller's scope
# via a side-channel file (avoids subshell limitation).
cf_curl_post_raw() {
local endpoint="$1" data="$2"
local token="${CF_TOKEN//[[:space:]]/}"
local account_id="${CF_ACCOUNT_ID//[[:space:]]/}"
local tmpfile
tmpfile=$(mktemp)
local http_code
http_code=$(curl -s -w "%{http_code}" -o "$tmpfile" \
-X POST "${CF_API}${endpoint}" \
-H "Authorization: Bearer ${token}" \
-H "Content-Type: application/json" \
--data "$data" 2>/dev/null)
local resp
resp=$(cat "$tmpfile" 2>/dev/null || echo "")
rm -f "$tmpfile"
[[ -z "$resp" ]] && resp="{\"success\":false,\"errors\":[{\"message\":\"HTTP ${http_code}\"}]}"
printf '%s' "$resp"
}
# select_from_list PROMPT ITEM...
# Prints a numbered list of items to stderr, reads a selection, echoes
# the chosen item to stdout. Returns 1 on cancel/invalid.
select_from_list() {
local prompt="$1"; shift
local -a items=("$@")
if [[ ${#items[@]} -eq 0 ]]; then
warn "No items to select from." >&2
return 1
fi
echo -e "${W}${prompt}:${NC}\n" >&2
for i in "${!items[@]}"; do
printf " ${C}%d${NC}. %s\n" "$((i+1))" "${items[$i]}" >&2
done
echo -ne "\n${W}Choice (0=cancel):${NC} " >&2
local sel
read -r sel
[[ "$sel" == "0" || -z "$sel" ]] && return 1
local idx=$((sel-1))
if [[ $idx -lt 0 || $idx -ge ${#items[@]} ]]; then
error "Invalid selection." >&2
return 1
fi
printf '%s' "${items[$idx]}"
}
# prompt_binding_name VAR_NAME_REF
# Prompt the user for a valid identifier to use as a worker binding name.
# Stores result in the nameref variable; returns 1 on cancel/invalid.
prompt_binding_name() {
local -n _pbn_result="$1"
local hint="${2:-}"
[[ -n "$hint" ]] && echo -e "${DM}${hint}${NC}"
read -rp "$(echo -e "${W}Binding name:${NC} ")" _pbn_result
[[ -z "$_pbn_result" ]] && info "Cancelled." && return 1
if ! [[ "$_pbn_result" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
error "Invalid name. Letters, numbers, underscores only (must start with a letter or _)."
return 1
fi
}
# binding_dedup_replace BINDINGS_VAR BINDING_NAME
# If a binding named BINDING_NAME already exists in the JSON array stored in
# BINDINGS_VAR, offer to replace it. Updates BINDINGS_VAR in place (nameref).
# Returns 1 if the user declines to replace.
binding_dedup_replace() {
local -n _bdr_bindings="$1"
local bname="$2"
if echo "$_bdr_bindings" | jq -e --arg n "$bname" '.[] | select(.name==$n)' &>/dev/null; then
warn "Binding '${bname}' already exists."
confirm "Replace it?" || return 1
_bdr_bindings=$(echo "$_bdr_bindings" | jq --arg n "$bname" '[.[] | select(.name != $n)]')
fi
}
# split_pipe VARREF_LEFT VARREF_RIGHT VALUE
# Split "left|right" into two variables. Works around the common
# local foo="${picked%%|*}"; local bar="${picked#*|}"
# pattern that's duplicated a dozen times.
split_pipe() {
local -n _sp_left="$1"
local -n _sp_right="$2"
local value="$3"
_sp_left="${value%%|*}"
_sp_right="${value#*|}"
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# ACCOUNTS STORAGE (plaintext — master password removed)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# This is a personal/local tool, so the master-password vault has been
# removed. $ACCOUNTS_ENC now stores plain JSON (still mode 600, readable
# only by you). decrypt_data() and verify_master_password() are kept only
# so maybe_migrate_legacy_vault() can read an old encrypted vault once and
# convert it; nothing new is ever encrypted with them.
decrypt_data() {
local data="$1"
local pass="$2"
echo "$data" | openssl enc -d -aes-256-cbc -pbkdf2 -iter 100000 -pass pass:"$pass" -base64 2>/dev/null
}
verify_master_password() {
local pass="$1"
local salt stored_hash input_hash
salt=$(cat "$SALT_FILE" 2>/dev/null) || return 1
stored_hash=$(cat "$MASTER_HASH" 2>/dev/null) || return 1
input_hash=$(echo -n "${salt}${pass}" | openssl dgst -sha256 | awk '{print $2}')
[[ "$input_hash" == "$stored_hash" ]]
}
# One-time migration: if $ACCOUNTS_ENC is still an old openssl-encrypted
# blob (from a previous version that used a master password), decrypt it
# once and rewrite it as plain JSON. Then remove the now-unused master
# password files. Safe to call on every startup — it's a no-op once the
# file is already plain JSON or doesn't exist yet.
maybe_migrate_legacy_vault() {
[[ -f "$ACCOUNTS_ENC" ]] || return 0
# Already plain JSON? Nothing to migrate.
if jq -e . "$ACCOUNTS_ENC" &>/dev/null; then
return 0
fi
echo -e "\n${Y}${BLD}One-time migration:${NC} removing master-password encryption from stored accounts.${NC}"
if [[ ! -f "$MASTER_HASH" || ! -f "$SALT_FILE" ]]; then
die "Found an encrypted accounts file ($ACCOUNTS_ENC) but no master-password record to decrypt it with. Migration aborted — nothing was changed."
fi
local data="" old_pass attempts=3
while [[ $attempts -gt 0 ]]; do
read -rsp "$(echo -e "${W}Enter your existing master password to migrate stored accounts:${NC} ")" old_pass; echo
if verify_master_password "$old_pass"; then
data=$(decrypt_data "$(cat "$ACCOUNTS_ENC")" "$old_pass")
break
fi
dec attempts
error "Wrong password. $attempts attempt(s) remaining."
done
if [[ -z "$data" ]]; then
die "Could not decrypt existing accounts — migration aborted. Vault left untouched."
fi
echo "$data" > "$ACCOUNTS_ENC"
chmod 600 "$ACCOUNTS_ENC"
rm -f "$MASTER_HASH" "$SALT_FILE" "${SESSION_FILE}.ts"
success "Accounts migrated to plain storage. Master password removed."
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# ACCOUNTS MANAGEMENT
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
load_accounts_data() {
[[ -f "$ACCOUNTS_ENC" ]] || { echo "{}"; return; }
local data
data=$(cat "$ACCOUNTS_ENC" 2>/dev/null)
[[ -z "$data" ]] && echo "{}" || echo "$data"
}
save_accounts_data() {
local data="$1"
echo "$data" > "$ACCOUNTS_ENC"
chmod 600 "$ACCOUNTS_ENC"
}
list_accounts() {
local data
data=$(load_accounts_data)
echo "$data" | jq -r 'keys[]' 2>/dev/null
}
get_account_field() {
local name="$1" field="$2"
local data
data=$(load_accounts_data)
echo "$data" | jq -r --arg n "$name" --arg f "$field" '.[$n][$f] // ""'
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# WORKER ADMIN-PANEL PASSWORD STORAGE (plaintext, mode 600 — same
# trust model as the accounts store above: local personal tool only)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# Keyed by "<cf-account-name>::<worker-url>" so the same worker name
# deployed under two different Cloudflare accounts (or a custom domain
# reused across accounts) never shares — or overwrites — a password.
_panel_pass_key() {
local account="$1" worker_url="$2"
printf '%s::%s' "$account" "$worker_url"
}
load_panel_passwords() {
[[ -f "$PANEL_PASS_FILE" ]] || { echo "{}"; return; }
local data
data=$(cat "$PANEL_PASS_FILE" 2>/dev/null)
[[ -z "$data" ]] && echo "{}" || echo "$data"
}
# get_saved_panel_password ACCOUNT WORKER_URL
get_saved_panel_password() {
local account="$1" worker_url="$2" key data
key=$(_panel_pass_key "$account" "$worker_url")
data=$(load_panel_passwords)
echo "$data" | jq -r --arg k "$key" '.[$k] // ""'
}
# save_panel_password ACCOUNT WORKER_URL PASSWORD
save_panel_password() {
local account="$1" worker_url="$2" pass="$3" key data
key=$(_panel_pass_key "$account" "$worker_url")
data=$(load_panel_passwords)
data=$(echo "$data" | jq --arg k "$key" --arg p "$pass" '.[$k] = $p')
echo "$data" > "$PANEL_PASS_FILE"
chmod 600 "$PANEL_PASS_FILE"
}
# forget_panel_password ACCOUNT WORKER_URL
# Drops a saved password — used when a saved password turns out to be
# stale (login rejected) so the next run prompts fresh instead of
# looping on a bad credential forever.
forget_panel_password() {
local account="$1" worker_url="$2" key data
key=$(_panel_pass_key "$account" "$worker_url")
[[ -f "$PANEL_PASS_FILE" ]] || return 0
data=$(load_panel_passwords)
data=$(echo "$data" | jq --arg k "$key" 'del(.[$k])')
echo "$data" > "$PANEL_PASS_FILE"
chmod 600 "$PANEL_PASS_FILE"
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# ANALYTICS-ONLY TOKEN STORE
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
#
# Lives as an `analytics_token` field on the account's own record in
# $ACCOUNTS_ENC (same file as everything else, same plaintext/mode-600
# trust model) — not a separate file. A "Account Analytics Read" token
# is scoped to the whole account, so once minted it's valid for every
# worker under that account. This lets mint_analytics_token() save the
# token once and push_analytics_token() reuse it across as many
# workers as you like without minting a new one each time.
# One-time migration: fold any tokens saved by an older version into
# .analytics_tokens back into their account record, then remove that
# file. No-op once it's gone.
maybe_migrate_analytics_tokens() {
[[ -f "$ANALYTICS_TOKEN_FILE" ]] || return 0
local old data
old=$(cat "$ANALYTICS_TOKEN_FILE" 2>/dev/null)
[[ -z "$old" ]] && { rm -f "$ANALYTICS_TOKEN_FILE"; return 0; }
data=$(load_accounts_data)
data=$(echo "$data" | jq --argjson old "$old" '
reduce (($old | keys)[]) as $k (.;
if has($k) then .[$k].analytics_token = $old[$k] else . end)
')
save_accounts_data "$data"
rm -f "$ANALYTICS_TOKEN_FILE"
info "Migrated saved Analytics token(s) into the main accounts store."
}
# get_saved_analytics_token ACCOUNT
get_saved_analytics_token() {
local account="$1"
load_accounts_data | jq -r --arg n "$account" '.[$n].analytics_token.token // ""'
}
# get_saved_analytics_token_label ACCOUNT
get_saved_analytics_token_label() {
local account="$1"
load_accounts_data | jq -r --arg n "$account" '.[$n].analytics_token.label // ""'
}
# save_analytics_token ACCOUNT TOKEN LABEL
save_analytics_token() {
local account="$1" token="$2" label="${3:-}" data
data=$(load_accounts_data)
data=$(echo "$data" | jq --arg n "$account" --arg t "$token" --arg l "$label" --arg d "$(date '+%Y-%m-%d %H:%M:%S')" \
'.[$n].analytics_token = {token:$t, label:$l, saved_at:$d}')
save_accounts_data "$data"
}
# forget_analytics_token ACCOUNT
forget_analytics_token() {
local account="$1" data
data=$(load_accounts_data)
data=$(echo "$data" | jq --arg n "$account" 'del(.[$n].analytics_token)')
save_accounts_data "$data"
}
# push_saved_analytics_token_to_bindings BINDINGS_VAR TOKEN ACCOUNT_ID
# Shared helper: given a bindings JSON array (nameref) plus a token and
# account id, replaces/sets CF_API_TOKEN (secret) + CF_ACCOUNT_ID (var).
# Used by both mint_analytics_token() and push_analytics_token() so the
# two flows can't drift apart.
push_saved_analytics_token_to_bindings() {
local -n _psat_bindings="$1"
local token="$2" acct_id="$3"
_psat_bindings=$(echo "$_psat_bindings" | jq --arg t "$token" \
'[.[] | select(.name != "CF_API_TOKEN")] + [{type:"secret_text", name:"CF_API_TOKEN", text:$t}]')
_psat_bindings=$(echo "$_psat_bindings" | jq --arg a "$acct_id" \
'[.[] | select(.name != "CF_ACCOUNT_ID")] + [{type:"plain_text", name:"CF_ACCOUNT_ID", text:$a}]')
}
# Push a previously-minted, saved Analytics-only token to another worker
# without minting (or pasting) a new one. Since the token is scoped to
# "Account Analytics Read" at the account level, it's valid for any
# worker under the same Cloudflare account.
push_analytics_token() {
header "Push Saved Analytics Token → Worker"
local accounts
mapfile -t accounts < <(list_accounts)
[[ ${#accounts[@]} -eq 0 ]] && warn "No accounts stored." && press_enter && return
# Only offer accounts that actually have a saved token.
local -a with_token=()
for a in "${accounts[@]}"; do
[[ -n "$(get_saved_analytics_token "$a")" ]] && with_token+=("$a")
done
if [[ ${#with_token[@]} -eq 0 ]]; then
warn "No saved Analytics tokens yet. Mint one first (Settings → mt), and it'll be saved for reuse."
press_enter; return
fi
echo -e "${W}Select account whose saved Analytics token to push:${NC}\n"
for i in "${!with_token[@]}"; do
local lbl
lbl=$(get_saved_analytics_token_label "${with_token[$i]}")
echo -e " ${C}$((i+1))${NC}. ${with_token[$i]} ${DM}(${lbl})${NC}"
done
echo -ne "\n${W}Select account (0=cancel):${NC} "
read -r sel
[[ "$sel" == "0" || -z "$sel" ]] && return
local idx=$((sel-1))
[[ $idx -lt 0 || $idx -ge ${#with_token[@]} ]] && error "Invalid selection." && press_enter && return
local name="${with_token[$idx]}"
local token acct_id
token=$(get_saved_analytics_token "$name")
acct_id=$(get_account_field "$name" "account_id")
echo ""
local worker_name
worker_name=$(select_worker "Select worker to receive the saved secret") || { press_enter; return; }
echo ""
local bindings
bindings=$(_env_get_bindings "$worker_name") || { press_enter; return; }
push_saved_analytics_token_to_bindings bindings "$token" "$acct_id"
if _env_put_bindings "$worker_name" "$bindings"; then
success "CF_API_TOKEN (secret) and CF_ACCOUNT_ID (var) pushed to '${BLD}${worker_name}${NC}' from saved token."
log "Saved analytics token pushed to worker: $worker_name (account: $name)"
warn "Remember to confirm the ANALYTICS Analytics Engine binding is present, then redeploy."
fi
press_enter
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# OAUTH2 + PKCE LOGIN (same flow as `wrangler login`)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CF_OAUTH_CLIENT_ID="54d11594-84e4-41aa-b438-e81b8fa78ee7"
CF_OAUTH_AUTH_URL="https://dash.cloudflare.com/oauth2/auth"
CF_OAUTH_TOKEN_URL="https://dash.cloudflare.com/oauth2/token"
CF_OAUTH_CALLBACK_PORT="8976"
CF_OAUTH_CALLBACK_URI="http://localhost:${CF_OAUTH_CALLBACK_PORT}/oauth/callback"
CF_OAUTH_SCOPES="account:read user:read workers:write workers_kv:write workers_routes:write workers_scripts:write workers_tail:read d1:write pages:write pages:read zone:read ssl_certs:write ai:write queues:write pipelines:write secrets_store:write offline_access"
# Generate a URL-safe base64 random string suitable for use as a PKCE verifier.
# RFC 7636 §4.1 restricts verifiers to [A-Za-z0-9\-._~], length 43–128.
# Strategy: generate more bytes than needed, keep only the unreserved-safe
# subset via tr, then trim to the requested length. Using tr '+/' '-_' before
# stripping '=' keeps the base64url alphabet intact and avoids the mid-character
# truncation that can occur when piping raw base64 directly into head -c.
_oauth_random() {
local length="${1:-43}"
local result=""
# Loop until we have enough characters (very rarely needs more than one pass)
while [[ ${#result} -lt $length ]]; do
result+=$(openssl rand -base64 $(( length * 2 )) \
| tr '+/' '-_' \
| tr -d '=' \
| tr -d '\n')
done
printf '%s' "${result:0:$length}"
}
# SHA-256 the verifier, base64url-encode it (PKCE S256 challenge)
_pkce_challenge() {
local verifier="$1"
printf '%s' "$verifier" \
| openssl dgst -sha256 -binary \
| openssl base64 \
| tr '+/' '-_' \
| tr -d '='
}
# Spin up a one-shot HTTP listener on $CF_OAUTH_CALLBACK_PORT.
# Blocks until Cloudflare redirects back, then returns "code\nstate\n".
# Prefers Python (reliable query-string parsing); falls back to nc.
_wait_for_oauth_callback() {
local tmpfile
tmpfile=$(mktemp)
if command -v python3 &>/dev/null; then
# Python's HTTPServer: parses the callback URL properly and validates cleanly
python3 - "$CF_OAUTH_CALLBACK_PORT" "$tmpfile" <<'PYEOF'
import sys, http.server, urllib.parse, threading
port = int(sys.argv[1])
outfile = sys.argv[2]
class Handler(http.server.BaseHTTPRequestHandler):
def log_message(self, *a): pass # silence access log in terminal
def do_GET(self):
params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
code = params.get('code', [''])[0]
state = params.get('state', [''])[0]
with open(outfile, 'w') as f:
f.write(code + '\n' + state + '\n')
body = (
b'<html><body style="font-family:sans-serif;text-align:center;padding:3em">'
b'<h2>✓ Logged in!</h2>'
b'<p>You can close this tab and return to Termux.</p>'
b'</body></html>'
)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
# Shut down after the first successful request
threading.Thread(target=self.server.shutdown, daemon=True).start()
with http.server.HTTPServer(('localhost', port), Handler) as srv:
srv.serve_forever()
PYEOF
local code state_recv
code=$(sed -n '1p' "$tmpfile" 2>/dev/null)
state_recv=$(sed -n '2p' "$tmpfile" 2>/dev/null)
rm -f "$tmpfile"
printf '%s\n%s\n' "$code" "$state_recv"
else
# Fallback: nc (less reliable on Termux busybox builds — no PCRE grep, -q flag varies)
warn "python3 not found — falling back to nc for OAuth callback"
(
printf 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n<!doctype html><html><head><meta charset=utf-8><title>CF-Manager</title></head><body style="font-family:sans-serif;text-align:center;padding:3em"><h2>✓ Logged in!</h2><p>You can close this tab and return to the terminal.</p></body></html>\r\n'
) | nc -l -p "$CF_OAUTH_CALLBACK_PORT" -q 2 > "$tmpfile" 2>/dev/null \
|| nc -l "$CF_OAUTH_CALLBACK_PORT" > "$tmpfile" 2>/dev/null \
|| { rm -f "$tmpfile"; return 1; }
local code_raw
code_raw=$(grep -m1 '^GET' "$tmpfile" \
| grep -oP '(?<=code=)[^&\s ]+' 2>/dev/null \
|| sed -n 's/.*GET \/oauth\/callback?.*code=\([^& ]*\).*/\1/p' "$tmpfile" | head -1)
rm -f "$tmpfile"
# nc path: no state available, emit empty second line so caller format stays consistent
printf '%s\n\n' "$code_raw"
fi
}
# Exchange the authorization code for an access token.