-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.sh
More file actions
executable file
·7746 lines (6934 loc) · 305 KB
/
Copy pathscript.sh
File metadata and controls
executable file
·7746 lines (6934 loc) · 305 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 FILE NOTICE: script.sh is built from src/ by ./build.sh — edit src/, not script.sh.
# Package Vulnerability Checker
# Analyzes package.json and lockfiles to detect vulnerable packages from custom data sources
set -e
# Version - automatically updated by release workflow
# Last release: https://github.com/maxgfr/package-checker.sh/releases
# NOTE: this exact 'VERSION="..."' format is sed-matched by .releaserc.json — do not reformat.
VERSION="1.11.35"
# Default configuration
CONFIG_FILE=".package-checker.config.json"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Global variables
VULN_DATA=""
DATA_SOURCES=()
FOUND_VULNERABLE=0
VULNERABLE_PACKAGES=()
CSV_COLUMNS=()
# Pre-built vulnerability lookup tables (for O(1) lookup)
declare -A VULN_EXACT_LOOKUP # VULN_EXACT_LOOKUP[package]="ver1|ver2|..."
declare -A VULN_RANGE_LOOKUP # VULN_RANGE_LOOKUP[package]="range1|range2|..."
declare -A VULN_METADATA_SEVERITY # VULN_METADATA_SEVERITY[package@version OR package]="critical|high|medium|low"
declare -A VULN_METADATA_GHSA # VULN_METADATA_GHSA[package@version OR package]="GHSA-xxxx-xxxx-xxxx"
declare -A VULN_METADATA_CVE # VULN_METADATA_CVE[package@version OR package]="CVE-YYYY-NNNNN"
declare -A VULN_METADATA_SOURCE # VULN_METADATA_SOURCE[package@version OR package]="ghsa|osv|custom"
declare -A VULN_ADVISORIES # VULN_ADVISORIES[package@version]="sev;ghsa;cve;src||sev;ghsa;cve;src" (all matching advisories)
declare -A VULN_PATCHED # VULN_PATCHED[package:GHSA-xxx]="patched_version" (highest upper bound per GHSA)
declare -A VULN_METADATA_FIX # VULN_METADATA_FIX[package:range]="fix_version" (upper bound from range)
VULN_LOOKUP_BUILT=false
# Configuration defaults (can be overridden by config file)
CONFIG_IGNORE_PATHS=("node_modules" ".yarn" ".git")
CONFIG_DEPENDENCY_TYPES=("dependencies" "devDependencies" "optionalDependencies")
CONFIG_ECOSYSTEMS="" # optional feed-loading override from config (options.ecosystems)
# Ecosystem registry lookup tables — derived from ECOSYSTEM_REGISTRY by
# build_ecosystem_tables() (see src/50-ecosystems/01-registry.sh)
declare -A LOCKFILE_PARSER # LOCKFILE_PARSER[basename]="analyze_fn"
declare -A LOCKFILE_ECO # LOCKFILE_ECO[basename]="purl-type"
declare -A LOCKFILE_ALIAS # LOCKFILE_ALIAS[basename]="type-alias"
KNOWN_LOCKFILE_ALIASES="" # space-separated unique alias list (validation + help)
# Ecosystems detected in the scanned project (eco -> 1); drives default-feed loading
declare -A DETECTED_ECOSYSTEMS
# ============================================================================
# Pure Bash JSON Parser Functions (no jq dependency)
# ============================================================================
# Escape special regex characters in a string
escape_regex() {
local str="$1"
printf '%s' "$str" | sed 's/[.[\*^$()+?{|\\]/\\&/g'
}
# Get a simple string value from JSON by key (top-level only)
# Usage: json_get_value "$json" "key"
json_get_value() {
local json="$1"
local key="$2"
local escaped_key=$(escape_regex "$key")
# Match "key": "value" or "key": value (for numbers/booleans)
local result=$(echo "$json" | grep -oE "\"$escaped_key\"[[:space:]]*:[[:space:]]*(\"[^\"]*\"|[0-9]+|true|false|null)" | head -1)
if [ -n "$result" ]; then
echo "$result" | sed -E 's/^"[^"]*"[[:space:]]*:[[:space:]]*//' | sed 's/^"//;s/"$//'
fi
}
# Get array length from JSON (for simple arrays at top level)
# Usage: json_array_length "$json"
json_array_length() {
local json="$1"
# Count elements by counting commas + 1 (or 0 if empty)
local trimmed=$(echo "$json" | tr -d '\n\r\t ' | sed 's/^\[//;s/\]$//')
if [ -z "$trimmed" ] || [ "$trimmed" = "[]" ]; then
echo "0"
return
fi
# Count top-level commas (not inside nested structures)
local count=1
local depth=0
local in_string=false
local prev_char=""
local i=0
local len=${#trimmed}
while [ $i -lt $len ]; do
local char="${trimmed:$i:1}"
if [ "$in_string" = true ]; then
if [ "$char" = '"' ] && [ "$prev_char" != "\\" ]; then
in_string=false
fi
else
case "$char" in
'"') in_string=true ;;
'[' | '{') depth=$((depth + 1)) ;;
']' | '}') depth=$((depth - 1)) ;;
',') [ $depth -eq 0 ] && count=$((count + 1)) ;;
esac
fi
prev_char="$char"
i=$((i + 1))
done
echo "$count"
}
# Get array element at index from JSON array
# Usage: json_array_get "$json_array" index
json_array_get() {
local json="$1"
local index="$2"
local trimmed=$(echo "$json" | tr -d '\n\r\t' | sed 's/^[[:space:]]*\[//;s/\][[:space:]]*$//')
local current=0
local depth=0
local in_string=false
local prev_char=""
local start=0
local i=0
local len=${#trimmed}
while [ $i -lt $len ]; do
local char="${trimmed:$i:1}"
if [ "$in_string" = true ]; then
if [ "$char" = '"' ] && [ "$prev_char" != "\\" ]; then
in_string=false
fi
else
case "$char" in
'"') in_string=true ;;
'[' | '{') depth=$((depth + 1)) ;;
']' | '}') depth=$((depth - 1)) ;;
',')
if [ $depth -eq 0 ]; then
if [ $current -eq $index ]; then
echo "${trimmed:$start:$((i - start))}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
return
fi
current=$((current + 1))
start=$((i + 1))
fi
;;
esac
fi
prev_char="$char"
i=$((i + 1))
done
# Last element
if [ $current -eq $index ]; then
echo "${trimmed:$start}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'
fi
}
# Get all keys from a JSON object
# Usage: json_keys "$json"
json_keys() {
local json="$1"
# Return only the top-level keys (children of the root object).
# Use an awk-based parser that respects strings, escapes and nesting depth.
echo "$json" | tr '\n' ' ' | awk '
{
s=$0
depth=0
in_str=0
prev=""
key=""
collecting=0
for(i=1;i<=length(s);i++){
c=substr(s,i,1)
if(in_str){
if(c=="\"" && prev!="\\"){
in_str=0
# look ahead for next non-space char
j=i+1
nextc=""
while(j<=length(s)){
nc=substr(s,j,1)
if(nc ~ /[[:space:]]/){ j++; continue }
nextc=nc
break
}
if(nextc==":" && depth==1){ print key }
collecting=0
key=""
} else {
if(collecting==1) key = key c
}
} else {
if(c=="\""){
in_str=1
collecting=1
key=""
} else if(c=="{"){
depth++
} else if(c=="}"){
depth--
}
}
prev=c
}
}' | sort -u
}
# Check if JSON object has a key
# Usage: json_has_key "$json" "key"
json_has_key() {
local json="$1"
local key="$2"
local escaped_key=$(escape_regex "$key")
if echo "$json" | grep -qE "\"$escaped_key\"[[:space:]]*:"; then
return 0
fi
return 1
}
# Get nested object value from JSON
# Usage: json_get_object "$json" "key"
json_get_object() {
local json="$1"
local key="$2"
# Flatten JSON to single line and extract object
local flat=$(echo "$json" | tr '\n' ' ' | tr -s ' ')
# Find position of key and extract content after it
# Use Python-like approach with awk
echo "$flat" | awk -v key="\"$key\"" '
{
# Find the key
idx = index($0, key)
if (idx == 0) { print "{}"; exit }
# Get everything after the key
rest = substr($0, idx + length(key))
# Skip whitespace and colon
match(rest, /^[[:space:]]*:[[:space:]]*/)
rest = substr(rest, RLENGTH + 1)
# Check first character
first = substr(rest, 1, 1)
if (first != "{" && first != "[") { print "{}"; exit }
# Count brackets to find the end
depth = 0
in_str = 0
result = ""
n = length(rest)
for (i = 1; i <= n; i++) {
c = substr(rest, i, 1)
result = result c
if (in_str) {
if (c == "\"" && substr(rest, i-1, 1) != "\\") in_str = 0
} else {
if (c == "\"") in_str = 1
else if (c == "{" || c == "[") depth++
else if (c == "}" || c == "]") {
depth--
if (depth == 0) { print result; exit }
}
}
}
print "{}"
}'
}
# Get array from JSON object by key
# Usage: json_get_array "$json" "key"
json_get_array() {
local json="$1"
local key="$2"
local result=$(json_get_object "$json" "$key")
# Return empty array if result is empty object or invalid
if [ -z "$result" ] || [ "$result" = "{}" ]; then
echo "[]"
else
echo "$result"
fi
}
# Iterate over array elements (outputs one element per line)
# Usage: json_array_iterate "$json_array"
json_array_iterate() {
local json="$1"
local len=$(json_array_length "$json")
local i=0
while [ $i -lt $len ]; do
local elem=$(json_array_get "$json" $i)
# Remove quotes from string elements
echo "$elem" | sed 's/^"//;s/"$//'
i=$((i + 1))
done
}
# Count keys in JSON object (object length)
# OPTIMIZED: Uses fast pattern matching instead of full JSON parsing
# Works for both compact and formatted JSON
# Usage: json_object_length "$json"
json_object_length() {
local json="$1"
# Fast method: count occurrences of "key": { pattern (with optional whitespace)
# This works for both compact JSON ("key":{) and formatted JSON ("key": {)
local count
count=$(echo "$json" | tr -d '\n\r\t' | grep -oE '"[^"]+"\s*:\s*\{' | wc -l | tr -d ' ')
echo "${count:-0}"
}
# Merge two JSON objects (simple merge, second overwrites first)
# Usage: json_merge "$json1" "$json2"
json_merge() {
# Merge two top-level JSON objects (both expected as object strings)
# - keys are merged
# - when a key exists in both, try to merge their versions and versions_range arrays
local json1="$1"
local json2="$2"
# Build a set of all top-level keys
local keys1=$(json_keys "$json1")
local keys2=$(json_keys "$json2")
local all_keys="$(printf '%s\n%s' "$keys1" "$keys2" | sort -u)"
local out="{"
local first=true
for key in $all_keys; do
[ -z "$key" ] && continue
# Extract object for this key from both inputs
local obj1=$(json_get_object "$json1" "$key")
local obj2=$(json_get_object "$json2" "$key")
# Normalize empty objects
[ -z "$obj1" ] && obj1='{}'
[ -z "$obj2" ] && obj2='{}'
local merged_obj=""
# If one of objects is empty, take the other
if [ "$obj1" = "{}" ] && [ "$obj2" = "{}" ]; then
merged_obj="{}"
elif [ "$obj1" = "{}" ]; then
merged_obj="$obj2"
elif [ "$obj2" = "{}" ]; then
merged_obj="$obj1"
else
# Merge versions and ranges from both objects into unique arrays
declare -A seen_versions
declare -A seen_ranges
local versions_list=()
local ranges_list=()
# Helper to add array items into set/array
add_items() {
local arr_json="$1"
local kind="$2" # version|range
# iterate elements
local len=$(json_array_length "$arr_json")
local i=0
while [ $i -lt $len ]; do
local v=$(json_array_get "$arr_json" $i)
# Strip surrounding quotes if present
v=$(echo "$v" | sed 's/^"//;s/"$//')
if [ -n "$v" ]; then
if [ "$kind" = "version" ]; then
if [ -z "${seen_versions[$v]+x}" ]; then
seen_versions[$v]=1
versions_list+=("$v")
fi
else
if [ -z "${seen_ranges[$v]+x}" ]; then
seen_ranges[$v]=1
ranges_list+=("$v")
fi
fi
fi
i=$((i+1))
done
}
# Extract arrays from objects if present
local v1=$(json_get_array "$obj1" "versions")
local v2=$(json_get_array "$obj2" "versions")
local r1=$(json_get_array "$obj1" "versions_range")
local r2=$(json_get_array "$obj2" "versions_range")
add_items "$v1" "version"
add_items "$v2" "version"
add_items "$r1" "range"
add_items "$r2" "range"
# Build merged object JSON
merged_obj="{"
local has=false
if [ ${#versions_list[@]} -gt 0 ]; then
merged_obj+="\"versions\":["
local firstv=true
for vv in "${versions_list[@]}"; do
if [ "$firstv" = false ]; then merged_obj+=","; fi
firstv=false
merged_obj+="\"${vv}\""
done
merged_obj+="]"
has=true
fi
if [ ${#ranges_list[@]} -gt 0 ]; then
if [ "$has" = true ]; then merged_obj+=","; fi
merged_obj+="\"versions_range\":["
local firstr=true
for rr in "${ranges_list[@]}"; do
if [ "$firstr" = false ]; then merged_obj+=","; fi
firstr=false
merged_obj+="\"${rr}\""
done
merged_obj+="]"
fi
merged_obj+="}"
fi
# Append to output
if [ "$first" = true ]; then
out+="\"${key}\":${merged_obj}"
first=false
else
out+=",\"${key}\":${merged_obj}"
fi
done
out+="}"
echo "$out"
}
# ============================================================================
# End of JSON Parser Functions
# ============================================================================
# Show version information
show_version() {
echo "package-checker.sh version $VERSION"
echo ""
echo "A tool to check Node.js projects for vulnerable packages against custom data sources."
echo "Repository: https://github.com/maxgfr/package-checker.sh"
exit 0
}
# Help message
show_help() {
cat << EOF
Usage: $0 [PATH] [OPTIONS]
A tool to check Node.js projects for vulnerable packages against custom data sources.
ARGUMENTS:
PATH Directory to scan (default: current directory)
OPTIONS:
-h, --help Show this help message
--help-ai Show AI help menu
--help-ai prompt Output the AI system prompt (prompt.md)
--help-ai doc Output the full AI guide (docs/ai-guide.md)
-v, --version Show version information
-s, --source SOURCE Data source path or URL (can be used multiple times)
--default-source-ghsa Use default GHSA source (auto-detect from brew, ./data/, /app/data/, or GitHub)
--default-source-osv Use default OSV source (auto-detect from brew, ./data/, /app/data/, or GitHub)
--default-source-ghsa-osv Use both default GHSA and OSV sources (recommended)
-f, --format FORMAT Data format: json, csv, purl, sarif, sbom-cyclonedx, or trivy-json (default: json)
-c, --config FILE Path to configuration file (default: .package-checker.config.json)
--no-config Skip loading configuration file
--csv-columns COLS CSV columns specification (e.g., "1,2" or "name,versions")
--package-name NAME Check vulnerability for a specific package name
--package-version VER Check specific version (requires --package-name)
--ecosystem ECO Ecosystem for --package-name (default: npm). One of:
npm, pypi, golang, maven, cargo, gem, composer, nuget, pub, hex, swift, githubactions
--export-json FILE Export vulnerability results to JSON file (default: vulnerabilities.json)
--export-csv FILE Export vulnerability results to CSV file (default: vulnerabilities.csv)
--github-org ORG GitHub organization to fetch package.json files from
--github-repo REPO GitHub repository to fetch package.json files from (format: owner/repo)
--github-token TOKEN GitHub personal access token (or use GITHUB_TOKEN env var)
--github-output DIR Output directory for fetched packages (default: ./packages)
--github-only Only fetch packages from GitHub, don't analyze local files
--create-multiple-issues Create one GitHub issue per vulnerable package (requires --github-token)
--create-single-issue Create a single GitHub issue with all vulnerabilities (requires --github-token)
--fetch-all DIR Fetch GHSA + OSV feeds for ALL ecosystems to DIR (default: data)
--fetch-osv [ECOS] Fetch OSV feeds; optional comma list of ecosystems (default: all)
--fetch-ghsa [ECOS] Fetch GHSA feeds (single clone); optional comma list (default: all)
--only-package-json Scan only package.json files (skip lockfiles)
--only-lockfiles Scan only lockfiles (skip package.json files)
--lockfile-types TYPES Comma-separated list of lockfile types to scan
(npm, yarn, pnpm, bun, deno, rust, go, python, ruby, php,
maven, nuget, dart, hex, swift, actions). "actions" scans
GitHub Actions workflow files (.github/workflows/*.yml).
Example: --lockfile-types yarn,npm
--ecosystems ECOS Comma-separated ecosystems to load default feeds for,
overriding auto-detection. Accepts lockfile-type aliases
(npm, yarn, pnpm, bun, deno, rust, go, python, ruby, php,
maven, nuget, dart, hex, swift, actions) or purl types
(npm, pypi, golang, cargo, githubactions, ...).
Example: --ecosystems npm
EXAMPLES:
# Scan current directory with default sources (recommended)
$0 --default-source
# Scan specific directory
$0 ./my-project --default-source-osv
$0 /absolute/path/to/project --default-source-ghsa-osv
# Use configuration file
$0 --config .package-checker.config.json
# Use custom source
$0 --source https://example.com/vulns.json
# GitHub organization scan
$0 --github-org myorg --github-token ghp_xxxx --default-source-ghsa-osv
# Check specific package
$0 --package-name express --package-version 4.17.1
# Fetch vulnerability feeds (all ecosystems)
$0 --fetch-all data
# Fetch feeds for specific ecosystems only
$0 --fetch-osv pypi,golang
$0 --fetch-ghsa cargo
# Scan only lockfiles in specific directory
$0 ./subfolder --only-lockfiles --lockfile-types yarn,npm
For configuration file format, use: $0 --help format
EOF
exit 0
}
# Show configuration format help
show_format_help() {
cat << 'EOF'
CONFIGURATION FILE FORMAT (.package-checker.config.json):
{
"sources": [
{
"source": "https://example.com/vulns.json",
"format": "json",
"name": "My Vulnerability List"
},
{
"source": "https://example.com/vulns.csv",
"format": "csv",
"columns": "name,versions",
"name": "CSV Vulnerabilities"
}
],
"github": {
"org": "my-organization",
"repo": "owner/repo",
"token": "ghp_xxxx",
"output": "./packages"
},
"options": {
"ignore_paths": ["node_modules", ".yarn", ".git"],
"dependency_types": ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]
}
}
DATA FORMATS:
JSON format (object with package names as keys):
{
"package-name": {
"versions": ["1.0.0", "2.0.0"]
}
}
CSV format (default: package,version):
package-name,1.0.0
package-name,2.0.0
another-package,3.0.0
CSV format with custom columns:
name,versions,sources
express,4.16.0,"datadog, helixguard"
lodash,4.17.19,"koi, reversinglabs"
Use --csv-columns to specify which columns to use:
--csv-columns "1,2" # Use columns 1 and 2 (name, versions)
--csv-columns "name,versions" # Use column names
EOF
exit 0
}
# GitHub raw base URL for AI docs
GITHUB_RAW_BASE="https://raw.githubusercontent.com/maxgfr/package-checker.sh/refs/heads/main"
# Resolve an AI doc file: try local paths first, then fetch from GitHub
# Usage: resolve_ai_doc <relative-path>
# Output: file content to stdout
resolve_ai_doc() {
local file_path="$1"
local script_dir=""
# Try to find the script's own directory
if [ -n "${BASH_SOURCE[0]}" ]; then
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
fi
# 1. Local relative to script location
if [ -n "$script_dir" ] && [ -f "$script_dir/$file_path" ]; then
cat "$script_dir/$file_path"
return 0
fi
# 2. Local relative to cwd
if [ -f "./$file_path" ]; then
cat "./$file_path"
return 0
fi
# 3. Homebrew prefix
local brew_prefix=""
if command -v brew &> /dev/null; then
brew_prefix="$(brew --prefix 2>/dev/null)/share/package-checker"
if [ -f "$brew_prefix/$file_path" ]; then
cat "$brew_prefix/$file_path"
return 0
fi
fi
# 4. Docker path
if [ -f "/app/$file_path" ]; then
cat "/app/$file_path"
return 0
fi
# 5. Fetch from GitHub
local url="${GITHUB_RAW_BASE}/${file_path}"
local content
content=$(curl -fsSL "$url" 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$content" ]; then
echo "$content"
return 0
fi
return 1
}
# Show AI help menu or subcommand
show_ai_help() {
local subcommand="${1:-}"
case "$subcommand" in
prompt)
echo -e "${BLUE}package-checker.sh — AI System Prompt${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""
echo -e "${YELLOW}Source: ${GITHUB_RAW_BASE}/prompt.md${NC}"
echo ""
local content
content=$(resolve_ai_doc "prompt.md")
if [ $? -eq 0 ]; then
echo "$content"
else
echo -e "${RED}❌ Error: Could not load prompt.md${NC}"
echo ""
echo "Try one of:"
echo " - Clone the repo and run locally"
echo " - curl -fsSL ${GITHUB_RAW_BASE}/prompt.md"
fi
;;
doc)
echo -e "${BLUE}package-checker.sh — AI Guide (Full Reference)${NC}"
echo -e "${BLUE}================================================${NC}"
echo ""
echo -e "${YELLOW}Source: ${GITHUB_RAW_BASE}/docs/ai-guide.md${NC}"
echo ""
local content
content=$(resolve_ai_doc "docs/ai-guide.md")
if [ $? -eq 0 ]; then
echo "$content"
else
echo -e "${RED}❌ Error: Could not load docs/ai-guide.md${NC}"
echo ""
echo "Try one of:"
echo " - Clone the repo and run locally"
echo " - curl -fsSL ${GITHUB_RAW_BASE}/docs/ai-guide.md"
fi
;;
*)
cat << EOF
AI-Assisted Usage for package-checker.sh
=========================================
Use these commands to get AI-ready documentation:
$(basename "$0") --help-ai prompt Output the system prompt (prompt.md)
Paste this into any AI assistant as context.
$(basename "$0") --help-ai doc Output the full AI guide (docs/ai-guide.md)
Complete schemas, validation rules, and recipes.
One-liner to inject into an AI conversation:
$(basename "$0") --help-ai prompt | pbcopy # macOS: copy to clipboard
$(basename "$0") --help-ai prompt | xclip # Linux: copy to clipboard
$(basename "$0") --help-ai prompt > context.md # Save to file and attach
GitHub URLs (always up-to-date):
Prompt: ${GITHUB_RAW_BASE}/prompt.md
Guide: ${GITHUB_RAW_BASE}/docs/ai-guide.md
EOF
;;
esac
exit 0
}
# Check that curl is installed
check_dependencies() {
if ! command -v curl &> /dev/null; then
echo "❌ Error: 'curl' must be installed to run this script"
exit 1
fi
}
# GitHub API functions
GITHUB_TOKEN="${GITHUB_TOKEN:-}"
GITHUB_ORG="${GITHUB_ORG:-}"
GITHUB_REPO="${GITHUB_REPO:-}"
GITHUB_OUTPUT_DIR="${GITHUB_OUTPUT_DIR:-./packages}"
GITHUB_ONLY=false
GITHUB_RATE_LIMIT_DELAY=2
CREATE_GITHUB_ISSUE=false
CREATE_SINGLE_ISSUE=false
# Make a GitHub API request with automatic retry on rate limit
github_request() {
local url="$1"
local max_retries=3
local retry_delay=60
local attempt=1
while [ $attempt -le $max_retries ]; do
local response
local http_code
response=$(curl -sS -w "\n%{http_code}" \
${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \
-H "Accept: application/vnd.github.v3+json" \
-H "User-Agent: package-checker-script" \
"$url")
http_code=$(echo "$response" | tail -n1)
response=$(echo "$response" | sed '$d')
if [ "$http_code" = "200" ]; then
echo "$response"
return 0
fi
# Handle rate limiting (403 or 429)
if [ "$http_code" = "403" ] || [ "$http_code" = "429" ]; then
if [ $attempt -lt $max_retries ]; then
# Check for Retry-After header or rate limit reset time
local wait_time=$retry_delay
if echo "$response" | grep -q "rate limit"; then
echo -e "${YELLOW}⚠️ Rate limit hit, waiting ${wait_time}s before retry ($attempt/$max_retries)...${NC}" >&2
sleep $wait_time
attempt=$((attempt + 1))
continue
fi
fi
fi
# Non-retryable error or max retries reached
echo -e "${RED}❌ GitHub API error ($http_code): $response${NC}" >&2
return 1
done
return 1
}
# Get all repositories from a GitHub organization
# OPTIMIZED: Returns newline-separated list of "name|full_name" instead of JSON
get_github_repositories() {
echo -e "${BLUE}🔍 Fetching repositories for organization: $GITHUB_ORG${NC}" >&2
local all_repos=""
local page=1
local per_page=100
while true; do
local url="https://api.github.com/orgs/${GITHUB_ORG}/repos?page=${page}&per_page=${per_page}"
local repos
repos=$(github_request "$url") || return 1
# FIXED: Use grep -o | wc -l to count occurrences correctly (grep -c counts lines, not occurrences)
local count=$(echo "$repos" | grep -o '"full_name"' | wc -l | tr -d ' ')
if [ "$count" -eq 0 ]; then
break
fi
# OPTIMIZED: Extract name and full_name pairs using grep/sed
# Format: name|full_name (one per line)
local repo_pairs
repo_pairs=$(echo "$repos" | tr '\n' ' ' | grep -oE '"name"[[:space:]]*:[[:space:]]*"[^"]*"[^}]*"full_name"[[:space:]]*:[[:space:]]*"[^"]*"' | \
sed 's/"name"[[:space:]]*:[[:space:]]*"//;s/"[^}]*"full_name"[[:space:]]*:[[:space:]]*"/|/;s/"$//')
if [ -z "$all_repos" ]; then
all_repos="$repo_pairs"
else
all_repos="$all_repos"$'\n'"$repo_pairs"
fi
echo " Found $count repositories on page $page" >&2
if [ "$count" -lt "$per_page" ]; then
break
fi
page=$((page + 1))
sleep "$GITHUB_RATE_LIMIT_DELAY"
done
local total=$(echo "$all_repos" | wc -l | tr -d ' ')
echo -e "${GREEN}✅ Total repositories found: $total${NC}" >&2
echo "" >&2
echo "$all_repos"
}
# Search for package.json and lockfiles in a repository using tree API (works without token for public repos)
search_package_json_in_repo_tree() {
local repo_full_name="$1"
local repo_name="$2"
echo -e " ${BLUE}Fetching repository tree...${NC}"
# Get the default branch first
local repo_info
repo_info=$(github_request "https://api.github.com/repos/${repo_full_name}") || return 1
local default_branch=$(json_get_value "$repo_info" "default_branch")
# Get the full tree recursively
local tree_url="https://api.github.com/repos/${repo_full_name}/git/trees/${default_branch}?recursive=1"
local tree_response
tree_response=$(github_request "$tree_url") || return 1
# OPTIMIZED: Use grep/sed to extract paths directly instead of slow JSON parsing
# Extract all "path" values from the tree response and filter for target files
# This is MUCH faster than iterating with json_array_get for large trees
# Build the filename match regex from the ecosystem registry (+ package.json)
local scan_regex="" _name
for _name in $(ecosystem_scan_filenames); do
scan_regex="${scan_regex:+$scan_regex|}${_name//./\\.}"
done
local target_files
target_files=$(echo "$tree_response" | \
grep -oE '"path"[[:space:]]*:[[:space:]]*"[^"]*"' | \
sed 's/"path"[[:space:]]*:[[:space:]]*"//;s/"$//' | \
grep -v 'node_modules' | \
grep -E "(${scan_regex})\$")
if [ -z "$target_files" ]; then
echo " ✗ No package.json or lockfiles found"
return 0
fi
# Count files by type
local pkg_count=$(echo "$target_files" | grep -c "package.json" || echo "0")
local lock_count=$(echo "$target_files" | grep -v "package.json" | grep -c "." || echo "0")
echo " Found $pkg_count package.json file(s) and $lock_count lockfile(s)"
# Create repo directory
local repo_dir="${GITHUB_OUTPUT_DIR}/${repo_name}"
mkdir -p "$repo_dir"
# Fetch each file
while IFS= read -r file_path; do
[ -z "$file_path" ] && continue
local raw_url="https://raw.githubusercontent.com/${repo_full_name}/${default_branch}/${file_path}"
local file_content
file_content=$(curl -sS \
${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \
-H "User-Agent: package-checker-script" \
"$raw_url")
# Save the file
local full_path="${repo_dir}/${file_path}"
local dir=$(dirname "$full_path")
mkdir -p "$dir"
echo "$file_content" > "$full_path"
local file_name=$(basename "$file_path")
if [ "$file_name" = "package.json" ]; then
echo -e " ${GREEN}✓ Saved: ${repo_name}/${file_path}${NC}"
else
echo -e " ${BLUE}✓ Saved: ${repo_name}/${file_path}${NC}"
fi
done <<< "$target_files"
}
# Search for package.json and lockfiles in a repository using Search API (requires token)
search_package_json_in_repo() {
local repo_full_name="$1"
local repo_name="$2"
echo -e " ${BLUE}Searching for package.json and lockfiles...${NC}"
# Search for multiple file types (derived from the ecosystem registry)
local all_files=""
local search_terms=() _term
for _term in $(ecosystem_scan_filenames); do
search_terms+=("$_term")
done
for term in "${search_terms[@]}"; do
local search_url="https://api.github.com/search/code?q=filename:${term}+repo:${repo_full_name}"
local search_results
search_results=$(github_request "$search_url") 2>/dev/null || continue
# OPTIMIZED: Extract path and url pairs using grep/sed instead of slow JSON parsing
# Format: path|url (one per line)
local file_pairs
file_pairs=$(echo "$search_results" | tr '\n' ' ' | \
grep -oE '"path"[[:space:]]*:[[:space:]]*"[^"]*"[^}]*"url"[[:space:]]*:[[:space:]]*"[^"]*"' | \
sed 's/"path"[[:space:]]*:[[:space:]]*"//;s/"[^}]*"url"[[:space:]]*:[[:space:]]*"/|/;s/"$//')
if [ -n "$file_pairs" ]; then
if [ -z "$all_files" ]; then
all_files="$file_pairs"
else
all_files="$all_files"$'\n'"$file_pairs"
fi
fi
sleep 1 # Rate limiting between searches
done
if [ -z "$all_files" ]; then
echo " ✗ No package.json or lockfiles found"
return 0
fi
# Remove duplicates and count
all_files=$(echo "$all_files" | sort -u)
local count=$(echo "$all_files" | wc -l | tr -d ' ')
echo " Found $count file(s)"
# Create repo directory
local repo_dir="${GITHUB_OUTPUT_DIR}/${repo_name}"
mkdir -p "$repo_dir"
# Fetch each file
while IFS='|' read -r file_path file_url; do
[ -z "$file_path" ] && continue
# Get file content
local content_response
content_response=$(github_request "$file_url") || continue
local download_url=$(json_get_value "$content_response" "download_url")
if [ -n "$download_url" ] && [ "$download_url" != "null" ]; then
local file_content
file_content=$(curl -sS \
${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \
-H "User-Agent: package-checker-script" \
"$download_url")
# Save the file
local full_path="${repo_dir}/${file_path}"
local dir=$(dirname "$full_path")
mkdir -p "$dir"
echo "$file_content" > "$full_path"
local file_name=$(basename "$file_path")
if [ "$file_name" = "package.json" ]; then
echo -e " ${GREEN}✓ Saved: ${repo_name}/${file_path}${NC}"
else
echo -e " ${BLUE}✓ Saved: ${repo_name}/${file_path}${NC}"
fi