summaryrefslogtreecommitdiff
path: root/plugins/claude-security/scripts/lib
diff options
context:
space:
mode:
authorBryan Thompson <238056179+bryan-anthropic@users.noreply.github.com>2026-08-20 14:50:15 -0500
committerGitHub <noreply@github.com>2026-08-20 14:50:15 -0500
commit240c4b2c17b19868e880f2bfdd909144d67224e1 (patch)
tree9deddb18cf7c137cd56c93b25763eba0946a7ad6 /plugins/claude-security/scripts/lib
parent81182783dc1c15ae70e8a489b1edee5450b1434d (diff)
parentcbe94d02bc8ea7375e13b39cc400e17eeabfcbee (diff)
Merge branch 'main' into add-unleashadd-unleash
Diffstat (limited to 'plugins/claude-security/scripts/lib')
-rw-r--r--plugins/claude-security/scripts/lib/__init__.py1
-rw-r--r--plugins/claude-security/scripts/lib/absolute.py15
-rw-r--r--plugins/claude-security/scripts/lib/console.py17
-rw-r--r--plugins/claude-security/scripts/lib/cwe-categories.json1473
-rw-r--r--plugins/claude-security/scripts/lib/cwe.py79
-rw-r--r--plugins/claude-security/scripts/lib/finding.py241
-rw-r--r--plugins/claude-security/scripts/lib/plugin.py31
-rw-r--r--plugins/claude-security/scripts/lib/sarif.py373
-rw-r--r--plugins/claude-security/scripts/lib/secret.py32
-rw-r--r--plugins/claude-security/scripts/lib/strictjson.py83
10 files changed, 2345 insertions, 0 deletions
diff --git a/plugins/claude-security/scripts/lib/__init__.py b/plugins/claude-security/scripts/lib/__init__.py
new file mode 100644
index 00000000..c180a3d7
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/__init__.py
@@ -0,0 +1 @@
+"""Modules shared by the plugin's entry-point scripts."""
diff --git a/plugins/claude-security/scripts/lib/absolute.py b/plugins/claude-security/scripts/lib/absolute.py
new file mode 100644
index 00000000..45f28ed3
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/absolute.py
@@ -0,0 +1,15 @@
+"""Whether a path is spelled absolutely on any platform, not just the one this runs on."""
+
+from __future__ import annotations
+
+import ntpath
+import os
+
+
+def spelled(path: str) -> bool:
+ """True for a rooted, drive-qualified or UNC path, whichever platform reads it."""
+ return (
+ os.path.isabs(path)
+ or path.replace("\\", "/").startswith("/")
+ or bool(ntpath.splitdrive(path)[0])
+ )
diff --git a/plugins/claude-security/scripts/lib/console.py b/plugins/claude-security/scripts/lib/console.py
new file mode 100644
index 00000000..b8a32635
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/console.py
@@ -0,0 +1,17 @@
+"""The scripts' console output: undecodable path names and failed removals, printed readably."""
+
+from __future__ import annotations
+
+import io
+import sys
+
+
+def tolerate_undecodable_names() -> None:
+ """Make stdout print an undecodable path name as escapes instead of raising."""
+ if isinstance(sys.stdout, io.TextIOWrapper):
+ sys.stdout.reconfigure(errors="backslashreplace")
+
+
+def removal_failure_detail(error: OSError) -> object:
+ """The operator-readable reason a tree removal failed."""
+ return str(error) if error.strerror or not error.args else error.args[0]
diff --git a/plugins/claude-security/scripts/lib/cwe-categories.json b/plugins/claude-security/scripts/lib/cwe-categories.json
new file mode 100644
index 00000000..de95259d
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/cwe-categories.json
@@ -0,0 +1,1473 @@
+{
+ "source": "Derived mechanically from the CWE 4.20 catalog published at https://cwe.mitre.org/.",
+ "cwe_version": "4.20",
+ "view": "CWE-1003",
+ "categories": {
+ "20": {
+ "name": "Improper Input Validation",
+ "title": "Improper Input Validation"
+ },
+ "22": {
+ "name": "Path Traversal",
+ "title": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"
+ },
+ "59": {
+ "name": "Link Following",
+ "title": "Improper Link Resolution Before File Access ('Link Following')"
+ },
+ "74": {
+ "name": "Injection",
+ "title": "Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')"
+ },
+ "77": {
+ "name": "Command Injection",
+ "title": "Improper Neutralization of Special Elements used in a Command ('Command Injection')"
+ },
+ "78": {
+ "name": "OS Command Injection",
+ "title": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"
+ },
+ "79": {
+ "name": "Cross-site Scripting",
+ "title": "Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')"
+ },
+ "88": {
+ "name": "Argument Injection",
+ "title": "Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')"
+ },
+ "89": {
+ "name": "SQL Injection",
+ "title": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"
+ },
+ "91": {
+ "name": "XML Injection (aka Blind XPath Injection)",
+ "title": "XML Injection (aka Blind XPath Injection)"
+ },
+ "94": {
+ "name": "Code Injection",
+ "title": "Improper Control of Generation of Code ('Code Injection')"
+ },
+ "116": {
+ "name": "Improper Encoding or Escaping of Output",
+ "title": "Improper Encoding or Escaping of Output"
+ },
+ "119": {
+ "name": "Improper Restriction of Operations within the Bounds of a Memory Buffer",
+ "title": "Improper Restriction of Operations within the Bounds of a Memory Buffer"
+ },
+ "120": {
+ "name": "Classic Buffer Overflow",
+ "title": "Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')"
+ },
+ "125": {
+ "name": "Out-of-bounds Read",
+ "title": "Out-of-bounds Read"
+ },
+ "129": {
+ "name": "Improper Validation of Array Index",
+ "title": "Improper Validation of Array Index"
+ },
+ "131": {
+ "name": "Incorrect Calculation of Buffer Size",
+ "title": "Incorrect Calculation of Buffer Size"
+ },
+ "134": {
+ "name": "Use of Externally-Controlled Format String",
+ "title": "Use of Externally-Controlled Format String"
+ },
+ "178": {
+ "name": "Improper Handling of Case Sensitivity",
+ "title": "Improper Handling of Case Sensitivity"
+ },
+ "190": {
+ "name": "Integer Overflow or Wraparound",
+ "title": "Integer Overflow or Wraparound"
+ },
+ "191": {
+ "name": "Integer Underflow (Wrap or Wraparound)",
+ "title": "Integer Underflow (Wrap or Wraparound)"
+ },
+ "193": {
+ "name": "Off-by-one Error",
+ "title": "Off-by-one Error"
+ },
+ "200": {
+ "name": "Exposure of Sensitive Information to an Unauthorized Actor",
+ "title": "Exposure of Sensitive Information to an Unauthorized Actor"
+ },
+ "203": {
+ "name": "Observable Discrepancy",
+ "title": "Observable Discrepancy"
+ },
+ "209": {
+ "name": "Generation of Error Message Containing Sensitive Information",
+ "title": "Generation of Error Message Containing Sensitive Information"
+ },
+ "212": {
+ "name": "Improper Removal of Sensitive Information Before Storage or Transfer",
+ "title": "Improper Removal of Sensitive Information Before Storage or Transfer"
+ },
+ "252": {
+ "name": "Unchecked Return Value",
+ "title": "Unchecked Return Value"
+ },
+ "269": {
+ "name": "Improper Privilege Management",
+ "title": "Improper Privilege Management"
+ },
+ "273": {
+ "name": "Improper Check for Dropped Privileges",
+ "title": "Improper Check for Dropped Privileges"
+ },
+ "276": {
+ "name": "Incorrect Default Permissions",
+ "title": "Incorrect Default Permissions"
+ },
+ "281": {
+ "name": "Improper Preservation of Permissions",
+ "title": "Improper Preservation of Permissions"
+ },
+ "287": {
+ "name": "Improper Authentication",
+ "title": "Improper Authentication"
+ },
+ "290": {
+ "name": "Authentication Bypass by Spoofing",
+ "title": "Authentication Bypass by Spoofing"
+ },
+ "294": {
+ "name": "Authentication Bypass by Capture-replay",
+ "title": "Authentication Bypass by Capture-replay"
+ },
+ "295": {
+ "name": "Improper Certificate Validation",
+ "title": "Improper Certificate Validation"
+ },
+ "306": {
+ "name": "Missing Authentication for Critical Function",
+ "title": "Missing Authentication for Critical Function"
+ },
+ "307": {
+ "name": "Improper Restriction of Excessive Authentication Attempts",
+ "title": "Improper Restriction of Excessive Authentication Attempts"
+ },
+ "311": {
+ "name": "Missing Encryption of Sensitive Data",
+ "title": "Missing Encryption of Sensitive Data"
+ },
+ "312": {
+ "name": "Cleartext Storage of Sensitive Information",
+ "title": "Cleartext Storage of Sensitive Information"
+ },
+ "319": {
+ "name": "Cleartext Transmission of Sensitive Information",
+ "title": "Cleartext Transmission of Sensitive Information"
+ },
+ "326": {
+ "name": "Inadequate Encryption Strength",
+ "title": "Inadequate Encryption Strength"
+ },
+ "327": {
+ "name": "Use of a Broken or Risky Cryptographic Algorithm",
+ "title": "Use of a Broken or Risky Cryptographic Algorithm"
+ },
+ "330": {
+ "name": "Use of Insufficiently Random Values",
+ "title": "Use of Insufficiently Random Values"
+ },
+ "331": {
+ "name": "Insufficient Entropy",
+ "title": "Insufficient Entropy"
+ },
+ "335": {
+ "name": "Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG)",
+ "title": "Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG)"
+ },
+ "338": {
+ "name": "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)",
+ "title": "Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)"
+ },
+ "345": {
+ "name": "Insufficient Verification of Data Authenticity",
+ "title": "Insufficient Verification of Data Authenticity"
+ },
+ "346": {
+ "name": "Origin Validation Error",
+ "title": "Origin Validation Error"
+ },
+ "347": {
+ "name": "Improper Verification of Cryptographic Signature",
+ "title": "Improper Verification of Cryptographic Signature"
+ },
+ "352": {
+ "name": "Cross-Site Request Forgery (CSRF)",
+ "title": "Cross-Site Request Forgery (CSRF)"
+ },
+ "354": {
+ "name": "Improper Validation of Integrity Check Value",
+ "title": "Improper Validation of Integrity Check Value"
+ },
+ "362": {
+ "name": "Race Condition",
+ "title": "Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')"
+ },
+ "367": {
+ "name": "Time-of-check Time-of-use (TOCTOU) Race Condition",
+ "title": "Time-of-check Time-of-use (TOCTOU) Race Condition"
+ },
+ "369": {
+ "name": "Divide By Zero",
+ "title": "Divide By Zero"
+ },
+ "384": {
+ "name": "Session Fixation",
+ "title": "Session Fixation"
+ },
+ "400": {
+ "name": "Uncontrolled Resource Consumption",
+ "title": "Uncontrolled Resource Consumption"
+ },
+ "401": {
+ "name": "Missing Release of Memory after Effective Lifetime",
+ "title": "Missing Release of Memory after Effective Lifetime"
+ },
+ "404": {
+ "name": "Improper Resource Shutdown or Release",
+ "title": "Improper Resource Shutdown or Release"
+ },
+ "407": {
+ "name": "Inefficient Algorithmic Complexity",
+ "title": "Inefficient Algorithmic Complexity"
+ },
+ "415": {
+ "name": "Double Free",
+ "title": "Double Free"
+ },
+ "416": {
+ "name": "Use After Free",
+ "title": "Use After Free"
+ },
+ "425": {
+ "name": "Forced Browsing",
+ "title": "Direct Request ('Forced Browsing')"
+ },
+ "426": {
+ "name": "Untrusted Search Path",
+ "title": "Untrusted Search Path"
+ },
+ "427": {
+ "name": "Uncontrolled Search Path Element",
+ "title": "Uncontrolled Search Path Element"
+ },
+ "428": {
+ "name": "Unquoted Search Path or Element",
+ "title": "Unquoted Search Path or Element"
+ },
+ "434": {
+ "name": "Unrestricted Upload of File with Dangerous Type",
+ "title": "Unrestricted Upload of File with Dangerous Type"
+ },
+ "436": {
+ "name": "Interpretation Conflict",
+ "title": "Interpretation Conflict"
+ },
+ "444": {
+ "name": "HTTP Request/Response Smuggling",
+ "title": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')"
+ },
+ "459": {
+ "name": "Incomplete Cleanup",
+ "title": "Incomplete Cleanup"
+ },
+ "470": {
+ "name": "Unsafe Reflection",
+ "title": "Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')"
+ },
+ "476": {
+ "name": "NULL Pointer Dereference",
+ "title": "NULL Pointer Dereference"
+ },
+ "494": {
+ "name": "Download of Code Without Integrity Check",
+ "title": "Download of Code Without Integrity Check"
+ },
+ "502": {
+ "name": "Deserialization of Untrusted Data",
+ "title": "Deserialization of Untrusted Data"
+ },
+ "521": {
+ "name": "Weak Password Requirements",
+ "title": "Weak Password Requirements"
+ },
+ "522": {
+ "name": "Insufficiently Protected Credentials",
+ "title": "Insufficiently Protected Credentials"
+ },
+ "532": {
+ "name": "Insertion of Sensitive Information into Log File",
+ "title": "Insertion of Sensitive Information into Log File"
+ },
+ "552": {
+ "name": "Files or Directories Accessible to External Parties",
+ "title": "Files or Directories Accessible to External Parties"
+ },
+ "565": {
+ "name": "Reliance on Cookies without Validation and Integrity Checking",
+ "title": "Reliance on Cookies without Validation and Integrity Checking"
+ },
+ "601": {
+ "name": "Open Redirect",
+ "title": "URL Redirection to Untrusted Site ('Open Redirect')"
+ },
+ "610": {
+ "name": "Externally Controlled Reference to a Resource in Another Sphere",
+ "title": "Externally Controlled Reference to a Resource in Another Sphere"
+ },
+ "611": {
+ "name": "Improper Restriction of XML External Entity Reference",
+ "title": "Improper Restriction of XML External Entity Reference"
+ },
+ "613": {
+ "name": "Insufficient Session Expiration",
+ "title": "Insufficient Session Expiration"
+ },
+ "617": {
+ "name": "Reachable Assertion",
+ "title": "Reachable Assertion"
+ },
+ "639": {
+ "name": "Authorization Bypass Through User-Controlled Key",
+ "title": "Authorization Bypass Through User-Controlled Key"
+ },
+ "640": {
+ "name": "Weak Password Recovery Mechanism for Forgotten Password",
+ "title": "Weak Password Recovery Mechanism for Forgotten Password"
+ },
+ "662": {
+ "name": "Improper Synchronization",
+ "title": "Improper Synchronization"
+ },
+ "665": {
+ "name": "Improper Initialization",
+ "title": "Improper Initialization"
+ },
+ "667": {
+ "name": "Improper Locking",
+ "title": "Improper Locking"
+ },
+ "668": {
+ "name": "Exposure of Resource to Wrong Sphere",
+ "title": "Exposure of Resource to Wrong Sphere"
+ },
+ "669": {
+ "name": "Incorrect Resource Transfer Between Spheres",
+ "title": "Incorrect Resource Transfer Between Spheres"
+ },
+ "670": {
+ "name": "Always-Incorrect Control Flow Implementation",
+ "title": "Always-Incorrect Control Flow Implementation"
+ },
+ "672": {
+ "name": "Operation on a Resource after Expiration or Release",
+ "title": "Operation on a Resource after Expiration or Release"
+ },
+ "674": {
+ "name": "Uncontrolled Recursion",
+ "title": "Uncontrolled Recursion"
+ },
+ "681": {
+ "name": "Incorrect Conversion between Numeric Types",
+ "title": "Incorrect Conversion between Numeric Types"
+ },
+ "682": {
+ "name": "Incorrect Calculation",
+ "title": "Incorrect Calculation"
+ },
+ "697": {
+ "name": "Incorrect Comparison",
+ "title": "Incorrect Comparison"
+ },
+ "704": {
+ "name": "Incorrect Type Conversion or Cast",
+ "title": "Incorrect Type Conversion or Cast"
+ },
+ "706": {
+ "name": "Use of Incorrectly-Resolved Name or Reference",
+ "title": "Use of Incorrectly-Resolved Name or Reference"
+ },
+ "732": {
+ "name": "Incorrect Permission Assignment for Critical Resource",
+ "title": "Incorrect Permission Assignment for Critical Resource"
+ },
+ "754": {
+ "name": "Improper Check for Unusual or Exceptional Conditions",
+ "title": "Improper Check for Unusual or Exceptional Conditions"
+ },
+ "755": {
+ "name": "Improper Handling of Exceptional Conditions",
+ "title": "Improper Handling of Exceptional Conditions"
+ },
+ "763": {
+ "name": "Release of Invalid Pointer or Reference",
+ "title": "Release of Invalid Pointer or Reference"
+ },
+ "770": {
+ "name": "Allocation of Resources Without Limits or Throttling",
+ "title": "Allocation of Resources Without Limits or Throttling"
+ },
+ "772": {
+ "name": "Missing Release of Resource after Effective Lifetime",
+ "title": "Missing Release of Resource after Effective Lifetime"
+ },
+ "776": {
+ "name": "XML Entity Expansion",
+ "title": "Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')"
+ },
+ "787": {
+ "name": "Out-of-bounds Write",
+ "title": "Out-of-bounds Write"
+ },
+ "798": {
+ "name": "Use of Hard-coded Credentials",
+ "title": "Use of Hard-coded Credentials"
+ },
+ "824": {
+ "name": "Access of Uninitialized Pointer",
+ "title": "Access of Uninitialized Pointer"
+ },
+ "829": {
+ "name": "Inclusion of Functionality from Untrusted Control Sphere",
+ "title": "Inclusion of Functionality from Untrusted Control Sphere"
+ },
+ "834": {
+ "name": "Excessive Iteration",
+ "title": "Excessive Iteration"
+ },
+ "835": {
+ "name": "Infinite Loop",
+ "title": "Loop with Unreachable Exit Condition ('Infinite Loop')"
+ },
+ "838": {
+ "name": "Inappropriate Encoding for Output Context",
+ "title": "Inappropriate Encoding for Output Context"
+ },
+ "843": {
+ "name": "Type Confusion",
+ "title": "Access of Resource Using Incompatible Type ('Type Confusion')"
+ },
+ "862": {
+ "name": "Missing Authorization",
+ "title": "Missing Authorization"
+ },
+ "863": {
+ "name": "Incorrect Authorization",
+ "title": "Incorrect Authorization"
+ },
+ "908": {
+ "name": "Use of Uninitialized Resource",
+ "title": "Use of Uninitialized Resource"
+ },
+ "909": {
+ "name": "Missing Initialization of Resource",
+ "title": "Missing Initialization of Resource"
+ },
+ "913": {
+ "name": "Improper Control of Dynamically-Managed Code Resources",
+ "title": "Improper Control of Dynamically-Managed Code Resources"
+ },
+ "916": {
+ "name": "Use of Password Hash With Insufficient Computational Effort",
+ "title": "Use of Password Hash With Insufficient Computational Effort"
+ },
+ "917": {
+ "name": "Expression Language Injection",
+ "title": "Improper Neutralization of Special Elements used in an Expression Language Statement ('Expression Language Injection')"
+ },
+ "918": {
+ "name": "Server-Side Request Forgery (SSRF)",
+ "title": "Server-Side Request Forgery (SSRF)"
+ },
+ "920": {
+ "name": "Improper Restriction of Power Consumption",
+ "title": "Improper Restriction of Power Consumption"
+ },
+ "922": {
+ "name": "Insecure Storage of Sensitive Information",
+ "title": "Insecure Storage of Sensitive Information"
+ },
+ "924": {
+ "name": "Improper Enforcement of Message Integrity During Transmission in a Communication Channel",
+ "title": "Improper Enforcement of Message Integrity During Transmission in a Communication Channel"
+ },
+ "1021": {
+ "name": "Improper Restriction of Rendered UI Layers or Frames",
+ "title": "Improper Restriction of Rendered UI Layers or Frames"
+ },
+ "1188": {
+ "name": "Initialization of a Resource with an Insecure Default",
+ "title": "Initialization of a Resource with an Insecure Default"
+ },
+ "1236": {
+ "name": "Improper Neutralization of Formula Elements in a CSV File",
+ "title": "Improper Neutralization of Formula Elements in a CSV File"
+ },
+ "1284": {
+ "name": "Improper Validation of Specified Quantity in Input",
+ "title": "Improper Validation of Specified Quantity in Input"
+ },
+ "1321": {
+ "name": "Prototype Pollution",
+ "title": "Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')"
+ },
+ "1333": {
+ "name": "Inefficient Regular Expression Complexity",
+ "title": "Inefficient Regular Expression Complexity"
+ }
+ },
+ "category_of": {
+ "5": 319,
+ "6": 330,
+ "7": 755,
+ "8": 668,
+ "9": 269,
+ "11": null,
+ "12": 755,
+ "13": 522,
+ "14": null,
+ "15": 610,
+ "20": 20,
+ "22": 22,
+ "23": 22,
+ "24": 22,
+ "25": 22,
+ "26": 22,
+ "27": 22,
+ "28": 22,
+ "29": 22,
+ "30": 22,
+ "31": 22,
+ "32": 22,
+ "33": 22,
+ "34": 22,
+ "35": 22,
+ "36": 22,
+ "37": 22,
+ "38": 22,
+ "39": 22,
+ "40": 22,
+ "41": 706,
+ "42": 706,
+ "43": 706,
+ "44": 706,
+ "45": 706,
+ "46": 706,
+ "47": 706,
+ "48": 706,
+ "49": 706,
+ "50": 706,
+ "51": 706,
+ "52": 706,
+ "53": 706,
+ "54": 706,
+ "55": 706,
+ "56": 706,
+ "57": 706,
+ "58": 706,
+ "59": 59,
+ "61": 59,
+ "62": 59,
+ "64": 59,
+ "65": 59,
+ "66": 706,
+ "67": 706,
+ "69": 706,
+ "72": 706,
+ "73": 610,
+ "74": 74,
+ "75": 74,
+ "76": 74,
+ "77": 77,
+ "78": 78,
+ "79": 79,
+ "80": 79,
+ "81": 79,
+ "82": 79,
+ "83": 79,
+ "84": 79,
+ "85": 79,
+ "86": 79,
+ "87": 79,
+ "88": 88,
+ "89": 89,
+ "90": 74,
+ "91": 91,
+ "93": 74,
+ "94": 94,
+ "95": 94,
+ "96": 94,
+ "97": 94,
+ "98": 829,
+ "99": 74,
+ "102": 20,
+ "103": null,
+ "104": null,
+ "105": 20,
+ "106": 20,
+ "107": null,
+ "108": 20,
+ "109": 20,
+ "110": null,
+ "111": null,
+ "112": 20,
+ "113": 436,
+ "114": 610,
+ "115": 436,
+ "116": 116,
+ "117": 116,
+ "118": null,
+ "119": 119,
+ "120": 120,
+ "121": 787,
+ "122": 787,
+ "123": 787,
+ "124": 787,
+ "125": 125,
+ "126": 125,
+ "127": 125,
+ "128": 682,
+ "129": 129,
+ "130": null,
+ "131": 131,
+ "134": 134,
+ "135": 682,
+ "138": null,
+ "140": null,
+ "141": null,
+ "142": null,
+ "143": null,
+ "144": null,
+ "145": null,
+ "146": null,
+ "147": 436,
+ "148": null,
+ "149": null,
+ "150": null,
+ "151": null,
+ "152": null,
+ "153": null,
+ "154": null,
+ "155": 706,
+ "156": null,
+ "157": null,
+ "158": null,
+ "159": null,
+ "160": 22,
+ "161": 706,
+ "162": 706,
+ "163": 706,
+ "164": 706,
+ "165": 706,
+ "166": null,
+ "167": null,
+ "168": null,
+ "170": null,
+ "172": null,
+ "173": null,
+ "174": null,
+ "175": null,
+ "176": null,
+ "177": null,
+ "178": 178,
+ "179": 20,
+ "180": 20,
+ "181": 20,
+ "182": null,
+ "183": 697,
+ "184": 697,
+ "185": 697,
+ "186": 697,
+ "187": 697,
+ "188": null,
+ "190": 190,
+ "191": 191,
+ "192": 681,
+ "193": 193,
+ "194": 681,
+ "195": 681,
+ "196": 681,
+ "197": 681,
+ "198": null,
+ "200": 200,
+ "201": 200,
+ "202": null,
+ "203": 203,
+ "204": 203,
+ "205": 203,
+ "206": 203,
+ "207": 203,
+ "208": 203,
+ "209": 209,
+ "210": 209,
+ "211": 209,
+ "212": 212,
+ "213": 200,
+ "214": 200,
+ "215": 200,
+ "219": 552,
+ "220": 552,
+ "221": 755,
+ "222": null,
+ "223": null,
+ "224": null,
+ "226": 459,
+ "228": null,
+ "229": null,
+ "230": null,
+ "231": null,
+ "232": null,
+ "233": null,
+ "234": null,
+ "235": null,
+ "236": null,
+ "237": null,
+ "238": null,
+ "239": null,
+ "240": null,
+ "241": null,
+ "242": null,
+ "243": 669,
+ "244": 459,
+ "245": null,
+ "246": null,
+ "248": 755,
+ "250": 269,
+ "252": 252,
+ "253": 754,
+ "256": 522,
+ "257": 522,
+ "258": 521,
+ "259": 798,
+ "260": 522,
+ "261": 522,
+ "262": 287,
+ "263": 287,
+ "266": 269,
+ "267": 269,
+ "268": 269,
+ "269": 269,
+ "270": 269,
+ "271": 269,
+ "272": 269,
+ "273": 273,
+ "274": 755,
+ "276": 276,
+ "277": 732,
+ "278": 732,
+ "279": 732,
+ "280": 755,
+ "281": 281,
+ "282": null,
+ "283": null,
+ "284": null,
+ "285": null,
+ "286": null,
+ "287": 287,
+ "288": 306,
+ "289": 287,
+ "290": 290,
+ "291": 290,
+ "293": 290,
+ "294": 294,
+ "295": 295,
+ "296": 295,
+ "297": 295,
+ "298": 295,
+ "299": 295,
+ "300": null,
+ "301": 287,
+ "302": 287,
+ "303": 287,
+ "304": 287,
+ "305": 287,
+ "306": 306,
+ "307": 307,
+ "308": 287,
+ "309": 287,
+ "311": 311,
+ "312": 312,
+ "313": 312,
+ "314": 312,
+ "315": 312,
+ "316": 312,
+ "317": 312,
+ "318": 312,
+ "319": 319,
+ "321": 798,
+ "322": 306,
+ "323": 330,
+ "324": 672,
+ "325": 327,
+ "326": 326,
+ "327": 327,
+ "328": 327,
+ "329": 330,
+ "330": 330,
+ "331": 331,
+ "332": 331,
+ "333": 331,
+ "334": 330,
+ "335": 335,
+ "336": 335,
+ "337": 335,
+ "338": 338,
+ "339": 335,
+ "340": 330,
+ "341": 330,
+ "342": 330,
+ "343": 330,
+ "344": 330,
+ "345": 345,
+ "346": 346,
+ "347": 347,
+ "348": 345,
+ "349": 345,
+ "350": 290,
+ "351": 345,
+ "352": 352,
+ "353": 345,
+ "354": 354,
+ "356": null,
+ "357": null,
+ "358": null,
+ "359": 200,
+ "360": 345,
+ "362": 362,
+ "363": 367,
+ "364": 362,
+ "366": 362,
+ "367": 367,
+ "368": 362,
+ "369": 369,
+ "370": 295,
+ "372": null,
+ "374": 668,
+ "375": 668,
+ "377": 668,
+ "378": 668,
+ "379": 668,
+ "382": null,
+ "383": null,
+ "384": 384,
+ "385": null,
+ "386": 706,
+ "390": 755,
+ "391": 754,
+ "392": 755,
+ "393": null,
+ "394": 754,
+ "395": 755,
+ "396": 755,
+ "397": null,
+ "400": 400,
+ "401": 401,
+ "402": 668,
+ "403": 668,
+ "404": 404,
+ "405": 400,
+ "406": 400,
+ "407": 407,
+ "408": 400,
+ "409": 400,
+ "410": null,
+ "412": 667,
+ "413": 667,
+ "414": 667,
+ "415": 415,
+ "416": 416,
+ "419": null,
+ "420": 306,
+ "421": 362,
+ "422": 345,
+ "424": 862,
+ "425": 425,
+ "426": 426,
+ "427": 427,
+ "428": 428,
+ "430": null,
+ "431": null,
+ "432": 362,
+ "433": 552,
+ "434": 434,
+ "435": null,
+ "436": 436,
+ "437": 436,
+ "439": null,
+ "440": 665,
+ "441": 610,
+ "444": 444,
+ "446": null,
+ "447": null,
+ "448": null,
+ "449": null,
+ "450": null,
+ "451": 1021,
+ "453": 1188,
+ "454": 665,
+ "455": 665,
+ "456": 909,
+ "457": 908,
+ "459": 459,
+ "460": 459,
+ "462": 74,
+ "463": null,
+ "464": null,
+ "466": 119,
+ "467": 131,
+ "468": 682,
+ "469": 682,
+ "470": 470,
+ "471": 668,
+ "472": 668,
+ "473": null,
+ "474": null,
+ "475": null,
+ "476": 476,
+ "477": null,
+ "478": 697,
+ "479": 662,
+ "480": 670,
+ "481": 670,
+ "482": 670,
+ "483": 670,
+ "484": 670,
+ "486": 697,
+ "487": null,
+ "488": 668,
+ "489": null,
+ "491": 668,
+ "492": 668,
+ "493": 668,
+ "494": 494,
+ "495": null,
+ "496": null,
+ "497": 200,
+ "498": 668,
+ "499": 668,
+ "500": 668,
+ "501": null,
+ "502": 502,
+ "506": null,
+ "507": null,
+ "508": null,
+ "509": null,
+ "510": null,
+ "511": null,
+ "512": null,
+ "514": null,
+ "515": null,
+ "520": 269,
+ "521": 521,
+ "522": 522,
+ "523": 522,
+ "524": 668,
+ "525": 668,
+ "526": 312,
+ "527": 552,
+ "528": 552,
+ "529": 552,
+ "530": 552,
+ "531": 200,
+ "532": 532,
+ "535": 209,
+ "536": 209,
+ "537": 209,
+ "538": 200,
+ "539": 552,
+ "540": 200,
+ "541": 200,
+ "543": 662,
+ "544": 755,
+ "546": null,
+ "547": null,
+ "548": 200,
+ "549": 522,
+ "550": 209,
+ "551": 863,
+ "552": 552,
+ "553": 552,
+ "554": 20,
+ "555": 522,
+ "556": 269,
+ "558": 662,
+ "560": null,
+ "561": null,
+ "562": null,
+ "563": null,
+ "564": 89,
+ "565": 565,
+ "566": 639,
+ "567": 662,
+ "568": 459,
+ "570": null,
+ "571": null,
+ "572": 662,
+ "573": 74,
+ "574": 662,
+ "575": null,
+ "576": null,
+ "577": null,
+ "578": null,
+ "579": null,
+ "580": null,
+ "581": 697,
+ "582": 668,
+ "583": 668,
+ "584": null,
+ "585": null,
+ "586": null,
+ "587": 330,
+ "588": 704,
+ "589": null,
+ "590": 763,
+ "591": 667,
+ "593": 287,
+ "594": null,
+ "595": 697,
+ "597": 670,
+ "598": 200,
+ "599": 295,
+ "600": 755,
+ "601": 601,
+ "602": 287,
+ "603": 287,
+ "605": null,
+ "606": 1284,
+ "607": null,
+ "608": 668,
+ "609": 667,
+ "610": 610,
+ "611": 611,
+ "612": null,
+ "613": 613,
+ "614": 319,
+ "615": 200,
+ "616": 345,
+ "617": 617,
+ "618": null,
+ "619": 668,
+ "620": 287,
+ "621": 913,
+ "622": 20,
+ "623": 269,
+ "624": 77,
+ "625": 697,
+ "626": 436,
+ "627": 913,
+ "628": null,
+ "636": 755,
+ "637": null,
+ "638": 862,
+ "639": 639,
+ "640": 640,
+ "641": 74,
+ "642": 668,
+ "643": 91,
+ "644": 116,
+ "645": 287,
+ "646": 345,
+ "647": 863,
+ "648": 269,
+ "649": 345,
+ "650": 436,
+ "651": 200,
+ "652": 91,
+ "653": 668,
+ "654": 287,
+ "655": null,
+ "656": null,
+ "657": null,
+ "662": 662,
+ "663": 662,
+ "664": null,
+ "665": 665,
+ "666": null,
+ "667": 667,
+ "668": 668,
+ "669": 669,
+ "670": 670,
+ "671": 798,
+ "672": 672,
+ "673": 426,
+ "674": 674,
+ "675": 667,
+ "676": 120,
+ "680": 190,
+ "681": 681,
+ "682": 682,
+ "683": null,
+ "684": 755,
+ "685": null,
+ "686": null,
+ "687": null,
+ "688": null,
+ "689": 362,
+ "690": 252,
+ "691": null,
+ "692": 697,
+ "693": null,
+ "694": 74,
+ "695": 662,
+ "696": 20,
+ "697": 697,
+ "698": 670,
+ "703": null,
+ "704": 704,
+ "705": 755,
+ "706": 706,
+ "707": null,
+ "708": null,
+ "710": null,
+ "732": 732,
+ "733": null,
+ "749": null,
+ "754": 754,
+ "755": 755,
+ "756": 755,
+ "757": null,
+ "758": 330,
+ "759": 916,
+ "760": 916,
+ "761": 763,
+ "762": 763,
+ "763": 763,
+ "764": 667,
+ "765": 667,
+ "766": 732,
+ "767": 668,
+ "768": null,
+ "770": 770,
+ "771": 400,
+ "772": 772,
+ "773": 400,
+ "774": 770,
+ "775": 772,
+ "776": 776,
+ "777": 697,
+ "778": null,
+ "779": 400,
+ "780": 327,
+ "781": 20,
+ "782": null,
+ "783": 670,
+ "784": 565,
+ "785": 120,
+ "786": 119,
+ "787": 787,
+ "788": 119,
+ "789": 770,
+ "790": null,
+ "791": null,
+ "792": null,
+ "793": null,
+ "794": null,
+ "795": null,
+ "796": null,
+ "797": null,
+ "798": 798,
+ "799": 307,
+ "804": 863,
+ "805": 119,
+ "806": 119,
+ "807": 287,
+ "820": 662,
+ "821": 662,
+ "822": 119,
+ "823": 119,
+ "824": 824,
+ "825": 119,
+ "826": null,
+ "827": 706,
+ "828": 362,
+ "829": 829,
+ "830": 829,
+ "831": 362,
+ "832": 667,
+ "833": 667,
+ "834": 834,
+ "835": 835,
+ "836": 287,
+ "837": null,
+ "838": 838,
+ "839": 697,
+ "841": null,
+ "842": null,
+ "843": 843,
+ "862": 862,
+ "863": 863,
+ "908": 908,
+ "909": 909,
+ "910": 672,
+ "911": null,
+ "912": null,
+ "913": 913,
+ "914": 913,
+ "915": 913,
+ "916": 916,
+ "917": 917,
+ "918": 918,
+ "920": 920,
+ "921": 922,
+ "922": 922,
+ "923": 290,
+ "924": 924,
+ "925": 346,
+ "926": null,
+ "927": 668,
+ "939": 862,
+ "940": 346,
+ "941": null,
+ "942": 863,
+ "943": 74,
+ "1004": 732,
+ "1007": null,
+ "1021": 1021,
+ "1022": 269,
+ "1023": 697,
+ "1024": 697,
+ "1025": 697,
+ "1037": null,
+ "1038": null,
+ "1039": 697,
+ "1041": null,
+ "1042": 400,
+ "1043": null,
+ "1044": null,
+ "1045": null,
+ "1046": 400,
+ "1047": null,
+ "1048": null,
+ "1049": 400,
+ "1050": 400,
+ "1051": 665,
+ "1052": 665,
+ "1053": null,
+ "1054": null,
+ "1055": null,
+ "1056": null,
+ "1057": null,
+ "1058": 662,
+ "1059": null,
+ "1060": null,
+ "1061": 732,
+ "1062": null,
+ "1063": 400,
+ "1064": null,
+ "1065": null,
+ "1066": null,
+ "1067": 400,
+ "1068": null,
+ "1069": null,
+ "1070": null,
+ "1071": null,
+ "1072": 400,
+ "1073": 400,
+ "1074": null,
+ "1075": null,
+ "1076": null,
+ "1077": 697,
+ "1078": null,
+ "1079": null,
+ "1080": null,
+ "1082": null,
+ "1083": null,
+ "1084": 400,
+ "1085": null,
+ "1086": null,
+ "1087": null,
+ "1088": 662,
+ "1089": 400,
+ "1090": null,
+ "1091": 772,
+ "1092": null,
+ "1093": null,
+ "1094": 400,
+ "1095": null,
+ "1096": 662,
+ "1097": null,
+ "1098": null,
+ "1099": null,
+ "1100": null,
+ "1101": null,
+ "1102": null,
+ "1103": null,
+ "1104": null,
+ "1105": null,
+ "1106": null,
+ "1107": null,
+ "1108": null,
+ "1109": null,
+ "1110": null,
+ "1111": null,
+ "1112": null,
+ "1113": null,
+ "1114": null,
+ "1115": null,
+ "1116": null,
+ "1117": null,
+ "1118": null,
+ "1119": null,
+ "1120": null,
+ "1121": null,
+ "1122": null,
+ "1123": null,
+ "1124": null,
+ "1125": null,
+ "1126": null,
+ "1127": null,
+ "1164": null,
+ "1173": 20,
+ "1174": 20,
+ "1176": 400,
+ "1177": 120,
+ "1188": 1188,
+ "1189": 668,
+ "1190": null,
+ "1191": null,
+ "1192": null,
+ "1193": null,
+ "1204": 330,
+ "1209": null,
+ "1220": null,
+ "1221": 665,
+ "1222": null,
+ "1223": 362,
+ "1224": null,
+ "1229": null,
+ "1230": null,
+ "1231": null,
+ "1232": 667,
+ "1233": 667,
+ "1234": 667,
+ "1235": 400,
+ "1236": 1236,
+ "1239": 459,
+ "1240": 327,
+ "1241": 330,
+ "1242": null,
+ "1243": null,
+ "1244": 863,
+ "1245": null,
+ "1246": 400,
+ "1247": null,
+ "1248": null,
+ "1249": null,
+ "1250": null,
+ "1251": null,
+ "1252": null,
+ "1253": null,
+ "1254": 697,
+ "1255": 203,
+ "1256": null,
+ "1257": null,
+ "1258": 212,
+ "1259": null,
+ "1260": null,
+ "1261": null,
+ "1262": null,
+ "1263": null,
+ "1264": 662,
+ "1265": 662,
+ "1266": 404,
+ "1267": null,
+ "1268": 269,
+ "1269": null,
+ "1270": null,
+ "1271": 909,
+ "1272": 459,
+ "1273": 200,
+ "1274": null,
+ "1275": null,
+ "1276": null,
+ "1277": null,
+ "1278": null,
+ "1279": 665,
+ "1280": null,
+ "1281": null,
+ "1282": 668,
+ "1283": null,
+ "1284": 1284,
+ "1285": 20,
+ "1286": 20,
+ "1287": 20,
+ "1288": 20,
+ "1289": 20,
+ "1290": null,
+ "1291": null,
+ "1292": null,
+ "1293": 345,
+ "1294": null,
+ "1295": 200,
+ "1296": null,
+ "1297": null,
+ "1298": 362,
+ "1299": 306,
+ "1300": 203,
+ "1301": 459,
+ "1302": null,
+ "1303": 203,
+ "1304": null,
+ "1310": null,
+ "1311": null,
+ "1312": null,
+ "1313": null,
+ "1314": 862,
+ "1315": null,
+ "1316": null,
+ "1317": null,
+ "1318": null,
+ "1319": null,
+ "1320": null,
+ "1321": 1321,
+ "1322": 834,
+ "1323": null,
+ "1325": 770,
+ "1326": null,
+ "1327": 668,
+ "1328": null,
+ "1329": null,
+ "1330": 459,
+ "1331": 668,
+ "1332": null,
+ "1333": 1333,
+ "1334": null,
+ "1335": 682,
+ "1336": 94,
+ "1338": null,
+ "1339": 682,
+ "1341": 415,
+ "1342": 459,
+ "1351": null,
+ "1357": null,
+ "1384": null,
+ "1385": 346,
+ "1386": 59,
+ "1389": 704,
+ "1390": 287,
+ "1391": 287,
+ "1392": 287,
+ "1393": 287,
+ "1394": 287,
+ "1395": null,
+ "1419": 665,
+ "1420": 669,
+ "1421": 669,
+ "1422": 669,
+ "1423": 669,
+ "1426": null,
+ "1427": 77,
+ "1428": 319,
+ "1429": null,
+ "1431": 200,
+ "1434": 665
+ }
+}
diff --git a/plugins/claude-security/scripts/lib/cwe.py b/plugins/claude-security/scripts/lib/cwe.py
new file mode 100644
index 00000000..1f7a38be
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/cwe.py
@@ -0,0 +1,79 @@
+"""CWE data the plugin ships: the weaknesses, and the Simplified Mapping entry each belongs to."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TypedDict, cast
+
+from . import strictjson
+
+UNCATEGORIZED = "Uncategorized"
+
+
+class CategoryNames(TypedDict):
+ """One entry's names in cwe-categories.json."""
+
+ name: str
+ title: str
+
+
+class CatalogFile(TypedDict):
+ """The shape of cwe-categories.json."""
+
+ cwe_version: str
+ categories: dict[str, CategoryNames]
+ category_of: dict[str, int | None]
+
+
+@dataclass(frozen=True)
+class Category:
+ """One entry of the view: its CWE number, its common name, its full catalog title."""
+
+ number: int
+ name: str
+ title: str
+
+ @property
+ def id(self) -> str:
+ """The entry's CWE id, `CWE-<number>`."""
+ return f"CWE-{self.number}"
+
+
+@dataclass(frozen=True)
+class Catalog:
+ """One CWE release: the view's entries, and for every weakness the entry it rolls up to."""
+
+ version: str
+ categories: dict[int, Category]
+ category_of: dict[int, int | None]
+
+ @classmethod
+ def load(cls, path: Path) -> Catalog:
+ """The catalog stored at `path`."""
+ raw = cast("CatalogFile", strictjson.load(path))
+ return cls(
+ raw["cwe_version"],
+ {
+ int(number): Category(int(number), names["name"], names["title"])
+ for number, names in raw["categories"].items()
+ },
+ {int(number): category for number, category in raw["category_of"].items()},
+ )
+
+ def category(self, cwe: int) -> Category | None:
+ """The entry `cwe` rolls up to; None when it reaches none or is not a known weakness."""
+ number = self.category_of.get(cwe)
+ return self.categories[number] if number is not None else None
+
+ def defines(self, cwe: int) -> bool:
+ """Whether the release defines weakness `cwe` at all; category() is None either way."""
+ return cwe in self.category_of
+
+
+def id_number(cwe_id: str) -> int:
+ """The number of a canonical `CWE-<number>` id, the spelling every validated finding carries."""
+ return int(cwe_id.removeprefix("CWE-"))
+
+
+catalog = Catalog.load(Path(__file__).resolve().with_name("cwe-categories.json"))
diff --git a/plugins/claude-security/scripts/lib/finding.py b/plugins/claude-security/scripts/lib/finding.py
new file mode 100644
index 00000000..c6f0ffa1
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/finding.py
@@ -0,0 +1,241 @@
+"""The Finding record every product carries, and build_finding, which validates a raw one."""
+
+from __future__ import annotations
+
+import os
+import re
+from typing import TypedDict
+
+from . import absolute, cwe
+from .strictjson import JsonMap, has_lone_surrogate, is_int, is_list, is_map, is_str
+
+
+class Panel(TypedDict):
+ """A validated panel round: the vote counts and the fixed voter count."""
+
+ true: int
+ false: int
+ voters: int
+
+
+class Finding(TypedDict):
+ """One validated finding: the JSONL record, whose field order is this class's order."""
+
+ id: str
+ title: str
+ impact: str
+ file: str
+ line: int
+ description: str
+ exploit_scenario: str
+ preconditions: list[str]
+ category: str
+ severity: str
+ confidence: str
+ recommendation: str
+ cwe_id: str
+ snippet: str
+ symbol: str
+
+
+SEVERITIES = ("HIGH", "MEDIUM", "LOW")
+CONFIDENCES = ("low", "medium", "high")
+CONFIDENCE_RANK = {"low": 1, "medium": 2, "high": 3}
+
+PANEL_VOTER_COUNT = 3
+PANEL_KEEP_QUORUM = 2
+
+# \Z, not $: `$` also matches before a trailing newline, and this names a file.
+FINDING_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}\Z")
+
+
+class FindingError(Exception):
+ """A refusal; the message names what a findings.json record got wrong."""
+
+
+def cwe_number(item: JsonMap, finding_id: str) -> int:
+ """A finding's CWE number; a cwe_id missing, unreadable or malformed is refused.
+
+ A well-formed id is accepted as declared, whether or not the pinned CWE
+ release defines it; one the release does not define files the finding
+ under Uncategorized, and the renderer discloses the substitution.
+ """
+ declared = text_field(item, "cwe_id", finding_id, required=True)
+ matched = re.fullmatch(
+ r"(?:CWE-)?0*([1-9][0-9]{0,4})", declared.strip().upper().replace("_", "-")
+ )
+ if not matched:
+ msg = f"finding {finding_id} cwe_id {declared!r} is not a CWE id such as CWE-89"
+ raise FindingError(msg)
+ return int(matched[1])
+
+
+def confidence_value(raw: object) -> str:
+ """A finding's stated confidence, normalized to low|medium|high; refuses others."""
+ if is_str(raw):
+ word = raw.strip().lower()
+ if word in CONFIDENCE_RANK:
+ return word
+ msg = f"confidence {raw!r} is not one of {'/'.join(CONFIDENCES)}"
+ raise FindingError(msg)
+
+
+def panel_complete(record: object) -> Panel | None:
+ """One round record's panel when the full voter count returned an integer tally, else None."""
+ if not is_map(record):
+ return None
+ panel = record.get("panel")
+ if not is_map(panel):
+ return None
+ panel_true = panel.get("true")
+ if not is_int(panel_true):
+ return None
+ if panel.get("voters") != PANEL_VOTER_COUNT:
+ return None
+ false_votes = panel.get("false")
+ return {
+ "true": panel_true,
+ "false": false_votes if is_int(false_votes) else 0,
+ "voters": PANEL_VOTER_COUNT,
+ }
+
+
+def vote_confidence_ceiling(record: object) -> str | None:
+ """A finding's vote-backed confidence: `high` if unanimous, `medium` if complete, else None."""
+ panel = panel_complete(record)
+ if panel is None:
+ return None
+ return "high" if panel["true"] >= PANEL_VOTER_COUNT else "medium"
+
+
+def text_field(item: JsonMap, key: str, finding_id: str, required: bool = False) -> str:
+ """One of a finding's text fields; absent or null reads as empty unless it is required."""
+ value = item.get(key)
+ if value is None:
+ text = ""
+ elif is_str(value):
+ text = value
+ else:
+ msg = f"finding {finding_id} {key} is {type(value).__name__}, not a string"
+ raise FindingError(msg)
+ if has_lone_surrogate(text):
+ msg = f"finding {finding_id} {key} contains an unpaired surrogate"
+ raise FindingError(msg)
+ if required and not text.strip():
+ msg = f"finding {finding_id} is missing required field {key!r}"
+ raise FindingError(msg)
+ return text
+
+
+def file_field(
+ item: JsonMap, finding_id: str, scan_root: str, scan_prefix: str, must_exist: bool
+) -> str:
+ """A finding's file relative to the scan root; a path that leaves the repository is refused.
+
+ `scan_prefix` is the scan root's path below the repository top level (`a/b/`,
+ or empty): a file may climb one directory per prefix component and no further.
+ A file spelled relative to the top level, absent under the scan root but
+ present under the top level, is respelled relative to the scan root.
+ With `must_exist` (a codebase scan, whose whole tree is still present when
+ the report renders), a path that exists neither under the scan root nor at
+ the repository top level is refused.
+ """
+ declared = text_field(item, "file", finding_id, required=True).strip()
+ depth = scan_prefix.count("/")
+ beyond = "repository" if depth else "scan root"
+ refusal = f"finding {finding_id} file {declared!r} escapes the {beyond}"
+ path = declared.replace("\\", "/")
+ prefix = scan_root.replace("\\", "/").rstrip("/") + "/"
+ if scan_root and path.startswith(prefix):
+ path = path[len(prefix) :].lstrip("/")
+ if os.path.isabs(path):
+ try:
+ path = os.path.relpath(os.path.realpath(path), scan_root).replace("\\", "/")
+ except (ValueError, OSError) as error:
+ raise FindingError(refusal) from error
+ parts = [part for part in path.split("/") if part and part != "."]
+ climb = next((i for i, part in enumerate(parts) if part != ".."), len(parts))
+ inside = parts[climb:]
+ if not inside or absolute.spelled(path) or ".." in inside or climb > depth:
+ raise FindingError(refusal)
+ if not os.path.lexists(os.path.join(scan_root, *parts)):
+ # A file only the repository top level holds was spelled relative to it, not the scan root.
+ if depth and not climb:
+ at_top = os.path.join(os.path.normpath(os.path.join(scan_root, "../" * depth)), *parts)
+ if os.path.lexists(at_top):
+ return os.path.relpath(at_top, scan_root).replace("\\", "/")
+ if must_exist:
+ msg = f"finding {finding_id} file {declared!r} does not exist in the scanned tree"
+ raise FindingError(msg)
+ return "/".join(parts)
+
+
+def build_finding(
+ raw: object,
+ index: int,
+ rounds_by_id: JsonMap,
+ scan_root: str,
+ scan_prefix: str,
+ must_exist: bool,
+) -> Finding:
+ """Validate one raw findings.json record into a Finding."""
+ if not is_map(raw):
+ msg = f"findings.json item {index} is not an object"
+ raise FindingError(msg)
+ numbered = f"F{index + 1}"
+ finding_id = text_field(raw, "id", numbered) or numbered
+ if not FINDING_ID_RE.match(finding_id):
+ msg = f"finding id {finding_id!r} is not a valid id"
+ raise FindingError(msg)
+
+ severity = str(raw.get("severity", "")).strip().upper()
+ if severity not in SEVERITIES:
+ msg = (
+ f"finding {finding_id} severity {raw.get('severity')!r} is not one of "
+ f"{'/'.join(SEVERITIES)}"
+ )
+ raise FindingError(msg)
+
+ confidence = confidence_value(raw.get("confidence"))
+ ceiling = vote_confidence_ceiling(rounds_by_id.get(finding_id))
+ if ceiling is not None and CONFIDENCE_RANK[confidence] > CONFIDENCE_RANK[ceiling]:
+ confidence = ceiling
+
+ line = raw.get("line", 0)
+ if is_str(line) and re.fullmatch(r"\s*-?[0-9]{1,15}\s*", line):
+ line = int(line)
+ if not is_int(line):
+ msg = f"finding {finding_id} line {raw.get('line')!r} is not an integer"
+ raise FindingError(msg)
+
+ preconditions: list[str] = []
+ declared = raw.get("preconditions")
+ if declared is not None:
+ if not is_list(declared):
+ msg = f"finding {finding_id} preconditions must be a list"
+ raise FindingError(msg)
+ preconditions = [item for item in declared if is_str(item)]
+ if len(preconditions) != len(declared) or any(map(has_lone_surrogate, preconditions)):
+ msg = f"finding {finding_id} preconditions must be a list of strings"
+ raise FindingError(msg)
+
+ number = cwe_number(raw, finding_id)
+ category = cwe.catalog.category(number)
+
+ return {
+ "id": finding_id,
+ "title": text_field(raw, "title", finding_id, required=True),
+ "impact": text_field(raw, "impact", finding_id),
+ "file": file_field(raw, finding_id, scan_root, scan_prefix, must_exist),
+ "line": line,
+ "description": text_field(raw, "description", finding_id, required=True),
+ "exploit_scenario": text_field(raw, "exploit_scenario", finding_id, required=True),
+ "preconditions": preconditions,
+ "category": category.name if category is not None else cwe.UNCATEGORIZED,
+ "severity": severity,
+ "confidence": confidence,
+ "recommendation": text_field(raw, "recommendation", finding_id),
+ "cwe_id": f"CWE-{number}",
+ "snippet": text_field(raw, "snippet", finding_id),
+ "symbol": text_field(raw, "symbol", finding_id),
+ }
diff --git a/plugins/claude-security/scripts/lib/plugin.py b/plugins/claude-security/scripts/lib/plugin.py
new file mode 100644
index 00000000..c5daa153
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/plugin.py
@@ -0,0 +1,31 @@
+"""The plugin's fixed names, and its own manifest."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from . import strictjson
+from .strictjson import is_map, is_str
+
+NAME = "claude-security"
+ROOT = Path(__file__).resolve().parents[2]
+RUN_DIR_NAME = ".claude-security-run"
+MODES = ("scan", "changes", "commit")
+REPORT_DIR_PREFIX = "CLAUDE-SECURITY-"
+# \Z, not $: `$` also matches before a trailing newline, and this id names product files.
+SHA_RE = re.compile(r"^[0-9a-fA-F]{7,64}\Z")
+
+
+def version() -> str | None:
+ """The non-blank version string in the plugin's manifest, or None when there is not one."""
+ try:
+ manifest = strictjson.load(ROOT / ".claude-plugin" / "plugin.json")
+ except (OSError, ValueError):
+ return None
+ if not is_map(manifest):
+ return None
+ declared = manifest.get("version")
+ if not is_str(declared):
+ return None
+ return declared.strip() or None
diff --git a/plugins/claude-security/scripts/lib/sarif.py b/plugins/claude-security/scripts/lib/sarif.py
new file mode 100644
index 00000000..f30d0afa
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/sarif.py
@@ -0,0 +1,373 @@
+"""SARIF 2.1.0 for one scan: the log encoder."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import posixpath
+import re
+from bisect import bisect_right
+from dataclasses import dataclass
+from itertools import accumulate
+from typing import TYPE_CHECKING, NamedTuple
+from urllib.parse import quote
+
+from . import cwe, secret
+
+if TYPE_CHECKING:
+ import uuid
+ from collections.abc import Mapping, Sequence
+
+ from .finding import Finding, Panel
+
+SCHEMA_ID = (
+ "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"
+)
+# The driver name GitHub keys alert identity on; renaming it orphans every open alert.
+TOOL_NAME = "Claude Security Plugin for Claude Code"
+TOOL_URI = "https://claude.com/product/claude-security"
+PROPERTY_BAG = "claudeSecurityPlugin"
+ID_PREFIX = "claude-security-plugin"
+FINGERPRINT_KEY = ID_PREFIX + "/v2"
+CONTEXT_LINES = 3
+SRCROOT = "%SRCROOT%"
+LEVEL = {"HIGH": "error", "MEDIUM": "warning", "LOW": "note"}
+
+
+@dataclass(frozen=True)
+class Scan:
+ """The one scan a log describes: its identity, where it ran, and the repository it names."""
+
+ id: uuid.UUID
+ mode: str
+ # The scan root below the repository top level, slash-terminated; "" when there is none.
+ prefix: str
+ # The credential-free https form of the repository's remote; None when there is not one.
+ remote: str | None
+ # The directories the scan was limited to, relative to the scan root; empty for all of it.
+ scope: tuple[str, ...]
+ # The commit the scanned tree was exactly at; None when it was dirty, unversioned or unknown.
+ revision: str | None
+
+
+def log(
+ findings: Sequence[Finding],
+ scan: Scan,
+ tool_version: str | None,
+ run_properties: Mapping[str, object],
+ panels: Mapping[str, Panel],
+ sources: Mapping[str, str],
+ notifications: Sequence[Mapping[str, object]],
+) -> dict[str, object]:
+ """The SARIF 2.1.0 log for one scan: one run, one rule per category, one result per finding.
+
+ `sources` is the text of each scanned file a finding names, keyed by the
+ finding's `file`; a finding whose file is absent from it is fingerprinted
+ on its own quote of the code instead.
+ """
+ filed = [(item, category_of(item)) for item in findings]
+ categories = list(dict.fromkeys(category for _, category in filed))
+ index = {category: position for position, category in enumerate(categories)}
+ driver: dict[str, object] = {
+ "name": TOOL_NAME,
+ "organization": "Anthropic",
+ "informationUri": TOOL_URI,
+ **({"version": tool_version} if tool_version else {}),
+ "rules": [rule(category) for category in categories],
+ }
+ invocation: dict[str, object] = {"executionSuccessful": True}
+ if notifications:
+ invocation["toolExecutionNotifications"] = list(notifications)
+ base_description = (
+ "The top level of the scanned repository, or the scanned directory when the scan did "
+ "not run inside a git checkout."
+ )
+ run: dict[str, object] = {
+ "tool": {"driver": driver},
+ "automationDetails": {"id": automation_id(scan), "guid": str(scan.id)},
+ "invocations": [invocation],
+ "originalUriBaseIds": {SRCROOT: {"description": {"text": base_description}}},
+ "results": [
+ result(
+ item,
+ category,
+ index[category],
+ scan,
+ panels.get(item["id"]),
+ sources.get(item["file"]),
+ )
+ for item, category in filed
+ ],
+ "properties": {
+ PROPERTY_BAG: {
+ **run_properties,
+ "target_kind": "git-remote" if scan.remote else "local-path",
+ }
+ },
+ }
+ if scan.remote:
+ provenance: dict[str, object] = {"repositoryUri": scan.remote}
+ if scan.revision:
+ provenance["revisionId"] = scan.revision
+ run["versionControlProvenance"] = [provenance]
+ return {"$schema": SCHEMA_ID, "version": "2.1.0", "runs": [run]}
+
+
+def automation_id(scan: Scan) -> str:
+ """The run's automation id: the plugin prefix, the mode, the scan's extent if any, its id."""
+ category = f"{ID_PREFIX}/{scan.mode}"
+ if scan.scope:
+ extent = ",".join(scan.prefix + entry.strip("/") for entry in sorted(scan.scope))
+ else:
+ extent = scan.prefix.rstrip("/")
+ if extent:
+ category += "/" + quote(uri_bytes(extent))
+ return f"{category}/{scan.id}"
+
+
+def category_of(finding: Finding) -> cwe.Category | None:
+ """The Simplified Mapping entry the finding's CWE rolls up to; None for Uncategorized."""
+ return cwe.catalog.category(cwe.id_number(finding["cwe_id"]))
+
+
+def rule_id(category: cwe.Category | None) -> str:
+ """A rule's id: its entry's CWE id (`CWE-89`), or `uncategorized`."""
+ return category.id if category is not None else cwe.UNCATEGORIZED.lower()
+
+
+def rule(category: cwe.Category | None) -> dict[str, object]:
+ """The reporting descriptor for one entry: the catalog's names, its page, its fixed tags."""
+ help_text = (
+ "Each alert's message names the finding's own CWE and states the impact, exploit "
+ "scenario, preconditions and recommended fix; the finding appears under its F<n> id "
+ "in CLAUDE-SECURITY-RESULTS.md."
+ )
+ if category is None:
+ return {
+ "id": rule_id(None),
+ "name": cwe.UNCATEGORIZED,
+ "shortDescription": {"text": cwe.UNCATEGORIZED},
+ "fullDescription": {
+ "text": "Findings whose CWE is not an entry of the CWE Simplified Mapping view "
+ f"and rolls up to none, reported by {TOOL_NAME} from static review of the "
+ "source."
+ },
+ "help": {"text": help_text},
+ "properties": {"tags": ["security"]},
+ }
+ return {
+ "id": category.id,
+ "name": rule_name(category.name),
+ "shortDescription": {"text": category.name},
+ "fullDescription": {
+ "text": f"{category.title} ({category.id}, CWE {cwe.catalog.version}): findings whose "
+ f"CWE is this entry of the Simplified Mapping view or rolls up to it, reported by "
+ f"{TOOL_NAME} from static review of the source."
+ },
+ "help": {"text": help_text},
+ "helpUri": f"https://cwe.mitre.org/data/definitions/{category.number}.html",
+ "properties": {"tags": ["security", f"external/cwe/cwe-{category.number}"]},
+ }
+
+
+def fingerprint(
+ finding: Finding, category: cwe.Category | None, scan: Scan, source: str | None
+) -> str:
+ """The finding's partial fingerprint: a sha256 over its rule, its path and the code it names.
+
+ `source` is the text of the finding's file. The code is the file's own
+ lines around the one that places the finding (see code_at); when the file
+ was not read, or no line of it places the finding, the finding's symbol
+ and snippet stand in for them, and the line when it has neither. A
+ hard-coded credential finding is the exception: its symbol and the number
+ of the line that places it stand in for the code always, so no text of a
+ file that holds a credential enters the hash.
+ """
+ parts = [scan.remote or "", rule_id(category), repository_path(scan, finding)]
+ symbol = finding["symbol"].strip()
+ snippet = quoted_line(finding)
+ if secret.is_credential(finding):
+ lines = None if source is None else normalized_lines(source)
+ placed = None if lines is None else placing_row(lines, finding["line"], snippet)
+ parts += [symbol, str(finding["line"] if placed is None else placed + 1)]
+ return hashlib.sha256(json.dumps(parts).encode()).hexdigest()
+ code = None if source is None else code_at(source, finding["line"], snippet)
+ if code is not None:
+ parts.append(code)
+ else:
+ parts += [symbol, snippet]
+ if not symbol and not snippet:
+ parts.append(str(finding["line"]))
+ return hashlib.sha256(json.dumps(parts).encode()).hexdigest()
+
+
+class Site(NamedTuple):
+ """What one result stands for: a rule at a line of a file; the log holds one result per site."""
+
+ rule: str
+ path: str
+ line: int
+
+
+def site(finding: Finding, scan: Scan, source: str | None) -> Site | None:
+ """The finding's site: its rule id, its repository path, and the line that places it.
+
+ The line is the one of `source`, the finding's file, that places the
+ finding (placing_row), so two findings that quote one line of code are one
+ site whatever lines they declare; it is the declared line when the file
+ was not read or no line of it places the finding. A finding left with no
+ line (it declared none, line < 1, and none places it) has no site: None.
+ """
+ line = finding["line"]
+ if source is not None:
+ row = placing_row(normalized_lines(source), line, quoted_line(finding))
+ if row is not None:
+ line = row + 1
+ if line < 1:
+ return None
+ return Site(rule_id(category_of(finding)), repository_path(scan, finding), line)
+
+
+def quoted_line(finding: Finding) -> str:
+ """The finding's snippet with its whitespace normalized, the form placing_row looks for."""
+ return " ".join(finding["snippet"].split())
+
+
+def normalized_lines(source: str) -> list[str]:
+ """A file's lines, split on the newline alone, each with its whitespace normalized."""
+ return [" ".join(each.split()) for each in source.split("\n")]
+
+
+def placing_row(lines: Sequence[str], line: int, quoted: str) -> int | None:
+ """The index into the normalized `lines` of the one placing a finding; None when none does.
+
+ The finding is placed on the line nearest its declared `line` where
+ `quoted`, its normalized snippet, appears, whitespace aside, and on the
+ declared line itself when it appears nowhere.
+ """
+ declared = line - 1
+ at = min(
+ (min(max(declared, first), last) for first, last in occurrences(lines, quoted)),
+ key=lambda row: abs(row - declared),
+ default=declared,
+ )
+ return at if 0 <= at < len(lines) else None
+
+
+def code_at(source: str, line: int, quoted: str) -> str | None:
+ """The normalized lines of `source` around the one placing a finding; None when none does."""
+ lines = normalized_lines(source)
+ at = placing_row(lines, line, quoted)
+ if at is None:
+ return None
+ return "\n".join(lines[max(at - CONTEXT_LINES, 0) : at + CONTEXT_LINES + 1])
+
+
+def occurrences(lines: Sequence[str], quoted: str) -> list[tuple[int, int]]:
+ """The (first, last) index into the normalized `lines` of each occurrence of `quoted`."""
+ if not quoted:
+ return []
+ filled = [row for row, line in enumerate(lines) if line]
+ starts = list(accumulate((len(lines[row]) + 1 for row in filled), initial=0))
+ flat = " ".join(lines[row] for row in filled)
+
+ def row_at(offset: int) -> int:
+ return filled[bisect_right(starts, offset) - 1]
+
+ return [
+ (row_at(found.start()), row_at(found.end() - 1))
+ for found in re.finditer(re.escape(quoted), flat)
+ ]
+
+
+def result(
+ finding: Finding,
+ category: cwe.Category | None,
+ rule_index: int,
+ scan: Scan,
+ panel: Panel | None,
+ source: str | None,
+) -> dict[str, object]:
+ """One result: the finding under its rule, its partial fingerprint, and its JSONL record."""
+ shown = secret.withheld(finding)
+ record: dict[str, object] = {**shown}
+ if panel is not None:
+ record["verification"] = {"panel": panel}
+ return {
+ "ruleId": rule_id(category),
+ "ruleIndex": rule_index,
+ "level": LEVEL[finding["severity"]],
+ "message": {"text": message(finding)},
+ "locations": [location(shown, scan)],
+ "partialFingerprints": {FINGERPRINT_KEY: fingerprint(finding, category, scan, source)},
+ "properties": {PROPERTY_BAG: record},
+ }
+
+
+def location(finding: Finding, scan: Scan) -> dict[str, object]:
+ """A result's one location: the file relative to SRCROOT, the line, the snippet, the symbol."""
+ line = finding["line"]
+ region: dict[str, object] = {"startLine": max(line, 1)}
+ if line >= 1 and finding["snippet"].strip():
+ region["snippet"] = {"text": finding["snippet"]}
+ place: dict[str, object] = {
+ "physicalLocation": {
+ "artifactLocation": {
+ "uri": quote(uri_bytes(repository_path(scan, finding))),
+ "uriBaseId": SRCROOT,
+ },
+ "region": region,
+ }
+ }
+ if symbol := finding["symbol"].strip():
+ place["logicalLocations"] = [{"name": symbol, "fullyQualifiedName": symbol}]
+ return place
+
+
+def repository_path(scan: Scan, finding: Finding) -> str:
+ """The finding's file relative to the repository top level, with any leading climb folded."""
+ return posixpath.normpath(scan.prefix + finding["file"])
+
+
+def uri_bytes(text: str) -> bytes:
+ """`text` as the bytes its uri must name; byte-faithful for a filesystem name."""
+ try:
+ return text.encode("utf-8", "surrogateescape")
+ except UnicodeEncodeError:
+ return text.encode("utf-8", "surrogatepass")
+
+
+def notification(descriptor_id: str, level: str, text: str) -> dict[str, object]:
+ """One invocation notification: its namespaced descriptor id, its level, and its message."""
+ return {"descriptor": {"id": descriptor_id}, "level": level, "message": {"text": text}}
+
+
+def message(finding: Finding) -> str:
+ """A result's message: the finding's prose, its stated parts labeled, then its ratings."""
+ parts = [sentence(finding["title"]), sentence(finding["description"])]
+ labeled = (
+ ("Impact", finding["impact"]),
+ ("Exploit scenario", finding["exploit_scenario"]),
+ ("Preconditions", "; ".join(finding["preconditions"])),
+ ("Recommendation", finding["recommendation"]),
+ )
+ parts += [f"{label}: {text}" for label, value in labeled if (text := sentence(value))]
+ if finding["line"] < 1:
+ parts.append("The exact line was not determined; see the description.")
+ if secret.is_credential(finding):
+ parts.append("The source line is not quoted because it holds the credential.")
+ parts.append(
+ f"{finding['cwe_id']}. Severity {finding['severity']}, confidence {finding['confidence']}."
+ )
+ return "\n\n".join(parts)
+
+
+def rule_name(category: str) -> str:
+ """A category's common name in PascalCase, for a rule name: `SQLInjection`."""
+ return "".join(word[:1].upper() + word[1:] for word in re.split(r"[^A-Za-z0-9]+", category))
+
+
+def sentence(text: str) -> str:
+ """`text` stripped and closed with a period unless it already ends in punctuation."""
+ text = text.strip()
+ return text if not text or text[-1] in ".!?" else text + "."
diff --git a/plugins/claude-security/scripts/lib/secret.py b/plugins/claude-security/scripts/lib/secret.py
new file mode 100644
index 00000000..9bf90a3a
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/secret.py
@@ -0,0 +1,32 @@
+"""The snippet of a hard-coded credential finding, withheld from what the products carry.
+
+The line such a finding quotes is the credential itself, and the JSONL and
+SARIF files exist to leave the machine (a code scanning upload, a CI
+artifact), so neither file quotes it: the finding's file, line and symbol
+still locate the code, and the SARIF result's message says why no line is
+quoted. Only the emitted copy changes: the finding is still placed on the
+snippet as the researcher quoted it, and its fingerprint hashes no text of
+the file (see sarif.fingerprint).
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from . import cwe
+
+if TYPE_CHECKING:
+ from .finding import Finding
+
+# CWE's Simplified Mapping entry Use of Hard-coded Credentials; CWE-259, 321 and 671 roll up to it.
+CREDENTIALS = 798
+
+
+def is_credential(finding: Finding) -> bool:
+ """Whether the finding's CWE rolls up to Use of Hard-coded Credentials."""
+ return cwe.catalog.category_of.get(cwe.id_number(finding["cwe_id"])) == CREDENTIALS
+
+
+def withheld(finding: Finding) -> Finding:
+ """`finding` as the products carry it: a hard-coded credential's snippet is empty."""
+ return {**finding, "snippet": ""} if is_credential(finding) else finding
diff --git a/plugins/claude-security/scripts/lib/strictjson.py b/plugins/claude-security/scripts/lib/strictjson.py
new file mode 100644
index 00000000..2c5a9900
--- /dev/null
+++ b/plugins/claude-security/scripts/lib/strictjson.py
@@ -0,0 +1,83 @@
+"""JSON in and out of the scripts, stricter than the json module in both directions.
+
+Input is model-written and output is read by other tools, so load() refuses
+what json.load admits but a conforming reader does not (NaN, Infinity, a
+number that overflows to infinity, nesting past the interpreter's limit), and
+text() keeps non-ASCII readable while escaping what UTF-8 or a JSONL line
+reader cannot take (an unpaired surrogate, the Unicode line separators).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, NoReturn, cast
+
+if TYPE_CHECKING:
+ import os
+ from typing import TypeGuard
+
+JsonMap = Mapping[str, object]
+
+# The separators a naive line reader would split a JSONL record on.
+_SEPARATOR_ESCAPES = {0x85: "\\u0085", 0x2028: "\\u2028", 0x2029: "\\u2029"}
+# The code units UTF-8 cannot encode; surrogateescape mints them from bytes.
+_SURROGATES = re.compile(r"[\ud800-\udfff]")
+
+
+def is_map(value: object) -> TypeGuard[JsonMap]:
+ """Whether `value` is a JSON object."""
+ return isinstance(value, dict)
+
+
+def is_list(value: object) -> TypeGuard[list[object]]:
+ """Whether `value` is a JSON array."""
+ return isinstance(value, list)
+
+
+def is_str(value: object) -> TypeGuard[str]:
+ """Whether `value` is a JSON string."""
+ return isinstance(value, str)
+
+
+def is_int(value: object) -> TypeGuard[int]:
+ """Whether `value` is a JSON integer; JSON's booleans are not numbers."""
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def has_lone_surrogate(value: str) -> bool:
+ """Whether `value` holds an unpaired surrogate, the one code unit UTF-8 cannot encode."""
+ return _SURROGATES.search(value) is not None
+
+
+def _refuse(token: str) -> NoReturn:
+ msg = f"{token} is not JSON"
+ raise ValueError(msg)
+
+
+def _finite(digits: str) -> float:
+ value = float(digits)
+ if not math.isfinite(value):
+ msg = f"{digits} is out of range"
+ raise ValueError(msg)
+ return value
+
+
+def load(path: str | os.PathLike[str]) -> object:
+ """The JSON value in `path`; OSError if unreadable, ValueError if not strict JSON."""
+ with open(path, encoding="utf-8") as handle:
+ try:
+ return cast("object", json.load(handle, parse_constant=_refuse, parse_float=_finite))
+ except RecursionError as error:
+ msg = "nested too deeply"
+ raise ValueError(msg) from error
+
+
+def text(value: object, indent: int | None = None) -> str:
+ """`value` as UTF-8-encodable JSON text: non-ASCII kept, finite only, separators escaped."""
+ dumped = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=indent)
+ return _SURROGATES.sub(
+ lambda match: f"\\u{ord(match.group()):04x}", dumped.translate(_SEPARATOR_ESCAPES)
+ )