driftlock-guard 0.1.1__py3-none-any.whl

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.
driftlock/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
driftlock/cli.py ADDED
@@ -0,0 +1,109 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+ from typing import List
6
+ from .schema import save_contract
7
+ from .differ import diff_payload_against_contract, DriftIssue
8
+ from .redact import redact_payload
9
+ from .license import verify_pro_license
10
+
11
+
12
+ def _load_json(filepath: str):
13
+ path = Path(filepath)
14
+ if not path.exists():
15
+ print(f"Error: File not found -> {filepath}", file=sys.stderr)
16
+ sys.exit(2)
17
+ with open(path, "r", encoding="utf-8") as f:
18
+ return json.load(f)
19
+
20
+
21
+ def _format_markdown(issues: List[DriftIssue]) -> str:
22
+ if not issues:
23
+ return "### DriftLock Report: Passed\nNo schema or type drift detected."
24
+ lines = [
25
+ "### DriftLock Schema Report",
26
+ "",
27
+ "| Severity | Path | Details |",
28
+ "| :--- | :--- | :--- |",
29
+ ]
30
+ for issue in issues:
31
+ badge = "BREAKING" if issue.severity == "BREAKING" else "NON-BREAKING"
32
+ lines.append(f"| **{badge}** | `{issue.path}` | {issue.message} |")
33
+ return "\n".join(lines)
34
+
35
+
36
+ def _require_pro(license_key: str | None) -> None:
37
+ ok, reason = verify_pro_license(license_key)
38
+ if not ok:
39
+ print(f"[DriftLock Pro Required] {reason}", file=sys.stderr)
40
+ print("Upgrade for Pro license key (redact + strict CI gating).", file=sys.stderr)
41
+ sys.exit(3)
42
+
43
+
44
+ def main() -> None:
45
+ parser = argparse.ArgumentParser(
46
+ prog="driftlock",
47
+ description="Lock webhook & API JSON contracts and catch breaking schema drift.",
48
+ )
49
+ subparsers = parser.add_subparsers(dest="command", required=True)
50
+
51
+ # snapshot (Free)
52
+ snap_p = subparsers.add_parser("snapshot", help="Generate a baseline contract from a JSON payload")
53
+ snap_p.add_argument("payload", help="Path to sample JSON payload")
54
+ snap_p.add_argument("-o", "--output", default="driftlock.contract.json", help="Output contract path")
55
+
56
+ # diff (Free core; --strict is Pro)
57
+ diff_p = subparsers.add_parser("diff", help="Check a payload against a locked contract")
58
+ diff_p.add_argument("contract", help="Path to locked contract JSON")
59
+ diff_p.add_argument("payload", help="Path to incoming JSON payload")
60
+ diff_p.add_argument("--markdown", action="store_true", help="Output GitHub PR Markdown table")
61
+ diff_p.add_argument("--strict", action="store_true", help="[Pro] Fail on non-breaking field additions too")
62
+ diff_p.add_argument("--license-key", default=None, help="DriftLock Pro license key")
63
+
64
+ # redact (Pro)
65
+ red_p = subparsers.add_parser("redact", help="[Pro] Mask secrets and PII in a JSON payload for safe Git commits")
66
+ red_p.add_argument("payload", help="Path to raw JSON payload")
67
+ red_p.add_argument("-o", "--output", required=True, help="Output sanitized JSON path")
68
+ red_p.add_argument("--license-key", default=None, help="DriftLock Pro license key")
69
+
70
+ args = parser.parse_args()
71
+
72
+ if args.command == "snapshot":
73
+ payload = _load_json(args.payload)
74
+ save_contract(payload, args.output)
75
+ print(f"[DriftLock] Contract locked -> {args.output}")
76
+
77
+ elif args.command == "diff":
78
+ if args.strict:
79
+ _require_pro(args.license_key)
80
+
81
+ contract = _load_json(args.contract)
82
+ payload = _load_json(args.payload)
83
+ issues = diff_payload_against_contract(contract, payload)
84
+
85
+ if args.markdown:
86
+ print(_format_markdown(issues))
87
+ else:
88
+ if not issues:
89
+ print("[DriftLock] OK - Payload matches locked contract.")
90
+ for issue in issues:
91
+ tag = "[BREAKING]" if issue.severity == "BREAKING" else "[INFO]"
92
+ print(f"{tag} {issue.path}: {issue.message}")
93
+
94
+ breaking_count = sum(1 for i in issues if i.severity == "BREAKING")
95
+ if breaking_count > 0 or (args.strict and len(issues) > 0):
96
+ sys.exit(1)
97
+ sys.exit(0)
98
+
99
+ elif args.command == "redact":
100
+ _require_pro(args.license_key)
101
+ payload = _load_json(args.payload)
102
+ clean = redact_payload(payload)
103
+ with open(args.output, "w", encoding="utf-8") as f:
104
+ json.dump(clean, f, indent=2)
105
+ print(f"[DriftLock] Sanitized fixture written -> {args.output}")
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
driftlock/differ.py ADDED
@@ -0,0 +1,82 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Dict, List
3
+ from .schema import infer_schema
4
+
5
+
6
+ @dataclass
7
+ class DriftIssue:
8
+ severity: str # "BREAKING" or "NON_BREAKING"
9
+ path: str
10
+ message: str
11
+
12
+
13
+ def _is_compatible_number(expected: str, actual: str) -> bool:
14
+ # Widening int -> float is usually safe; narrowing float -> int is breaking
15
+ return expected == "float" and actual == "int"
16
+
17
+
18
+ def compare_schemas(expected: Dict[str, Any], actual: Dict[str, Any], path: str = "$") -> List[DriftIssue]:
19
+ issues: List[DriftIssue] = []
20
+
21
+ exp_type = expected.get("type", "unknown")
22
+ act_type = actual.get("type", "unknown")
23
+ exp_nullable = expected.get("nullable", False)
24
+
25
+ # 1. Handle nullability drift
26
+ if act_type == "null":
27
+ if not exp_nullable and exp_type != "null":
28
+ issues.append(DriftIssue(
29
+ severity="BREAKING",
30
+ path=path,
31
+ message=f"Field became null (expected non-null '{exp_type}')"
32
+ ))
33
+ return issues
34
+
35
+ # 2. Type mismatch check
36
+ if exp_type != act_type and exp_type != "unknown":
37
+ if not _is_compatible_number(exp_type, act_type):
38
+ issues.append(DriftIssue(
39
+ severity="BREAKING",
40
+ path=path,
41
+ message=f"Type changed from '{exp_type}' to '{act_type}'"
42
+ ))
43
+ return issues
44
+
45
+ # 3. Recurse into objects
46
+ if exp_type == "object" and act_type == "object":
47
+ exp_props = expected.get("properties", {})
48
+ act_props = actual.get("properties", {})
49
+
50
+ for key, exp_child in exp_props.items():
51
+ child_path = f"{path}.{key}"
52
+ if key not in act_props:
53
+ issues.append(DriftIssue(
54
+ severity="BREAKING",
55
+ path=child_path,
56
+ message="Required field missing from payload"
57
+ ))
58
+ else:
59
+ issues.extend(compare_schemas(exp_child, act_props[key], child_path))
60
+
61
+ for key in act_props:
62
+ if key not in exp_props:
63
+ issues.append(DriftIssue(
64
+ severity="NON_BREAKING",
65
+ path=f"{path}.{key}",
66
+ message=f"New field added (type: '{act_props[key].get('type')}')"
67
+ ))
68
+
69
+ # 4. Recurse into lists
70
+ elif exp_type == "list" and act_type == "list":
71
+ exp_items = expected.get("items", {})
72
+ act_items = actual.get("items", {})
73
+ if act_items.get("type") != "unknown":
74
+ issues.extend(compare_schemas(exp_items, act_items, f"{path}[]"))
75
+
76
+ return issues
77
+
78
+
79
+ def diff_payload_against_contract(contract_doc: Dict[str, Any], incoming_payload: Any) -> List[DriftIssue]:
80
+ expected_contract = contract_doc.get("contract", contract_doc)
81
+ actual_contract = infer_schema(incoming_payload)
82
+ return compare_schemas(expected_contract, actual_contract)
driftlock/license.py ADDED
@@ -0,0 +1,80 @@
1
+ import json
2
+ import os
3
+ import time
4
+ import urllib.parse
5
+ import urllib.request
6
+ from pathlib import Path
7
+ from typing import Optional, Tuple
8
+
9
+ GUMROAD_VERIFY_URL = "https://api.gumroad.com/v2/licenses/verify"
10
+ CACHE_TTL_SECONDS = 24 * 60 * 60 # 24 hours
11
+
12
+
13
+ def _cache_path() -> Path:
14
+ return Path.home() / ".driftlock" / "license.json"
15
+
16
+
17
+ def _load_cached_key(license_key: str) -> bool:
18
+ path = _cache_path()
19
+ if not path.exists():
20
+ return False
21
+ try:
22
+ data = json.loads(path.read_text(encoding="utf-8"))
23
+ if data.get("license_key") == license_key:
24
+ if time.time() - data.get("verified_at", 0) < CACHE_TTL_SECONDS:
25
+ return True
26
+ except Exception:
27
+ return False
28
+ return False
29
+
30
+
31
+ def _save_cached_key(license_key: str) -> None:
32
+ path = _cache_path()
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ path.write_text(
35
+ json.dumps({"license_key": license_key, "verified_at": time.time()}),
36
+ encoding="utf-8",
37
+ )
38
+
39
+
40
+ def verify_pro_license(license_key: Optional[str] = None) -> Tuple[bool, str]:
41
+ if os.environ.get("DRIFTLOCK_DEV_BYPASS") == "1":
42
+ return True, "Dev bypass active"
43
+
44
+ key = (license_key or os.environ.get("DRIFTLOCK_LICENSE_KEY") or "").strip()
45
+ product_id = os.environ.get("DRIFTLOCK_GUMROAD_PRODUCT_ID", "").strip()
46
+
47
+ if not key:
48
+ return False, "Missing license key. Set DRIFTLOCK_LICENSE_KEY or pass --license-key."
49
+
50
+ if _load_cached_key(key):
51
+ return True, "Verified (cached)"
52
+
53
+ if not product_id:
54
+ return False, "Missing DRIFTLOCK_GUMROAD_PRODUCT_ID for live verification."
55
+
56
+ payload = urllib.parse.urlencode({
57
+ "product_id": product_id,
58
+ "license_key": key,
59
+ "increment_uses_count": "false",
60
+ }).encode("utf-8")
61
+
62
+ req = urllib.request.Request(
63
+ GUMROAD_VERIFY_URL,
64
+ data=payload,
65
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
66
+ method="POST",
67
+ )
68
+
69
+ try:
70
+ with urllib.request.urlopen(req, timeout=10) as resp:
71
+ body = json.loads(resp.read().decode("utf-8"))
72
+ except Exception as exc:
73
+ return False, f"License server unreachable: {exc}"
74
+
75
+ purchase = body.get("purchase") or {}
76
+ if body.get("success") and not purchase.get("refunded") and not purchase.get("chargebacked"):
77
+ _save_cached_key(key)
78
+ return True, "Verified via Gumroad"
79
+
80
+ return False, body.get("message", "Invalid or inactive license key.")
driftlock/redact.py ADDED
@@ -0,0 +1,23 @@
1
+ import re
2
+ from typing import Any
3
+
4
+ SENSITIVE_KEY_PATTERN = re.compile(
5
+ r"(token|secret|password|passwd|api_?key|auth|bearer|signature|ssn|card|cvv|iban)",
6
+ re.IGNORECASE,
7
+ )
8
+ EMAIL_PATTERN = re.compile(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+")
9
+
10
+
11
+ def redact_payload(data: Any, key_name: str = "") -> Any:
12
+ if isinstance(data, dict):
13
+ return {k: redact_payload(v, k) for k, v in data.items()}
14
+ if isinstance(data, list):
15
+ return [redact_payload(item, key_name) for item in data]
16
+ if isinstance(data, str):
17
+ if key_name and SENSITIVE_KEY_PATTERN.search(key_name):
18
+ return "[REDACTED_SECRET]"
19
+ if EMAIL_PATTERN.fullmatch(data.strip()):
20
+ return "[REDACTED_EMAIL]"
21
+ if data.startswith(("sk_live_", "sk_test_", "whsec_", "ghp_", "eyJ")):
22
+ return "[REDACTED_TOKEN]"
23
+ return data
driftlock/schema.py ADDED
@@ -0,0 +1,78 @@
1
+ import json
2
+ from typing import Any, Dict
3
+
4
+
5
+ def _infer_type(value: Any) -> str:
6
+ if value is None:
7
+ return "null"
8
+ if isinstance(value, bool):
9
+ return "bool"
10
+ if isinstance(value, int):
11
+ return "int"
12
+ if isinstance(value, float):
13
+ return "float"
14
+ if isinstance(value, str):
15
+ return "str"
16
+ if isinstance(value, list):
17
+ return "list"
18
+ if isinstance(value, dict):
19
+ return "object"
20
+ return "unknown"
21
+
22
+
23
+ def infer_schema(data: Any) -> Dict[str, Any]:
24
+ """Recursively infers a DriftLock JSON contract from a sample payload."""
25
+ dtype = _infer_type(data)
26
+
27
+ if dtype == "object":
28
+ properties = {}
29
+ for key, val in sorted(data.items()):
30
+ properties[key] = infer_schema(val)
31
+ return {
32
+ "type": "object",
33
+ "nullable": False,
34
+ "properties": properties,
35
+ }
36
+
37
+ if dtype == "list":
38
+ if not data:
39
+ return {"type": "list", "nullable": False, "items": {"type": "unknown", "nullable": True}}
40
+ # Infer item contract from the first non-null element, or merge object keys across items
41
+ first_non_null = next((item for item in data if item is not None), None)
42
+ if first_non_null is None:
43
+ return {"type": "list", "nullable": False, "items": {"type": "null", "nullable": True}}
44
+
45
+ item_schema = infer_schema(first_non_null)
46
+ if item_schema["type"] == "object":
47
+ merged_props = dict(item_schema["properties"])
48
+ for item in data[1:]:
49
+ if isinstance(item, dict):
50
+ sub = infer_schema(item)["properties"]
51
+ for k, v in sub.items():
52
+ if k not in merged_props:
53
+ v["nullable"] = True
54
+ merged_props[k] = v
55
+ elif merged_props[k]["type"] == "null" and v["type"] != "null":
56
+ v["nullable"] = True
57
+ merged_props[k] = v
58
+ item_schema["properties"] = merged_props
59
+
60
+ return {
61
+ "type": "list",
62
+ "nullable": False,
63
+ "items": item_schema,
64
+ }
65
+
66
+ return {
67
+ "type": dtype,
68
+ "nullable": dtype == "null",
69
+ }
70
+
71
+
72
+ def save_contract(payload: Any, output_path: str) -> None:
73
+ contract = {
74
+ "driftlock_version": "1.0",
75
+ "contract": infer_schema(payload),
76
+ }
77
+ with open(output_path, "w", encoding="utf-8") as f:
78
+ json.dump(contract, f, indent=2)
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: driftlock-guard
3
+ Version: 0.1.1
4
+ Summary: Zero-dependency CLI & GitHub Action to catch breaking webhook and API JSON schema drift.
5
+ Author-email: DriftLock <driftlock.dev@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # DriftLock
13
+
14
+ **Lock webhook & API JSON contracts and catch breaking schema drift before it breaks production.**
15
+
16
+ Zero dependencies. Runs locally on any machine or directly inside GitHub Actions CI.
17
+
18
+ ## Quick Start
19
+
20
+ ```bash
21
+ pip install driftlock
22
+ driftlock snapshot examples/stripe_v1.json -o driftlock.contract.json
23
+ driftlock diff driftlock.contract.json examples/stripe_v2_drifted.json
24
+ ```
25
+
26
+ Contact: driftlock.dev@gmail.com
@@ -0,0 +1,12 @@
1
+ driftlock/__init__.py,sha256=Pru0BlFBASFCFo7McHdohtKkUtgMPDwbGfyUZlE2_Vw,21
2
+ driftlock/cli.py,sha256=_dtjKqBowyWIrtXGZ3Io8YvNEfRBLsnlFkOhkAu-zIo,4238
3
+ driftlock/differ.py,sha256=bPv_Vuj8UGb9oAyHcBXliATG98-1bQxKUBqn-pHwC2s,2920
4
+ driftlock/license.py,sha256=siacYFysRXgvZp9zN3qUp2Lv489vVKtijjhcscN_jqA,2480
5
+ driftlock/redact.py,sha256=BZpDLhgd3-lgXjgjwt6_JMu3rlh9C9n6z9XtycjX7m4,863
6
+ driftlock/schema.py,sha256=-mza0RLaNUAWbOI8H0oH8UzjBNLw4arQ0_hNuCfc_lk,2539
7
+ driftlock_guard-0.1.1.dist-info/licenses/LICENSE,sha256=3b9PWoMg2ZK1jAQYZcke91uzJsYYaqEcUpLnWrX8sDY,1069
8
+ driftlock_guard-0.1.1.dist-info/METADATA,sha256=nmf1QYmxkPe97A1KO1mtkhvIwIAK7ijekBbqdLV3K04,755
9
+ driftlock_guard-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ driftlock_guard-0.1.1.dist-info/entry_points.txt,sha256=KxJDpSicB9DZQnWzAEwKCInvrLKpoWxfJfkbbS2EodM,49
11
+ driftlock_guard-0.1.1.dist-info/top_level.txt,sha256=Gkivj7dorPj7RNXPBFHZNTCp5PH555yIbVbhO3kav8E,10
12
+ driftlock_guard-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ driftlock = driftlock.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DriftLock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ driftlock