From 93bb7dbf2d92dc00cc9885d8e9e6d5824fa1fdd8 Mon Sep 17 00:00:00 2001 From: Mehdi Date: Sun, 15 Nov 2026 21:35:36 -0600 Subject: [PATCH 1/4] Agent sign-in: per-machine config file (on/off and all sites only) Refs #41 --- README.md | 1 + docs/agent-protocol.md | 16 +++++ entrypoints/background.ts | 90 ++++++++++++++++++++++++-- entrypoints/options/App.tsx | 5 +- lib/agent.ts | 31 ++++++++- lib/types.ts | 6 ++ native/install.sh | 31 ++++++++- native/keytray-agent.py | 35 +++++++++++ native/test-host.py | 43 ++++++++++++- native/windows/install.ps1 | 19 +++++- tests/agent.test.ts | 41 ++++++++++++ tests/background-config.test.ts | 108 ++++++++++++++++++++++++++++++++ 12 files changed, 411 insertions(+), 15 deletions(-) create mode 100644 tests/background-config.test.ts diff --git a/README.md b/README.md index e4daf9f..c7b7cb5 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ 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. + Or skip the click: run the installer with `--enable` (Windows `-Enable`), or `--allow-all` (`-AllowAll`) to also allow all sites. This writes a per-machine `config.json` (`{"agentSignIn": true, "allowAll": true}`) in the helper's folder; Keytray reads it when it starts. It has only those two switches and no site list on purpose. The off switch in Options always wins, and any program running as your user can write that file (same trust as the helper itself). Details: `docs/agent-protocol.md`. Uninstall keeps the file. 3. Use the CLI: ``` diff --git a/docs/agent-protocol.md b/docs/agent-protocol.md index ded33dd..d1d8207 100644 --- a/docs/agent-protocol.md +++ b/docs/agent-protocol.md @@ -84,3 +84,19 @@ From the client side (no reply at all): ## All sites With `*` in the allowlist, listed sites work as before. A site that is not in the list only gets codes and links mailed from that same site (its registrable domain), and mail that failed Gmail's DMARC check is ignored for it. `pending` follows the same rule, and the tab is checked again just before each fill or open. + +## Config file + +The computer's owner can turn on Agent sign-in without clicking in Options. The helper reads `config.json` from its app folder (Windows `%LOCALAPPDATA%\Keytray\config.json`, macOS `~/Library/Application Support/Keytray/config.json`, Linux `${XDG_DATA_HOME:-~/.local/share}/Keytray/config.json`): + +```json +{"agentSignIn": true, "allowAll": true} +``` + +- Only these two keys count, and only as real booleans. Any other key is ignored, and a non-boolean value counts as absent. The file is read up to 4096 bytes. +- There is no site list on purpose: a list would bypass the sender-site check that `*` keeps. `allowAll: true` only adds `*` to the allowlist; `false` never removes anything. +- The extension asks the helper with `{"kind": "getConfig"}` over the native port and gets `{"kind": "config", "config": {...} | null}`. This is the only way it is read; messages from web pages or other extensions never set it. +- With Agent sign-in off, the extension asks once at start (5 s, no retries) when the user has not switched it off in Options. If the file says on, Agent sign-in turns on and Options shows "Set by this computer's Keytray config file." +- The Options off switch always wins: once the user turns Agent sign-in off, the file cannot turn it on again until the user turns it on. +- Any program running as the same user can write this file. That is the same trust level as the helper and its socket or pipe. +- `native/install.sh --enable` or `--allow-all` (Windows: `-Enable`, `-AllowAll`) writes the file; without a flag the installers never create or change it. Uninstall keeps `config.json`. diff --git a/entrypoints/background.ts b/entrypoints/background.ts index 95dc8db..8564406 100644 --- a/entrypoints/background.ts +++ b/entrypoints/background.ts @@ -1,6 +1,6 @@ import { browser } from 'wxt/browser'; import type { ExtensionRequest, ExtensionResponse, FillResponse, HasFieldResponse } from '~/lib/messages'; -import { RateLimiter, runAgentCommand, type AgentDeps, type AgentRequest } from '~/lib/agent'; +import { RateLimiter, applyFileConfig, runAgentCommand, type AgentFileConfig, type AgentDeps, type AgentRequest } from '~/lib/agent'; import { AuthError, HistoryExpiredError, gmailMessageUrl, pollGmail } from '~/lib/gmail'; import { extractCode } from '~/lib/extract'; import { notificationClickAction } from '~/lib/entry-display'; @@ -69,7 +69,7 @@ export default defineBackground(() => { }); return true; }); - void syncAgentConnection(); + void startAgent(); browser.storage.onChanged.addListener((changes, area) => { if (area === 'local' && changes.otpState) void syncAgentConnection(); }); @@ -102,17 +102,86 @@ async function syncAgentConnection(): Promise { if (!nativePort) connectAgent(); } -function connectAgent(): void { +/** + * At start, with Agent sign-in off and not switched off by the user, ask the + * helper once for the config file. No retries: a missing helper just ends the probe. + */ +async function startAgent(): Promise { + const { settings } = await loadState(); + if (!settings.agentEnabled && !settings.agentOffByUser) { + connectAgent(true); + return; + } + await syncAgentConnection(); +} + +const PROBE_TIMEOUT_MS = 5000; + +/** Applies a config reply. Returns true when Agent sign-in is on afterwards. */ +function applyConfigMessage(config: AgentFileConfig | null): Promise { + return enqueue(async () => { + const state = await loadState(); + const patch = applyFileConfig(state.settings, config); + if (patch) { + state.settings = { ...state.settings, ...patch }; + await saveState(state); + await publish(state); + } + return state.settings.agentEnabled; + }); +} + +function parseConfig(value: unknown): AgentFileConfig | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const raw = value as Record; + const config: AgentFileConfig = {}; + if (typeof raw.agentSignIn === 'boolean') config.agentSignIn = raw.agentSignIn; + if (typeof raw.allowAll === 'boolean') config.allowAll = raw.allowAll; + return config; +} + +function connectAgent(probe = false): void { let port: ReturnType; try { port = browser.runtime.connectNative(NATIVE_HOST); } catch (error) { console.error('[Keytray] agent host unavailable', error); - scheduleReconnect(); + if (!probe) scheduleReconnect(); return; } + let probing = probe; + let probeTimer: ReturnType | undefined; + const endProbe = (): void => { + clearTimeout(probeTimer); + probing = false; + }; + const dropProbe = (): void => { + endProbe(); + if (nativePort === port) nativePort = null; + try { + port.disconnect(); + } catch { + // Already closed. + } + }; + // Held as the connection from the start, so a storage change made by a + // config reply does not open a second port. nativePort = port; port.onMessage.addListener((message: unknown) => { + if (message && typeof message === 'object' && (message as { kind?: unknown }).kind === 'config') { + // Config comes only from the native port and never reaches runAgentCommand. + const wasProbe = probing; + void applyConfigMessage(parseConfig((message as { config?: unknown }).config)) + .then((enabled) => { + if (!wasProbe) return; + if (enabled) endProbe(); + else dropProbe(); + }) + .catch(() => { + if (wasProbe) dropProbe(); + }); + return; + } const request = message as AgentRequest; void runAgentCommand(request, agentDeps()) .catch((error: unknown) => ({ ok: false, error: error instanceof Error ? error.message : 'failed' })) @@ -125,10 +194,19 @@ function connectAgent(): void { }); }); port.onDisconnect.addListener(() => { + void browser.runtime.lastError; // read it so Chrome logs nothing + const wasProbing = probing; + endProbe(); if (nativePort === port) nativePort = null; - scheduleReconnect(); + if (!wasProbing) scheduleReconnect(); }); - reconnectDelay = 1000; + try { + port.postMessage({ kind: 'getConfig' }); + } catch { + // Port already closed; onDisconnect handles it. + } + if (probe) probeTimer = setTimeout(dropProbe, PROBE_TIMEOUT_MS); + else reconnectDelay = 1000; } function scheduleReconnect(): void { diff --git a/entrypoints/options/App.tsx b/entrypoints/options/App.tsx index ad22136..62f9d5a 100644 --- a/entrypoints/options/App.tsx +++ b/entrypoints/options/App.tsx @@ -73,7 +73,7 @@ export function App() { const toggleAgent = async (on: boolean) => { setError(''); - await updateSettings({ agentEnabled: on }); + await updateSettings({ agentEnabled: on, agentOffByUser: !on, agentConfigFromFile: false }); }; const saveAllowlist = async (text: string) => { @@ -274,6 +274,9 @@ export function App() { checked={state.settings.agentEnabled} onChange={(on) => void toggleAgent(on)} /> + {state.settings.agentConfigFromFile && ( +

Set by this computer's Keytray config file.

+ )}