Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -48,8 +49,10 @@ native/keytray-agent-cli.py open_link <tabId>
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-<user>`; 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.
9 changes: 9 additions & 0 deletions docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<user name>`. 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).
Expand Down
96 changes: 91 additions & 5 deletions native/keytray-agent-cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@
keytray-agent-cli.py pending <tabId>
keytray-agent-cli.py fill_code <tabId> [--wait SECONDS]
keytray-agent-cli.py open_link <tabId>

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():
Expand All @@ -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 <tabId> | fill_code <tabId> [--wait N] | open_link <tabId>")
Expand All @@ -56,24 +105,61 @@ 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)
if not chunk:
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:
Expand Down
Loading
Loading