Skip to content

API Reference

dump(cookies, f)

Dumps a Binary Cookies object to create a binary cookies file.

Parameters:

Name Type Description Default
cookies CookiesCollection

A Binary Cookies object to be serialized.

required
f Union[BufferedWriter, BytesIO, BinaryIO]

The file-like object to write the binary cookies data to.

required
Source code in src/binarycookies/_serialize.py
def dump(cookies: CookiesCollection, f: Union[BufferedWriter, BytesIO, BinaryIO]):
    """Dumps a Binary Cookies object to create a binary cookies file.

    Args:
        cookies: A Binary Cookies object to be serialized.
        f: The file-like object to write the binary cookies data to.
    """
    binary = dumps(cookies)
    f.write(binary)

dumps(cookies)

Dumps a Binary Cookies object to a byte string.

Parameters:

Name Type Description Default
cookies CookiesCollection

A Binary Cookies object to be serialized.

required

Returns: bytes: The serialized binary cookies data.

Source code in src/binarycookies/_serialize.py
def dumps(cookies: CookiesCollection) -> bytes:
    """Dumps a Binary Cookies object to a byte string.

    Args:
        cookies: A Binary Cookies object to be serialized.
    Returns:
        bytes: The serialized binary cookies data.
    """
    if isinstance(cookies, dict):
        cookies = [Cookie.parse_obj(cookies)] if IS_PYDANTIC_V1 else [Cookie.model_validate(cookies)]
    elif isinstance(cookies, (list, tuple)):
        if IS_PYDANTIC_V1:
            cookies = [Cookie.parse_obj(cookie) for cookie in cookies]
        else:
            cookies = [Cookie.model_validate(cookie) for cookie in cookies]
    elif isinstance(cookies, Cookie):
        cookies = [cookies]
    else:
        raise TypeError("Invalid type for cookies. Expected dict, list, tuple, or Cookie.")

    file_fields = FileFields()

    data = BytesIO()

    # Write file header
    write_field(data, file_fields.header, "cook")

    # Number of pages (1 for simplicity)
    write_field(data, file_fields.num_pages, 1)

    # Write number of cookies
    data.write(pack(Format.integer, len(cookies)))

    # Placeholder for page size
    page_size_offset = data.tell()
    data.write(b"\x00\x00\x00\x00")

    # Write number of cookies
    data.write(pack(Format.integer, len(cookies)))
    cookie_data_list = []
    # Write cookies
    for cookie in cookies:
        cookie_data_list.append(serialize_cookie(cookie))

    initial_cookie_offset = data.tell() + (len(cookies) * 4)
    initial_cookie = True
    previous_sizes = 0
    for cookie_data in cookie_data_list:
        if initial_cookie:
            data.write(pack(Format.integer, initial_cookie_offset))
            initial_cookie = False
        else:
            data.write(pack(Format.integer, previous_sizes + initial_cookie_offset))

        previous_sizes += len(cookie_data)

    # Unknown data
    data.write(b"\x00\x00\x00\x00")
    data.write(b"\x00\x00\x00\x00")
    data.write(b"\x00\x00\x00\x00")

    for cookie_data in cookie_data_list:
        data.write(cookie_data)

    # Update page size
    page_size = data.tell()
    data.seek(page_size_offset)
    data.write(pack(Format.integer, page_size))

    return data.getvalue()

load(bf)

Deserializes a binary cookie file and returns a list of Cookie objects.

Parameters:

Name Type Description Default
bf BinaryIO

A binary file object containing the binary cookie data.

required

Returns: List[Cookie]: A list of Cookie objects.

Source code in src/binarycookies/_deserialize.py
def load(bf: BinaryIO) -> List[Cookie]:
    """Deserializes a binary cookie file and returns a list of Cookie objects.

    Args:
        bf (BinaryIO): A binary file object containing the binary cookie data.
    Returns:
        List[Cookie]: A list of Cookie objects.
    """
    # Check if the file is empty
    if bf.readable() and bf.read(1) == b"":
        raise BinaryCookiesDecodeError("The file is empty.")
    # Reset the file pointer to the beginning
    bf.seek(0)
    # Check if the file is a valid binary cookies file
    if bf.readable() and bf.read(4) != b"cook":
        raise BinaryCookiesDecodeError("The file is not a valid binary cookies file. Missing magic String:cook.")
    # Reset the file pointer to the beginning
    bf.seek(0)
    # Deserialize the binary cookies file
    return loads(BytesIO(bf.read()))

loads(b)

Deserializes a binary cookie file and returns a list of Cookie objects.

Parameters:

Name Type Description Default
b BytesIO

A BytesIO object containing the binary cookie data.

required

Returns: List[Cookie]: A list of Cookie objects.

Source code in src/binarycookies/_deserialize.py
def loads(b: BytesIO) -> List[Cookie]:
    """Deserializes a binary cookie file and returns a list of Cookie objects.

    Args:
        b (BytesIO): A BytesIO object containing the binary cookie data.
    Returns:
        List[Cookie]: A list of Cookie objects.
    """
    all_cookies = []
    file_fields = FileFields()

    # Number of pages in the binary file: 4 bytes
    num_pages = read_field(b, field=file_fields.num_pages)
    page_sizes = get_file_pages(b, num_pages)

    pages = []
    b.seek(8 + (num_pages * 4))
    for ps in page_sizes:
        # Grab individual pages and each page will contain >= one cookie
        pages.append(b.read(ps))

    for page in pages:
        cookies = _deserialize_page(BytesIO(page))
        all_cookies.extend(cookies)

    return all_cookies

cli(file_path, output=OutputType.json)

CLI entrypoint for reading Binary Cookies

Source code in src/binarycookies/__main__.py
def cli(file_path: str, output: OutputType = OutputType.json):
    """CLI entrypoint for reading Binary Cookies"""
    with open(file_path, "rb") as f:
        cookies = load(f)

    handler = OUTPUT_HANDLERS.get(output)
    if not handler:
        rprint(f"[red]Error:[/red] Unsupported output type: {output}")
        raise typer.Exit(code=1)

    handler(cookies)

binarycookies.models.Cookie

Represents a cookie in the binary cookies format.

Attributes:

Name Type Description
name str

The name of the cookie.

value str

The value of the cookie.

url str

The URL associated with the cookie.

path str

The path for which the cookie is valid.

create_datetime datetime

The creation date and time of the cookie.

expiry_datetime datetime

The expiration date and time of the cookie.

flag Flag

The flags associated with the cookie, such as Secure or HttpOnly.

Source code in src/binarycookies/models.py
class Cookie(BaseModel):
    """Represents a cookie in the binary cookies format.

    Attributes:
        name (str): The name of the cookie.
        value (str): The value of the cookie.
        url (str): The URL associated with the cookie.
        path (str): The path for which the cookie is valid.
        create_datetime (datetime): The creation date and time of the cookie.
        expiry_datetime (datetime): The expiration date and time of the cookie.
        flag (Flag): The flags associated with the cookie, such as Secure or HttpOnly.
    """

    name: str
    value: str
    url: str
    path: str
    create_datetime: datetime
    expiry_datetime: datetime
    flag: Flag