-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·3197 lines (2821 loc) · 127 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·3197 lines (2821 loc) · 127 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
# @generated from canonical sources in install_modules/; DO NOT EDIT install.sh directly.
# install.sh — One-liner installer for cdidx (CodeIndex)
# cdidxワンライナーインストーラー
#
# Usage / 使い方:
# curl -fsSL https://raw.githubusercontent.com/Widthdom/CodeIndex/main/install.sh | bash
# curl -fsSL https://raw.githubusercontent.com/Widthdom/CodeIndex/v1.5.0/install.sh | bash -s -- v1.5.0
# export CDIDX_ALLOW_RISKY_INSTALL_DIR=1 CDIDX_INSTALL_DIR=/usr/local/bin; curl -fsSL ... | bash
# bash ./install.sh --self-test-local-mirror [--self-test-allow-overwrite] [vX.Y.Z]
# bash ./install.sh --reinstall-real vX.Y.Z
# bash ./install.sh --doctor [vX.Y.Z]
# bash ./install.sh --uninstall [--purge-cache]
# bash ./install.sh --verify-policy strict vX.Y.Z
# HTTPS_PROXY=http://proxy.example:8080 bash ./install.sh --doctor
# CDIDX_GITHUB_BASE_URL=https://github.example.internal \
# CDIDX_GITHUB_API_BASE_URL=https://github.example.internal/api/v3 \
# bash ./install.sh --doctor vX.Y.Z
#
# Optional env vars / 任意環境変数:
# CDIDX_GITHUB_BASE_URL Release download base URL override
# CDIDX_GITHUB_API_BASE_URL API base URL override for latest-release lookup
# CDIDX_NETWORK_CONNECT_TIMEOUT_SECONDS Connect timeout (default: 10; max: 120)
# CDIDX_NETWORK_MAX_TIME_SECONDS Total transfer/retry budget (default: 300; max: 3600)
# CDIDX_NETWORK_LOW_SPEED_LIMIT_BYTES Low-speed threshold (default: 1024; max: 1048576)
# CDIDX_NETWORK_LOW_SPEED_TIME_SECONDS Low-speed timeout (default: 30; max: 300)
# CDIDX_NETWORK_RETRY_COUNT Retry count (default: 2; max: 5)
# CDIDX_NETWORK_RETRY_DELAY_SECONDS Retry delay (default: 1; max: 60)
# CDIDX_VERIFY_POLICY=compat|strict Verification policy (default: strict)
# CDIDX_REQUIRE_ATTESTATION=1 Require GitHub provenance verification via gh
# CDIDX_STRICT_VERIFY=1 Require GPG checksum-manifest signature verification
# CDIDX_RELEASE_GPG_FINGERPRINT Expected checksum signer fingerprint
# CDIDX_ALLOW_RISKY_INSTALL_DIR=1 Allow root/home/system install targets
# CDIDX_LOCAL_MIRROR_PORT Local self-test HTTP server port (default: 18765)
# HTTPS_PROXY / HTTP_PROXY Proxy used by curl for release and API probes
# NO_PROXY Hosts that should bypass the proxy
#
# Self-test mock payload safety / セルフテスト mock 上書き防止:
# The --self-test-local-mirror path installs a **mock** cdidx that only
# handles --version. To prevent that mock from silently replacing a real
# ~/.local/bin/cdidx when CDIDX_INSTALL_DIR is pre-exported to a
# well-known system/user install path or to a directory that already
# holds a cdidx binary, the self-test aborts unless the caller also
# passes --self-test-allow-overwrite.
# --self-test-local-mirror は --version だけを返す mock cdidx を配置する。
# CDIDX_INSTALL_DIR が既知のシステム/ユーザー install 先や、既に cdidx を
# 持つディレクトリを指しているときは、--self-test-allow-overwrite を明示
# しない限り self-test を中断して real install の上書きを防ぐ。
#
# Real reinstall validation / 実リリースの再インストール検証:
# --reinstall-real vX.Y.Z downloads the real published release (no mock)
# into an **isolated temp dir** — it never touches the user's real install
# — and verifies the binary end-to-end: `cdidx --version` plus a real
# `cdidx . --db <tmp>` indexing run against a minimal scratch project.
# Catches regressions that --self-test-local-mirror cannot (symbol
# extraction, SQLite loading, FTS, etc.) because the mock only handles
# --version. CDIDX_INSTALL_DIR is intentionally ignored for this mode.
# --reinstall-real vX.Y.Z は、公開済みリリースを **隔離された temp dir** に
# 実ダウンロードし(ユーザーの実インストールには触らない)、`cdidx --version`
# だけでなく最小スクラッチプロジェクトに対する `cdidx . --db <tmp>` 実行まで
# 含めた end-to-end 検証を行う。--self-test-local-mirror の mock は --version
# しか返さないため拾えない、シンボル抽出・SQLite ロード・FTS 等のリグレッション
# を検出できる。このモードでは CDIDX_INSTALL_DIR は意図的に無視する。
#
# Network diagnostics / ネットワーク診断:
# --doctor [vX.Y.Z] does not install anything. It prints the active proxy
# environment variables and probes the installer's upstream URLs (the
# latest-release API endpoint plus the release tarball and sha256sums asset
# URLs for the requested version — or the version recorded in version.json
# if no version is provided) with `curl -sSI`. Each probe reports its HTTP
# status. On `CONNECT tunnel failed, response 403` (curl exit 56) the doctor
# prints the canonical upstream-proxy guidance so users get a single,
# actionable next step without needing prior network knowledge. Exits 0 when
# every probe returns a 2xx/3xx response, 1 otherwise.
# --doctor [vX.Y.Z] は何もインストールせず、有効な proxy 環境変数と、
# installer が叩く upstream URL(latest-release API と、指定バージョン
# または version.json 記載バージョンのリリース tarball / sha256sums)を
# `curl -sSI` で probe し、各結果の HTTP status を表示する。
# `CONNECT tunnel failed, response 403` (curl exit 56) を検知した場合は、
# upstream proxy / egress policy 側の拒否であり経路差し替えでは解消しない
# という定型ガイダンスを出力し、ユーザーがネットワーク知識なしで次の一手
# を取れるようにする。全 probe が 2xx/3xx を返したら exit 0、それ以外は 1。
set -euo pipefail
REPO="Widthdom/CodeIndex"
RELEASE_ATTESTATION_SIGNER_WORKFLOW="github.com/Widthdom/CodeIndex/.github/workflows/release.yml"
INSTALL_DIR="${CDIDX_INSTALL_DIR-${HOME:-}/.local/bin}"
BINARY_NAME="cdidx"
MANIFEST_REQUIRED_VERSION="1.24.6"
AUTHENTICATED_MANIFEST_REQUIRED_VERSION="1.38.1"
GITHUB_BASE_URL="${CDIDX_GITHUB_BASE_URL:-https://github.com}"
GITHUB_API_BASE_URL="${CDIDX_GITHUB_API_BASE_URL:-https://api.github.com}"
CURL_STDERR_SAMPLE_BYTES=8192
LATEST_RELEASE_RESPONSE_MAX_BYTES=65536
CURL_CONNECT_TIMEOUT_SECONDS="${CDIDX_NETWORK_CONNECT_TIMEOUT_SECONDS:-10}"
CURL_MAX_TIME_SECONDS="${CDIDX_NETWORK_MAX_TIME_SECONDS:-300}"
CURL_LOW_SPEED_LIMIT_BYTES="${CDIDX_NETWORK_LOW_SPEED_LIMIT_BYTES:-1024}"
CURL_LOW_SPEED_TIME_SECONDS="${CDIDX_NETWORK_LOW_SPEED_TIME_SECONDS:-30}"
CURL_RETRY_COUNT="${CDIDX_NETWORK_RETRY_COUNT:-2}"
CURL_RETRY_DELAY_SECONDS="${CDIDX_NETWORK_RETRY_DELAY_SECONDS:-1}"
RELEASE_ARCHIVE_MAX_BYTES=536870912
RELEASE_METADATA_MAX_BYTES=1048576
ARCHIVE_MEMBER_MAX_COUNT=4096
ARCHIVE_DECLARED_MAX_BYTES=1073741824
ARCHIVE_EXPANDED_STREAM_MAX_BYTES=1207959552
ARCHIVE_COMPRESSION_RATIO_MAX=250
EXTRACTED_PAYLOAD_MAX_BYTES=1073741824
VALIDATED_ARCHIVE_DECLARED_BYTES=0
VALIDATED_ARCHIVE_MEMBER_COUNT=0
VERIFY_POLICY="${CDIDX_VERIFY_POLICY:-strict}"
REQUIRE_ATTESTATION="${CDIDX_REQUIRE_ATTESTATION:-0}"
STRICT_VERIFY="${CDIDX_STRICT_VERIFY:-0}"
REQUIRE_RELEASE_PROVENANCE=0
MANIFEST_PROVENANCE_VERIFIED=0
PAYLOAD_MANIFEST_AUTHENTICATED=0
DEFAULT_RELEASE_GPG_FINGERPRINT=""
RELEASE_GPG_FINGERPRINT="${CDIDX_RELEASE_GPG_FINGERPRINT:-$DEFAULT_RELEASE_GPG_FINGERPRINT}"
# Normalize optional base URL overrides by removing a trailing slash.
# 末尾スラッシュ付きでも URL 連結が壊れないようにする。
GITHUB_BASE_URL="${GITHUB_BASE_URL%/}"
GITHUB_API_BASE_URL="${GITHUB_API_BASE_URL%/}"
TMPDIR_CLEANUP=""
TRANSFER_DIR_CLEANUP=""
STAGE_DIR_CLEANUP=""
BACKUP_DIR_CLEANUP=""
LOCAL_MIRROR_DIR_CLEANUP=""
LOCAL_MIRROR_PID=""
SELF_TEST_INSTALL_DIR_CLEANUP=""
REINSTALL_SCRATCH_CLEANUP=""
INSTALL_LOCK_DIR_CLEANUP=""
SELF_TEST_LOCAL_MIRROR=0
# Only set via the --self-test-allow-overwrite CLI flag. We intentionally do
# NOT inherit this from the environment so that a stale SELF_TEST_ALLOW_OVERWRITE=1
# in the caller's shell / CI cannot silently bypass the install-dir guard.
# CLI フラグ --self-test-allow-overwrite 経由でのみ 1 になる。環境変数からは
# 継承しない (呼び出し側のシェルに残った SELF_TEST_ALLOW_OVERWRITE=1 が
# install-dir ガードを黙って無効化しないようにするため)。
SELF_TEST_ALLOW_OVERWRITE=0
EXISTING_BIN=""
EXISTING_VERSION=""
EXPLICIT_VERSION_REQUESTED=0
PURGE_CACHE_ON_UNINSTALL=0
# --- Helpers / ヘルパー ---
info() { printf '\033[1;34m==>\033[0m %s\n' "$1"; }
warn() { printf '\033[1;33mWARN:\033[0m %s\n' "$1" >&2; }
error() { printf '\033[1;31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
report_error() { printf '\033[1;31mERROR:\033[0m %s\n' "$1" >&2; }
published_release_rids() {
printf '%s' "linux-x64, linux-arm64, osx-arm64, win-x64, win-arm64"
}
platform_support_request_url() {
printf 'https://github.com/%s/issues/new?title=Request%%20official%%20release%%20asset%%20for%%20RID' "$REPO"
}
is_published_release_rid() {
case "$1" in
linux-x64|linux-arm64|osx-arm64|win-x64|win-arm64)
return 0
;;
*)
return 1
;;
esac
}
validate_published_release_rid() {
if is_published_release_rid "$RID"; then
return 0
fi
error "Unsupported release asset RID: ${RID}. Official release assets are published for $(published_release_rids). Install via 'dotnet tool install -g cdidx' with the .NET SDK, build from source with 'dotnet publish src/CodeIndex/CodeIndex.csproj -c Release -r ${RID} --self-contained true', or request official platform support at $(platform_support_request_url). See https://github.com/${REPO}/blob/main/docs/platform-support.md."
}
cleanup() {
if [ -n "$TRANSFER_DIR_CLEANUP" ]; then
rm -rf "$TRANSFER_DIR_CLEANUP"
fi
if [ -n "$TMPDIR_CLEANUP" ]; then
rm -rf "$TMPDIR_CLEANUP"
fi
if [ -n "$STAGE_DIR_CLEANUP" ]; then
rm -rf "$STAGE_DIR_CLEANUP"
fi
if [ -n "$BACKUP_DIR_CLEANUP" ]; then
rm -rf "$BACKUP_DIR_CLEANUP"
fi
if [ -n "$LOCAL_MIRROR_PID" ]; then
kill "$LOCAL_MIRROR_PID" > /dev/null 2>&1 || true
fi
if [ -n "$LOCAL_MIRROR_DIR_CLEANUP" ]; then
rm -rf "$LOCAL_MIRROR_DIR_CLEANUP"
fi
if [ -n "$SELF_TEST_INSTALL_DIR_CLEANUP" ]; then
rm -rf "$SELF_TEST_INSTALL_DIR_CLEANUP"
fi
if [ -n "$REINSTALL_SCRATCH_CLEANUP" ]; then
rm -rf "$REINSTALL_SCRATCH_CLEANUP"
fi
if [ -n "$INSTALL_LOCK_DIR_CLEANUP" ]; then
rm -rf "$INSTALL_LOCK_DIR_CLEANUP"
fi
}
trap cleanup EXIT
preserve_recovery_artifacts() {
report_error "Rollback incomplete. Preserving recovery artifacts for manual recovery."
if [ -n "${BACKUP_DIR_CLEANUP:-}" ]; then
report_error "Backup: ${BACKUP_DIR_CLEANUP}"
fi
if [ -n "${STAGE_DIR_CLEANUP:-}" ]; then
report_error "Stage: ${STAGE_DIR_CLEANUP}"
fi
BACKUP_DIR_CLEANUP=""
STAGE_DIR_CLEANUP=""
}
need_cmd() {
if ! command -v "$1" > /dev/null 2>&1; then
error "Required command not found: $1"
fi
}
has_cmd() {
command -v "$1" > /dev/null 2>&1
}
apply_verification_policy() {
case "$VERIFY_POLICY" in
compat)
VERIFY_POLICY="compat"
;;
""|strict)
VERIFY_POLICY="strict"
REQUIRE_RELEASE_PROVENANCE=1
;;
*)
error "CDIDX_VERIFY_POLICY must be 'compat' or 'strict' (got '${VERIFY_POLICY}')."
;;
esac
}
release_attestation_supported() {
if [ "${CDIDX_INSTALL_SH_LIB_ONLY:-0}" = "1" ] && [ "${CDIDX_TEST_ENABLE_ATTESTATION:-0}" != "1" ]; then
return 1
fi
[ "$GITHUB_BASE_URL" = "https://github.com" ] && [ "${SELF_TEST_LOCAL_MIRROR:-0}" != "1" ]
}
verify_release_attestation() {
local artifact_path="$1"
local artifact_name="$2"
if ! release_attestation_supported; then
if [ "$REQUIRE_ATTESTATION" = "1" ]; then
error "GitHub provenance attestation verification is required, but the release host is not github.com. Set CDIDX_VERIFY_POLICY=compat or unset CDIDX_REQUIRE_ATTESTATION, or install from the public GitHub release."
fi
return 0
fi
if ! has_cmd gh; then
if [ "$REQUIRE_ATTESTATION" = "1" ]; then
error "GitHub provenance attestation verification is required, but the 'gh' command was not found. Install GitHub CLI, set CDIDX_VERIFY_POLICY=compat, or unset CDIDX_REQUIRE_ATTESTATION."
fi
warn "Skipping GitHub provenance attestation for ${artifact_name}: 'gh' command not found. Set CDIDX_VERIFY_POLICY=strict or CDIDX_REQUIRE_ATTESTATION=1 to require this verification."
return 0
fi
info "Verifying GitHub provenance attestation for ${artifact_name}..."
if gh attestation verify "$artifact_path" \
-R "$REPO" \
--signer-workflow "$RELEASE_ATTESTATION_SIGNER_WORKFLOW" \
--source-ref "refs/tags/${VERSION}" > /dev/null; then
if [ "$artifact_name" = "sha256sums.txt" ]; then
MANIFEST_PROVENANCE_VERIFIED=1
fi
return 0
fi
if [ "$REQUIRE_ATTESTATION" = "1" ]; then
error "GitHub provenance attestation verification failed for ${artifact_name}."
fi
warn "GitHub provenance attestation verification failed for ${artifact_name}; continuing with checksum verification. Set CDIDX_VERIFY_POLICY=strict or CDIDX_REQUIRE_ATTESTATION=1 to fail closed."
}
checksum_signature_supported() {
if [ "${CDIDX_INSTALL_SH_LIB_ONLY:-0}" = "1" ] && [ "${CDIDX_TEST_ENABLE_SIGNATURE_VERIFY:-0}" != "1" ]; then
return 1
fi
return 0
}
normalize_gpg_fingerprint() {
printf '%s' "$1" | tr -d '[:space:]' | tr '[:lower:]' '[:upper:]'
}
extract_validsig_fingerprint() {
awk '$1 == "[GNUPG:]" && $2 == "VALIDSIG" { print $3; exit }' "$1"
}
verify_checksum_signature() {
local checksums_path="$1"
local signature_path="$2"
if ! has_cmd gpg; then
if [ "$STRICT_VERIFY" = "1" ]; then
error "GPG signature verification is required, but the 'gpg' command was not found. Install GnuPG, set CDIDX_VERIFY_POLICY=compat, or unset CDIDX_STRICT_VERIFY."
fi
warn "Skipping GPG signature verification for sha256sums.txt: 'gpg' command not found. Set CDIDX_VERIFY_POLICY=strict or CDIDX_STRICT_VERIFY=1 to require this verification."
return 0
fi
local gpg_status="${signature_path}.status"
local gpg_stderr="${signature_path}.stderr"
info "Verifying checksum signature..."
if ! gpg --batch --status-fd 1 --verify "$signature_path" "$checksums_path" > "$gpg_status" 2> "$gpg_stderr"; then
if [ "$STRICT_VERIFY" = "1" ]; then
error "GPG signature verification failed for sha256sums.txt."
fi
warn "GPG signature verification failed for sha256sums.txt; continuing with checksum verification. Set CDIDX_VERIFY_POLICY=strict or CDIDX_STRICT_VERIFY=1 to fail closed."
return 0
fi
local actual_fingerprint
actual_fingerprint="$(extract_validsig_fingerprint "$gpg_status")"
if [ -z "$actual_fingerprint" ]; then
if [ "$STRICT_VERIFY" = "1" ]; then
error "GPG signature verification did not report a signer fingerprint."
fi
warn "GPG signature verification succeeded but no signer fingerprint was reported; continuing without fingerprint pinning."
return 0
fi
if [ -z "$RELEASE_GPG_FINGERPRINT" ]; then
if [ "$STRICT_VERIFY" = "1" ]; then
error "GPG signature verification is strict, but no expected release signer fingerprint is configured. Set CDIDX_RELEASE_GPG_FINGERPRINT to the trusted release signing key fingerprint, or set CDIDX_VERIFY_POLICY=compat."
fi
warn "GPG signature verification succeeded for sha256sums.txt, but no expected release signing fingerprint is configured. Set CDIDX_RELEASE_GPG_FINGERPRINT to pin the signer, or set CDIDX_VERIFY_POLICY=strict to require it."
return 0
fi
local expected_fingerprint
expected_fingerprint="$(normalize_gpg_fingerprint "$RELEASE_GPG_FINGERPRINT")"
actual_fingerprint="$(normalize_gpg_fingerprint "$actual_fingerprint")"
if [ "$actual_fingerprint" != "$expected_fingerprint" ]; then
error "GPG signature fingerprint mismatch for sha256sums.txt. Expected ${expected_fingerprint}, got ${actual_fingerprint}."
fi
MANIFEST_PROVENANCE_VERIFIED=1
}
enforce_manifest_provenance() {
if [ "$MANIFEST_PROVENANCE_VERIFIED" = "1" ]; then
return 0
fi
if [ "$REQUIRE_RELEASE_PROVENANCE" = "1" ]; then
error "Independent provenance verification failed for sha256sums.txt. Install GitHub CLI for release attestation verification, or configure GnuPG with CDIDX_RELEASE_GPG_FINGERPRINT. Use CDIDX_VERIFY_POLICY=compat only as an explicit, audited opt-in."
fi
warn "AUDIT: CDIDX_VERIFY_POLICY=compat permits installation without independently verified release provenance."
}
temp_root() {
printf '%s' "${TMPDIR:-/tmp}"
}
probe_temp_root() {
local root
root="$(temp_root)"
if [ ! -d "$root" ]; then
error "TMPDIR not usable: ${root} is not a directory. Set TMPDIR to a writable directory with at least 100 MiB free."
fi
local probe
if ! probe="$(mktemp "${root%/}/.cdidx-install-probe.XXXXXX")"; then
error "TMPDIR not writable: ${root}. Set TMPDIR to a writable directory and rerun the installer."
fi
rm -f "$probe"
local free_kb=""
if command -v df > /dev/null 2>&1; then
free_kb="$(df -Pk "$root" 2>/dev/null | awk 'NR==2 {print $4}' || true)"
fi
if [ -n "$free_kb" ] && [ "$free_kb" -lt 102400 ] 2>/dev/null; then
error "Insufficient temp space in ${root}: ${free_kb} KiB available; need at least 102400 KiB. Set TMPDIR to a larger writable directory."
fi
if command -v mount > /dev/null 2>&1 && mount 2>/dev/null | awk -v root="$root" '
index($0, " on " root " ") && index($0, "noexec") { found = 1 }
END { exit found ? 0 : 1 }
'; then
warn "TMPDIR appears to be on a noexec filesystem: ${root}. The installer will avoid executing staged files from TMPDIR."
fi
}
verify_temp_path_space() {
local path="$1"
local free_kb=""
if command -v df > /dev/null 2>&1; then
free_kb="$(df -Pk "$path" 2>/dev/null | awk 'NR==2 {print $4}' || true)"
fi
if [ -n "$free_kb" ] && [ "$free_kb" -lt 102400 ] 2>/dev/null; then
error "Insufficient temp space for ${path}: ${free_kb} KiB available; need at least 102400 KiB."
fi
}
acquire_install_lock() {
mkdir -p "$INSTALL_DIR"
local lock_path="${INSTALL_DIR}/.cdidx-install.lock"
if command -v flock > /dev/null 2>&1; then
exec 9>"$lock_path"
if ! flock -n 9; then
error "Another cdidx install is already running for ${INSTALL_DIR}. Retry after it finishes."
fi
return 0
fi
local lock_dir="${INSTALL_DIR}/.cdidx-install.lockdir"
if ! mkdir "$lock_dir" 2>/dev/null; then
error "Another cdidx install is already running for ${INSTALL_DIR}. Retry after it finishes."
fi
INSTALL_LOCK_DIR_CLEANUP="$lock_dir"
return 0
}
strip_version_prefix() {
printf '%s' "$1" | sed 's/^[^0-9]*//'
}
semver_core() {
printf '%s' "$1" | sed 's/^[^0-9]*//' | sed 's/[^0-9.].*$//'
}
semver_ge() {
local left right
left="$(semver_core "$1")"
right="$(semver_core "$2")"
awk -v left="$left" -v right="$right" '
BEGIN {
split(left, l, ".")
split(right, r, ".")
for (i = 1; i <= 3; i++) {
li = (l[i] == "" ? 0 : l[i]) + 0
ri = (r[i] == "" ? 0 : r[i]) + 0
if (li > ri) exit 0
if (li < ri) exit 1
}
exit 0
}'
}
verify_cdidx_binary() {
local binary_path="$1"
local expected_version="${VERSION#v}"
local version_output=""
local actual_version=""
if [ ! -x "$binary_path" ]; then
report_error "Installed binary is not executable: ${binary_path}."
return 1
fi
if ! version_output="$("$binary_path" --version 2>&1)"; then
report_error "Installed binary failed to run: ${binary_path} --version."
report_error "Output: ${version_output}"
report_error "Likely causes include a wrong-architecture release asset or missing native runtime dependency next to the binary."
return 1
fi
actual_version="$(semver_core "$version_output")"
if [ -z "$actual_version" ]; then
report_error "Installed binary returned an unparsable version from ${binary_path}: ${version_output}"
return 1
fi
if [ -n "$expected_version" ] && [ "$actual_version" != "$expected_version" ]; then
report_error "Installed binary version mismatch at ${binary_path}: expected ${expected_version}, got ${actual_version}."
report_error "Check for a stale release archive, wrong architecture, or PATH shadowing by an older cdidx."
return 1
fi
return 0
}
extract_release_tag_name() {
local api_response="$1"
local version=""
if command -v jq > /dev/null 2>&1; then
version="$(printf '%s' "$api_response" | jq -r '.tag_name // empty' 2>/dev/null || true)"
fi
if [ -z "$version" ]; then
version="$(printf '%s' "$api_response" | grep '"tag_name"' | head -1 | sed 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')"
fi
printf '%s' "$version"
}
default_self_test_version() {
local script_dir
local version_file
local version
script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
version_file="${script_dir}/version.json"
version=""
if [ -f "$version_file" ]; then
if command -v jq > /dev/null 2>&1; then
version="$(jq -r '.version // empty' "$version_file" 2>/dev/null || true)"
fi
if [ -z "$version" ]; then
version="$(grep '"version"' "$version_file" | head -1 | sed 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')"
fi
fi
if [ -z "$version" ]; then
printf '%s' "v0.0.0"
return 0
fi
case "$version" in
v*) printf '%s' "$version" ;;
*) printf 'v%s' "$version" ;;
esac
}
latest_release_api_url() {
printf '%s/repos/%s/releases/latest' "$GITHUB_API_BASE_URL" "$REPO"
}
latest_release_api_diagnostic_label() {
if [ "$GITHUB_API_BASE_URL" = "https://api.github.com" ]; then
printf '%s' "GitHub API"
else
printf 'configured latest-release API (%s)' "$GITHUB_API_BASE_URL"
fi
}
release_host_diagnostic_label() {
if [ "$GITHUB_BASE_URL" = "https://github.com" ]; then
printf '%s' "GitHub release host"
else
printf 'configured release host (%s)' "$GITHUB_BASE_URL"
fi
}
is_loopback_url() {
local remainder authority port
case "$1" in
http://*|https://*) remainder="${1#*://}" ;;
*) return 1 ;;
esac
authority="${remainder%%/*}"
case "$authority" in
127.0.0.1:*|localhost:*) port="${authority#*:}" ;;
*) return 1 ;;
esac
case "$port" in
""|*[!0-9]*) return 1 ;;
esac
[ "$port" -ge 1 ] && [ "$port" -le 65535 ]
}
append_loopback_no_proxy_list() {
local current_value="${1:-}"
if [ -n "$current_value" ]; then
printf '%s,%s' "$current_value" "127.0.0.1,localhost"
else
printf '%s' "127.0.0.1,localhost"
fi
}
prepare_loopback_no_proxy_env() {
NO_PROXY="$(append_loopback_no_proxy_list "${NO_PROXY:-}")"
no_proxy="$(append_loopback_no_proxy_list "${no_proxy:-}")"
export NO_PROXY no_proxy
}
validate_bounded_network_integer() {
local environment_variable="$1"
local value="$2"
local minimum="$3"
local maximum="$4"
local maximum_digits="${#maximum}"
case "$value" in
""|*[!0-9]*)
report_error "Invalid ${environment_variable}: expected an integer from ${minimum} to ${maximum}, got ${value:-<empty>}."
return 1
;;
esac
# Reject values too wide for the small documented bounds before using
# shell integer operators. Otherwise an attacker-controlled digit string
# can overflow `test`, turn both comparisons into errors, and pass through.
if [ "${#value}" -gt "$maximum_digits" ]; then
report_error "Invalid ${environment_variable}: expected an integer from ${minimum} to ${maximum}, got ${value}."
return 1
fi
if [ "$value" -lt "$minimum" ] || [ "$value" -gt "$maximum" ]; then
report_error "Invalid ${environment_variable}: expected an integer from ${minimum} to ${maximum}, got ${value}."
return 1
fi
}
validate_network_policy() {
validate_bounded_network_integer "CDIDX_NETWORK_CONNECT_TIMEOUT_SECONDS" "$CURL_CONNECT_TIMEOUT_SECONDS" 1 120 || return 1
validate_bounded_network_integer "CDIDX_NETWORK_MAX_TIME_SECONDS" "$CURL_MAX_TIME_SECONDS" 10 3600 || return 1
validate_bounded_network_integer "CDIDX_NETWORK_LOW_SPEED_LIMIT_BYTES" "$CURL_LOW_SPEED_LIMIT_BYTES" 1 1048576 || return 1
validate_bounded_network_integer "CDIDX_NETWORK_LOW_SPEED_TIME_SECONDS" "$CURL_LOW_SPEED_TIME_SECONDS" 1 300 || return 1
validate_bounded_network_integer "CDIDX_NETWORK_RETRY_COUNT" "$CURL_RETRY_COUNT" 0 5 || return 1
validate_bounded_network_integer "CDIDX_NETWORK_RETRY_DELAY_SECONDS" "$CURL_RETRY_DELAY_SECONDS" 0 60 || return 1
if [ "$CURL_CONNECT_TIMEOUT_SECONDS" -gt "$CURL_MAX_TIME_SECONDS" ]; then
report_error "Invalid installer network policy: CDIDX_NETWORK_CONNECT_TIMEOUT_SECONDS must not exceed CDIDX_NETWORK_MAX_TIME_SECONDS."
return 1
fi
}
run_curl_with_optional_loopback_bypass() {
local url="$1"
local retry_count="${CURL_ATTEMPT_RETRY_COUNT:-$CURL_RETRY_COUNT}"
local max_time_seconds="${CURL_ATTEMPT_MAX_TIME_SECONDS:-$CURL_MAX_TIME_SECONDS}"
shift
if ! validate_network_policy; then
return 96
fi
if is_loopback_url "$url"; then
# Local installer self-tests are the only scoped HTTP exception. Keep
# the initial URL confined to a validated loopback authority, reject
# every redirect, and bypass proxy state.
curl --noproxy 127.0.0.1,localhost --proto '=http,https' --proto-redir '=https' --max-redirs 0 \
--connect-timeout "$CURL_CONNECT_TIMEOUT_SECONDS" --max-time "$max_time_seconds" \
--speed-limit "$CURL_LOW_SPEED_LIMIT_BYTES" --speed-time "$CURL_LOW_SPEED_TIME_SECONDS" \
--retry "$retry_count" --retry-delay "$CURL_RETRY_DELAY_SECONDS" \
--retry-max-time "$max_time_seconds" "$@"
return
fi
case "$url" in
https://*) ;;
*)
report_error "Installer protocol policy rejected non-HTTPS public URL: ${url}. Configure an HTTPS release/API endpoint; only loopback self-tests may use HTTP. [protocol_rejected]"
return 97
;;
esac
curl --proto '=https' --proto-redir '=https' \
--connect-timeout "$CURL_CONNECT_TIMEOUT_SECONDS" --max-time "$max_time_seconds" \
--speed-limit "$CURL_LOW_SPEED_LIMIT_BYTES" --speed-time "$CURL_LOW_SPEED_TIME_SECONDS" \
--retry "$retry_count" --retry-delay "$CURL_RETRY_DELAY_SECONDS" \
--retry-max-time "$max_time_seconds" "$@"
}
has_explicit_self_test_install_dir() {
[ -n "${CDIDX_INSTALL_DIR:-}" ]
}
# Decide whether an explicit CDIDX_INSTALL_DIR is risky enough to refuse the
# self-test mock install. A "risky" dir is either a well-known system/user
# install path (where a real cdidx would normally live) or any directory that
# already contains an executable cdidx binary. Callers can opt out of this
# guard with --self-test-allow-overwrite.
# 明示指定された CDIDX_INSTALL_DIR が、既知のシステム/ユーザー install 先か
# 既に cdidx を持つディレクトリなら、mock での上書きを拒否する。解除には
# --self-test-allow-overwrite を使う。
is_self_test_install_dir_risky() {
local dir="$1"
if [ -z "$dir" ]; then
return 1
fi
# Expand a leading ~ manually; bash does not expand ~ inside env values.
# 先頭の ~ は env の値内では展開されないので手動で置換する。
case "$dir" in
"~"|"~/"*)
if [ -n "${HOME:-}" ]; then
dir="${HOME}${dir#\~}"
fi
;;
esac
# Normalize trailing slashes so /usr/local/bin and /usr/local/bin/ (or
# "$HOME/.local/bin/") match the well-known-path branches below. Leave a
# lone "/" intact so we don't turn it into an empty string.
# 末尾スラッシュを正規化し、/usr/local/bin と /usr/local/bin/ などを同一視する。
# ルート "/" は空文字にならないよう保持する。
while [ "${#dir}" -gt 1 ]; do
case "$dir" in
*/) dir="${dir%/}" ;;
*) break ;;
esac
done
case "$dir" in
/usr/local/bin|/usr/bin|/opt/homebrew/bin|/opt/local/bin)
return 0
;;
esac
if [ -n "${HOME:-}" ] && [ "$dir" = "${HOME}/.local/bin" ]; then
return 0
fi
if [ -x "${dir}/${BINARY_NAME}" ]; then
return 0
fi
return 1
}
allow_risky_install_dir() {
[ "${CDIDX_ALLOW_RISKY_INSTALL_DIR:-0}" = "1" ]
}
expand_install_dir_path() {
local dir="$1"
case "$dir" in
"~"|"~/"*)
if [ -z "${HOME:-}" ] || [ "$HOME" = "/" ]; then
report_error "Cannot expand cdidx install directory ${dir}: HOME is empty or root."
return 1
fi
dir="${HOME}${dir#\~}"
;;
esac
while [ "${#dir}" -gt 1 ]; do
case "$dir" in
*/) dir="${dir%/}" ;;
*) break ;;
esac
done
printf '%s\n' "$dir"
}
normalize_install_dir_path() {
local path="$1"
local existing="$path"
local suffix=""
local base
local normalized_existing
while [ ! -e "$existing" ] && [ "$existing" != "/" ]; do
base="$(basename -- "$existing")"
suffix="/${base}${suffix}"
existing="$(dirname -- "$existing")"
done
if [ ! -d "$existing" ]; then
report_error "Install directory ancestor is not a directory: ${existing}"
return 1
fi
normalized_existing="$(CDPATH= cd -P -- "$existing" && pwd)" || return 1
if [ "$normalized_existing" = "/" ]; then
if [ -n "$suffix" ]; then
printf '%s\n' "$suffix"
else
printf '/\n'
fi
else
printf '%s%s\n' "$normalized_existing" "$suffix"
fi
}
normalized_home_dir() {
local home_dir="${HOME:-}"
if [ -z "$home_dir" ]; then
return 1
fi
while [ "${#home_dir}" -gt 1 ]; do
case "$home_dir" in
*/) home_dir="${home_dir%/}" ;;
*) break ;;
esac
done
if [ -d "$home_dir" ]; then
(CDPATH= cd -P -- "$home_dir" && pwd)
else
printf '%s\n' "$home_dir"
fi
}
is_high_risk_install_dir() {
local dir="$1"
local home_dir
case "$dir" in
/|/bin|/sbin|/tmp|/var|/var/tmp|/private/tmp|/private/var|/private/var/tmp|/usr|/usr/bin|/usr/sbin|/usr/local|/usr/local/bin|/usr/local/sbin|/usr/share|/usr/local/share|/usr/lib|/usr/local/lib|/opt|/opt/bin|/opt/homebrew|/opt/homebrew/bin|/opt/local|/opt/local/bin|/Applications|/Library|/System)
return 0
;;
esac
home_dir="$(normalized_home_dir || true)"
if [ -n "$home_dir" ] && [ "$dir" = "$home_dir" ]; then
return 0
fi
return 1
}
validate_normal_install_dir() {
local expanded
local normalized
if [ -z "${CDIDX_INSTALL_DIR+x}" ] && { [ -z "${HOME:-}" ] || [ "$HOME" = "/" ]; }; then
report_error "Cannot safely derive cdidx install directory: HOME is empty or root."
return 1
fi
if ! expanded="$(expand_install_dir_path "$INSTALL_DIR")"; then
return 1
fi
case "$expanded" in
"")
report_error "Refusing empty cdidx install directory. Set CDIDX_INSTALL_DIR to an absolute directory."
return 1
;;
//*)
report_error "Refusing ambiguous cdidx install directory: ${expanded}"
return 1
;;
"."|".."|./*|../*|*/./*|*/../*|*/.|*/..)
report_error "Refusing ambiguous cdidx install directory: ${expanded}"
return 1
;;
/*) ;;
*)
report_error "Refusing non-absolute cdidx install directory: ${expanded}"
return 1
;;
esac
if ! normalized="$(normalize_install_dir_path "$expanded")"; then
return 1
fi
if is_high_risk_install_dir "$normalized" && ! allow_risky_install_dir; then
report_error "Refusing risky install directory: ${normalized}. Set CDIDX_ALLOW_RISKY_INSTALL_DIR=1 to override."
return 1
fi
INSTALL_DIR="$normalized"
return 0
}
normalize_existing_or_parent_directory() {
local path="$1"
local parent
local base
local normalized_parent
while [ "${#path}" -gt 1 ]; do
case "$path" in
*/) path="${path%/}" ;;
*) break ;;
esac
done
if [ -d "$path" ]; then
(CDPATH= cd -P -- "$path" && pwd)
return
fi
parent="$(dirname -- "$path")"
base="$(basename -- "$path")"
if [ ! -d "$parent" ]; then
report_error "Cache root parent does not exist: ${parent}"
return 1
fi
normalized_parent="$(CDPATH= cd -P -- "$parent" && pwd)" || return 1
if [ "$normalized_parent" = "/" ]; then
printf '/%s\n' "$base"
else
printf '%s/%s\n' "$normalized_parent" "$base"
fi
}
resolve_purge_cache_dir() {
local cache_root
local normalized_root
if [ -n "${XDG_CACHE_HOME:-}" ]; then
cache_root="$XDG_CACHE_HOME"
else
if [ -z "${HOME:-}" ] || [ "$HOME" = "/" ]; then
report_error "Cannot safely derive cdidx cache directory: HOME is empty or root."
return 1
fi
cache_root="${HOME}/.cache"
fi
case "$cache_root" in
""|"/"|".")
report_error "Refusing to purge cdidx cache from unsafe cache root: ${cache_root:-<empty>}"
return 1
;;
/*) ;;
*)
report_error "Refusing to purge cdidx cache from non-absolute cache root: ${cache_root}"
return 1
;;
esac
if ! normalized_root="$(normalize_existing_or_parent_directory "$cache_root")"; then
return 1
fi
case "$normalized_root" in
""|"/")
report_error "Refusing to purge cdidx cache from unsafe normalized cache root: ${normalized_root:-<empty>}"
return 1
;;
esac
printf '%s/cdidx\n' "$normalized_root"
}
release_download_base_url() {
printf '%s/%s/releases/download/%s' "$GITHUB_BASE_URL" "$REPO" "$VERSION"
}
is_proxy_tunnel_403() {
printf '%s' "$1" | grep -Eqi 'CONNECT tunnel failed, response 403|HTTP code 403 from proxy after CONNECT'
}
is_curl_protocol_rejection() {
printf '%s' "$1" | grep -Eqi 'protocol .* disabled|unsupported protocol|redirect.*protocol'
}
file_size_bytes() {
wc -c < "$1" | tr -d '[:space:]'
}
read_bounded_file_sample() {
local path="$1"
local max_bytes="$2"
local label="$3"
local byte_count
if ! byte_count="$(file_size_bytes "$path")"; then
return 1
fi
if [ "${byte_count:-0}" -le "$max_bytes" ]; then
cat "$path"
return 0
fi
head -c "$max_bytes" "$path"
printf '\n[cdidx installer truncated %s: showing first %s of %s bytes]\n' "$label" "$max_bytes" "$byte_count"
}
is_retryable_http_code() {
case "$1" in
408|429|500|502|503|504) return 0 ;;
*) return 1 ;;
esac
}
curl_http_get() {
local url="$1"
local output_path="$2"
local source_label="${3:-remote host}"
local max_bytes="${4:-$LATEST_RELEASE_RESPONSE_MAX_BYTES}"
local http_code curl_status reader_status downloaded_bytes stderr_text