#!/usr/bin/env python3 """Independently check existing Angry Porter JSONL exports; no app imports or network.""" import argparse import hashlib import json import re import sys import tempfile class InvalidExport(ValueError): pass def require(condition, message): if not condition: raise InvalidExport(message) def unique_object(pairs): result = {} for key, value in pairs: require(key not in result, "duplicate JSON key") result[key] = value return result def reject_number(_): raise InvalidExport("non-integer JSON number") DECODER = json.JSONDecoder( object_pairs_hook=unique_object, parse_float=reject_number, parse_constant=reject_number ) HASH = re.compile(r"[0-9a-f]{64}\Z") def canonical(value): # Valid Unicode code point order and UTF-8 byte order agree. Python uses the # same control-character escapes as Event.canonicalJSON; '/' stays literal. return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8") def sequence(value): require(type(value) is int and 0 <= value <= 2**63 - 1, "invalid sequence") return value def digest(value): require(isinstance(value, str) and HASH.fullmatch(value), "invalid hash") return value def verify(source, checkpoint=None, replay=None): """Replay receives bytes only; callers must release them after this succeeds. Hash validation covers exact event bytes, not the complete Swift payload schema. A rollup is an untrusted boundary assertion, never proof of expired contents. """ previous = None first_sequence = None first_previous = None last_sequence = None events = rollups = ignored = 0 boundary_matches = 0 checkpoint_seen = False for line_number, raw in enumerate(source, 1): try: require(raw.endswith(b"\n"), "missing final newline") text = raw[:-1].decode("utf-8") item = DECODER.decode(text) require(isinstance(item, dict), "line is not an object") kind = item.get("kind") require(isinstance(kind, str), "missing line kind") if kind == "event": require(rollups == 0, "event follows rollup") require(set(item) == {"event", "hash", "kind", "previousHash", "sequence"}, "event envelope keys") current_sequence = sequence(item["sequence"]) current_hash = digest(item["hash"]) before = item["previousHash"] require(before == "genesis" or isinstance(before, str) and HASH.fullmatch(before), "invalid previous hash") require(text.startswith('{"event":'), "event must be first in canonical envelope") event, end = DECODER.raw_decode(text, len('{"event":')) require(isinstance(event, dict), "event is not an object") event_bytes = text[len('{"event":'):end].encode("utf-8") require(event_bytes == canonical(event), "noncanonical event bytes") expected = hashlib.sha256(before.encode("ascii") + b"\n" + str(current_sequence).encode("ascii") + b"\n" + event_bytes).hexdigest() require(current_hash == expected, "event hash mismatch") if last_sequence is None: first_sequence, first_previous = current_sequence, before require(current_sequence != 0 or before == "genesis", "invalid genesis") else: require(current_sequence == last_sequence + 1, "sequence gap or reorder") require(before == previous, "broken link") if checkpoint and current_sequence == checkpoint[0]: require(current_hash == checkpoint[1], "trusted checkpoint mismatch") checkpoint_seen = True previous, last_sequence = current_hash, current_sequence events += 1 if replay is not None: replay.write(event_bytes + b"\n") elif kind == "rollup": replaced = sequence(item.get("lastReplacedSequence")) replaced_hash = digest(item.get("lastReplacedHash")) require(last_sequence is None or replaced < first_sequence, "rollup overlaps retained events") if first_sequence is not None and replaced == first_sequence - 1: require(replaced_hash == first_previous, "rollup boundary mismatch") boundary_matches += 1 rollups += 1 else: # ADR-0004 asks readers to ignore future line kinds. Report the # resulting incomplete coverage explicitly instead of blessing it. ignored += 1 except (ValueError, TypeError, KeyError, UnicodeError, RecursionError) as error: # Do not include payload values or decoder excerpts in diagnostics. reason = str(error) if isinstance(error, InvalidExport) else "invalid JSON or field type" raise InvalidExport(f"line {line_number}: {reason}") from None if first_sequence is not None and first_sequence > 0: require(boundary_matches == 1, "missing or ambiguous retention boundary") if checkpoint: require(checkpoint_seen, "trusted checkpoint absent (truncation, rollback, or expired record)") return { "status": "partial" if rollups or ignored else "internally-consistent", "events": events, "rollups": rollups, "ignoredLines": ignored, "firstSequence": first_sequence, "lastSequence": last_sequence, "lastHash": previous, "checkpointMatched": checkpoint_seen, "authenticityProven": False, "rollupContentsAuthenticated": False, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("export", help="local JSONL file; opened read-only") parser.add_argument("--checkpoint", nargs=2, metavar=("SEQUENCE", "HASH"), help="previously trusted event head; must still be present") parser.add_argument("--replay", action="store_true", help="emit verified event JSONL in append order; never execute recorded tools") args = parser.parse_args() try: checkpoint = None if args.checkpoint: checkpoint = (sequence(int(args.checkpoint[0])), digest(args.checkpoint[1])) # Stage replay until the ENTIRE file and checkpoint have been checked. # This also avoids a second read of an input someone might replace. with open(args.export, "rb") as source, tempfile.TemporaryFile() as staged: result = verify(source, checkpoint, staged if args.replay else None) print(json.dumps(result, sort_keys=True), file=sys.stderr if args.replay else sys.stdout) if args.replay: staged.seek(0) while chunk := staged.read(65536): sys.stdout.buffer.write(chunk) return 3 if result["status"] == "partial" else 0 except (OSError, ValueError, OverflowError) as error: reason = str(error) if isinstance(error, InvalidExport) else "cannot read export or invalid checkpoint" print(f"Verification failed: {reason}", file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())