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
8 changes: 6 additions & 2 deletions docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,12 @@ From the extension:
| `tab id required` | `args[0]` is missing or not a non-negative integer |
| `rate limit reached` | More than 10 requests in a rolling 10 min (`status` is not counted) |
| `tab not found` | No tab with that id |
| `site is not allowlisted` | The tab's host is not in the allowlist (exact host or subdomain, https only) |
| `site is not allowlisted` | The tab's host is not in the allowlist (exact host or subdomain, https only), or the tab moved to such a site while waiting |
| `no fresh code` | `fill_code` without wait: no unused code from the last 10 min |
| `timed out waiting for a code` | `fill_code` with wait: none arrived in time |
| `no code field filled on this tab` | A code exists but no allowlisted frame had a field that took it |
| `no fresh sign-in link` | `open_link`: no unused link from the last 10 min |
| `link site is not allowlisted` | The link's own host is not in the allowlist |
| `link site is not allowlisted` | The link's own host is not in the allowlist (with all sites on: not on the sender's own site) |
| any other text | An exception inside the extension (its message) |

From the host:
Expand All @@ -80,3 +80,7 @@ From the client side (no reply at all):
| Socket file missing (ENOENT) | Host not running: Agent sign-in is off, the permission is not granted, `native/install.sh` was not run, or the browser is closed |
| Connection refused (ECONNREFUSED) | Stale socket from a host that crashed; the browser will start a new host when it reconnects |
| Empty reply / closed early | Host exited mid-request |

## 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.
1 change: 1 addition & 0 deletions entrypoints/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ async function pollOne(state: PersistedState, account: Account): Promise<CodeEnt
receivedAt: message.receivedAt,
kind: code ? 'code' : 'link',
...(link ? { url: link.url } : {}),
...(message.dmarc ? { dmarc: message.dmarc } : {}),
});
}
return found;
Expand Down
2 changes: 1 addition & 1 deletion entrypoints/options/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ export function App() {
</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.
All https sites. A site that is not in the list only gets codes and links mailed from that same site, and the rate limit stays.
</p>
)}
<h3 className="text-sm font-semibold">Recent requests</h3>
Expand Down
114 changes: 93 additions & 21 deletions lib/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* code or the URL. Chrome access is injected through AgentDeps so this file
* is unit-testable.
*/
import { getDomain } from 'tldts';
import { CODE_MAX_AGE_MS, type CodeEntry } from './types';

export const DEFAULT_AGENT_ALLOWLIST = ['github.com', 'google.com', 'vercel.com', 'apple.com'];
Expand Down Expand Up @@ -75,18 +76,49 @@ export function isAllowedUrl(url: string, allowlist: string[]): boolean {
);
}

/** 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;
/**
* Registrable domain (site) of a host, counting private suffixes such as
* vercel.app or github.io as public. Empty when unparsable or when the host is
* itself a public suffix. Fails closed.
*/
export function siteOf(host: string): string {
try {
parsed = new URL(url);
const name = new URL('https://' + host.trim()).hostname.toLowerCase().replace(/\.$/, '');
return getDomain(name, { allowPrivateDomains: true }) ?? '';
} catch {
return false;
return '';
}
}

/** Domain of the address in a From header: after the last '@' of the last <...>. */
export function senderDomain(from: string): string {
const brackets = [...from.matchAll(/<([^<>]*)>/g)];
const addr = (brackets.length ? brackets[brackets.length - 1][1] : from).trim();
const at = addr.lastIndexOf('@');
if (at < 0) return '';
const domain = addr.slice(at + 1).replace(/[>\s]+$/, '');
if (!domain) return '';
try {
return new URL('https://' + domain).hostname;
} catch {
return '';
}
}

/** Site of the entry's sender; empty when unknown or when the mail failed DMARC. */
export function entrySite(e: CodeEntry): string {
if (e.dmarc === 'fail') return '';
return siteOf(senderDomain(e.from));
}

/** Site of an https URL; empty for anything else. */
export function urlSite(url: string): string {
try {
const parsed = new URL(url);
return parsed.protocol === 'https:' ? siteOf(parsed.hostname) : '';
} catch {
return '';
}
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 @@ -136,11 +168,13 @@ export function newestUsable(
used: ReadonlySet<string>,
now: number,
want: 'code' | 'link',
accept?: (e: CodeEntry) => boolean,
): CodeEntry | undefined {
return entries
.filter((e) => {
if (used.has(e.id)) return false;
if (now - e.receivedAt > CODE_MAX_AGE_MS) return false;
if (accept && !accept(e)) return false;
return want === 'code' ? (e.kind ?? 'code') === 'code' : Boolean(e.url);
})
.sort((a, b) => b.receivedAt - a.receivedAt)[0];
Expand Down Expand Up @@ -217,31 +251,64 @@ export async function runAgentCommand(request: AgentRequest, deps: AgentDeps): P
if (tabId === null) return finish({ ok: false, error: 'tab id required' });
if (!deps.limiter.take(deps.now())) return finish({ ok: false, error: 'rate limit reached' });

const url = await deps.getTabUrl(tabId);
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));

type Ctx =
| { error: string }
| {
accept: (e: CodeEntry) => boolean;
frameOk: (e: CodeEntry) => (u: string) => boolean;
linkOk: (e: CodeEntry, u: string) => boolean;
};
/**
* Reads the tab's current URL and decides the mode. Listed sites take any
* sender. With '*', other https sites only take mail from their own site.
*/
const context = async (): Promise<Ctx> => {
const url = await deps.getTabUrl(tabId);
if (!url) return { error: 'tab not found' };
host = hostOf(url);
if (isAllowedUrl(url, listedOnly)) {
return {
accept: () => true,
frameOk: () => (u) => isAllowedUrl(u, listedOnly),
linkOk: (_e, u) => isAllowedUrl(u, listedOnly),
};
}
const tabSite = hasAll ? urlSite(url) : '';
if (!tabSite) return { error: 'site is not allowlisted' };
return {
accept: (e) => entrySite(e) !== '' && entrySite(e) === tabSite,
frameOk: (e) => (u) => urlSite(u) === entrySite(e),
linkOk: (e, u) => urlSite(u) === entrySite(e),
};
};

if (command === 'pending') {
const ctx = await context();
if ('error' in ctx) return finish({ ok: false, error: ctx.error });
const [hasField, entries, used] = await Promise.all([deps.hasCodeField(tabId), deps.getEntries(), deps.getUsed()]);
const now = deps.now();
const code = newestUsable(entries, used, now, 'code');
const link = newestUsable(entries, used, now, 'link');
const code = newestUsable(entries, used, now, 'code', ctx.accept);
const link = newestUsable(entries, used, now, 'link', ctx.accept);
const pick = (e?: CodeEntry) => (e ? { sender: senderName(e.from), ageSeconds: age(e, now) } : null);
return finish({ ok: true, hasField, codeAvailable: pick(code), linkAvailable: pick(link) });
}

if (command === 'fill_code') {
const deadline = deps.now() + waitArg(request.args) * 1000;
for (;;) {
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'code');
// Re-read the tab on every pass: it may have navigated while we waited.
let ctx = await context();
if ('error' in ctx) return finish({ ok: false, error: ctx.error });
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'code', ctx.accept);
if (entry) {
const filled = await deps.fill(tabId, entry.code, destinationOk);
ctx = await context();
if ('error' in ctx) return finish({ ok: false, error: ctx.error });
if (!ctx.accept(entry)) return finish({ ok: false, error: 'site is not allowlisted' });
const filled = await deps.fill(tabId, entry.code, ctx.frameOk(entry));
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 @@ -260,9 +327,14 @@ export async function runAgentCommand(request: AgentRequest, deps: AgentDeps): P
}

// open_link
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'link');
let ctx = await context();
if ('error' in ctx) return finish({ ok: false, error: ctx.error });
const entry = newestUsable(await deps.getEntries(), await deps.getUsed(), deps.now(), 'link', ctx.accept);
if (!entry?.url) return finish({ ok: false, error: 'no fresh sign-in link' });
if (!destinationOk(entry.url)) return finish({ ok: false, error: 'link site is not allowlisted' });
ctx = await context();
if ('error' in ctx) return finish({ ok: false, error: ctx.error });
if (!ctx.accept(entry)) return finish({ ok: false, error: 'site is not allowlisted' });
if (!ctx.linkOk(entry, 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
6 changes: 5 additions & 1 deletion lib/gmail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface ParsedMessage {
/** Raw HTML part, kept so verification buttons can be read from hrefs. */
html: string;
receivedAt: number;
dmarc?: 'pass' | 'fail';
}

interface GmailHeader {
Expand Down Expand Up @@ -149,7 +150,10 @@ export function parseGmailMessage(raw: GmailMessage): ParsedMessage {
const html = htmlPart ? decodeBody(htmlPart) : '';
const body = plain ? decodeBody(plain) : html ? htmlToText(html) : raw.snippet ?? '';
const receivedAt = raw.internalDate ? Number(raw.internalDate) : Date.parse(header(headers, 'Date')) || Date.now();
return { id: raw.id, from, subject, body, html, receivedAt };
// The first Authentication-Results header is the one Gmail itself added.
const auth = header(headers, 'Authentication-Results').toLowerCase();
const dmarc = /\bdmarc=fail\b/.test(auth) ? 'fail' : /\bdmarc=pass\b/.test(auth) ? 'pass' : undefined;
return { id: raw.id, from, subject, body, html, receivedAt, ...(dmarc ? { dmarc } : {}) };
}

function header(headers: GmailHeader[], name: string): string {
Expand Down
2 changes: 2 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export interface CodeEntry {
kind?: EntryKind;
/** Verification or sign-in URL. Present on link entries, and on a code when the same message has both. */
url?: string;
/** Gmail's own DMARC verdict for the message, when it reported one. */
dmarc?: 'pass' | 'fail';
}

export type PopupShows = 'all' | 'codes' | 'links';
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"dependencies": {
"extpay": "^3.1.2",
"react": "^19.1.0",
"react-dom": "^19.1.0"
"react-dom": "^19.1.0",
"tldts": "^7.5.4"
},
"devDependencies": {
"@types/react": "^19.1.0",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading