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
2 changes: 1 addition & 1 deletion SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ P="$HOME/Library/Application Support/PassBridge"

Apple's Passwords asks for Touch ID every time a password is read (except within 15 s of the last read), so each agent sign-in needs one Touch ID approval; when no saved login exists the agent gets `no_login` and the person signs in themselves.

Errors you may see: `not_enabled`, `bad_pin`, `wrong_pin`, `locked`, `no_tab`, `not_allowed`, `no_login`, `choose_login`, `rate_limited` (10 per 10 minutes), `needs_user` (pair the extension or approve Touch ID), `fill_failed`. Requests are logged on the Agents tab of the settings page.
Errors you may see: `not_enabled`, `bad_pin`, `wrong_pin`, `locked`, `no_tab`, `not_allowed`, `no_login`, `choose_login`, `username_mismatch`, `rate_limited` (10 per 10 minutes), `needs_user` (pair the extension or approve Touch ID), `fill_failed`. Requests are logged on the Agents tab of the settings page.

### Verification codes (macOS and Windows)

Expand Down
5 changes: 4 additions & 1 deletion docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ Off by default. In Settings, on the Agents tab, the user can turn on Allow every

If `username` is left out and the site has exactly one login, that login is used. With several logins, the reply is `choose_login` with the list. Usernames are matched without regard to case or surrounding spaces.

When the page already shows a fixed account (a password-only step: a hidden or read-only username, an account chip or the address in the text near the password field), only that account is filled. With no `username`, the saved login matching it is picked; a `username` for a different account, or no saved login for it, is `username_mismatch` and nothing is filled.

## Replies

Success:
Expand All @@ -147,7 +149,7 @@ Success:

The three lines are `status`, `logins` and `sign_in`. `save` succeeds with `{"id":"…","ok":true,"domain":"github.com","username":"octocat"}`.

Failure: `{"id":"…","ok":false,"error":"<code>"}`. `choose_login` also carries `usernames`. `not_allowed` may carry `reason`; the values are `site_mismatch` and `save_off`, and the Agents > Activity list shows it.
Failure: `{"id":"…","ok":false,"error":"<code>"}`. `choose_login` and `username_mismatch` also carry `usernames`. `not_allowed` may carry `reason`; the values are `site_mismatch` and `save_off`, and the Agents > Activity list shows it.

| error | meaning |
|---|---|
Expand All @@ -164,6 +166,7 @@ Failure: `{"id":"…","ok":false,"error":"<code>"}`. `choose_login` also carries
| `needs_user` | the user has to act: the extension isn't paired, or the Passwords approval (Touch ID) was refused or not given in time |
| `no_login` | no saved login for the site, or none matching `username` |
| `choose_login` | several logins and no `username` given; pick one from `usernames` |
| `username_mismatch` | `sign_in`: the page shows a fixed account that differs from `username`, or no saved login matches it; `usernames` lists the saved ones. Go back on the page and enter the right account first |
| `fill_failed` | no sign-in form was found or the fill didn't take (`verify_code`: the code was read but not entered) |
| `no_field` | `verify_code`: the tab has no code field |
| `no_code` | `verify_code` on a non-Apple site: Apple Passwords offers no code for it; carries `hint` (use Keytray for emailed and SMS codes) |
Expand Down
15 changes: 13 additions & 2 deletions src/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// replies carry status and usernames only, never a password or a code.
import { SETTINGS_AREA, getSettings, hostBlocked } from "./settings.js";
import { hostOfSite, siteHosts } from "./session/password-search.js";
import { usernameMatchesPage } from "./session/username-match.js";

/**
* Injected collaborators. Results are `any` where they are owned by background.js or the vault (shapes not typed there).
Expand All @@ -27,6 +28,7 @@ import { hostOfSite, siteHosts } from "./session/password-search.js";
* @property {(kind?: "pin") => Promise<{ ok: boolean, code?: string, error?: string }>} [readCode] kind "pin" reads the pairing code shown for an unlock
* @property {(tab: any, frame: { frameId: number, host: string }, username?: string) => Promise<{ ok: boolean, code?: string, source?: string, usernames?: string[], error?: string }>} [vaultCode] the one-time code Apple Passwords offers for this tab (other sites than Apple sign-in)
* @property {(host: string, filled: boolean) => void} [notifyCode]
* @property {(tab: any) => Promise<{ username?: string, fixed?: boolean } | null>} [pageUsername] the account the page already shows; fixed when the fill cannot change it
*/

const HOST = "com.passbridge.agent";
Expand Down Expand Up @@ -526,13 +528,22 @@ export async function handleAgentRequest(msg, deps, limiter, now = Date.now()) {

if (op === "sign_in") {
if (!names.length) return done(fail("no_login"));
// a page that shows a fixed account (a password-only step) only gets that account's password
let fixedName = "";
try {
const page = deps.pageUsername ? await deps.pageUsername(tab) : null;
if (page?.fixed === true && typeof page.username === "string") fixedName = page.username.trim().slice(0, 320);
} catch {}
let username = msg.username;
if (username == null || username === "") {
if (names.length > 1) return done(fail("choose_login", { usernames: names }));
username = names[0];
const pool = fixedName ? names.filter((n) => usernameMatchesPage(n, fixedName)) : names;
if (!pool.length) return done(fail("username_mismatch", { usernames: names }));
if (pool.length > 1) return done(fail("choose_login", { usernames: pool }));
username = pool[0];
} else {
const hit = names.find((n) => same(n, username));
if (!hit) return done(fail("no_login"));
if (fixedName && !usernameMatchesPage(hit, fixedName)) return done(fail("username_mismatch", { usernames: names }));
username = hit;
}
base.username = username;
Expand Down
8 changes: 8 additions & 0 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -2081,6 +2081,14 @@ const agent = initAgent({
}
},
vaultCode: vaultCodeForAgent,
pageUsername: async (tab) => {
try {
const r = await chrome.tabs.sendMessage(tab.id ?? 0, { type: "pageUsername" }, { frameId: 0 });
return typeof r?.username === "string" ? { username: r.username.slice(0, 320), fixed: r.fixed === true } : null;
} catch {
return null;
}
},
notifyCode: (host, filled) =>
chrome.notifications?.create({ type: "basic", iconUrl: chrome.runtime.getURL("icons/icon128.png"), title: t("extensionName"), message: t(filled ? "agentCodeFilled" : "agentCodeNotFilled", [host]) }),
notifySaved: (host, username) =>
Expand Down
18 changes: 12 additions & 6 deletions src/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ onChrome(chrome.runtime.onMessage, (/** @type {any} */ msg, /** @type {chrome.ru
case "pageUsername": {
if (window !== window.top) return false;
const f = anchorPwField(document) || document.querySelector('input[type="password"]');
sendResponse({ username: f ? findPageUsername(f) : "" });
sendResponse(f ? pageUsernameInfo(f) : { username: "", fixed: false });
return true;
}
case "qrImageRect": {
Expand Down Expand Up @@ -1266,6 +1266,12 @@ const EMAIL_RE = /[^\s@<>()"',;:]+@[^\s@<>()"',;:]+\.[^\s@<>()"',;:]+/;

// the username this page is for: a filled username input, a hidden identifier, or an email shown near the password field
function findPageUsername(/** @type {HTMLInputElement} */ field) {
return pageUsernameInfo(field).username;
}

// fixed: the page shows the account and the fill cannot change it (hidden or read-only input, account chip, text)
/** @returns {{ username: string, fixed: boolean }} */
function pageUsernameInfo(/** @type {HTMLInputElement} */ field) {
try {
const scopes = /** @type {ParentNode[]} */ ([field?.form, document].filter(Boolean));
for (const scope of scopes) {
Expand All @@ -1274,26 +1280,26 @@ function findPageUsername(/** @type {HTMLInputElement} */ field) {
const v = (el.value || "").trim();
if (!v || v.length > 320) continue;
if (el.type === "hidden") {
if (/^(identifier|username|email|login)$/i.test(el.name || "") || /^(identifier|username|email|login)$/i.test(el.id || "")) return v;
if (/^(identifier|username|email|login)$/i.test(el.name || "") || /^(identifier|username|email|login)$/i.test(el.id || "")) return { username: v, fixed: true };
} else if (el.type === "email" || (isUsernameField(el) && isVisible(el))) {
return v;
return { username: v, fixed: el.readOnly || el.disabled };
}
}
}
// an account chip (Google's 2-step page) carries the address in data-email
const chip = (document.querySelector("[data-email]")?.getAttribute("data-email") || "").trim();
if (chip && chip.length <= 320 && EMAIL_RE.test(chip)) return chip;
if (chip && chip.length <= 320 && EMAIL_RE.test(chip)) return { username: chip, fixed: true };
/** @type {HTMLElement | null} */
let node = field;
for (let i = 0; node && i < 6; i++) {
node = node.parentElement;
if (!node) break;
const text = (node.innerText || "").slice(0, 2000);
const m = text.match(EMAIL_RE);
if (m) return m[0];
if (m) return { username: m[0], fixed: true };
}
} catch {}
return "";
return { username: "", fixed: false };
}

function pageUsernameQuery(/** @type {HTMLInputElement} */ field) {
Expand Down
17 changes: 17 additions & 0 deletions test-harness/automation/unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,23 @@ ok("agent: an empty allowlist refuses everything", !hostAllowed("github.com", []
await run({ op: "sign_in", tabId: 1, username: "a@x.com" }, deps(), lim);
ok("agent: the second fill in the window is rate_limited", (await run({ op: "sign_in", tabId: 1, username: "a@x.com" }, deps(), lim)).reply.error === "rate_limited");
ok("agent: fill_code is gone", (await run({ op: "fill_code", tabId: 1 })).reply.error === "unknown_op");
{
let filled = "";
const page = (username: string, fixed: boolean) =>
deps({ pageUsername: async () => ({ username, fixed }), fillLoginOnTab: async (_t: any, u: any) => ((filled = u), { filled: true, username: u }) });
filled = "";
const mm = await run({ op: "sign_in", tabId: 1, username: "a@x.com" }, page("c@x.com", true));
ok("agent: a fixed page account that differs from the asked login is username_mismatch, nothing filled", mm.reply.error === "username_mismatch" && filled === "");
filled = "";
const none = await run({ op: "sign_in", tabId: 1 }, page("c@x.com", true));
ok("agent: no saved login for the fixed page account is username_mismatch with the saved list", none.reply.error === "username_mismatch" && none.reply.usernames.length === 2 && filled === "");
const pick = await run({ op: "sign_in", tabId: 1 }, page("B@x.com", true));
ok("agent: with no username, the login matching the fixed page account is picked", pick.reply.ok && filled === "b@x.com");
const free = await run({ op: "sign_in", tabId: 1, username: "a@x.com" }, page("c@x.com", false));
ok("agent: an editable username field does not block the fill", free.reply.ok && filled === "a@x.com");
const failed = await run({ op: "sign_in", tabId: 1, username: "a@x.com" }, deps({ pageUsername: async () => { throw new Error("no frame"); } }));
ok("agent: a page that cannot be asked still fills", failed.reply.ok);
}
const fr = pickAllowedFrames(
[
{ frameId: 0, url: "https://account.apple.com/" },
Expand Down
Loading