#!/usr/bin/env python3 """Scan human-facing text for a small set of exposure-aware hard leaks.""" from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any EXPOSURES = ("private", "internal", "external", "public") ALLOWED_PROFILE_KEYS = { "profile_version", "author_label", "languages", "mode_preferences", "global_prefer", "global_avoid", } PATTERNS = { "local_path": re.compile(r"(?|\r\n]+)+' ), "internal_marker": re.compile( r"【(?:待校正|TODO|信息缺失)|(?:internal|内部)\s+(?:SOP|workflow|marker)", re.IGNORECASE, ), "credential_assignment": re.compile( r"(?(?:[A-Za-z][A-Za-z0-9]*[_-]){0,2}api[_ -]?(?:key|token)|" r"access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|" r"client[_ -]?secret|secret|token|password|passwd)" r"(?![\w-])\s*[:=]\s*" r"(?P[\"']?)" r"(?P[A-Za-z0-9][A-Za-z0-9_./+=:@!#$%&*?~-]{7,})" r"(?P=quote)", re.IGNORECASE, ), "credential_bearer": re.compile( r"(?authorization)\s*:\s*bearer\s+" r"(?P[A-Za-z0-9][A-Za-z0-9._~+/\-=]{7,})", re.IGNORECASE, ), } EXTERNAL_ONLY_FINDINGS = {"local_path", "unc_path", "internal_marker"} CREDENTIAL_FINDINGS = {"credential_assignment", "credential_bearer"} NON_SECRET_VALUES = { "authentication", "authorization", "changeme", "example", "hidden", "masked", "omitted", "placeholder", "redacted", "your_token", "your_token_here", } class CheckError(RuntimeError): pass def validate_profile(path: Path) -> dict[str, Any]: profile = json.loads(path.read_text(encoding="utf-8")) if not isinstance(profile, dict): raise CheckError("voice profile must be a JSON object") extra = sorted(set(profile) - ALLOWED_PROFILE_KEYS) if extra: raise CheckError(f"voice profile has unknown fields: {extra}") if not isinstance(profile.get("profile_version"), str): raise CheckError("voice profile requires string profile_version") languages = profile.get("languages") if ( not isinstance(languages, list) or not languages or not set(languages) <= {"zh-CN", "en"} ): raise CheckError("voice profile languages must be a non-empty zh-CN/en list") if len(languages) != len(set(languages)): raise CheckError("voice profile languages must not contain duplicates") if "author_label" in profile and not isinstance(profile["author_label"], str): raise CheckError("voice profile author_label must be a string") for field in ("global_prefer", "global_avoid"): if field in profile and ( not isinstance(profile[field], list) or not all(isinstance(item, str) for item in profile[field]) ): raise CheckError(f"voice profile {field} must be a string list") preferences = profile.get("mode_preferences", {}) if not isinstance(preferences, dict): raise CheckError("voice profile mode_preferences must be an object") for mode, values in preferences.items(): if not isinstance(values, dict) or set(values) - {"prefer", "avoid"}: raise CheckError(f"voice profile mode {mode} must contain prefer/avoid only") for field, items in values.items(): if not isinstance(items, list) or not all(isinstance(item, str) for item in items): raise CheckError(f"voice profile mode {mode}.{field} must be a string list") return profile def scan_text(text: str, exposure: str) -> list[dict[str, str]]: findings: list[dict[str, str]] = [] for kind, pattern in PATTERNS.items(): if kind in EXTERNAL_ONLY_FINDINGS and exposure not in {"external", "public"}: continue match = next( ( candidate for candidate in pattern.finditer(text) if kind not in CREDENTIAL_FINDINGS or candidate.group("value").casefold() not in NON_SECRET_VALUES ), None, ) if match: if kind == "credential_bearer": preview = f"{match.group('label')}: Bearer [REDACTED]" elif kind == "credential_assignment": preview = f"{match.group('label')}=[REDACTED]" else: preview = match.group(0)[:80] findings.append( { "kind": kind, "severity": "P0", "preview": preview, } ) return findings def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--exposure", required=True, choices=EXPOSURES) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--text") source.add_argument("--file") parser.add_argument("--voice-profile") return parser def main() -> int: args = build_parser().parse_args() try: if args.file: text = Path(args.file).read_text(encoding="utf-8") else: text = args.text profile = validate_profile(Path(args.voice_profile)) if args.voice_profile else None result = { "exposure": args.exposure, "voice_profile_loaded": profile is not None, "findings": scan_text(text, args.exposure), } except (OSError, CheckError, ValueError, json.JSONDecodeError) as exc: print(f"check: {exc}", file=sys.stderr) return 1 print(json.dumps(result, ensure_ascii=False, indent=2)) return 2 if result["findings"] else 0 if __name__ == "__main__": raise SystemExit(main())