feat(bird): read X cookies from Brave only
Bird 0.8.0 asks Keychain for Chrome Safe Storage, but Brave stores its key under Brave Safe Storage, so the reader fails before it can use Brave. Manage the Bird config in Nix and add a wrapper at ~/.pi/agent/bin/bird. The wrapper decrypts auth_token and ct0 from Brave cookie database with the Brave Safe Storage key and passes them to bird as env vars. It has no browser fallback, writes no Keychain item, and never opens the credentials file. Add an end-to-end shell check with a fake Brave cookie source and keychain. The check fails before the wrapper exists and passes after implementation.
This commit is contained in:
1 parent
fd96dc6dc0
commit
aae4dfd6d0
8 files changed
+413
-9
No files matched your search
@@ -0,0 +1,9 @@
|
||||
{
|
||||
// Bird calls its Chromium cookie reader "chrome". This profile path points
|
||||
// that reader at Brave only. Do not add Safari or Firefox sources.
|
||||
// The ~/.pi/agent/bin/bird wrapper supplies the cookies itself from Brave
|
||||
// Safe Storage, so bird never asks Keychain for Chrome Safe Storage.
|
||||
cookieSource: "chrome",
|
||||
chromeProfileDir: "/Users/laptran/Library/Application Support/BraveSoftware/Brave-Browser/Default/Cookies",
|
||||
cookieTimeoutMs: 30000
|
||||
}
|
||||
@@ -5,15 +5,15 @@ description: Use when the user asks to read, fetch, or show the content of an X
|
||||
|
||||
# Read X/Twitter Tweet Content with bird
|
||||
|
||||
When the user asks to read, fetch, view, or summarize a tweet (or thread), use the locally installed `bird` CLI instead of `webfetch` — it authenticates via the active browser session and returns full tweet content + metadata.
|
||||
When the user asks to read, fetch, view, or summarize a tweet (or thread), use the local `bird` CLI instead of `webfetch`. It authenticates through the Brave cookie session and returns full tweet content and metadata.
|
||||
|
||||
## Commands
|
||||
|
||||
Use `/opt/homebrew/bin/bird` (absolute path since PATH can be sparse in non-interactive shells):
|
||||
Use `$HOME/.pi/agent/bin/bird`, the Brave-only wrapper. It reads the X cookies from Brave and execs the installed bird. Use an absolute path because PATH can be sparse in non-interactive shells. Do not call `/opt/homebrew/bin/bird` directly, since that skips the wrapper and asks Keychain for Chrome Safe Storage.
|
||||
|
||||
- Single tweet: `bird read <tweet-url-or-id> --json`
|
||||
- Full thread/conversation: `bird thread <tweet-url-or-id> --json`
|
||||
- Replies to a tweet: `bird replies <tweet-url-or-id> --json`
|
||||
- Single tweet: `$HOME/.pi/agent/bin/bird read <tweet-url-or-id> --json`
|
||||
- Full thread/conversation: `$HOME/.pi/agent/bin/bird thread <tweet-url-or-id> --json`
|
||||
- Replies to a tweet: `$HOME/.pi/agent/bin/bird replies <tweet-url-or-id> --json`
|
||||
|
||||
Prefer `--json` for parseable output (author, text, media, created_at, metrics). Drop `--json` only if the user wants pretty-printed terminal output.
|
||||
|
||||
@@ -25,11 +25,12 @@ Prefer `--json` for parseable output (author, text, media, created_at, metrics).
|
||||
|
||||
## When NOT to use
|
||||
|
||||
- User asks to post, reply, like, bookmark, follow, or search tweets — use other `bird` subcommands directly (see `bird --help`)
|
||||
- User asks to post, reply, like, bookmark, follow, or search tweets — use other subcommands through the same wrapper (see `$HOME/.pi/agent/bin/bird --help`)
|
||||
- User asks about article content linked FROM a tweet — `bird` only returns tweet text/metadata, not outbound article bodies; fall back to `webfetch` on the linked URL
|
||||
|
||||
## Notes
|
||||
|
||||
- `bird` reads `auth_token` and `ct0` cookies from Safari/Chrome/Firefox; no paid dev account needed
|
||||
- If a fetch fails with auth errors, tell the user to sign in to x.com in their browser and retry
|
||||
- The wrapper reads `auth_token` and `ct0` from Brave only and passes them to bird as env vars. No paid dev account needed.
|
||||
- If the wrapper cannot read Brave Safe Storage, approve the Keychain dialog and retry. Do not switch browsers or call the Homebrew binary directly.
|
||||
- If a fetch fails with auth errors, tell the user to sign in to x.com in Brave and retry
|
||||
- Quote tweets and retweets include the referenced tweet in the JSON payload
|
||||
Executable
+161
@@ -0,0 +1,161 @@
|
||||
#!/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()
|
||||
Reference in new issue
Block a user