#!/usr/bin/env python3
"""Brave-only cookie bridge for the bird X reader.

Bird 0.8.0 reads browser cookies through sweet-cookie 0.1.0. On macOS that
library asks Keychain for "Chrome Safe Storage", while Brave keeps its key
under "Brave Safe Storage". Bird therefore fails before it can read Brave.

This wrapper reads auth_token and ct0 from Brave's cookie database, decrypts
them with the Brave Safe Storage key, and passes them to the real bird as
AUTH_TOKEN and CT0. Bird then takes its env-cookie path and never calls its
Safari, Chrome, or Firefox providers.

No cookie value, keychain password, or X token is printed. This script never
opens ~/.config/bird/credentials and never writes a Keychain item.
"""

import ctypes
import hashlib
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path

REAL_BIRD = os.environ.get("BIRD_BRAVE_REAL_BIRD", "/opt/homebrew/bin/bird")
SERVICE = "Brave Safe Storage"
ACCOUNT = "Brave"
COOKIE_DB = Path(os.path.expanduser(
    "~/Library/Application Support/BraveSoftware/Brave-Browser/Default/Cookies"
))
COOKIE_NAMES = ("auth_token", "ct0")
IV = b" " * 16
HOST_PREFIX_BYTES = 32


def fail(message):
    print("bird-brave: " + message, file=sys.stderr)
    raise SystemExit(1)


def safe_storage_password():
    try:
        result = subprocess.run(
            ["security", "find-generic-password", "-s", SERVICE,
             "-a", ACCOUNT, "-w"],
            capture_output=True,
            timeout=30,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired):
        fail("cannot read " + SERVICE + " from Keychain")
    if result.returncode != 0 or not result.stdout.strip():
        fail("cannot read " + SERVICE + " from Keychain")
    return result.stdout.rstrip(b"\r\n")


def aes_key(password):
    return hashlib.pbkdf2_hmac("sha1", password, b"saltysalt", 1003, 16)


def crypt(operation, key, data):
    lib = ctypes.CDLL("/usr/lib/libSystem.B.dylib")
    lib.CCCrypt.argtypes = [
        ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32,
        ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p,
        ctypes.c_char_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t,
        ctypes.POINTER(ctypes.c_size_t),
    ]
    lib.CCCrypt.restype = ctypes.c_int32
    output = ctypes.create_string_buffer(len(data) + 32)
    moved = ctypes.c_size_t(0)
    status = lib.CCCrypt(
        1, 0, 1, key, len(key), IV, data, len(data),
        output, len(output), ctypes.byref(moved),
    )
    if status != 0:
        return None
    return output.raw[:moved.value]


def decrypt_value(blob, key, strip_prefix):
    if not blob or blob[:3] not in (b"v10", b"v11"):
        return None
    plain = crypt(1, key, blob[3:])
    if plain is None:
        return None
    if strip_prefix and len(plain) > HOST_PREFIX_BYTES:
        plain = plain[HOST_PREFIX_BYTES:]
    try:
        text = plain.decode("utf-8")
    except UnicodeDecodeError:
        return None
    return text or None


def brave_cookie_rows():
    if not COOKIE_DB.is_file():
        fail("Brave cookie database missing at " + str(COOKIE_DB))
    with tempfile.TemporaryDirectory(prefix="bird-brave-") as temp:
        copy = Path(temp) / "Cookies"
        try:
            shutil.copy2(COOKIE_DB, copy)
            for suffix in ("-wal", "-shm"):
                sidecar = Path(str(COOKIE_DB) + suffix)
                if sidecar.is_file():
                    shutil.copy2(sidecar, Path(str(copy) + suffix))
            conn = sqlite3.connect(str(copy))
        except (OSError, sqlite3.Error):
            fail("cannot open Brave cookie database")
        try:
            version_row = conn.execute(
                "SELECT value FROM meta WHERE key = 'version'"
            ).fetchone()
            strip_prefix = bool(
                version_row and version_row[0] and int(version_row[0]) >= 24
            )
            rows = conn.execute(
                "SELECT name, host_key, value, encrypted_value FROM cookies "
                "WHERE name IN ('auth_token', 'ct0')"
            ).fetchall()
        except (sqlite3.Error, ValueError, TypeError):
            fail("cannot read Brave cookies")
        finally:
            conn.close()
    return rows, strip_prefix


def main():
    if not os.path.exists(REAL_BIRD):
        fail("real bird not found at " + REAL_BIRD)

    # Help and version need no cookies. Pass them straight through.
    if any(arg in ("--help", "-h", "--version", "-V") for arg in sys.argv[1:]):
        os.execv(REAL_BIRD, [REAL_BIRD] + sys.argv[1:])

    rows, strip_prefix = brave_cookie_rows()
    key = aes_key(safe_storage_password())
    found = {}
    for name, host_key, value, encrypted in rows:
        if not (host_key.endswith("x.com") or host_key.endswith("twitter.com")):
            continue
        plain = value or decrypt_value(encrypted, key, strip_prefix)
        if not plain:
            continue
        rank = 0 if host_key.endswith("x.com") else 1
        if name not in found or rank < found[name][0]:
            found[name] = (rank, plain)

    missing = [name for name in COOKIE_NAMES if name not in found]
    if missing:
        fail("Brave has no x.com cookie for " + " or ".join(missing))

    os.environ["AUTH_TOKEN"] = found["auth_token"][1]
    os.environ["CT0"] = found["ct0"][1]
    os.execv(REAL_BIRD, [REAL_BIRD] + sys.argv[1:])


if __name__ == "__main__":
    main()
