@openai/codex-security 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -0
- package/_bundled_plugin/scripts/deep_scan_workbench.py +1 -1
- package/_bundled_plugin/scripts/finalize_scan_contract.py +289 -4
- package/_bundled_plugin/scripts/workbench_db.py +5 -2
- package/dist/bulk-scan-discovery.js +10 -11
- package/dist/bulk-scan-discovery.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +10 -6
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -197,6 +197,9 @@ the implied provider. Use `--model gpt-5.6-terra` to switch models and
|
|
|
197
197
|
`--codex KEY=VALUE` for other Codex settings; existing
|
|
198
198
|
`--codex 'model_reasoning_effort="high"'` overrides remain supported.
|
|
199
199
|
|
|
200
|
+
These overrides do not change the scan's approval policy or filesystem
|
|
201
|
+
permissions. See [Local security model](#local-security-model).
|
|
202
|
+
|
|
200
203
|
Scan progress identifies the requested paths and reports actual ranking,
|
|
201
204
|
file-review, validation, and attack-path phases as they become available.
|
|
202
205
|
Completion summarizes findings, severity, coverage, elapsed time, available
|
|
@@ -344,6 +347,30 @@ Progress remains on stderr so JSON output stays machine readable. Network
|
|
|
344
347
|
failures and rate limits remain retryable; definitive authentication and model
|
|
345
348
|
authorization failures stop immediately.
|
|
346
349
|
|
|
350
|
+
## Local security model
|
|
351
|
+
|
|
352
|
+
Codex Security runs with your local operating-system permissions. Scan only
|
|
353
|
+
repositories you trust and either own or are authorized to assess. Your
|
|
354
|
+
repository, Git installation, configured tools, and other scans under the
|
|
355
|
+
same account are not separate security principals.
|
|
356
|
+
|
|
357
|
+
Every scan uses the `codex_security_scan` filesystem profile and
|
|
358
|
+
`approvalPolicy: "never"`. It can read the local filesystem and write to
|
|
359
|
+
workspace roots and the selected scan state directory. Scans do not request
|
|
360
|
+
interactive approval. Setting `approval_policy`, `sandbox_mode`, or permissions
|
|
361
|
+
through `--codex` or SDK `codexOverrides` does not replace these controls or
|
|
362
|
+
make them more restrictive. Independently enforced host and network
|
|
363
|
+
restrictions still apply.
|
|
364
|
+
|
|
365
|
+
Scan and workbench subprocesses can inherit your environment, including
|
|
366
|
+
unrelated API tokens and cloud credentials. Start a scan with only the
|
|
367
|
+
credentials it needs.
|
|
368
|
+
|
|
369
|
+
The scanner must stay within the target and output paths you authorize and
|
|
370
|
+
must not disclose private data beyond the operation you requested. Its results
|
|
371
|
+
must accurately report the scan mode, reviewed files, and exclusions. Consult
|
|
372
|
+
the security policy for the full threat model and private reporting process.
|
|
373
|
+
|
|
347
374
|
## Documentation and security
|
|
348
375
|
|
|
349
376
|
- [CLI quickstart](https://developers.openai.com/codex/security/cli)
|
|
@@ -239,7 +239,7 @@ def deep_scan_path(
|
|
|
239
239
|
resolved.relative_to(scan_dir)
|
|
240
240
|
except (OSError, RuntimeError, ValueError) as exc:
|
|
241
241
|
raise SystemExit(f"{label} must be an existing path inside the scan directory.") from exc
|
|
242
|
-
if resolved != supplied.absolute():
|
|
242
|
+
if os.path.normcase(resolved) != os.path.normcase(supplied.absolute()):
|
|
243
243
|
raise SystemExit(f"{label} must be a canonical non-symlink path.")
|
|
244
244
|
if kind == "file" and not resolved.is_file():
|
|
245
245
|
raise SystemExit(f"{label} must be a regular file.")
|
|
@@ -316,7 +316,7 @@ def _require_scan_directory(scan_dir: Path) -> Path:
|
|
|
316
316
|
resolved = scan_dir.resolve(strict=True)
|
|
317
317
|
except OSError as exc:
|
|
318
318
|
raise ContractError("scan directory: expected an existing non-symlink directory") from exc
|
|
319
|
-
if resolved != scan_dir:
|
|
319
|
+
if os.path.normcase(resolved) != os.path.normcase(scan_dir):
|
|
320
320
|
raise ContractError("scan directory: expected a canonical non-symlink directory")
|
|
321
321
|
return resolved
|
|
322
322
|
|
|
@@ -327,7 +327,10 @@ def _validate_scan_local_output_path(scan_dir: Path, path: Path, relative_path:
|
|
|
327
327
|
resolved_parent.relative_to(scan_dir)
|
|
328
328
|
except (OSError, RuntimeError, ValueError) as exc:
|
|
329
329
|
raise ContractError(f"{relative_path}: expected a path inside the scan directory") from exc
|
|
330
|
-
if
|
|
330
|
+
if (
|
|
331
|
+
os.path.normcase(resolved_parent) != os.path.normcase(path.parent)
|
|
332
|
+
or path.is_symlink()
|
|
333
|
+
):
|
|
331
334
|
raise ContractError(
|
|
332
335
|
f"{relative_path}: expected a non-symlink path inside the scan directory"
|
|
333
336
|
)
|
|
@@ -767,6 +770,267 @@ def _populate_unsealed_finding_identities(
|
|
|
767
770
|
finding["fingerprints"] = fingerprints
|
|
768
771
|
|
|
769
772
|
|
|
773
|
+
def _finding_strength(finding: dict[str, Any]) -> tuple[int, int, int]:
|
|
774
|
+
return (
|
|
775
|
+
("informational", "low", "medium", "high", "critical").index(finding["severity"]["level"]),
|
|
776
|
+
("low", "medium", "high").index(finding["confidence"]["level"]),
|
|
777
|
+
len(finding.get("codeEvidence") or []),
|
|
778
|
+
)
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _recover_unsealed_findings(
|
|
782
|
+
manifest: dict[str, Any],
|
|
783
|
+
findings: dict[str, Any],
|
|
784
|
+
schema_dir: Path,
|
|
785
|
+
scan_dir: Path,
|
|
786
|
+
warnings: list[str],
|
|
787
|
+
) -> list[str]:
|
|
788
|
+
schema = _read_json(schema_dir / "findings.schema.json")
|
|
789
|
+
_require_safe_schema(schema, "findings.schema.json")
|
|
790
|
+
properties = _require_dict(schema, "properties", "findings.schema")
|
|
791
|
+
finding_array = _require_dict(properties, "findings", "findings.schema.properties")
|
|
792
|
+
finding_schema = _require_dict(finding_array, "items", "findings.schema.properties.findings")
|
|
793
|
+
finding_properties = _require_dict(
|
|
794
|
+
finding_schema, "properties", "findings.schema.properties.findings.items"
|
|
795
|
+
)
|
|
796
|
+
writeup_schema = _require_dict(
|
|
797
|
+
finding_properties, "writeup", "findings.schema.properties.findings.items.properties"
|
|
798
|
+
)
|
|
799
|
+
scan = _require_dict(manifest, "scan", "manifest")
|
|
800
|
+
scan_id = _require_str(scan, "id", "manifest.scan")
|
|
801
|
+
if findings.get("scanId") != scan_id:
|
|
802
|
+
raise ContractError("findings.scanId: must match manifest scan id")
|
|
803
|
+
|
|
804
|
+
recovered: list[dict[str, Any]] = []
|
|
805
|
+
discarded: list[str] = []
|
|
806
|
+
finding_positions: dict[str, int] = {}
|
|
807
|
+
writeup_paths: set[str] = set()
|
|
808
|
+
for index, finding in enumerate(_require_list(findings, "findings", "findings")):
|
|
809
|
+
context = f"findings.findings[{index}]"
|
|
810
|
+
try:
|
|
811
|
+
if not isinstance(finding, dict):
|
|
812
|
+
raise ContractError(f"{context}: expected an object")
|
|
813
|
+
identity = _require_dict(finding, "identity", context)
|
|
814
|
+
fields: list[tuple[dict[str, Any], str, str, str]] = [
|
|
815
|
+
(finding, "ruleId", context, "rule identifier"),
|
|
816
|
+
(identity, "anchor", f"{context}.identity", "semantic anchor"),
|
|
817
|
+
]
|
|
818
|
+
if "instance" in identity:
|
|
819
|
+
fields.append((identity, "instance", f"{context}.identity", "instance"))
|
|
820
|
+
normalized_fields = []
|
|
821
|
+
for parent, field, field_context, label in fields:
|
|
822
|
+
value = _require_str(parent, field, field_context)
|
|
823
|
+
if SLUG_RE.fullmatch(value):
|
|
824
|
+
continue
|
|
825
|
+
normalized = re.sub(r"[^a-z0-9._/-]+", "-", value.lower()).strip("._/-")
|
|
826
|
+
if not SLUG_RE.fullmatch(normalized):
|
|
827
|
+
raise ContractError(
|
|
828
|
+
f"{field_context}.{field}: expected a stable lowercase semantic slug"
|
|
829
|
+
)
|
|
830
|
+
parent[field] = normalized
|
|
831
|
+
normalized_fields.append(label)
|
|
832
|
+
|
|
833
|
+
_populate_unsealed_finding_identities(
|
|
834
|
+
manifest,
|
|
835
|
+
{"scanId": scan_id, "findings": [finding]},
|
|
836
|
+
)
|
|
837
|
+
finding_id = finding["findingId"]
|
|
838
|
+
previous_position = finding_positions.get(finding_id)
|
|
839
|
+
_validate_finding(finding, context)
|
|
840
|
+
if "writeup" in finding:
|
|
841
|
+
try:
|
|
842
|
+
_validate_schema_node(finding["writeup"], writeup_schema, f"{context}.writeup")
|
|
843
|
+
report_path = finding["writeup"]["reportPath"]
|
|
844
|
+
previous_writeup = (
|
|
845
|
+
recovered[previous_position].get("writeup")
|
|
846
|
+
if previous_position is not None
|
|
847
|
+
else None
|
|
848
|
+
)
|
|
849
|
+
if report_path in writeup_paths and (
|
|
850
|
+
previous_writeup is None or previous_writeup["reportPath"] != report_path
|
|
851
|
+
):
|
|
852
|
+
raise ContractError(f"{context}.writeup.reportPath: duplicate report path")
|
|
853
|
+
_require_scan_local_file(scan_dir, report_path, f"{context}.writeup.reportPath")
|
|
854
|
+
except ContractError as exc:
|
|
855
|
+
finding.pop("writeup")
|
|
856
|
+
warnings.append(f"Skipped malformed writeup for finding {index + 1}: {exc}.")
|
|
857
|
+
_validate_schema_node(finding, finding_schema, context)
|
|
858
|
+
except ContractError as exc:
|
|
859
|
+
warning = f"Skipped malformed finding {index + 1}: {exc}."
|
|
860
|
+
warnings.append(warning)
|
|
861
|
+
discarded.append(warning)
|
|
862
|
+
continue
|
|
863
|
+
|
|
864
|
+
if previous_position is not None:
|
|
865
|
+
previous = recovered[previous_position]
|
|
866
|
+
if _finding_strength(finding) <= _finding_strength(previous):
|
|
867
|
+
warnings.append(
|
|
868
|
+
f"Skipped malformed finding {index + 1}: duplicate logical finding."
|
|
869
|
+
)
|
|
870
|
+
continue
|
|
871
|
+
previous_writeup = previous.get("writeup")
|
|
872
|
+
if previous_writeup is not None:
|
|
873
|
+
writeup_paths.discard(previous_writeup["reportPath"])
|
|
874
|
+
recovered[previous_position] = finding
|
|
875
|
+
warnings.append(
|
|
876
|
+
f"Recovered finding {index + 1}: retained stronger duplicate logical finding."
|
|
877
|
+
)
|
|
878
|
+
else:
|
|
879
|
+
finding_positions[finding_id] = len(recovered)
|
|
880
|
+
recovered.append(finding)
|
|
881
|
+
|
|
882
|
+
if "writeup" in finding:
|
|
883
|
+
writeup_paths.add(finding["writeup"]["reportPath"])
|
|
884
|
+
if normalized_fields:
|
|
885
|
+
warnings.append(
|
|
886
|
+
f"Recovered finding {index + 1}: normalized {', '.join(normalized_fields)}."
|
|
887
|
+
)
|
|
888
|
+
|
|
889
|
+
findings["findings"] = recovered
|
|
890
|
+
return discarded
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _recover_unsealed_coverage(
|
|
894
|
+
coverage: dict[str, Any],
|
|
895
|
+
schema_dir: Path,
|
|
896
|
+
scan_dir: Path,
|
|
897
|
+
warnings: list[str],
|
|
898
|
+
discarded_findings: list[str],
|
|
899
|
+
) -> None:
|
|
900
|
+
schema = _read_json(schema_dir / "coverage.schema.json")
|
|
901
|
+
_require_safe_schema(schema, "coverage.schema.json")
|
|
902
|
+
properties = _require_dict(schema, "properties", "coverage.schema")
|
|
903
|
+
completeness = coverage.get("completeness")
|
|
904
|
+
partial = completeness not in ("complete", "partial", "unknown")
|
|
905
|
+
if partial:
|
|
906
|
+
warnings.append("Recovered malformed coverage completeness; marked coverage as partial.")
|
|
907
|
+
|
|
908
|
+
surface_ids: set[str] = set()
|
|
909
|
+
for field, label in (
|
|
910
|
+
("surfaces", "coverage surface"),
|
|
911
|
+
("explicitExclusions", "coverage exclusion"),
|
|
912
|
+
("deferred", "deferred coverage item"),
|
|
913
|
+
):
|
|
914
|
+
array_schema = _require_dict(properties, field, "coverage.schema.properties")
|
|
915
|
+
item_schema = _require_dict(array_schema, "items", f"coverage.schema.properties.{field}")
|
|
916
|
+
items = coverage.get(field)
|
|
917
|
+
if not isinstance(items, list):
|
|
918
|
+
warnings.append(f"Skipped malformed {label} records: expected an array.")
|
|
919
|
+
coverage[field] = []
|
|
920
|
+
partial = True
|
|
921
|
+
continue
|
|
922
|
+
|
|
923
|
+
recovered: list[dict[str, Any]] = []
|
|
924
|
+
for index, item in enumerate(items):
|
|
925
|
+
context = f"coverage.{field}[{index}]"
|
|
926
|
+
try:
|
|
927
|
+
if not isinstance(item, dict):
|
|
928
|
+
raise ContractError(f"{context}: expected an object")
|
|
929
|
+
if field == "surfaces":
|
|
930
|
+
surface_id = _require_str(item, "id", context)
|
|
931
|
+
if surface_id in surface_ids:
|
|
932
|
+
raise ContractError(f"{context}.id: duplicate surface id")
|
|
933
|
+
disposition = item.get("disposition")
|
|
934
|
+
surface_recovered = False
|
|
935
|
+
if not isinstance(disposition, str) or disposition not in DISPOSITIONS:
|
|
936
|
+
warnings.append(
|
|
937
|
+
f"Recovered coverage surface {index + 1}: "
|
|
938
|
+
"the review disposition could not be verified."
|
|
939
|
+
)
|
|
940
|
+
item["disposition"] = "needs_follow_up"
|
|
941
|
+
surface_recovered = True
|
|
942
|
+
|
|
943
|
+
receipt_refs = item.get("receiptRefs")
|
|
944
|
+
if not isinstance(receipt_refs, list):
|
|
945
|
+
warnings.append(
|
|
946
|
+
f"Skipped malformed receipt references for coverage surface "
|
|
947
|
+
f"{index + 1}: expected an array."
|
|
948
|
+
)
|
|
949
|
+
receipt_refs = []
|
|
950
|
+
surface_recovered = True
|
|
951
|
+
|
|
952
|
+
recovered_receipts: list[str] = []
|
|
953
|
+
for ref_index, ref in enumerate(receipt_refs):
|
|
954
|
+
ref_context = f"{context}.receiptRefs[{ref_index}]"
|
|
955
|
+
try:
|
|
956
|
+
if not isinstance(ref, str):
|
|
957
|
+
raise ContractError(f"{ref_context}: expected a string")
|
|
958
|
+
normalized_ref = _require_safe_relative_path(ref, ref_context)
|
|
959
|
+
if not normalized_ref.startswith("artifacts/"):
|
|
960
|
+
raise ContractError(
|
|
961
|
+
f"{ref_context}: expected a file under artifacts/"
|
|
962
|
+
)
|
|
963
|
+
_require_scan_local_file(scan_dir, normalized_ref, ref_context)
|
|
964
|
+
except ContractError as exc:
|
|
965
|
+
warnings.append(
|
|
966
|
+
f"Skipped malformed coverage receipt "
|
|
967
|
+
f"{index + 1}.{ref_index + 1}: {exc}."
|
|
968
|
+
)
|
|
969
|
+
surface_recovered = True
|
|
970
|
+
continue
|
|
971
|
+
recovered_receipts.append(normalized_ref)
|
|
972
|
+
|
|
973
|
+
item["receiptRefs"] = recovered_receipts
|
|
974
|
+
if surface_recovered or item["disposition"] == "needs_follow_up":
|
|
975
|
+
if not surface_recovered and completeness != "partial":
|
|
976
|
+
warnings.append(
|
|
977
|
+
f"Coverage surface {index + 1} requires follow-up; "
|
|
978
|
+
"marked coverage as partial."
|
|
979
|
+
)
|
|
980
|
+
item["disposition"] = "needs_follow_up"
|
|
981
|
+
partial = True
|
|
982
|
+
|
|
983
|
+
_validate_schema_node(item, item_schema, context)
|
|
984
|
+
except ContractError as exc:
|
|
985
|
+
warnings.append(f"Skipped malformed {label} {index + 1}: {exc}.")
|
|
986
|
+
partial = True
|
|
987
|
+
continue
|
|
988
|
+
|
|
989
|
+
if field == "surfaces":
|
|
990
|
+
surface_ids.add(surface_id)
|
|
991
|
+
recovered.append(item)
|
|
992
|
+
|
|
993
|
+
coverage[field] = recovered
|
|
994
|
+
|
|
995
|
+
if discarded_findings:
|
|
996
|
+
for surface in coverage["surfaces"]:
|
|
997
|
+
surface["disposition"] = "needs_follow_up"
|
|
998
|
+
coverage["deferred"].extend(
|
|
999
|
+
{"id": f"discarded-finding-{index}", "reason": warning}
|
|
1000
|
+
for index, warning in enumerate(discarded_findings, 1)
|
|
1001
|
+
)
|
|
1002
|
+
partial = True
|
|
1003
|
+
|
|
1004
|
+
if coverage["deferred"] and completeness != "partial":
|
|
1005
|
+
if not discarded_findings:
|
|
1006
|
+
warnings.append("Coverage has deferred review work; marked coverage as partial.")
|
|
1007
|
+
partial = True
|
|
1008
|
+
if partial:
|
|
1009
|
+
coverage["completeness"] = "partial"
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def _recover_unsealed_hardening(
|
|
1013
|
+
manifest: dict[str, Any],
|
|
1014
|
+
scan_dir: Path,
|
|
1015
|
+
warnings: list[str],
|
|
1016
|
+
) -> None:
|
|
1017
|
+
scan = _require_dict(manifest, "scan", "manifest")
|
|
1018
|
+
if "hardening" not in scan:
|
|
1019
|
+
return
|
|
1020
|
+
|
|
1021
|
+
try:
|
|
1022
|
+
hardening = _require_dict(scan, "hardening", "manifest.scan")
|
|
1023
|
+
portfolio_path = _require_str(hardening, "portfolioPath", "manifest.scan.hardening")
|
|
1024
|
+
if portfolio_path != "hardening/hardening.md":
|
|
1025
|
+
raise ContractError(
|
|
1026
|
+
"manifest.scan.hardening.portfolioPath: expected hardening/hardening.md"
|
|
1027
|
+
)
|
|
1028
|
+
_require_hardening_portfolio_file(scan_dir, scan)
|
|
1029
|
+
except ContractError as exc:
|
|
1030
|
+
scan.pop("hardening")
|
|
1031
|
+
warnings.append(f"Skipped malformed hardening portfolio: {exc}.")
|
|
1032
|
+
|
|
1033
|
+
|
|
770
1034
|
def _validate_derived_finding_identities(
|
|
771
1035
|
manifest: dict[str, Any],
|
|
772
1036
|
findings: dict[str, Any],
|
|
@@ -1792,8 +2056,21 @@ def build_sarif_projection(
|
|
|
1792
2056
|
source_root_is_directory = False
|
|
1793
2057
|
if not source_root_is_directory:
|
|
1794
2058
|
raise ContractError("source root: expected an existing directory")
|
|
1795
|
-
manifest, findings,
|
|
2059
|
+
manifest, findings, coverage, _ = _read_sealed_scan(scan_dir, schema_dir, "SARIF projection")
|
|
1796
2060
|
sarif = build_sarif(manifest, findings, source_root)
|
|
2061
|
+
if coverage["completeness"] != "complete":
|
|
2062
|
+
run = sarif["runs"][0]
|
|
2063
|
+
run["properties"]["codexSecurityCoverageCompleteness"] = coverage["completeness"]
|
|
2064
|
+
if coverage["deferred"]:
|
|
2065
|
+
run["invocations"] = [
|
|
2066
|
+
{
|
|
2067
|
+
"executionSuccessful": True,
|
|
2068
|
+
"toolExecutionNotifications": [
|
|
2069
|
+
{"level": "warning", "message": {"text": item["reason"]}}
|
|
2070
|
+
for item in coverage["deferred"]
|
|
2071
|
+
],
|
|
2072
|
+
}
|
|
2073
|
+
]
|
|
1797
2074
|
_validate_sarif(sarif)
|
|
1798
2075
|
return sarif
|
|
1799
2076
|
|
|
@@ -2009,6 +2286,7 @@ def _prepare_scan_finalization(
|
|
|
2009
2286
|
*,
|
|
2010
2287
|
expected_coverage_mode: str | None = None,
|
|
2011
2288
|
completion_binding: dict[str, Any] | None = None,
|
|
2289
|
+
completion_warnings: list[str] | None = None,
|
|
2012
2290
|
) -> PreparedScanFinalization:
|
|
2013
2291
|
"""Read, populate, and validate a scan without writing any output files."""
|
|
2014
2292
|
|
|
@@ -2061,8 +2339,15 @@ def _prepare_scan_finalization(
|
|
|
2061
2339
|
_validate_completion_binding(manifest, findings, coverage, completion_binding)
|
|
2062
2340
|
if was_sealed:
|
|
2063
2341
|
_validate_findings(manifest, findings)
|
|
2064
|
-
if was_sealed:
|
|
2065
2342
|
_validate_derived_finding_identities(manifest, findings)
|
|
2343
|
+
elif completion_warnings is not None:
|
|
2344
|
+
discarded_findings = _recover_unsealed_findings(
|
|
2345
|
+
manifest, findings, schema_dir, scan_dir, completion_warnings
|
|
2346
|
+
)
|
|
2347
|
+
_recover_unsealed_coverage(
|
|
2348
|
+
coverage, schema_dir, scan_dir, completion_warnings, discarded_findings
|
|
2349
|
+
)
|
|
2350
|
+
_recover_unsealed_hardening(manifest, scan_dir, completion_warnings)
|
|
2066
2351
|
else:
|
|
2067
2352
|
_populate_unsealed_finding_identities(manifest, findings)
|
|
2068
2353
|
_validate_findings(manifest, findings)
|
|
@@ -1430,6 +1430,7 @@ def complete_scan_locked(
|
|
|
1430
1430
|
scan_dir,
|
|
1431
1431
|
expected_coverage_mode=expected_coverage_mode(scan),
|
|
1432
1432
|
completion_binding=completion_binding,
|
|
1433
|
+
completion_warnings=warnings,
|
|
1433
1434
|
)
|
|
1434
1435
|
warning = scan_target_warning(scan)
|
|
1435
1436
|
if warning is not None and warning not in warnings:
|
|
@@ -3435,7 +3436,7 @@ def artifact_path(scan_dir: Path, file_name: str, *, required: bool) -> Path | N
|
|
|
3435
3436
|
raise SystemExit(
|
|
3436
3437
|
f"{file_name}: expected a regular file inside the scan directory."
|
|
3437
3438
|
) from exc
|
|
3438
|
-
if resolved != candidate or not candidate.is_file():
|
|
3439
|
+
if os.path.normcase(resolved) != os.path.normcase(candidate) or not candidate.is_file():
|
|
3439
3440
|
raise SystemExit(f"{file_name}: expected a regular non-symlink file.")
|
|
3440
3441
|
return resolved
|
|
3441
3442
|
|
|
@@ -3449,7 +3450,9 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:
|
|
|
3449
3450
|
raise SystemExit(
|
|
3450
3451
|
"Scan directory must be an existing canonical non-symlink directory."
|
|
3451
3452
|
) from exc
|
|
3452
|
-
if not stat.S_ISDIR(metadata.st_mode) or resolved !=
|
|
3453
|
+
if not stat.S_ISDIR(metadata.st_mode) or os.path.normcase(resolved) != os.path.normcase(
|
|
3454
|
+
scan_dir
|
|
3455
|
+
):
|
|
3453
3456
|
raise SystemExit("Scan directory must be an existing canonical non-symlink directory.")
|
|
3454
3457
|
return scan_dir
|
|
3455
3458
|
|
|
@@ -95,18 +95,17 @@ export async function runBulkScanWizard(dependencies, signal) {
|
|
|
95
95
|
return { inputPath, outputDir, githubHost };
|
|
96
96
|
}
|
|
97
97
|
async function selectGitHubOwner(github, prompt, signal) {
|
|
98
|
-
const
|
|
99
|
-
per_page: 100,
|
|
100
|
-
request: { signal },
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
98
|
+
const [orgs, user] = await Promise.all([
|
|
99
|
+
github.request("GET /user/orgs", { per_page: 100, request: { signal } }),
|
|
100
|
+
github.request("GET /user", { request: { signal } }),
|
|
101
|
+
]);
|
|
102
|
+
const personal = user.data.login;
|
|
103
|
+
const owners = [personal, ...orgs.data.map(({ login }) => login)].sort();
|
|
104
|
+
if (owners.length > 1) {
|
|
105
|
+
return await prompt.select("Which account or organization should we scan?", owners.map((owner) => ({ label: owner, value: owner })));
|
|
105
106
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
prompt.write(`\nFinding repositories in ${owner}.\n`);
|
|
109
|
-
return owner;
|
|
107
|
+
prompt.write(`\nFinding repositories in ${personal}.\n`);
|
|
108
|
+
return personal;
|
|
110
109
|
}
|
|
111
110
|
async function selectGitHubRepositories(repositories, prompt) {
|
|
112
111
|
const selected = new Set();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,MAAM,QAAQ,GAAG,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAC7C,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;;CAmBjC,CAAC;AAmDF,MAAM,UAAU,mCAAmC,CAAC,OAInD;IACC,OAAO;QACL,MAAM,EAAE,oBAAoB,CAAC,OAAO,CAAC,MAAM,CAAC;QAC5C,GAAG,EAAE,OAAO,CAAC,GAAG;QACh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BACJ,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACpB,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CACxD;iBACA,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;SACzD,EACD,OAAO,EAAE,CACV;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { execFile as execFileCallback } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { promisify } from \"node:util\";\nimport { confirm, input, search } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { resolveTrustedExecutable } from \"./trusted-executable.js\";\n\nconst execFile = promisify(execFileCallback);\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(question: string, defaultValue?: boolean): Promise<boolean>;\n input(question: string, defaultValue?: string): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value }[],\n ): Promise<Value>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: async (host, signal) => {\n const trusted = await resolveTrustedExecutable(\n \"gh\",\n process.env,\n options.currentDirectory(),\n );\n if (trusted === null) {\n throw new Error(\n \"GitHub CLI is required. Install gh and sign in first.\",\n );\n }\n\n let token: string;\n try {\n const { stdout } = await execFile(\n trusted.executable,\n [\"auth\", \"token\", \"--hostname\", host],\n { env: trusted.environment, signal },\n );\n token = stdout.trim();\n } catch {\n signal?.throwIfAborted();\n throw new Error(\n \"GitHub sign-in is required. Run 'gh auth login' first.\",\n );\n }\n return new Octokit({\n auth: token,\n ...(host === \"github.com\" ? {} : { baseUrl: `https://${host}/api/v3` }),\n });\n },\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(discovered, prompt);\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n await prompt.input(\n \"Where should scan results be saved?\",\n \"./security-scans\",\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\"))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const { data } = await github.request(\"GET /user/orgs\", {\n per_page: 100,\n request: { signal },\n });\n const organizations = data.map(({ login }) => login).sort();\n if (organizations.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n organizations.map((owner) => ({ label: owner, value: owner })),\n );\n }\n const owner =\n organizations[0] ??\n (await github.request(\"GET /user\", { request: { signal } })).data.login;\n prompt.write(`\\nFinding repositories in ${owner}.\\n`);\n return owner;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n const hash = createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16);\n return `${id.slice(0, 111)}-${hash}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nfunction createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = () => ({\n input: stdin,\n output: new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n }),\n });\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false) =>\n confirm({ message, default: defaultValue }, context()),\n input: (message, defaultValue) =>\n input({ message, default: defaultValue }, context()),\n select: (message, options) =>\n search(\n {\n message,\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value }) => ({ name: label, value })),\n },\n context(),\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bulk-scan-discovery.js","sourceRoot":"","sources":["../src/bulk-scan-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,OAAO,E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C,CAAC;QACtB,CAAC;QACD,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,GAAG,KAAK,EAAE,EAAE,CACzC,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACxD,KAAK,EAAE,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,CAC/B,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,CAAC;QACtD,MAAM,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,CAC3B,MAAM,CACJ;YACE,OAAO;YACP,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CACf,OAAO;iBACJ,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACpB,KAAK,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CACxD;iBACA,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;SACzD,EACD,OAAO,EAAE,CACV;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import { execFile as execFileCallback } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { lstat, mkdir, writeFile } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { stdin } from \"node:process\";\nimport { Writable } from \"node:stream\";\nimport { promisify } from \"node:util\";\nimport { confirm, input, search } from \"@inquirer/prompts\";\nimport { Octokit } from \"@octokit/core\";\nimport Papa from \"papaparse\";\nimport { resolveTrustedExecutable } from \"./trusted-executable.js\";\n\nconst execFile = promisify(execFileCallback);\nconst GITHUB_REPOSITORIES_QUERY = `\n query($owner: String!, $cursor: String) {\n repositoryOwner(login: $owner) {\n repositories(\n first: 100\n after: $cursor\n isArchived: false\n isFork: false\n orderBy: { field: PUSHED_AT, direction: DESC }\n ) {\n nodes {\n nameWithOwner\n pushedAt\n defaultBranchRef { target { oid } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }\n }\n`;\n\ninterface GitHubRepository {\n fullName: string;\n url: string;\n revision: string;\n}\n\ninterface GitHubRepositoriesResponse {\n repositoryOwner: {\n repositories: {\n nodes: Array<{\n nameWithOwner: string;\n pushedAt: string;\n defaultBranchRef: { target: { oid: string } } | null;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n}\n\nexport interface BulkScanPrompt {\n isInteractive(): boolean;\n write(value: string): void;\n confirm(question: string, defaultValue?: boolean): Promise<boolean>;\n input(question: string, defaultValue?: string): Promise<string>;\n select<Value extends string>(\n question: string,\n options: readonly { label: string; value: Value }[],\n ): Promise<Value>;\n}\n\nexport interface BulkScanDiscoveryDependencies {\n prompt: BulkScanPrompt;\n now(): number;\n currentDirectory(): string;\n githubHost?: string;\n createGitHub(host: string, signal?: AbortSignal): Promise<Octokit>;\n}\n\nexport interface BulkScanWizardResult {\n inputPath: string;\n outputDir: string;\n githubHost: string;\n}\n\ninterface PromptOutput {\n write(value: string): unknown;\n readonly isTTY?: boolean;\n}\n\nexport function createBulkScanDiscoveryDependencies(options: {\n output: PromptOutput;\n now(): number;\n currentDirectory(): string;\n}): BulkScanDiscoveryDependencies {\n return {\n prompt: createTerminalPrompt(options.output),\n now: options.now,\n currentDirectory: options.currentDirectory,\n ...(process.env[\"GH_HOST\"]?.trim()\n ? { githubHost: process.env[\"GH_HOST\"].trim() }\n : {}),\n createGitHub: async (host, signal) => {\n const trusted = await resolveTrustedExecutable(\n \"gh\",\n process.env,\n options.currentDirectory(),\n );\n if (trusted === null) {\n throw new Error(\n \"GitHub CLI is required. Install gh and sign in first.\",\n );\n }\n\n let token: string;\n try {\n const { stdout } = await execFile(\n trusted.executable,\n [\"auth\", \"token\", \"--hostname\", host],\n { env: trusted.environment, signal },\n );\n token = stdout.trim();\n } catch {\n signal?.throwIfAborted();\n throw new Error(\n \"GitHub sign-in is required. Run 'gh auth login' first.\",\n );\n }\n return new Octokit({\n auth: token,\n ...(host === \"github.com\" ? {} : { baseUrl: `https://${host}/api/v3` }),\n });\n },\n };\n}\n\nexport async function runBulkScanWizard(\n dependencies: BulkScanDiscoveryDependencies,\n signal?: AbortSignal,\n): Promise<BulkScanWizardResult | null> {\n const { prompt } = dependencies;\n if (!prompt.isInteractive()) {\n throw new Error(\n \"Interactive repository selection requires a terminal. Provide a CSV with 'codex-security bulk-scan repositories.csv --output-dir ./security-scans'.\",\n );\n }\n signal?.throwIfAborted();\n\n const githubHost = dependencies.githubHost ?? \"github.com\";\n const github = await dependencies.createGitHub(githubHost, signal);\n const owner = await selectGitHubOwner(github, prompt, signal);\n prompt.write(\"\\nFinding active repositories...\\n\");\n const discovered = await discoverGitHubRepositories(\n github,\n githubHost,\n owner,\n dependencies.now() - 90 * 86_400_000,\n signal,\n );\n if (discovered.length === 0) {\n prompt.write(\"\\nNo repositories matched your selection.\\n\");\n return null;\n }\n\n prompt.write(`\\nFound ${discovered.length} repositories.\\n`);\n const repositories = await selectGitHubRepositories(discovered, prompt);\n\n const outputDir = resolve(\n dependencies.currentDirectory(),\n await prompt.input(\n \"Where should scan results be saved?\",\n \"./security-scans\",\n ),\n );\n const inputPath = join(outputDir, \"repositories.csv\");\n await validateWizardOutput(outputDir);\n prompt.write(\n `\\nReady to scan ${repositories.length} repositories?\\n` +\n `Results: ${outputDir}\\nRepository list: ${inputPath}\\n`,\n );\n if (!(await prompt.confirm(\"Start scanning?\"))) {\n prompt.write(\"\\nScan canceled.\\n\");\n return null;\n }\n signal?.throwIfAborted();\n\n await mkdir(outputDir, { recursive: true, mode: 0o700 });\n await writeFile(\n inputPath,\n `${Papa.unparse(\n repositories.map(({ fullName, url, revision }) => ({\n id: repositoryId(fullName),\n repository: url,\n revision,\n })),\n )}\\n`,\n { flag: \"wx\", mode: 0o600, ...(signal === undefined ? {} : { signal }) },\n );\n return { inputPath, outputDir, githubHost };\n}\n\nasync function selectGitHubOwner(\n github: Octokit,\n prompt: BulkScanPrompt,\n signal?: AbortSignal,\n): Promise<string> {\n const [orgs, user] = await Promise.all([\n github.request(\"GET /user/orgs\", { per_page: 100, request: { signal } }),\n github.request(\"GET /user\", { request: { signal } }),\n ]);\n const personal = user.data.login;\n const owners = [personal, ...orgs.data.map(({ login }) => login)].sort();\n if (owners.length > 1) {\n return await prompt.select(\n \"Which account or organization should we scan?\",\n owners.map((owner) => ({ label: owner, value: owner })),\n );\n }\n prompt.write(`\\nFinding repositories in ${personal}.\\n`);\n return personal;\n}\n\nasync function selectGitHubRepositories(\n repositories: GitHubRepository[],\n prompt: BulkScanPrompt,\n): Promise<GitHubRepository[]> {\n const selected = new Set<string>();\n while (selected.size < repositories.length) {\n const choice = await prompt.select(\n \"Select repositories to scan (type to filter)\",\n [\n {\n label: selected.size\n ? `Done (${selected.size} selected)`\n : `All ${repositories.length} repositories`,\n value: \"\",\n },\n ...repositories\n .filter(({ fullName }) => !selected.has(fullName))\n .map(({ fullName }) => ({ label: fullName, value: fullName })),\n ],\n );\n if (!choice) break;\n selected.add(choice);\n }\n return selected.size\n ? repositories.filter(({ fullName }) => selected.has(fullName))\n : repositories;\n}\n\nasync function discoverGitHubRepositories(\n github: Octokit,\n host: string,\n owner: string,\n cutoff: number,\n signal?: AbortSignal,\n): Promise<GitHubRepository[]> {\n const repositories: GitHubRepository[] = [];\n let cursor: string | null = null;\n\n do {\n signal?.throwIfAborted();\n const result: GitHubRepositoriesResponse = await github.graphql(\n GITHUB_REPOSITORIES_QUERY,\n { owner, cursor, request: { signal } },\n );\n const connection = result.repositoryOwner?.repositories;\n if (connection === undefined) {\n throw new Error(\"GitHub could not list repositories for this account.\");\n }\n\n for (const repository of connection.nodes) {\n if (Date.parse(repository.pushedAt) < cutoff) return repositories;\n if (repository.defaultBranchRef === null) continue;\n repositories.push({\n fullName: repository.nameWithOwner,\n url: `https://${host}/${repository.nameWithOwner}.git`,\n revision: repository.defaultBranchRef.target.oid.toLowerCase(),\n });\n }\n cursor = connection.pageInfo.hasNextPage\n ? connection.pageInfo.endCursor\n : null;\n } while (cursor !== null);\n\n return repositories;\n}\n\nfunction repositoryId(fullName: string): string {\n const id = fullName.replace(\"/\", \"--\");\n if (id.length <= 128) return id;\n const hash = createHash(\"sha256\").update(fullName).digest(\"hex\").slice(0, 16);\n return `${id.slice(0, 111)}-${hash}`;\n}\n\nasync function validateWizardOutput(outputDir: string): Promise<void> {\n let metadata;\n try {\n metadata = await lstat(outputDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw error;\n }\n if (!metadata.isDirectory()) {\n throw new Error(\"The scan output must be a real directory.\");\n }\n\n for (const name of [\"repositories.csv\", \"manifest.json\"]) {\n try {\n await lstat(join(outputDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw error;\n }\n throw new Error(\n \"The selected output directory already contains a repository list or scan. Choose a new directory or resume the existing scan.\",\n );\n }\n}\n\nfunction createTerminalPrompt(output: PromptOutput): BulkScanPrompt {\n const context = () => ({\n input: stdin,\n output: new Writable({\n write(chunk: Buffer, _encoding, callback) {\n output.write(chunk.toString(\"utf8\"));\n callback();\n },\n }),\n });\n\n return {\n isInteractive: () => stdin.isTTY === true && output.isTTY === true,\n write: (value) => {\n output.write(value);\n },\n confirm: (message, defaultValue = false) =>\n confirm({ message, default: defaultValue }, context()),\n input: (message, defaultValue) =>\n input({ message, default: defaultValue }, context()),\n select: (message, options) =>\n search(\n {\n message,\n source: (term) =>\n options\n .filter(({ label }) =>\n label.toLowerCase().includes(term?.toLowerCase() ?? \"\"),\n )\n .map(({ label, value }) => ({ name: label, value })),\n },\n context(),\n ),\n };\n}\n"]}
|
package/dist/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AA2BA,O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AM,GACb,MAAM,CAyBR;AA+lBD,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,KAAK,CAAC,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,oBAAoB,GAC5B,UAAU,CAgEZ;AAwBD,qBAAa,QAAQ;;gBAajB,MAAM,GAAE,QAAyB,EACjC,YAAY,GAAE,IAAI,CAChB,eAAe,EACf,KAAK,GAAG,aAAa,GAAG,eAAe,CACjB,EACxB,WAAW,UAAO;IAQpB,IAAW,WAAW,IAAI,OAAO,CAEhC;IAED,IAAW,cAAc,IAAI,MAAM,CAKlC;IAEM,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAI5B,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAcjC,SAAS,IAAI,IAAI;CA4BzB"}
|
package/dist/cli.js
CHANGED
|
@@ -1077,9 +1077,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1077
1077
|
errorOutput.write("To use a ChatGPT sign-in, unset OPENAI_API_KEY and CODEX_API_KEY.\n");
|
|
1078
1078
|
}
|
|
1079
1079
|
}
|
|
1080
|
-
else if (exitCode === 0 &&
|
|
1081
|
-
!options.withApiKey &&
|
|
1082
|
-
!options.withAccessToken) {
|
|
1080
|
+
else if (exitCode === 0 && !options.withApiKey) {
|
|
1083
1081
|
const authentication = scanAuthentication(dependencies.environment);
|
|
1084
1082
|
if (authentication.method === "api_key") {
|
|
1085
1083
|
const configuredApiKeyVariables = Object.entries(dependencies.environment)
|
|
@@ -1087,9 +1085,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1087
1085
|
(name.toUpperCase() === "OPENAI_API_KEY" ||
|
|
1088
1086
|
name.toUpperCase() === "CODEX_API_KEY"))
|
|
1089
1087
|
.map(([name]) => name);
|
|
1090
|
-
|
|
1091
|
-
`noninteractive scans will use ${authentication.source}.\n`
|
|
1092
|
-
"
|
|
1088
|
+
const loginWarning = options.withAccessToken
|
|
1089
|
+
? `Access-token login succeeded, but noninteractive scans will use ${authentication.source}.\n`
|
|
1090
|
+
: "ChatGPT login succeeded. Interactive scans will ask which account to use; " +
|
|
1091
|
+
`noninteractive scans will use ${authentication.source}.\n`;
|
|
1092
|
+
const storedCredentials = options.withAccessToken
|
|
1093
|
+
? "your stored credentials"
|
|
1094
|
+
: "your ChatGPT sign-in";
|
|
1095
|
+
errorOutput.write(loginWarning +
|
|
1096
|
+
`To use ${storedCredentials}, pass '--auth chatgpt' or run ` +
|
|
1093
1097
|
`'unset ${configuredApiKeyVariables.join(" ")}'.\n`);
|
|
1094
1098
|
}
|
|
1095
1099
|
}
|