Replace shared bearer token with registered Ed25519 client keys.

This commit is contained in:
alexveley
2026-09-22 06:54:43 -04:00
parent 535b3ce837
commit 43d94932fb
9 changed files with 412 additions and 100 deletions
+32 -15
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Minimal client for Firefox Agent Bridge. Stdlib only."""
"""Call Firefox Agent Bridge with a registered Ed25519 client key."""
from __future__ import annotations
import argparse
@@ -11,33 +11,49 @@ import urllib.request
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from fab_auth import load_key_bundle, sign_headers # noqa: E402
DEFAULT_BASE = os.environ.get("FAB_URL", "http://127.0.0.1:17634")
TOKEN_PATH = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "firefox-agent-bridge" / "token"
def token() -> str:
env = os.environ.get("FAB_TOKEN")
def key_path() -> Path:
env = os.environ.get("FAB_KEY_FILE")
if env:
return env.strip()
if TOKEN_PATH.exists():
return TOKEN_PATH.read_text(encoding="utf-8").strip()
raise SystemExit(f"no token: set FAB_TOKEN or create {TOKEN_PATH}")
return Path(env)
raise SystemExit(
"no client key: set FAB_KEY_FILE or pass --key "
"(python tools/register_client.py add --name NAME --write-key PATH)"
)
def call(method: str, args: list[Any] | None = None, base: str = DEFAULT_BASE) -> Any:
def call(
method: str,
args: list[Any] | None = None,
base: str = DEFAULT_BASE,
key_file: Path | None = None,
) -> Any:
payload = json.dumps({"method": method, "args": args or []}).encode("utf-8")
path = "/v1/call"
bundle = load_key_bundle(key_file or key_path())
headers = {
"Content-Type": "application/json",
**sign_headers(bundle, "POST", path, payload),
}
req = urllib.request.Request(
base.rstrip("/") + "/v1/call",
base.rstrip("/") + path,
data=payload,
method="POST",
headers={
"Authorization": f"Bearer {token()}",
"Content-Type": "application/json",
},
headers=headers,
)
try:
with urllib.request.urlopen(req, timeout=20) as resp:
body = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")
raise SystemExit(f"bridge HTTP {exc.code}: {detail}") from exc
except urllib.error.URLError as exc:
raise SystemExit(
f"bridge unreachable at {base} ({exc}). "
@@ -53,11 +69,12 @@ def main() -> int:
parser.add_argument("method", help="e.g. bookmarks.search or meta.methods")
parser.add_argument("args_json", nargs="?", default="[]", help="JSON array of arguments")
parser.add_argument("--url", default=DEFAULT_BASE)
parser.add_argument("--key", type=Path, help="client key bundle (or FAB_KEY_FILE)")
ns = parser.parse_args()
args = json.loads(ns.args_json)
if not isinstance(args, list):
raise SystemExit("args_json must be a JSON array")
print(json.dumps(call(ns.method, args, base=ns.url), indent=2))
print(json.dumps(call(ns.method, args, base=ns.url, key_file=ns.key), indent=2))
return 0
+6 -11
View File
@@ -16,14 +16,9 @@ if (-not (Test-Path $CmdPath)) {
}
New-Item -ItemType Directory -Force -Path $StateDir | Out-Null
if (-not (Test-Path $TokenPath) -or -not (Get-Content -Raw $TokenPath).Trim()) {
$bytes = New-Object byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$token = -join ($bytes | ForEach-Object { $_.ToString("x2") })
[System.IO.File]::WriteAllText($TokenPath, $token)
Write-Host "wrote $TokenPath"
} else {
Write-Host "kept existing token at $TokenPath"
if (Test-Path $TokenPath) {
Remove-Item -Force $TokenPath
Write-Host "removed leftover shared token $TokenPath"
}
$manifest = @{
@@ -42,6 +37,6 @@ Set-ItemProperty -Path $regPath -Name "(default)" -Value $ManifestPath
Write-Host "registered $regPath"
Write-Host ""
Write-Host "Next: in Firefox open about:debugging#/runtime/this-firefox"
Write-Host "Load Temporary Add-on and pick extension\manifest.json"
Write-Host "Token is read from $TokenPath (Authorization: Bearer ...)"
Write-Host "Register a client key for tooling (private key stays out of $StateDir):"
Write-Host " python tools\register_client.py add --name cursor-agent --write-key `$HOME\.fab\cursor-agent.json"
Write-Host "Then load the extension and set FAB_KEY_FILE to that path."
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Register, list, or revoke Ed25519 clients for Firefox Agent Bridge."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from fab_auth import CLIENTS_PATH, load_clients, register_client, revoke_client # noqa: E402
def main() -> int:
parser = argparse.ArgumentParser(description="Manage Firefox Agent Bridge clients")
sub = parser.add_subparsers(dest="cmd", required=True)
add = sub.add_parser("add", help="generate a keypair and register the public half")
add.add_argument("--name", required=True, help="label, e.g. cursor-agent")
add.add_argument(
"--write-key",
required=True,
type=Path,
help="private key bundle path for tooling (must not be under LocalAppData\\firefox-agent-bridge)",
)
sub.add_parser("list", help="show registered public clients")
drop = sub.add_parser("revoke", help="drop a client by name or id")
drop.add_argument("name_or_id")
ns = parser.parse_args()
if ns.cmd == "add":
info = register_client(ns.name, ns.write_key)
print(json.dumps(info, indent=2))
print(f"give {info['key_file']} to tooling via FAB_KEY_FILE or --key", file=sys.stderr)
return 0
if ns.cmd == "list":
rows = [
{"id": c.get("id"), "name": c.get("name"), "created": c.get("created")}
for c in load_clients()
]
print(json.dumps({"store": str(CLIENTS_PATH), "clients": rows}, indent=2))
return 0
revoke_client(ns.name_or_id)
print(json.dumps({"revoked": ns.name_or_id}))
return 0
if __name__ == "__main__":
raise SystemExit(main())