diff --git a/README.md b/README.md index e4daf9f..a7b6748 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,8 @@ 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. +2. Open Keytray Options, go to "Agent sign-in" and turn it on. + 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; `agentSignIn` false or missing never turns it off by itself; deleting the file or setting `allowAll` to false removes the `*` the file added on the next browser start, and any program running as your user can write that file, and so can turn Agent sign-in on and allow all sites; switching Agent sign-in off in Options blocks that. 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..882b9c9 100644 --- a/docs/agent-protocol.md +++ b/docs/agent-protocol.md @@ -84,3 +84,21 @@ 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." +- Deleting the file, or setting `allowAll` to false, removes the `*` the file added, on the next browser start (a `*` the user added in Options stays). If the user removes `*` in Options, the file does not add it again until the user does. +- `agentSignIn` false or missing never turns Agent sign-in off by itself; only the Options switch does. +- 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, and so can turn Agent sign-in on and allow all sites. Switching Agent sign-in off in Options blocks that. +- `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..27c1793 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'; @@ -46,7 +46,12 @@ export default defineBackground(() => { void cachePaid(user.paid === true); }); void ensureAlarm(); + // The config-file probe runs only at browser start and install, never on a plain worker wake. + browser.runtime.onStartup.addListener(() => { + void probeIfAgentOff(); + }); browser.runtime.onInstalled.addListener(() => { + void probeIfAgentOff(); void ensureAlarm(); }); browser.alarms.onAlarm.addListener((alarm) => { @@ -102,17 +107,84 @@ async function syncAgentConnection(): Promise { if (!nativePort) connectAgent(); } -function connectAgent(): void { +/** + * At browser start or install, 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 probeIfAgentOff(): Promise { + const { settings } = await loadState(); + if (!settings.agentEnabled && !settings.agentOffByUser && !nativePort) connectAgent(true); +} + +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. + } + // The user may have switched it on while the probe ran. + void syncAgentConnection(); + }; + // 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 +197,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 { @@ -231,7 +312,7 @@ function markAllNeedReauth(state: PersistedState): void { } /** Messages only the extension's own pages (options, popup) may send, never a content script. */ -const PAGE_ONLY_MESSAGES = new Set(['SET_CUSTOM_OAUTH', 'CLEAR_CUSTOM_OAUTH']); +const PAGE_ONLY_MESSAGES = new Set(['SET_CUSTOM_OAUTH', 'CLEAR_CUSTOM_OAUTH', 'SET_SETTINGS']); /** Options opens in a tab, so sender.tab is set there; a content script's url is the web page's. */ export function fromExtensionPage(sender: { id?: string; url?: string }): boolean { diff --git a/entrypoints/options/App.tsx b/entrypoints/options/App.tsx index ad22136..1acb14f 100644 --- a/entrypoints/options/App.tsx +++ b/entrypoints/options/App.tsx @@ -73,12 +73,19 @@ 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) => { const list = normalizeAllowlist(text.split(/[\s,]+/)); - await updateSettings({ agentAllowlist: list }); + const hadAll = state?.settings.agentAllowlist.includes(ALL_SITES) ?? false; + const hasAll = list.includes(ALL_SITES); + await updateSettings({ + agentAllowlist: list, + // Keep the from-file flag while the file's own * stays; clear it when the user removes or adds *. + agentAllowAllFromFile: hadAll && hasAll ? (state?.settings.agentAllowAllFromFile ?? false) : false, + agentAllowAllOffByUser: hasAll ? false : hadAll ? true : (state?.settings.agentAllowAllOffByUser ?? false), + }); setAllowlistDirty(false); setAllowlistText(list.join('\n')); }; @@ -274,6 +281,9 @@ export function App() { checked={state.settings.agentEnabled} onChange={(on) => void toggleAgent(on)} /> + {state.settings.agentConfigFromFile && ( +

Set by this computer's Keytray config file.

+ )}