#!/usr/bin/env python3 """Encode reference lists using BrowseComp's SHA-256/XOR/Base64 algorithm.""" from __future__ import annotations import argparse import base64 import hashlib import json import sys from pathlib import Path ALGORITHM = "browsecomp-sha256-xor-base64" def derive_key(password: str, length: int) -> bytes: digest = hashlib.sha256(password.encode("utf-8")).digest() return digest * (length // len(digest)) + digest[: length % len(digest)] def encrypt(plaintext: str, password: str) -> str: raw = plaintext.encode("utf-8") encrypted = bytes(a ^ b for a, b in zip(raw, derive_key(password, len(raw)))) return base64.b64encode(encrypted).decode("ascii") def decrypt(ciphertext_b64: str, password: str) -> str: encrypted = base64.b64decode(ciphertext_b64, validate=True) plaintext = bytes( a ^ b for a, b in zip(encrypted, derive_key(password, len(encrypted))) ) return plaintext.decode("utf-8") def validate_answers(value: object) -> list[str]: if ( not isinstance(value, list) or not value or any(not isinstance(item, str) or not item.strip() for item in value) ): raise ValueError("Accepted answers must be a non-empty list of non-empty strings") return value def encode_answers(answers: list[str], canary: str) -> str: serialized = json.dumps( validate_answers(answers), ensure_ascii=False, separators=(",", ":") ) return encrypt(serialized, canary) def decode_answers(record: dict) -> list[str]: if record["answer_encoding"] != ALGORITHM: raise ValueError(f"Unsupported answer encoding {record['answer_encoding']!r}") return validate_answers(json.loads(decrypt(record["answer"], record["canary"]))) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=Path, help="Public JSONL or one encrypted JSON record") parser.add_argument("--output", type=Path, help="Write decoded JSONL to this new file") args = parser.parse_args() if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) output = args.output.open("x", encoding="utf-8") if args.output else sys.stdout try: with args.input.open(encoding="utf-8") as stream: if args.input.suffix == ".json": records = [json.load(stream)] else: records = (json.loads(line) for line in stream if line.strip()) for record in records: decoded = {**record, "accepted_answers": decode_answers(record)} output.write(json.dumps(decoded, ensure_ascii=False) + "\n") finally: if args.output: output.close() if __name__ == "__main__": main()