返回 last30days-skill
safari_cookies.py
根目录 / skills / last30days / scripts / lib / safari_cookies.py
1 """
2 Safari binary cookie extractor for macOS.
3
4 Parses ~/Library/Cookies/Cookies.binarycookies (unencrypted binary format)
5 using only stdlib. Zero pip dependencies.
6
7 Reference: github.com/mdegrazia/Safari-Binary-Cookie-Parser
8 """
9
10 from __future__ import annotations
11
12 import io
13 import struct
14 import sys
15 from pathlib import Path
16
17 from .cookie_paths import path_exists
18
19 # Mac epoch: 2001-01-01 00:00:00 UTC (not used for filtering, but documented)
20 _MAC_EPOCH_OFFSET = 978307200 # seconds between Unix epoch and Mac epoch
21
22 _MAGIC = b"cook"
23
24
25 def _read_null_terminated(data: bytes, offset: int) -> str:
26 """Read a null-terminated string from data starting at offset."""
27 end = data.find(b"\x00", offset)
28 if end == -1:
29 end = len(data)
30 return data[offset:end].decode("utf-8", errors="replace")
31
32
33 def _parse_cookie_record(data: bytes) -> dict | None:
34 """Parse a single cookie record. Returns dict with url, name, value, path or None."""
35 if len(data) < 44:
36 return None
37 try:
38 (size,) = struct.unpack("<I", data[0:4])
39 # flags at offset 4 (4 bytes, little-endian) — not needed for extraction
40 (url_offset,) = struct.unpack("<I", data[16:20])
41 (name_offset,) = struct.unpack("<I", data[20:24])
42 (path_offset,) = struct.unpack("<I", data[24:28])
43 (value_offset,) = struct.unpack("<I", data[28:32])
44 # expiry at offset 40 (8-byte double, little-endian) — not needed for filtering
45 # creation at offset 48 (8-byte double, little-endian) — not needed
46
47 url = _read_null_terminated(data, url_offset)
48 name = _read_null_terminated(data, name_offset)
49 path = _read_null_terminated(data, path_offset)
50 value = _read_null_terminated(data, value_offset)
51
52 return {"url": url, "name": name, "value": value, "path": path}
53 except (struct.error, IndexError, UnicodeDecodeError):
54 return None
55
56
57 def _parse_page(page_data: bytes) -> list[dict]:
58 """Parse a single page of cookies. Returns list of cookie dicts."""
59 cookies = []
60 if len(page_data) < 8:
61 return cookies
62
63 # Page header: 4 bytes (always 00 00 01 00), then 4-byte LE cookie count
64 try:
65 (num_cookies,) = struct.unpack("<I", page_data[4:8])
66 except struct.error:
67 return cookies
68
69 # Sanity check
70 if num_cookies > 10000:
71 return cookies
72
73 # Cookie offsets: array of 4-byte LE uint32 starting at offset 8
74 offsets_end = 8 + num_cookies * 4
75 if offsets_end > len(page_data):
76 return cookies
77
78 for i in range(num_cookies):
79 off_start = 8 + i * 4
80 try:
81 (cookie_offset,) = struct.unpack("<I", page_data[off_start : off_start + 4])
82 except struct.error:
83 continue
84
85 if cookie_offset >= len(page_data):
86 continue
87
88 cookie_data = page_data[cookie_offset:]
89 record = _parse_cookie_record(cookie_data)
90 if record:
91 cookies.append(record)
92
93 return cookies
94
95
96 def extract_safari_cookies_macos(
97 domain: str, cookie_names: list[str]
98 ) -> dict[str, str] | None:
99 """
100 Extract cookies from Safari on macOS.
101
102 Args:
103 domain: Registrable host to match, with or without a leading dot
104 (e.g. "x.com" or ".x.com"). A stored cookie host matches when it
105 equals the domain or is a subdomain of it; unrelated hosts that
106 merely contain the text (e.g. "x.com.evil.tld") do not.
107 cookie_names: List of cookie names to extract (e.g. ["auth_token", "ct0"])
108
109 Returns:
110 Dict mapping cookie name to value for found cookies, or None on failure.
111 """
112 if sys.platform != "darwin":
113 return None
114
115 cookie_paths = [
116 Path.home()
117 / "Library"
118 / "Containers"
119 / "com.apple.Safari"
120 / "Data"
121 / "Library"
122 / "Cookies"
123 / "Cookies.binarycookies",
124 Path.home() / "Library" / "Cookies" / "Cookies.binarycookies",
125 ]
126 denied = None
127 partial = None
128 for cookie_path in cookie_paths:
129 try:
130 if not path_exists(cookie_path):
131 continue
132 raw = cookie_path.read_bytes()
133 except PermissionError as exc:
134 if denied is None:
135 denied = exc
136 continue
137 except OSError:
138 continue
139 result = _parse_binary_cookies(raw, domain, cookie_names)
140 if result and all(result.get(name) for name in cookie_names):
141 return result
142 if result and partial is None:
143 partial = result
144
145 if denied is not None:
146 print(
147 "[safari] Permission denied reading Cookies.binarycookies. "
148 "Check the invoking app's browser-data permissions in System Settings > "
149 "Privacy & Security, then retry setup.",
150 file=sys.stderr,
151 )
152 raise denied
153 return partial
154
155
156 def _host_matches(stored_host: str, domain: str) -> bool:
157 """True when stored_host equals domain or is a subdomain of it.
158
159 Safari stores domain cookies with a leading dot (".x.com") and host-only
160 cookies without one ("x.com"); both spellings are accepted on either side.
161 """
162 host = stored_host.strip().lstrip(".").lower()
163 wanted = domain.strip().lstrip(".").lower()
164 if not host or not wanted:
165 return False
166 return host == wanted or host.endswith("." + wanted)
167
168
169 def _parse_binary_cookies(
170 raw: bytes, domain: str, cookie_names: list[str]
171 ) -> dict[str, str] | None:
172 """Parse raw binary cookie data. Separated for testability."""
173 if len(raw) < 8:
174 return None
175
176 # Validate magic
177 if raw[:4] != _MAGIC:
178 return None
179
180 try:
181 (num_pages,) = struct.unpack(">I", raw[4:8])
182 except struct.error:
183 return None
184
185 if num_pages > 100000:
186 return None
187
188 # Read page sizes (big-endian uint32 array)
189 page_sizes_end = 8 + num_pages * 4
190 if page_sizes_end > len(raw):
191 return None
192
193 page_sizes = []
194 for i in range(num_pages):
195 off = 8 + i * 4
196 try:
197 (ps,) = struct.unpack(">I", raw[off : off + 4])
198 page_sizes.append(ps)
199 except struct.error:
200 return None
201
202 # Parse each page
203 names_set = set(cookie_names)
204 result: dict[str, str] = {}
205 offset = page_sizes_end
206
207 for ps in page_sizes:
208 if offset + ps > len(raw):
209 break
210 page_data = raw[offset : offset + ps]
211 cookies = _parse_page(page_data)
212 for c in cookies:
213 if _host_matches(c["url"], domain) and c["name"] in names_set:
214 result[c["name"]] = c["value"]
215 offset += ps
216
217 if not result:
218 return None
219
220 return result
221
221 lines PYTHON