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
15 changes: 13 additions & 2 deletions entrypoints/options/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { browser } from 'wxt/browser';
import { signInInteractive } from '~/lib/auth';
import { FREE_ACCOUNT_LIMIT } from '~/lib/account-limit';
import { openPaymentPage } from '~/lib/billing';
import { DEFAULT_AGENT_ALLOWLIST, normalizeAllowlist, type AgentLogEntry } from '~/lib/agent';
import { ALL_SITES, DEFAULT_AGENT_ALLOWLIST, normalizeAllowlist, type AgentLogEntry } from '~/lib/agent';
import { loadAgentLog, validateCustomOAuth } from '~/lib/storage';
import type { ExtensionResponse } from '~/lib/messages';
import type { CodeClickAction, Mode, PopupShows, PublicState, Settings } from '~/lib/types';
Expand Down Expand Up @@ -267,7 +267,7 @@ export function App() {
<h2 className="text-lg font-semibold">Agent sign-in</h2>
<p className="text-xs text-ink/60">
Lets a local program on this computer ask Keytray to fill the newest code, or open the newest sign-in link, in
a tab. The program never sees the code or the link. It needs the helper from native/install.sh.
a tab. The program never sees the code or the link. It needs the helper from native/install.sh (macOS, Linux) or native\windows\install.ps1 (Windows).
</p>
<Toggle
label="Allow agent sign-in"
Expand Down Expand Up @@ -299,7 +299,18 @@ export function App() {
>
Reset to defaults
</button>
<button
className="rounded-md border border-line px-3 py-1.5 text-sm"
onClick={() => void saveAllowlist(ALL_SITES)}
>
Allow all sites
</button>
</div>
{state.settings.agentAllowlist.includes(ALL_SITES) && (
<p className="text-xs text-ink/60">
All https sites. The code still goes only to the tab’s own site, and the rate limit stays.
</p>
)}
<h3 className="text-sm font-semibold">Recent requests</h3>
{agentLog.length === 0 ? (
<p className="text-sm text-ink/70">No requests yet.</p>
Expand Down
38 changes: 34 additions & 4 deletions lib/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import { CODE_MAX_AGE_MS, type CodeEntry } from './types';

export const DEFAULT_AGENT_ALLOWLIST = ['github.com', 'google.com', 'vercel.com', 'apple.com'];
/** Allowlist entry meaning every https site. */
export const ALL_SITES = '*';
export const RATE_LIMIT_MAX = 10;
export const RATE_LIMIT_WINDOW_MS = 10 * 60 * 1000;
export const LOG_MAX = 200;
Expand Down Expand Up @@ -43,14 +45,21 @@ export function normalizeAllowlist(list: string[]): string[] {
for (const raw of list) {
let item = raw.trim().toLowerCase();
if (!item) continue;
if (item === ALL_SITES) {
if (!out.includes(ALL_SITES)) out.push(ALL_SITES);
continue;
}
if (item.includes('://')) item = hostOf(item);
item = item.replace(/^\*\./, '').replace(/\/.*$/, '').replace(/\.$/, '');
if (item && !out.includes(item)) out.push(item);
}
return out;
}

/** True when the URL's host equals an allowlisted host or is a subdomain of it. https only. */
/**
* True when the URL is https and its host equals an allowlisted host or is a
* subdomain of it. A '*' entry allows any https host.
*/
export function isAllowedUrl(url: string, allowlist: string[]): boolean {
let parsed: URL;
try {
Expand All @@ -61,7 +70,23 @@ export function isAllowedUrl(url: string, allowlist: string[]): boolean {
if (parsed.protocol !== 'https:') return false;
const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
if (!host) return false;
return normalizeAllowlist(allowlist).some((entry) => host === entry || host.endsWith(`.${entry}`));
return normalizeAllowlist(allowlist).some(
(entry) => entry === ALL_SITES || host === entry || host.endsWith(`.${entry}`),
);
}

/** True when the URL is https and on the tab's own host or a subdomain of it. */
export function sameSite(url: string, tabHost: string): boolean {
if (!tabHost) return false;
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return false;
}
if (parsed.protocol !== 'https:') return false;
const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
return host === tabHost || host.endsWith(`.${tabHost}`);
}

export class RateLimiter {
Expand Down Expand Up @@ -196,6 +221,11 @@ export async function runAgentCommand(request: AgentRequest, deps: AgentDeps): P
if (!url) return finish({ ok: false, error: 'tab not found' });
host = hostOf(url);
if (!isAllowedUrl(url, config.allowlist)) return finish({ ok: false, error: 'site is not allowlisted' });
// With '*' the code and links still go only to listed hosts or the tab's own site.
const normalized = normalizeAllowlist(config.allowlist);
const hasAll = normalized.includes(ALL_SITES);
const listedOnly = normalized.filter((e) => e !== ALL_SITES);
const destinationOk = (u: string): boolean => isAllowedUrl(u, listedOnly) || (hasAll && sameSite(u, host));

if (command === 'pending') {
const [hasField, entries, used] = await Promise.all([deps.hasCodeField(tabId), deps.getEntries(), deps.getUsed()]);
Expand All @@ -211,7 +241,7 @@ export async function runAgentCommand(request: AgentRequest, deps: AgentDeps): P
for (;;) {
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'code');
if (entry) {
const filled = await deps.fill(tabId, entry.code, (u) => isAllowedUrl(u, config.allowlist));
const filled = await deps.fill(tabId, entry.code, destinationOk);
if (!filled) return finish({ ok: false, error: 'no code field filled on this tab' });
await deps.markUsed(entry.id);
return finish({ ok: true, filled: true, sender: senderName(entry.from), ageSeconds: age(entry, deps.now()) });
Expand All @@ -232,7 +262,7 @@ export async function runAgentCommand(request: AgentRequest, deps: AgentDeps): P
// open_link
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'link');
if (!entry?.url) return finish({ ok: false, error: 'no fresh sign-in link' });
if (!isAllowedUrl(entry.url, config.allowlist)) return finish({ ok: false, error: 'link site is not allowlisted' });
if (!destinationOk(entry.url)) return finish({ ok: false, error: 'link site is not allowlisted' });
await deps.navigate(tabId, entry.url);
await deps.markUsed(entry.id);
return finish({ ok: true, opened: true, sender: senderName(entry.from), ageSeconds: age(entry, deps.now()) });
Expand Down
44 changes: 42 additions & 2 deletions tests/agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
RateLimiter,
appendLog,
isAllowedUrl,
normalizeAllowlist,
runAgentCommand,
sanitizeReply,
type AgentDeps,
Expand All @@ -29,6 +30,17 @@ describe('isAllowedUrl', () => {
});
});

describe('all sites', () => {
it('normalizeAllowlist keeps * exactly once', () => {
expect(normalizeAllowlist(['*', ' * ', 'github.com'])).toEqual(['*', 'github.com']);
});
it('isAllowedUrl with * allows any https host', () => {
expect(isAllowedUrl('https://example.org', ['*'])).toBe(true);
expect(isAllowedUrl('https://a.b.example.org', ['*'])).toBe(true);
expect(isAllowedUrl('http://example.org', ['*'])).toBe(false);
});
});

describe('RateLimiter', () => {
it('allows 10 per rolling 10 minutes', () => {
const rl = new RateLimiter();
Expand Down Expand Up @@ -83,9 +95,10 @@ function makeDeps(opts: {
entries?: CodeEntry[];
fillResult?: boolean;
onPoll?: () => void;
allowlist?: string[];
} = {}) {
let t = NOW;
const calls = { fill: [] as string[], nav: [] as string[], polls: 0, frameChecks: [] as boolean[] };
const calls = { fill: [] as string[], nav: [] as string[], polls: 0, frameChecks: [] as boolean[], probe: [] as boolean[] };
const used = new Set<string>();
const log: AgentLogEntry[] = [];
const entries = opts.entries ?? [entry()];
Expand All @@ -94,7 +107,7 @@ function makeDeps(opts: {
sleep: async (ms) => {
t += ms;
},
getConfig: async () => ({ enabled: opts.enabled ?? true, allowlist: DEFAULT_AGENT_ALLOWLIST }),
getConfig: async () => ({ enabled: opts.enabled ?? true, allowlist: opts.allowlist ?? DEFAULT_AGENT_ALLOWLIST }),
getTabUrl: async () => (opts.tabUrl === undefined ? 'https://github.com/sessions/two-factor' : opts.tabUrl),
hasCodeField: async () => true,
getEntries: async () => entries,
Expand All @@ -104,6 +117,11 @@ function makeDeps(opts: {
},
fill: async (_tab, code, allowed) => {
calls.frameChecks.push(allowed('https://github.com/x'), allowed('https://evil.com/x'));
calls.probe.push(
allowed('https://example.org/x'),
allowed('https://login.example.org'),
allowed('https://ads.other.net'),
);
calls.fill.push(code);
return opts.fillResult ?? true;
},
Expand Down Expand Up @@ -220,4 +238,26 @@ describe('runAgentCommand', () => {
expect(await runAgentCommand({ command: 'rm' }, deps)).toMatchObject({ ok: false });
expect(await runAgentCommand({ command: 'pending' }, deps)).toMatchObject({ error: 'tab id required' });
});

it('with * fills on any https tab but only into the tab site and listed frames', async () => {
const h = makeDeps({ tabUrl: 'https://example.org/login', allowlist: ['*'] });
expect(await runAgentCommand({ command: 'fill_code', args: [5] }, h.deps)).toMatchObject({ ok: true, filled: true });
expect(h.calls.probe).toEqual([true, true, false]);
const listed = makeDeps({ tabUrl: 'https://example.org/login', allowlist: ['*', 'other.net'] });
await runAgentCommand({ command: 'fill_code', args: [5] }, listed.deps);
expect(listed.calls.probe).toEqual([true, true, true]);
});

it('with * open_link opens a link on the tab host but not another host', async () => {
const opts = { tabUrl: 'https://example.org/login', allowlist: ['*'] };
const good = makeDeps({ ...opts, entries: [entry({ kind: 'link', url: 'https://login.example.org/v?t=s' })] });
expect(await runAgentCommand({ command: 'open_link', args: [5] }, good.deps)).toMatchObject({ ok: true, opened: true });
expect(good.calls.nav).toEqual(['https://login.example.org/v?t=s']);
const bad = makeDeps({ ...opts, entries: [entry({ kind: 'link', url: 'https://other.net/v' })] });
expect(await runAgentCommand({ command: 'open_link', args: [5] }, bad.deps)).toMatchObject({
ok: false,
error: 'link site is not allowlisted',
});
expect(bad.calls.nav).toHaveLength(0);
});
});
Loading