Compare commits

..
Author SHA1 Message Date
hermes 80fb47f050 fix(rebuild): restore both trusted Homebrew taps before switch 2026-11-29 13:29:44 -05:00
hermes e4c67f0080 fix(skills): share deleted-upstream denylist between Nix and rebuild 2026-11-29 13:22:54 -05:00
hermes 72a23ff0d0 fix(bird): put Brave wrapper first on PATH and check the wiring 2026-11-29 10:37:58 -05:00
hermes 8378ac41fd Merge pull request 'feat(bird): read X cookies from Brave only' (#25) from fm/dotfiles-bird-brave-reader into main 2026-11-28 17:25:25 -05:00
Lap Tran aae4dfd6d0 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.
2026-11-28 15:46:40 -05:00
12 changed files with 684 additions and 13 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
agent-self-scheduling
codex-goal-loop
delegating-to-agents
markdown-rendering
run-deep-swe
cyber-audit
pi-custom-model
vps-server-management
pi-web-search
research-prompt
youtube-polls
youtube-transcript
distribute-skill-to-all-agents
folder-specific-claude-and-agents-md
push-skill-to-github
brain-to-docs
grill-me
interview-style-doc-building
short
teach
+60
View File
@@ -33,6 +33,13 @@ let
rev = "6b0300214a09fd6029cfb7077043125758cd1fd2";
hash = "sha256-TDuZ1v+taPdqyvvCs1VHUjtpSy8zHxhQKJv/kIPTpK8=";
};
# Skills deleted upstream from davidondrej/skills. rebuild.sh reads the same
# file to keep these names out of the Skills CLI update. One name per line.
deletedSkillNames = lib.pipe (builtins.readFile ./deleted-upstream-skills.txt) [
(lib.splitString "\n")
(map lib.trim)
(builtins.filter (name: name != ""))
];
in
{
@@ -71,6 +78,10 @@ in
syntaxHighlighting.enable = true; # commands turn green when valid
initContent = ''
bindkey '^f' autosuggest-accept
# Brave-only bird wrapper wins over Homebrew's npm bird shim. zshrc runs
# after .zprofile, whose brew shellenv puts /opt/homebrew/bin first.
typeset -U path
path=("$HOME/.pi/agent/bin" $path)
# Keep the OpenCode Go CLI, Pi, no-mistakes, and Hermes key aligned with
# the desktop app login after an account switch.
if [ -x "$HOME/.local/bin/opencode-go-key-sync" ]; then
@@ -293,6 +304,22 @@ in
force = true;
};
# Brave-only bird reader. The config points bird's Chromium source at Brave;
# the wrapper decrypts Brave cookies with the Brave Safe Storage key and
# hands them to bird as env vars. The session PATH puts ~/.pi/agent/bin
# before Homebrew, so `bird` resolves to this wrapper and not the npm shim.
# force = true on the config is needed once: a pre-existing unmanaged
# ~/.config/bird/config.json5 would otherwise make home-manager refuse the
# switch. The wrapper path is new, so no force.
home.sessionPath = [ "${home}/.pi/agent/bin" ];
home.file.".config/bird/config.json5" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.config/bird/config.json5";
force = true;
};
home.file.".pi/agent/bin/bird" = {
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/.pi/agent/bin/bird";
};
# firstmate is a mutable agent distro (self-update, state/, projects/). Clone once;
# never put it in the Nix store. Seed OpenCode+herdr defaults only when absent.
# Do NOT npm install -g here: activation PATH often resolves Nix's npm, which
@@ -583,6 +610,39 @@ in
echo "pstackSkills: installed ${toString (lib.length pstackSkillNames)} pinned skills into $dest"
'';
# Remove only the skills deleted upstream from davidondrej/skills. The names
# come from the source-controlled denylist that rebuild.sh also reads. The
# guard below leaves every other skill, the skill lock, house-authored skills,
# and the pinned pstack copies alone. Only exact directory or link names in
# the agent skill folders used on this Mac are removed.
home.activation.removeDeletedUpstreamSkills = lib.hm.dag.entryAfter [ "writeBoundary" ] ''
set -euo pipefail
deny_file=${./deleted-upstream-skills.txt}
if [ ! -r "$deny_file" ]; then
echo "removeDeletedUpstreamSkills: denylist missing at $deny_file" >&2
exit 1
fi
skill_dirs=(
"$HOME/.agents/skills"
"$HOME/.claude/skills"
"$HOME/.config/opencode/skills"
"$HOME/.grok/skills"
)
count=0
while IFS= read -r name; do
[ -n "$name" ] || continue
count=$((count + 1))
for dir in "''${skill_dirs[@]}"; do
target="$dir/$name"
if [ -e "$target" ] || [ -L "$target" ]; then
rm -rf -- "$target"
echo "removeDeletedUpstreamSkills: removed $target"
fi
done
done < "$deny_file"
echo "removeDeletedUpstreamSkills: checked $count deleted skill names"
'';
# OpenSuperWhisper - local voice-first prompting (cask in configuration.nix).
# The app reads its model from its own Application Support directory, so the
# 1.6 GB Whisper model is downloaded here once and kept outside the Nix store.
+9
View File
@@ -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
+161
View File
@@ -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()
+28
View File
@@ -55,6 +55,7 @@ The captain confirmed the split on 2026-11-15. Leave it unchanged:
./tests/fm-launcher.sh # generated zshrc; must pass
./tests/crew-dispatch.sh # routing via firstmate, model IDs via opencode models
./tests/rebuild-update-steps.sh # isolated updater execution and activation checks
./tests/bird-brave-e2e.sh # Brave-only bird cookies, throwaway HOME fixture
./tests/run.sh # all checks
```
@@ -76,6 +77,21 @@ The Nix sources in this repository are the durable record. The live files are ge
This follows the NIST SP 800-128 Rev. 1 (2019) Section 3.3 "Controlling Configuration Change" (CM-3) practice: route every change through review and approval, test it, record it in version control, and restrict who can change the operational configuration. The 2011 edition is withdrawn and superseded by Revision 1.
## Brave-only bird cookie reader
`rebuild.sh` installs `bird` as a global npm package. Bird 0.8.0 asks Keychain for "Chrome Safe Storage" when it reads browser cookies, but Brave keeps its key under "Brave Safe Storage". The reader failed before it could use Brave cookies.
Two tracked files make the reader Brave-only:
- `home/.config/bird/config.json5` installs as `~/.config/bird/config.json5`. It sets `cookieSource` to `chrome`, which is Bird's name for its Chromium reader, and points `chromeProfileDir` at the Brave cookie database. No Safari or Firefox source is configured.
- `home/.pi/agent/bin/bird` installs as `~/.pi/agent/bin/bird`. PATH puts that directory before `/opt/homebrew/bin`, so `bird` runs the wrapper first.
The wrapper reads `auth_token` and `ct0` from the Brave cookie database, decrypts them with the Brave Safe Storage key, and passes them to the real bird as `AUTH_TOKEN` and `CT0`. Bird then uses its env-cookie path and never calls its Safari, Chrome, or Firefox providers. The wrapper never opens `~/.config/bird/credentials` and never writes a Keychain item. No cookie value or token appears in its output.
The first use can show a macOS dialog asking to allow access to "Brave Safe Storage". Approve that read. The wrapper never creates or copies a Chrome Safe Storage item.
If Bird changes its env-cookie names or its cookie store, stop and update the wrapper in this repo. Do not work around the mismatch by adding a Chrome Safe Storage item or copying the Brave key into one. Run `./tests/bird-brave-e2e.sh` after any change.
## What `rebuild.sh` updates
`./rebuild.sh` updates the components below. The npm updater skips packages already at the registry version. Other tools use their own update commands on each run. Optional updater failures print warnings and allow the rebuild to continue. A failed switch stops the script before the post-switch updates.
@@ -87,6 +103,7 @@ Before the switch:
- `no-mistakes update`, using `~/.no-mistakes/bin/no-mistakes`, or the command on `PATH` if that binary is absent.
- `hermes update --yes`, which pulls the configured channel and restarts the services that run its new code.
- `nix flake update`, so the switch builds from the newest locked inputs. Commit the resulting `flake.lock` change.
- `brew trust can1357/tap` and `brew trust incoai/tap`, so `brew bundle` can install formulae from those third-party taps. Trust can revert between runs, so every rebuild restores it. The `whisper-cpp was renamed to whisper.cpp` notice is a warning. It does not abort the rebuild.
During the switch:
@@ -99,6 +116,17 @@ After the switch:
- The Skills CLI updates skills tracked in `~/.agents/.skill-lock.json`, except `security-audit`. See [security-audit skill](#security-audit-skill-agent-security-reviews) for its freeze policy and manual update command. Untracked skills receive no update here. See [pstack skills](#pstack-skills-pinned-on-every-rebuild) for the pinned skills and their update procedure.
- `pi update --extensions --no-approve`, run after the switch because the Homebrew bundle may have upgraded the `pi` binary.
## Deleted upstream skills denylist
`deleted-upstream-skills.txt` at the repo root names the 20 skills deleted upstream from `davidondrej/skills`. It holds one name per line. Both paths read this same source-controlled file:
- `rebuild.sh` filters those names out of the `skills@latest update` arguments, even when they return to `~/.agents/.skill-lock.json`.
- `home.nix` reads the file into `deletedSkillNames` and runs `home.activation.removeDeletedUpstreamSkills`. That step removes only exact directory or link names under `~/.agents/skills`, `~/.claude/skills`, `~/.config/opencode/skills`, and `~/.grok/skills`. It leaves the skill lock, house-authored skills, pinned pstack skills, and every other skill untouched.
The list keeps local skill trees in sync with upstream. It also stops a deleted skill from returning through the CLI updater. Add a name here only when upstream deletes that skill. Do not add house-authored or pinned names.
`tests/skill-denylist.sh` checks that both paths read the list. `tests/rebuild-update-steps.py` runs `rebuild.sh` with a lock that contains denied names and asserts the update call excludes them.
## security-audit skill (agent security reviews)
`home.activation.securityAuditSkill` installs Cloudflare's `security-audit` skill from `https://github.com/cloudflare/security-audit-skill` so the coding agents can run a structured vulnerability audit. The exact command:
+18 -2
View File
@@ -13,6 +13,8 @@
# A failed switch stops the script before post-switch updates.
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
# Shared with home.nix: skills deleted upstream must stay out of the CLI update.
DENYLIST="$DIR/deleted-upstream-skills.txt"
ln -sfn "$DIR" ~/.dotfiles
NPM=/opt/homebrew/bin/npm
@@ -148,6 +150,7 @@ managed=(
"$HOME/.codex/AGENTS.md"
"$HOME/.codex/luna.config.toml"
"$HOME/.config/herdr/config.toml"
"$HOME/.config/bird/config.json5"
"$HOME/.config/opencode/AGENTS.md"
"$HOME/.config/opencode/opencode.json"
"$HOME/.config/opencode2/opencode.json"
@@ -160,6 +163,7 @@ managed=(
"$HOME/.pi/agent/settings.json"
"$HOME/.pi/agent/models.json"
"$HOME/.pi/agent/AGENTS.md"
"$HOME/.pi/agent/bin/bird"
"$HOME/.pi/agent/extensions/terminal-status-title.js"
)
for path in "${managed[@]}"; do
@@ -191,6 +195,14 @@ else
echo "==> WARNING: flake update failed. Continuing with locked inputs."
fi
# Trust third-party Homebrew taps before the switch. `brew bundle` refuses to
# install formulae from an untrusted tap, and a trust can revert between runs.
# The whisper-cpp rename notice is only a warning and stays harmless here.
if command -v brew >/dev/null 2>&1; then
brew trust can1357/tap 2>/dev/null || true
brew trust incoai/tap 2>/dev/null || true
fi
sudo darwin-rebuild switch --flake ~/.dotfiles#lt-mbp
# Update tracked skills after activation. Exclude security-audit to preserve
@@ -203,15 +215,19 @@ if [ ! -x "$NPX" ]; then
echo "==> WARNING: $NPX not found. Skipping agent skill update."
elif [ ! -f "$SKILL_LOCK" ]; then
echo "==> WARNING: $SKILL_LOCK not found. Skipping agent skill update."
elif [ ! -f "$DENYLIST" ]; then
echo "==> WARNING: $DENYLIST not found. Skipping agent skill update."
else
skill_names="$(/usr/bin/python3 - "$SKILL_LOCK" 2>/dev/null <<'PY' || true
skill_names="$(/usr/bin/python3 - "$SKILL_LOCK" "$DENYLIST" 2>/dev/null <<'PY' || true
import json
import sys
with open(sys.argv[1]) as lock_file:
skills = json.load(lock_file).get("skills", {})
with open(sys.argv[2]) as deny_file:
denied = {line.strip() for line in deny_file if line.strip()}
for name in sorted(skills):
if name != "security-audit":
if name != "security-audit" and name not in denied:
print(name)
PY
)"
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env bash
# End-to-end check for the Brave-only bird wrapper.
#
# The check runs the real wrapper from this repo against a throwaway HOME with:
# - a fake Brave cookie database with encrypted x.com auth_token and ct0;
# - a fake Brave Safe Storage password served by a `security` spy on PATH;
# - fake Safari, Chrome, and Firefox cookie databases with decoy tokens;
# - a fake credentials file with a decoy token;
# - a fake "real bird" that records argv and the environment it receives.
#
# It proves the wrapper decrypts Brave cookies with the Brave key, passes the
# two cookies to bird as AUTH_TOKEN and CT0, prints no cookie or credential
# value, and never opens Safari, Chrome, Firefox, or the credentials file.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
WRAPPER="$ROOT/home/.pi/agent/bin/bird"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/bird-brave-e2e.XXXXXX")
trap 'chmod -R u+rwX "$TMP" 2>/dev/null || true; rm -rf "$TMP"' EXIT
fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; }
pass() { printf 'PASS: %s\n' "$1"; }
[ -f "$WRAPPER" ] || fail "wrapper missing at $WRAPPER"
[ -x "$WRAPPER" ] || fail "wrapper is not executable at $WRAPPER"
FIX="$TMP/home"
BRAVE_DIR="$FIX/Library/Application Support/BraveSoftware/Brave-Browser/Default"
CHROME_DIR="$FIX/Library/Application Support/Google/Chrome/Default"
FIREFOX_DIR="$FIX/Library/Application Support/Firefox/Profiles/default"
SAFARI_DIR="$FIX/Library/Safari"
CRED_FILE="$FIX/.config/bird/credentials"
mkdir -p "$TMP/bin" "$BRAVE_DIR" "$CHROME_DIR" "$FIREFOX_DIR" "$SAFARI_DIR" \
"$(dirname "$CRED_FILE")"
AUTH_VALUE='BRAVE_AUTH_SENTINEL_7f3a'
CT0_VALUE='BRAVE_CT0_SENTINEL_91c2'
FAKE_KEY='brave-fixture-password'
# Build the fake cookie databases. The Brave values use the same v10 scheme as
# real Brave: PBKDF2-HMAC-SHA1(saltysalt, 1003) and AES-128-CBC with a space IV.
python3 - "$BRAVE_DIR/Cookies" "$CHROME_DIR/Cookies" "$FIREFOX_DIR/cookies.sqlite" \
"$SAFARI_DIR/Cookies.binarycookies" "$AUTH_VALUE" "$CT0_VALUE" "$FAKE_KEY" <<'PY'
import ctypes
import hashlib
import sqlite3
import sys
brave_db, chrome_db, firefox_db, safari_db, auth_value, ct0_value, password = sys.argv[1:]
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
key = hashlib.pbkdf2_hmac("sha1", password.encode(), b"saltysalt", 1003, 16)
iv = b" " * 16
def encrypted(host_key, value):
payload = hashlib.sha256(host_key.encode()).digest() + value.encode()
out = ctypes.create_string_buffer(len(payload) + 32)
moved = ctypes.c_size_t(0)
status = lib.CCCrypt(0, 0, 1, key, len(key), iv, payload, len(payload),
out, len(out), ctypes.byref(moved))
assert status == 0, status
return b"v10" + out.raw[:moved.value]
def make_cookie_db(path, rows, version=24):
conn = sqlite3.connect(path)
conn.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
conn.execute("INSERT INTO meta (key, value) VALUES ('version', ?)", (str(version),))
conn.execute(
"CREATE TABLE cookies (host_key TEXT, name TEXT, value TEXT, encrypted_value BLOB)"
)
conn.executemany("INSERT INTO cookies VALUES (?, ?, '', ?)", rows)
conn.commit()
conn.close()
make_cookie_db(brave_db, [
("x.com", "auth_token", encrypted("x.com", auth_value)),
(".x.com", "ct0", encrypted(".x.com", ct0_value)),
("example.com", "auth_token", encrypted("example.com", "OTHER_DOMAIN_DECOY")),
])
make_cookie_db(chrome_db, [
("x.com", "auth_token", b"CHROME_AUTH_DECOY"),
("x.com", "ct0", b"CHROME_CT0_DECOY"),
])
make_cookie_db(firefox_db, [
("x.com", "auth_token", b"FIREFOX_AUTH_DECOY"),
("x.com", "ct0", b"FIREFOX_CT0_DECOY"),
])
with open(safari_db, "wb") as handle:
handle.write(b"SAFARI_AUTH_DECOY")
PY
printf 'CREDENTIALS_DECOY_NEVER_READ\n' > "$CRED_FILE"
cat > "$TMP/bin/security" <<'SH'
#!/usr/bin/env bash
printf '%s\n' "$*" >> "$BIRD_E2E_KEYCHAIN_LOG"
case " $* " in
*"add-generic-password"*|*"delete-generic-password"*|*"Chrome Safe Storage"*)
printf 'unexpected keychain operation\n' >&2
exit 9 ;;
esac
if [ "$1" = "find-generic-password" ] && [ "$3" = "Brave Safe Storage" ] \
&& [ "$5" = "Brave" ]; then
printf '%s' "$BIRD_E2E_FAKE_KEY"
exit 0
fi
exit 8
SH
cat > "$TMP/bin/fake-bird" <<'SH'
#!/usr/bin/env bash
{
printf 'args:'
for arg in "$@"; do printf ' <%s>' "$arg"; done
printf '\n'
printf 'auth=%s\n' "${AUTH_TOKEN-<unset>}"
printf 'ct0=%s\n' "${CT0-<unset>}"
} > "$BIRD_E2E_BIRD_LOG"
printf 'fake bird ok\n'
SH
chmod +x "$TMP/bin/security" "$TMP/bin/fake-bird"
: > "$TMP/keychain.log"
: > "$TMP/bird.log"
: > "$TMP/stdout"
: > "$TMP/stderr"
before_brave=$(shasum -a 256 "$BRAVE_DIR/Cookies" | awk '{print $1}')
before_chrome=$(shasum -a 256 "$CHROME_DIR/Cookies" | awk '{print $1}')
before_firefox=$(shasum -a 256 "$FIREFOX_DIR/cookies.sqlite" | awk '{print $1}')
before_safari=$(shasum -a 256 "$SAFARI_DIR/Cookies.binarycookies" | awk '{print $1}')
before_creds=$(shasum -a 256 "$CRED_FILE" | awk '{print $1}')
# A read attempt on any of these files must fail. The wrapper only needs Brave.
chmod 000 "$CHROME_DIR/Cookies" "$FIREFOX_DIR/cookies.sqlite" \
"$SAFARI_DIR/Cookies.binarycookies" "$CRED_FILE"
set +e
env -i \
HOME="$FIX" \
PATH="$TMP/bin:/opt/homebrew/bin:/usr/bin:/bin" \
BIRD_E2E_FAKE_KEY="$FAKE_KEY" \
BIRD_E2E_KEYCHAIN_LOG="$TMP/keychain.log" \
BIRD_E2E_BIRD_LOG="$TMP/bird.log" \
BIRD_BRAVE_REAL_BIRD="$TMP/bin/fake-bird" \
"$WRAPPER" read https://x.com/i/status/123 --json \
>"$TMP/stdout" 2>"$TMP/stderr"
status=$?
set -e
chmod 644 "$CHROME_DIR/Cookies" "$FIREFOX_DIR/cookies.sqlite" \
"$SAFARI_DIR/Cookies.binarycookies" "$CRED_FILE"
[ "$status" -eq 0 ] || fail "wrapper exited $status: $(cat "$TMP/stderr")"
grep -q 'fake bird ok' "$TMP/stdout" || fail 'real bird was not executed'
grep -Fxq 'args: <read> <https://x.com/i/status/123> <--json>' "$TMP/bird.log" \
|| fail "bird argv was not passed through: $(cat "$TMP/bird.log")"
grep -Fxq "auth=$AUTH_VALUE" "$TMP/bird.log" \
|| fail 'bird did not receive the Brave auth_token'
grep -Fxq "ct0=$CT0_VALUE" "$TMP/bird.log" \
|| fail 'bird did not receive the Brave ct0'
pass 'wrapper decrypts Brave cookies and passes them to bird'
grep -Fxq 'find-generic-password -s Brave Safe Storage -a Brave -w' "$TMP/keychain.log" \
|| fail "unexpected keychain calls: $(cat "$TMP/keychain.log")"
[ "$(wc -l < "$TMP/keychain.log" | tr -d ' ')" -eq 1 ] \
|| fail 'wrapper made more than one keychain call'
pass 'wrapper reads Brave Safe Storage only and writes no keychain item'
for value in "$AUTH_VALUE" "$CT0_VALUE" 'CREDENTIALS_DECOY_NEVER_READ' \
'CHROME_AUTH_DECOY' 'FIREFOX_AUTH_DECOY' 'SAFARI_AUTH_DECOY'; do
if grep -Fq "$value" "$TMP/stdout" || grep -Fq "$value" "$TMP/stderr"; then
fail "wrapper printed a secret value: $value"
fi
done
pass 'wrapper prints no cookie or credential value'
after_chrome=$(shasum -a 256 "$CHROME_DIR/Cookies" | awk '{print $1}')
after_firefox=$(shasum -a 256 "$FIREFOX_DIR/cookies.sqlite" | awk '{print $1}')
after_safari=$(shasum -a 256 "$SAFARI_DIR/Cookies.binarycookies" | awk '{print $1}')
after_creds=$(shasum -a 256 "$CRED_FILE" | awk '{print $1}')
after_brave=$(shasum -a 256 "$BRAVE_DIR/Cookies" | awk '{print $1}')
[ "$before_brave" = "$after_brave" ] || fail 'Brave cookie database changed'
[ "$before_chrome" = "$after_chrome" ] || fail 'Chrome cookies were touched'
[ "$before_firefox" = "$after_firefox" ] || fail 'Firefox cookies were touched'
[ "$before_safari" = "$after_safari" ] || fail 'Safari cookies were touched'
[ "$before_creds" = "$after_creds" ] || fail 'credentials file was touched'
pass 'wrapper touches Brave only, never Safari, Chrome, Firefox, or credentials'
printf 'OK: bird brave-only end-to-end check passed\n'
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Check that the Nix source wires the Brave-only bird wrapper into the shell.
#
# The Bird merge added home.file entries for the wrapper and the Brave config,
# but no PATH entry. A rebuild installs the wrapper at ~/.pi/agent/bin/bird and
# leaves `bird` resolving to Homebrew's npm shim. This check evaluates the real
# home-manager config, then runs the generated zshrc in a fresh zsh with a fake
# Homebrew bird ahead of the wrapper. It passes only when the wrapper wins.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
TMP=$(mktemp -d "${TMPDIR:-/tmp}/bird-path.XXXXXX")
trap 'rm -rf "$TMP"' EXIT
fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; }
pass() { printf 'PASS: %s\n' "$1"; }
command -v nix >/dev/null 2>&1 \
|| { echo "bird-path: nix is required to evaluate the configuration" >&2; exit 2; }
command -v jq >/dev/null 2>&1 \
|| { echo "bird-path: jq is required to read the session path" >&2; exit 2; }
command -v zsh >/dev/null 2>&1 \
|| { echo "bird-path: zsh is required to run the generated zshrc" >&2; exit 2; }
CONFIG='(builtins.getFlake (toString '"$ROOT"')).darwinConfigurations."lt-mbp".config.home-manager.users.laptran'
wrapper_source=$(nix eval --raw --impure --expr "$CONFIG.home.file.\".pi/agent/bin/bird\".source")
wrapper_target=$(readlink "$wrapper_source" 2>/dev/null || printf '%s' "$wrapper_source")
case "$wrapper_target" in
*"home/.pi/agent/bin/bird") pass "source declares the Brave-only bird wrapper" ;;
*) fail "wrapper home.file source points to $wrapper_target" ;;
esac
nix eval --json --impure --expr "$CONFIG.home.sessionPath" > "$TMP/session-path.json"
first_path=$(jq -r '.[0] // ""' "$TMP/session-path.json")
case "$first_path" in
*"/.pi/agent/bin") pass "session PATH puts the wrapper directory first" ;;
*) fail "first session PATH entry is '$first_path', not the bird wrapper directory" ;;
esac
nix eval --raw --impure --expr "$CONFIG.home.file.\"./.zshrc\".text" > "$TMP/zshrc"
mkdir -p "$TMP/home/.pi/agent/bin" "$TMP/homebrew/bin"
printf '#!/bin/sh\nprintf wrapper\n' > "$TMP/home/.pi/agent/bin/bird"
printf '#!/bin/sh\nprintf homebrew\n' > "$TMP/homebrew/bin/bird"
chmod +x "$TMP/home/.pi/agent/bin/bird" "$TMP/homebrew/bin/bird"
# shellcheck disable=SC2016 # the snippet expands inside the fresh zsh
resolved=$(HOME="$TMP/home" ZSHRC="$TMP/zshrc" \
PATH="$TMP/homebrew/bin:/usr/bin:/bin" \
timeout 60 zsh -f -i -c '
source "$ZSHRC" >/dev/null 2>&1 || exit 4
command -v bird
' 2>"$TMP/stderr") || {
echo "bird-path: failed to run generated zshrc" >&2
cat "$TMP/stderr" >&2
exit 2
}
[ "$resolved" = "$TMP/home/.pi/agent/bin/bird" ] \
|| fail "generated zshrc resolves bird to $resolved instead of the wrapper"
pass "generated zshrc resolves bird to the wrapper ahead of Homebrew"
+54 -2
View File
@@ -105,6 +105,15 @@ elif kind in ("no-mistakes", "hermes", "nix", "npx", "pi"):
else:
state["components"][kind] = "new"
save()
elif kind == "brew":
if state.get("fail_brew_trust"):
sys.exit(1)
trusted = state.setdefault("trusted_taps", [])
if len(args) >= 2 and args[0] == "trust" and args[1] not in trusted:
trusted.append(args[1])
# The rename notice is a harmless brew warning, never a rebuild failure.
print("Warning: Formula whisper-cpp was renamed to whisper.cpp.")
save()
elif kind == "sudo":
sys.exit(state.get("switch_status", 0))
else:
@@ -174,7 +183,9 @@ class RebuildUpdates(unittest.TestCase):
self.state = json.loads((self.root / "state.json").read_text())
self.calls = [json.loads(line) for line in
(self.root / "calls.jsonl").read_text().splitlines()]
self.assertFalse(any(call[0] in ("brew", "bare-npm") for call in self.calls))
self.assertFalse(any(call[0] == "bare-npm" for call in self.calls))
self.assertFalse(any(call[0] == "brew" and (len(call) < 2 or call[1] != "trust")
for call in self.calls))
self.assertFalse(any(call[:2] == ["npm", "view"] and
call[2] in ACTIVATION_GLOBALS for call in self.calls))
self.assertEqual(Path(os.readlink(self.home / ".dotfiles")), ROOT)
@@ -210,6 +221,46 @@ class RebuildUpdates(unittest.TestCase):
self.execute()
self.assertFalse(any(call[:2] == ["npm", "install"] for call in self.calls))
def test_brew_trust_is_restored_before_switch(self):
output = self.execute()
self.assert_update_order()
trust_calls = [call for call in self.calls if call[0] == "brew"]
self.assertEqual(trust_calls, [
["brew", "trust", "can1357/tap"],
["brew", "trust", "incoai/tap"],
])
switch_index = next(i for i, call in enumerate(self.calls)
if call[0] == "sudo")
self.assertLess(self.calls.index(trust_calls[-1]), switch_index)
self.assertEqual(self.state["trusted_taps"],
["can1357/tap", "incoai/tap"])
self.assertIn("whisper-cpp was renamed", output)
self.assertNotIn("brew bundle failed", output)
def test_brew_trust_failure_still_switches(self):
self.state["fail_brew_trust"] = True
self.execute()
self.assertTrue(any(call[0] == "sudo" for call in self.calls))
def test_deleted_upstream_skills_never_reach_the_cli(self):
denied = (ROOT / "deleted-upstream-skills.txt").read_text().split()
self.assertEqual(len(denied), 20)
names = denied + ["tdd", "security-audit", "codebase-design"]
(self.home / ".agents/.skill-lock.json").write_text(
json.dumps({"skills": {name: {} for name in names}}))
self.state["skills"] = {name: "old" for name in names}
self.execute()
skills_call = next(call for call in self.calls if call[0] == "npx")
for name in denied:
self.assertNotIn(name, skills_call)
self.assertEqual(self.state["skills"][name], "old")
self.assertIn("tdd", skills_call)
self.assertEqual(self.state["skills"]["tdd"], "new")
self.assertNotIn("security-audit", skills_call)
self.assertEqual(self.state["skills"]["security-audit"], "old")
self.assertIn("codebase-design", skills_call)
self.assertEqual(self.state["skills"]["codebase-design"], "new")
def test_absent_packages_are_not_installed_or_queried(self):
self.state["packages"] = {}
self.execute()
@@ -248,7 +299,8 @@ class RebuildUpdates(unittest.TestCase):
(self.home / ".no-mistakes/bin/no-mistakes").unlink()
output = self.execute()
self.assertGreaterEqual(output.count("WARNING:"), 5)
self.assertEqual([call[0] for call in self.calls], ["nix", "sudo"])
self.assertEqual([call[0] for call in self.calls],
["nix", "brew", "brew", "sudo"])
def test_no_mistakes_path_fallback(self):
(self.home / ".no-mistakes/bin/no-mistakes").unlink()
+4 -1
View File
@@ -4,7 +4,7 @@
# The launcher check builds the zshrc from the home-manager configuration and
# runs `fm`, `fm-oc2`, and `fm-pi` with spies. The dispatch check reads the crew
# dispatch config through firstmate's bootstrap validator. Neither starts a real
# agent session.
# agent session. The bird check runs the Brave-only wrapper in a throwaway HOME.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
@@ -13,5 +13,8 @@ status=0
"$ROOT/tests/fm-launcher.sh" || status=1
"$ROOT/tests/crew-dispatch.sh" || status=1
"$ROOT/tests/rebuild-update-steps.sh" || status=1
"$ROOT/tests/bird-brave-e2e.sh" || status=1
"$ROOT/tests/bird-path.sh" || status=1
"$ROOT/tests/skill-denylist.sh" || status=1
exit "$status"
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
# End-to-end check for the shared deleted-upstream skill denylist.
#
# The same source-controlled file must drive both paths. home.nix copies it to
# the Nix store and reads it in home.activation.removeDeletedUpstreamSkills.
# rebuild.sh reads it from its own checkout before calling the Skills CLI. This
# check compares the Nix copy with the source file and confirms rebuild.sh uses
# the same name to filter CLI arguments. The CLI call itself is exercised with
# spies in tests/rebuild-update-steps.py.
set -euo pipefail
ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)
LIST="$ROOT/deleted-upstream-skills.txt"
CONFIG='(builtins.getFlake (toString '"$ROOT"')).darwinConfigurations."lt-mbp".config.home-manager.users.laptran'
fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; }
pass() { printf 'PASS: %s\n' "$1"; }
command -v nix >/dev/null 2>&1 \
|| { echo "skill-denylist: nix is required to evaluate the configuration" >&2; exit 2; }
[ -r "$LIST" ] || fail "denylist missing at $LIST"
expected='agent-self-scheduling
codex-goal-loop
delegating-to-agents
markdown-rendering
run-deep-swe
cyber-audit
pi-custom-model
vps-server-management
pi-web-search
research-prompt
youtube-polls
youtube-transcript
distribute-skill-to-all-agents
folder-specific-claude-and-agents-md
push-skill-to-github
brain-to-docs
grill-me
interview-style-doc-building
short
teach'
[ "$(cat "$LIST")" = "$expected" ] || fail "denylist does not hold the 20 expected names"
pass "denylist holds the 20 deleted upstream skills"
activation=$(nix eval --raw --impure --expr "$CONFIG.home.activation.removeDeletedUpstreamSkills.data")
nix_list=$(printf '%s\n' "$activation" | sed -n 's/^deny_file=//p')
[ -n "$nix_list" ] || fail "activation script does not reference a denylist file"
cmp -s "$nix_list" "$LIST" || fail "Nix denylist copy differs from $LIST"
pass "home.nix activation reads the same denylist"
# shellcheck disable=SC2016 # the literal line in rebuild.sh is the assertion
grep -qF 'DENYLIST="$DIR/deleted-upstream-skills.txt"' "$ROOT/rebuild.sh" \
|| fail "rebuild.sh does not read the shared denylist"
grep -qF 'name not in denied' "$ROOT/rebuild.sh" \
|| fail "rebuild.sh does not filter denied names from the Skills CLI call"
pass "rebuild.sh reads the same denylist and filters CLI arguments"