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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

```
Expand Down
18 changes: 18 additions & 0 deletions docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
93 changes: 87 additions & 6 deletions entrypoints/background.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -102,17 +107,84 @@ async function syncAgentConnection(): Promise<void> {
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<void> {
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<boolean> {
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<string, unknown>;
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<typeof browser.runtime.connectNative>;
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<typeof setTimeout> | 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' }))
Expand All @@ -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 {
Expand Down Expand Up @@ -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<string>(['SET_CUSTOM_OAUTH', 'CLEAR_CUSTOM_OAUTH']);
const PAGE_ONLY_MESSAGES = new Set<string>(['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 {
Expand Down
14 changes: 12 additions & 2 deletions entrypoints/options/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
};
Expand Down Expand Up @@ -274,6 +281,9 @@ export function App() {
checked={state.settings.agentEnabled}
onChange={(on) => void toggleAgent(on)}
/>
{state.settings.agentConfigFromFile && (
<p className="text-xs text-ink/60">Set by this computer's Keytray config file.</p>
)}
<label className="block text-sm">
Allowed sites (one per line, subdomains included)
<textarea
Expand Down
57 changes: 56 additions & 1 deletion lib/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* is unit-testable.
*/
import { getDomain } from 'tldts';
import { CODE_MAX_AGE_MS, type CodeEntry } from './types';
import { CODE_MAX_AGE_MS, type CodeEntry, type Settings } from './types';

export const DEFAULT_AGENT_ALLOWLIST = ['github.com', 'google.com', 'vercel.com', 'apple.com'];
/** Allowlist entry meaning every https site. */
Expand Down Expand Up @@ -121,6 +121,61 @@ export function urlSite(url: string): string {
}
}

/** What the helper reads from the per-machine config.json. Never a site list. */
export interface AgentFileConfig {
agentSignIn?: boolean;
allowAll?: boolean;
}

/**
* Settings changes implied by the computer's config file, or null for no change.
* - The Options off switch (agentOffByUser) always wins over turning the agent on.
* - A missing file or agentSignIn not true never switches the agent off; it only
* clears the from-file flag.
* - '*' is added only for allowAll:true, once, and never after the user removed
* it (agentAllowAllOffByUser). The file removes only a '*' it added itself.
*/
export function applyFileConfig(
settings: Pick<
Settings,
| 'agentEnabled'
| 'agentAllowlist'
| 'agentConfigFromFile'
| 'agentOffByUser'
| 'agentAllowAllFromFile'
| 'agentAllowAllOffByUser'
>,
config: AgentFileConfig | null | undefined,
): Partial<Settings> | null {
const patch: Partial<Settings> = {};
const fileOn = config?.agentSignIn === true;
const wantAll = fileOn && config?.allowAll === true;

if (settings.agentAllowAllFromFile && !wantAll) {
patch.agentAllowAllFromFile = false;
if (settings.agentAllowlist.includes(ALL_SITES)) {
patch.agentAllowlist = settings.agentAllowlist.filter((e) => e !== ALL_SITES);
}
}
if (!fileOn) {
if (settings.agentConfigFromFile) patch.agentConfigFromFile = false;
} else if (!settings.agentOffByUser) {
if (!settings.agentEnabled) patch.agentEnabled = true;
// Claim it only when the file itself turned the agent on.
if (!settings.agentEnabled && !settings.agentConfigFromFile) patch.agentConfigFromFile = true;
if (
wantAll &&
!settings.agentAllowAllFromFile &&
!settings.agentAllowAllOffByUser &&
!settings.agentAllowlist.includes(ALL_SITES)
) {
patch.agentAllowlist = [...settings.agentAllowlist, ALL_SITES];
patch.agentAllowAllFromFile = true;
}
}
return Object.keys(patch).length ? patch : null;
}

export class RateLimiter {
private hits: number[] = [];
constructor(
Expand Down
12 changes: 12 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ export interface Settings {
agentEnabled: boolean;
/** Sites the agent may act on: exact host or any subdomain. */
agentAllowlist: string[];
/** Agent sign-in was switched on by the computer's config file. */
agentConfigFromFile: boolean;
/** The user switched Agent sign-in off in Options; the config file then cannot turn it on. */
agentOffByUser: boolean;
/** The '*' in the allowlist was added by the config file (and only then may the file remove it). */
agentAllowAllFromFile: boolean;
/** The user removed '*' in Options; the config file does not add it again until the user does. */
agentAllowAllOffByUser: boolean;
}

export interface PersistedState {
Expand Down Expand Up @@ -93,6 +101,10 @@ export const DEFAULT_SETTINGS: Settings = {
codeClickAction: 'open',
agentEnabled: false,
agentAllowlist: ['github.com', 'google.com', 'vercel.com', 'apple.com'],
agentConfigFromFile: false,
agentOffByUser: false,
agentAllowAllFromFile: false,
agentAllowAllOffByUser: false,
};

export const EMPTY_STATE: PersistedState = {
Expand Down
35 changes: 32 additions & 3 deletions native/install.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
#!/usr/bin/env bash
# Registers the Keytray native messaging host with Chrome, Edge and Brave.
# Usage: native/install.sh [extra-extension-id ...]
# Usage: native/install.sh [--enable | --allow-all] [extra-extension-id ...]
# --enable also write config.json with agentSignIn on (no site list)
# --allow-all like --enable, and allow all https sites
set -euo pipefail

CONFIG_MODE=""
IDS=()
for arg in "$@"; do
case "$arg" in
--enable) [ "$CONFIG_MODE" = allow-all ] || CONFIG_MODE=enable ;;
--allow-all) CONFIG_MODE=allow-all ;;
-*) echo "unknown option: $arg" >&2; exit 2 ;;
*)
if ! [[ "$arg" =~ ^[a-p]{32}$ ]]; then echo "not an extension id (32 letters a-p): $arg" >&2; exit 2; fi
IDS+=("$arg") ;;
esac
done

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HOST_PATH="$HERE/keytray-agent.py"
CONFIG="$HERE/../wxt.config.ts"
Expand All @@ -21,7 +36,7 @@ PY
)"

ORIGINS=""
for id in "$STORE_ID" "$DEV_ID" "$@"; do
for id in "$STORE_ID" "$DEV_ID" ${IDS[@]+"${IDS[@]}"}; do
case "$ORIGINS" in *"chrome-extension://$id/"*) continue ;; esac
ORIGINS="$ORIGINS\"chrome-extension://$id/\", "
done
Expand Down Expand Up @@ -56,7 +71,21 @@ for dir in "${DIRS[@]}"; do
echo "wrote $dir/com.keytray.agent.json"
done

if [ -n "$CONFIG_MODE" ]; then
case "$(uname -s)" in
Darwin) APPDIR="$HOME/Library/Application Support/Keytray" ;;
*) APPDIR="${XDG_DATA_HOME:-$HOME/.local/share}/Keytray" ;;
esac
(umask 077; mkdir -p "$APPDIR")
chmod 700 "$APPDIR"
if [ "$CONFIG_MODE" = allow-all ]; then ALL=true; else ALL=false; fi
TMP="$APPDIR/config.json.$$.tmp"
(umask 077; printf '{"agentSignIn": true, "allowAll": %s}\n' "$ALL" > "$TMP")
mv -f "$TMP" "$APPDIR/config.json"
echo "wrote $APPDIR/config.json (agentSignIn on, allowAll $ALL)"
fi

echo "Store extension id: $STORE_ID"
echo "Dev (key) extension id: $DEV_ID"
echo "Host: $HOST_PATH"
echo "Next: open Keytray Options and turn on Agent sign-in."
if [ -z "$CONFIG_MODE" ]; then echo "Next: open Keytray Options and turn on Agent sign-in."; fi
Loading
Loading