File size: 2,773 Bytes
bc02573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/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()