diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a939f0..53bf194 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,35 @@ jobs: - run: pnpm exec wxt prepare - run: pnpm compile - run: pnpm test + - run: python3 native/test-host.py - run: pnpm build env: WXT_GOOGLE_CLIENT_ID: ci-dummy-client-id WXT_GOOGLE_CLIENT_SECRET: ci-dummy-client-secret + + native-windows: + runs-on: windows-latest + strategy: + matrix: + python: ['3.9', '3.13'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - run: python native/test-host.py + - name: Install the helper + shell: powershell + run: powershell -ExecutionPolicy Bypass -File native/windows/install.ps1 + - name: Registry key exists + shell: cmd + run: reg query HKCU\Software\Google\Chrome\NativeMessagingHosts\com.keytray.agent + - name: Uninstall the helper + shell: powershell + run: powershell -ExecutionPolicy Bypass -File native/windows/install.ps1 -Uninstall + - name: Registry key is gone + shell: cmd + run: | + reg query HKCU\Software\Google\Chrome\NativeMessagingHosts\com.keytray.agent >nul 2>&1 + if %ERRORLEVEL% EQU 0 exit /b 1 + exit /b 0 diff --git a/AGENTS.md b/AGENTS.md index af2f73d..e275b5d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Keytray: a Chrome, Edge and Brave extension (WXT, React, TypeScript) that reads ## Setup - Needs pnpm (version pinned in `package.json`). `pnpm install --frozen-lockfile`, then `pnpm exec wxt prepare`. - Copy `.env.example` to `.env` and set `WXT_GOOGLE_CLIENT_ID` and `WXT_GOOGLE_CLIENT_SECRET` (Google Cloud OAuth client; steps in `SETUP.md`). Never commit `.env`. -- Native helper (agent sign-in): `native/install.sh` (needs Python 3). +- Native helper (agent sign-in): `native/install.sh` on macOS/Linux, `native\windows\install.ps1` on Windows (needs Python 3; WSL uses the Windows install through the CLI). `python native/test-host.py` tests it. ## Commands - `pnpm dev` (WXT dev), `pnpm build`, `pnpm zip` (store build), `pnpm zip:sideload`. diff --git a/README.md b/README.md index 873bc67..e4daf9f 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ A program on your computer (for example an AI agent driving Chrome) can ask Keyt Set up: 1. Run `native/install.sh`. It registers a small helper (`com.keytray.agent`) with Chrome, Edge and Brave. Python 3 is required. + On Windows run `powershell -ExecutionPolicy Bypass -File native\windows\install.ps1` instead (Chrome and Edge). The CLI is then `%LOCALAPPDATA%\Keytray\keytray.cmd`. In WSL, the repo's `native/keytray-agent-cli.py` works after the Windows install: it hands the call to the Windows helper. 2. Open Keytray Options, go to "Agent sign-in" and turn it on. Chrome asks for the native messaging permission. 3. Use the CLI: @@ -48,8 +49,10 @@ native/keytray-agent-cli.py open_link Safety rules: - Only sites on the allowlist work (default github.com, google.com, vercel.com, apple.com; exact host or subdomain). Edit it in Options. Every frame that receives a code must match too, and a link is only opened if its own host is allowed. +- Allowed sites can be `*` (Options: Allow all sites): every https site; the code still goes only to frames on the tab's own site or a listed site, a link opens only on the tab's site or a listed site, and the rate limit stays. - Fill never submits the form. The agent clicks the button itself. - A code is filled once, then marked used. - At most 10 requests per 10 minutes. The last 200 requests are listed in Options with time, command, site and result. They never contain codes or links. - Replies strip any field named code, otp, link, url, token, secret or password. +- On Windows the helper listens on the named pipe `\\.\pipe\keytray-agent-`; a client needs the key in `%LOCALAPPDATA%\Keytray\agent.key`. - The helper listens on `~/Library/Application Support/Keytray/agent.sock` (Linux: `~/.local/share/Keytray/agent.sock`), readable only by your user. Anything running as you can reach it, which is why the allowlist and the off switch exist. diff --git a/docs/agent-protocol.md b/docs/agent-protocol.md index 5a2233b..2bcc6fb 100644 --- a/docs/agent-protocol.md +++ b/docs/agent-protocol.md @@ -9,6 +9,15 @@ How a local program talks to Keytray's agent bridge (`native/keytray-agent.py`). - Override: `KEYTRAY_AGENT_SOCK` (read by both the host and the CLI). - Unix stream socket, mode 0600, directory 0700. The host is started by the extension (`connectNative`) only while Agent sign-in is on in Options. The host removes the socket when it exits. So "off" usually shows up as a missing socket, not as a reply. +## Windows + +- Named pipe `\\.\pipe\keytray-agent-`. Override: `KEYTRAY_AGENT_PIPE`. +- Key file: `%LOCALAPPDATA%\Keytray\agent.key` (override the folder with `KEYTRAY_APPDIR`). The host makes it with 32 random bytes on first start; a file of any other size counts as missing and is replaced. +- The handshake is `multiprocessing.connection` with `family="AF_PIPE"` and the key as `authkey`: `Listener(address, family="AF_PIPE", authkey=key)` on the host, `Client(address, family="AF_PIPE", authkey=key)` in the client. A client without the key fails the handshake and gets no reply. +- One request per connection. Use `send_bytes` and `recv_bytes` only, never `send` or `recv` (they use pickle). The request is the same JSON object as below, as bytes, 65,536 bytes max. The host waits 10 s for it (`poll(10)`); the client should `poll(140)` before `recv_bytes`. +- Known limit: a local process that connects and never answers the handshake can stall `accept()` until it gives up. It needs no key. It is the same class of problem as a local process filling the Unix socket backlog. +- WSL: `native/keytray-agent-cli.py` run inside WSL re-runs itself through the installed `%LOCALAPPDATA%\Keytray\keytray.cmd` (via `cmd.exe`), so the host and client use the same Windows Python. Set `KEYTRAY_NO_WSL_REEXEC=1` to turn that off. + ## Framing One request per connection. The client sends one line of UTF-8 JSON ending in `\n` (65,536 bytes max; the host stops reading after 10 s). The host writes one line of JSON ending in `\n` and closes the connection. The host waits up to 130 s for the extension's reply, so clients should time out after at least 140 s (the CLI uses 140 s). diff --git a/native/keytray-agent-cli.py b/native/keytray-agent-cli.py index a447f66..84daa3a 100755 --- a/native/keytray-agent-cli.py +++ b/native/keytray-agent-cli.py @@ -5,13 +5,20 @@ keytray-agent-cli.py pending keytray-agent-cli.py fill_code [--wait SECONDS] keytray-agent-cli.py open_link + +On Windows it talks to the helper over a named pipe; from WSL it re-runs itself +through the Windows install (%LOCALAPPDATA%\\Keytray\\keytray.cmd). """ +import getpass import json import os import socket +import subprocess import sys TIMEOUT = 140 +WINDOWS = os.name == "nt" +NOT_RUNNING = "Keytray host is not running. Install it with native/install.sh (Windows: native\\windows\\install.ps1) and enable Agent sign-in in Options." def socket_path(): @@ -25,11 +32,53 @@ def socket_path(): return os.path.join(base, "agent.sock") +def appdir(): + override = os.environ.get("KEYTRAY_APPDIR") + if override: + return override + return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "Keytray") + + +def pipe_name(): + override = os.environ.get("KEYTRAY_AGENT_PIPE") + if override: + return override + return "\\\\.\\pipe\\keytray-agent-" + getpass.getuser() + + def fail(message, code=2): print(json.dumps({"ok": False, "error": message})) sys.exit(code) +def under_wsl(): + # the pipe and agent.key exist only on the Windows side, so a WSL shell hands the call to Windows. + # KEYTRAY_NO_WSL_REEXEC=1 turns it off + if os.environ.get("KEYTRAY_NO_WSL_REEXEC"): + return False + try: + with open("/proc/sys/kernel/osrelease") as f: + return "microsoft" in f.read().lower() + except OSError: + return False + + +def wsl_reexec(argv): + missing = "Keytray helper is not installed on Windows: run native\\windows\\install.ps1" + try: + local = subprocess.run(["cmd.exe", "/c", "echo %LOCALAPPDATA%"], capture_output=True, text=True, + cwd="/mnt/c", check=True).stdout.strip().replace("\r", "") + if not local or "%" in local: + fail(missing) + target = local + "\\Keytray\\keytray.cmd" + unix = subprocess.run(["wslpath", "-u", target], capture_output=True, text=True, check=True).stdout.strip() + except (OSError, subprocess.CalledProcessError): + fail(missing) + if not os.path.exists(unix): + fail(missing) + sys.exit(subprocess.call(["cmd.exe", "/c", target] + argv, cwd="/mnt/c")) + + def parse(argv): if not argv: fail("usage: status | pending | fill_code [--wait N] | open_link ") @@ -56,13 +105,12 @@ def parse(argv): return command, args -def main(): - command, args = parse(sys.argv[1:]) +def ask_unix(request): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(TIMEOUT) try: sock.connect(socket_path()) - sock.sendall((json.dumps({"command": command, "args": args}) + "\n").encode()) + sock.sendall((json.dumps(request) + "\n").encode()) buf = b"" while b"\n" not in buf: chunk = sock.recv(65536) @@ -70,10 +118,48 @@ def main(): break buf += chunk except FileNotFoundError: - fail("Keytray host is not running. Install it with native/install.sh and enable Agent sign-in in Options.") + fail(NOT_RUNNING) except (OSError, socket.timeout) as error: fail("could not reach Keytray: %s" % error) - line = buf.split(b"\n", 1)[0].decode("utf-8") + return buf.split(b"\n", 1)[0] + + +def ask_pipe(request): + # send_bytes/recv_bytes only, never send()/recv() (pickle) + from multiprocessing import AuthenticationError + from multiprocessing.connection import Client + + try: + with open(os.path.join(appdir(), "agent.key"), "rb") as f: + key = f.read() + except OSError: + fail(NOT_RUNNING) + if len(key) != 32: + fail(NOT_RUNNING) + try: + conn = Client(pipe_name(), family="AF_PIPE", authkey=key) + except AuthenticationError: + fail("could not reach Keytray: key mismatch, rerun install.ps1") + except (FileNotFoundError, OSError): + fail(NOT_RUNNING) + with conn: + try: + conn.send_bytes(json.dumps(request).encode()) + if not conn.poll(TIMEOUT): + fail("could not reach Keytray: timed out") + return conn.recv_bytes() + except (EOFError, OSError): + return b"" + + +def main(): + argv = sys.argv[1:] + if not WINDOWS and under_wsl(): + wsl_reexec(argv) + command, args = parse(argv) + request = {"command": command, "args": args} + raw = ask_pipe(request) if WINDOWS else ask_unix(request) + line = raw.decode("utf-8").strip() if not line: fail("empty reply from Keytray") try: diff --git a/native/keytray-agent.py b/native/keytray-agent.py index 41a8e2e..9f7ad9a 100755 --- a/native/keytray-agent.py +++ b/native/keytray-agent.py @@ -3,17 +3,60 @@ Chrome starts this process and talks to it over stdio with 4-byte length-prefixed JSON. Local programs talk to it over a unix socket (mode 0600): they send one -JSON line and get one JSON line back. Python 3 standard library only. +JSON line and get one JSON line back. On Windows they use a named pipe instead, +authenticated with the key in agent.key. Python 3 standard library only. """ +import getpass import json import os import socket import struct import sys import threading +import time import uuid REPLY_TIMEOUT = 130 +WINDOWS = os.name == "nt" + + +def appdir(): + override = os.environ.get("KEYTRAY_APPDIR") + if override: + return override + return os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "Keytray") + + +def pipe_name(): + override = os.environ.get("KEYTRAY_AGENT_PIPE") + if override: + return override + return "\\\\.\\pipe\\keytray-agent-" + getpass.getuser() + + +def load_key(): + # 32 random bytes made on first start; a missing or wrong-sized file counts as missing. + # Written to a temp file and moved into place so two racing starts end up with one key. + directory = appdir() + keyfile = os.path.join(directory, "agent.key") + os.makedirs(directory, exist_ok=True) + + def read(): + try: + with open(keyfile, "rb") as f: + data = f.read() + except OSError: + return None + return data if len(data) == 32 else None + + key = read() + if key: + return key + tmp = os.path.join(directory, "agent.key.%s.tmp" % uuid.uuid4().hex) + with open(tmp, "wb") as f: + f.write(os.urandom(32)) + os.replace(tmp, keyfile) + return read() or load_key() def socket_path(): @@ -50,6 +93,31 @@ def send_to_extension(message): sys.stdout.buffer.flush() +def relay(raw): + try: + request = json.loads(raw.decode("utf-8")) + if not isinstance(request, dict): + raise ValueError("request must be an object") + except ValueError as error: + return {"ok": False, "error": "bad request: %s" % error} + req_id = uuid.uuid4().hex + slot = {"event": threading.Event(), "reply": None} + with pending_lock: + pending[req_id] = slot + try: + send_to_extension({"id": req_id, "command": request.get("command"), "args": request.get("args", [])}) + if slot["event"].wait(REPLY_TIMEOUT): + reply = slot["reply"] + else: + reply = {"ok": False, "error": "no reply from the extension"} + finally: + with pending_lock: + pending.pop(req_id, None) + reply = dict(reply) + reply.pop("id", None) + return reply + + def handle_client(conn): try: conn.settimeout(10) @@ -60,35 +128,49 @@ def handle_client(conn): break buf += chunk line = buf.split(b"\n", 1)[0] - try: - request = json.loads(line.decode("utf-8")) - if not isinstance(request, dict): - raise ValueError("request must be an object") - except ValueError as error: - conn.sendall((json.dumps({"ok": False, "error": "bad request: %s" % error}) + "\n").encode()) - return - req_id = uuid.uuid4().hex - slot = {"event": threading.Event(), "reply": None} - with pending_lock: - pending[req_id] = slot - try: - send_to_extension({"id": req_id, "command": request.get("command"), "args": request.get("args", [])}) - if slot["event"].wait(REPLY_TIMEOUT): - reply = slot["reply"] - else: - reply = {"ok": False, "error": "no reply from the extension"} - finally: - with pending_lock: - pending.pop(req_id, None) - reply = dict(reply) - reply.pop("id", None) - conn.sendall((json.dumps(reply) + "\n").encode()) + conn.sendall((json.dumps(relay(line)) + "\n").encode()) except OSError: pass finally: conn.close() +def handle_pipe_client(conn): + try: + if not conn.poll(10): + return + try: + raw = conn.recv_bytes(65536) + except (OSError, EOFError): + return + conn.send_bytes(json.dumps(relay(raw)).encode()) + except (OSError, EOFError): + pass + finally: + try: + conn.close() + except Exception: + pass + + +def serve_pipe(): + from multiprocessing.connection import Listener + + while True: + try: + listener = Listener(address=pipe_name(), family="AF_PIPE", authkey=load_key()) + except Exception: + time.sleep(5) # an old helper may still hold the pipe + continue + while True: + try: + conn = listener.accept() + except Exception: + time.sleep(0.05) # failed key handshake: drop it, keep listening, never spin + continue + threading.Thread(target=handle_pipe_client, args=(conn,), daemon=True).start() + + def serve(path): directory = os.path.dirname(path) os.makedirs(directory, mode=0o700, exist_ok=True) @@ -111,8 +193,11 @@ def serve(path): def main(): - path = socket_path() - threading.Thread(target=serve, args=(path,), daemon=True).start() + path = None if WINDOWS else socket_path() + if WINDOWS: + threading.Thread(target=serve_pipe, daemon=True).start() + else: + threading.Thread(target=serve, args=(path,), daemon=True).start() stdin = sys.stdin.buffer try: while True: @@ -133,10 +218,11 @@ def main(): slot["reply"] = message slot["event"].set() finally: - try: - os.unlink(path) - except OSError: - pass + if path: + try: + os.unlink(path) + except OSError: + pass if __name__ == "__main__": diff --git a/native/test-host.py b/native/test-host.py index 006e081..4c73590 100644 --- a/native/test-host.py +++ b/native/test-host.py @@ -1,13 +1,40 @@ #!/usr/bin/env python3 -"""Smoke test: spawn keytray-agent.py with a fake extension on stdio, run the CLI against it.""" -import json, os, struct, subprocess, sys, tempfile, threading, time +"""Smoke test: spawn keytray-agent.py with a fake extension on stdio, run the CLI against it. + +Works on Unix (socket) and Windows (named pipe + key file). Exits non-zero on any failure. +""" +import json, os, shutil, struct, subprocess, sys, tempfile, threading, time, uuid here = os.path.dirname(os.path.abspath(__file__)) -sock = os.path.join(tempfile.mkdtemp(), "k", "agent.sock") -env = dict(os.environ, KEYTRAY_AGENT_SOCK=sock) +windows = os.name == "nt" +tmp = tempfile.mkdtemp() +env = dict(os.environ, KEYTRAY_NO_WSL_REEXEC="1") +if windows: + appdir = os.path.join(tmp, "Keytray") + pipe = r"\\.\pipe\keytray-test-" + uuid.uuid4().hex + env.update(KEYTRAY_APPDIR=appdir, KEYTRAY_AGENT_PIPE=pipe) + os.makedirs(appdir) + keyfile = os.path.join(appdir, "agent.key") + with open(keyfile, "wb") as f: + f.write(b"short") # a wrong-sized key must be replaced +else: + sock = os.path.join(tmp, "k", "agent.sock") + env["KEYTRAY_AGENT_SOCK"] = sock + +cli = os.path.join(here, "keytray-agent-cli.py") +failures = [] + + +def check(ok, what): + if not ok: + failures.append(what) + print("FAIL:", what) + + host = subprocess.Popen([sys.executable, os.path.join(here, "keytray-agent.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env) + def fake_extension(): while True: h = host.stdout.read(4) @@ -19,27 +46,66 @@ def fake_extension(): host.stdin.write(struct.pack("= (3, 8) else '')" 2>$null + if ($LASTEXITCODE -eq 0 -and $real -and (Test-Path -LiteralPath $real)) { $py = $real; break } + } + if ($py) { break } +} +if (-not $py) { + throw "Python 3.8 or newer was not found. Install it from https://www.python.org/downloads/ and run this script again." +} + +New-Item -ItemType Directory -Force -Path $Dest | Out-Null +Copy-Item -Force (Join-Path $Native "keytray-agent.py") (Join-Path $Dest "keytray-agent.py") +Copy-Item -Force (Join-Path $Native "keytray-agent-cli.py") (Join-Path $Dest "keytray-agent-cli.py") + +function Write-Cmd([string]$ScriptName, [string]$CmdName) { + $cmdPath = Join-Path $Dest $CmdName + $scriptPath = Join-Path $Dest $ScriptName + $lines = @("@echo off", "`"$py`" -u `"$scriptPath`" %*") + [System.IO.File]::WriteAllText($cmdPath, ($lines -join "`r`n") + "`r`n", $Utf8) + return $cmdPath +} +$hostCmd = Write-Cmd "keytray-agent.py" "keytray-agent.cmd" +$cliCmd = Write-Cmd "keytray-agent-cli.py" "keytray.cmd" + +# Dev id: sha256 of the DER public key, first 32 hex chars mapped 0-f to a-p (same as install.sh) +$snippet = @' +import base64, hashlib, re, sys +text = open(sys.argv[1]).read() +key = re.search(r"EXTENSION_KEY\s*=\s*'([^']+)'", text).group(1) +digest = hashlib.sha256(base64.b64decode(key)).hexdigest()[:32] +print("".join(chr(ord("a") + int(c, 16)) for c in digest)) +'@ +$snipFile = Join-Path $Dest "devid.tmp.py" +[System.IO.File]::WriteAllText($snipFile, $snippet, $Utf8) +$devId = ((& $py $snipFile $Config) | Out-String).Trim() +Remove-Item -LiteralPath $snipFile -Force +if ($LASTEXITCODE -ne 0 -or -not $devId) { throw "Could not compute the dev extension id from wxt.config.ts." } + +$ids = @() +foreach ($id in (@($StoreId, $devId) + @($ExtraIds))) { + if ($id -and ($ids -notcontains $id)) { $ids += $id } +} +$origins = @($ids | ForEach-Object { "chrome-extension://$_/" }) +$body = [ordered]@{ + name = $HostName + description = "Keytray agent sign-in bridge" + path = $hostCmd + type = "stdio" + allowed_origins = $origins +} | ConvertTo-Json -Depth 4 +[System.IO.File]::WriteAllText($Manifest, $body + "`n", $Utf8) + +foreach ($root in $Roots) { + $key = Join-Path $root $HostName + New-Item -Path $key -Force | Out-Null + Set-Item -LiteralPath $key -Value $Manifest +} + +Write-Output "Store extension id: $StoreId" +Write-Output "Dev (key) extension id: $devId" +Write-Output "Host: $hostCmd" +Write-Output "CLI: $cliCmd" +Write-Output "Reload Keytray, then turn on Agent sign-in in Options."