diff --git a/AGENTS.md b/AGENTS.md index 82f7351..d9a647f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ PassBridge: a Chrome extension (macOS and Windows) that fills logins from the Ap ## Where things live - `src/`: extension code (`background.js`, `content.js`, `menu.js`, `autofill/`, `apple/`, `ui/`, `update/`, popup/options pages). -- `overlay/`: save and TOTP bar pages. `native/`: Python helper agent and install scripts. `manifest.json`: extension manifest (its key fixes the extension id). `native/code-reader/`: the Swift Accessibility app (PassBridge Code Reader) that presses Allow on Apple's prompt and reads the code; `sh native/code-reader/build.sh
"}`. `choose_login` also carries
| `locked` | `pair_pin`: 5 wrong codes in a row; send `pair_start` for a fresh code |
| `exists` | `save`: a login with that username already exists for the site |
| `no_tab` | no tab with that id, or it has no URL |
-| `not_allowed` | the tab's site isn't on the allowlist (and Allow every site is off), or PassBridge refuses to fill there (for example plain HTTP, a blocked domain or a dev host), or `site` doesn't match the tab (`reason: "site_mismatch"`), or `save` while Allow agents to save new logins is off (`reason: "save_off"`), or `verify_code` with the setting off (`reason: "code_reader_off"`), on a platform other than macOS and Windows (`reason: "mac_only"`) or on a page that is not an Apple sign-in host (`reason: "not_apple_site"`) |
+| `not_allowed` | the tab's site isn't on the allowlist (and Allow every site is off), or PassBridge refuses to fill there (for example plain HTTP, a blocked domain or a dev host), or `site` doesn't match the tab (`reason: "site_mismatch"`), or `save` while Allow agents to save new logins is off (`reason: "save_off"`), or `verify_code` with the setting off (`reason: "code_reader_off"`), on a platform other than macOS and Windows (`reason: "mac_only"`) or, on an Apple sign-in host, a site that is not on the allowlist (Allow every site does not apply there) |
| `rate_limited` | more than 10 `sign_in` or `save` requests in 10 minutes, or more than 3 `verify_code` requests in 10 minutes (counted separately) |
| `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` |
| `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) |
+| `several_codes` | `verify_code` on a non-Apple site: several codes and no matching `username`; may carry `usernames` |
| `busy`, `no_prompt`, `several_prompts`, `not_configured`, `reader_missing`, `reader_failed` | `verify_code`: see Verification codes (macOS and Windows); `unlock` shares `busy`, `no_prompt`, `reader_missing` and `reader_failed`, see Unlock (Windows) |
| `timeout` | the extension didn't answer within 90 s (sent by the host) |
| `extension_gone` | the browser or extension went away mid-request (sent by the host) |
diff --git a/native/passbridge-agent-cli.py b/native/passbridge-agent-cli.py
index 30d4171..5e78b17 100644
--- a/native/passbridge-agent-cli.py
+++ b/native/passbridge-agent-cli.py
@@ -8,7 +8,7 @@
import sys
import uuid
-USAGE = "usage: passbridge-agent-cli.py status | pair-start | pair-pin (pin on stdin) | logins | sign_in [username] | save | verify-code [site] | unlock | save --url (save reads the password from stdin)"
+USAGE = "usage: passbridge-agent-cli.py status | pair-start | pair-pin (pin on stdin) | logins | sign_in [username] | save | verify-code [site] [username] | unlock | save --url (save reads the password from stdin)"
WINDOWS = os.name == "nt"
if WINDOWS:
@@ -98,8 +98,10 @@ def main(argv):
req["tabId"] = int(argv[1])
if argv[0] == "sign_in" and len(argv) > 2:
req["username"] = argv[2]
- if argv[0] == "verify-code" and len(argv) > 2:
+ if argv[0] == "verify-code" and len(argv) > 2 and argv[2]:
req["site"] = argv[2]
+ if argv[0] == "verify-code" and len(argv) > 3:
+ req["username"] = argv[3]
if argv[0] == "save":
if by_url:
if len(argv) < 4:
diff --git a/src/agent.js b/src/agent.js
index d082798..f8f4ceb 100644
--- a/src/agent.js
+++ b/src/agent.js
@@ -25,6 +25,7 @@ import { hostOfSite, siteHosts } from "./session/password-search.js";
* @property {(tabId: number, frames: { frameId: number, host: string }[]) => Promise<{ frameId: number, host: string } | null>} [probeCodeField]
* @property {(tabId: number, frame: { frameId: number, host: string }, code: string) => Promise} [fillCode]
* @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]
*/
@@ -36,6 +37,7 @@ export const PIN_FAILS_MAX = 5;
export const RATE_MAX = 10;
export const RATE_WINDOW_MS = 10 * 60 * 1000;
export const CODE_RATE_MAX = 3;
+const NO_CODE_HINT = "No code for this site in Apple Passwords. Emailed and SMS codes: use Keytray.";
export const UNLOCK_RATE_MAX = 3;
// Apple sign-in hosts that may receive a verification code, matched exactly (no subdomains)
export const CODE_HOSTS = ["appleid.apple.com", "account.apple.com", "idmsa.apple.com", "www.icloud.com", "icloud.com"];
@@ -322,14 +324,24 @@ async function verifyCode(msg, deps, limiter, now, settings, base, done) {
if (!host || !want || !onSiteOrSubdomain(host, want)) return done(fail("not_allowed", { reason: "site_mismatch" }));
}
if (!host || hostBlocked(host, settings.blockedDomains)) return done(fail("not_allowed"));
- // the every-site path never applies here
- if (!hostAllowed(host, settings.agentAllowlist) || !(await deps.isFillUrlAllowed(tab.url))) return done(fail("not_allowed"));
- if (!isCodeHost(host)) return done(fail("not_allowed", { reason: "not_apple_site" }));
+ const apple = isCodeHost(host);
+ if (apple) {
+ // Apple's own prompt reader: allowlist only, the every-site path never applies here
+ if (!hostAllowed(host, settings.agentAllowlist) || !(await deps.isFillUrlAllowed(tab.url))) return done(fail("not_allowed"));
+ } else if (hostAllowed(host, settings.agentAllowlist)) {
+ if (!(await deps.isFillUrlAllowed(tab.url))) return done(fail("not_allowed"));
+ } else if (settings.agentAllowAll === true && /^https:\/\//i.test(tab.url) && !deps.isLocalDevHost(host)) {
+ if (!(await deps.isFillUrlAllowed(tab.url))) return done(fail("not_allowed"));
+ } else {
+ return done(fail("not_allowed"));
+ }
if (!limiter.peek(now, "verify_code", CODE_RATE_MAX)) return done(fail("rate_limited"));
- const frames = (await deps.codeFrames?.(tab)) || [];
+ // other sites: the top frame only, on the tab's own host
+ const frames = apple ? (await deps.codeFrames?.(tab)) || [] : [{ frameId: 0, host }];
const frame = await deps.probeCodeField?.(tab.id, frames);
if (!frame) return done(fail("no_field"));
if (!limiter.take(now, "verify_code", CODE_RATE_MAX)) return done(fail("rate_limited"));
+ if (!apple) return verifyVaultCode(msg, deps, tab, frame, host, done);
try {
const r = await deps.readCode?.();
if (!r?.ok) {
@@ -350,6 +362,38 @@ async function verifyCode(msg, deps, limiter, now, settings, base, done) {
}
}
+// any other site: the one-time code Apple Passwords offers for this tab. readCode (Apple's prompt) is never used here
+/**
+ * @param {any} msg
+ * @param {AgentDeps} deps
+ * @param {any} tab
+ * @param {{ frameId: number, host: string }} frame
+ * @param {string} host
+ * @param {(reply: any, extra?: Record) => any} done
+ */
+async function verifyVaultCode(msg, deps, tab, frame, host, done) {
+ if (!deps.vaultCode) return done(fail("reader_missing"));
+ try {
+ const r = await deps.vaultCode(tab, frame, typeof msg.username === "string" ? msg.username : undefined);
+ if (!r?.ok) {
+ const e = r?.error;
+ if (e === "no_code") return done(fail("no_code", { hint: NO_CODE_HINT }));
+ if (e === "several_codes") return done(fail("several_codes", Array.isArray(r.usernames) ? { usernames: r.usernames } : undefined));
+ if (e === "needs_user") return done(fail("needs_user"));
+ if (e === "not_apple_site" || e === "code_reader_off" || e === "mac_only" || e === "site_mismatch") return done(fail("not_allowed", { reason: e }));
+ return done(fail("reader_failed"));
+ }
+ if (typeof r.code !== "string" || !/^\d{4,10}$/.test(r.code)) return done(fail("reader_failed"));
+ if (!(await deps.codeReaderOn?.())) return done(fail("not_allowed", { reason: "code_reader_off" }));
+ const filled = await deps.fillCode?.(tab.id, frame, r.code);
+ deps.notifyCode?.(host, !!filled);
+ if (!filled) return done(fail("fill_failed"));
+ return done({ ok: true, domain: host, filled: true, source: r.source === "messages" ? "messages" : "totp" });
+ } catch {
+ return done(fail("reader_failed"));
+ }
+}
+
// your own sign-in: a code field got focus on an Apple sign-in page. No agent, no allowlist, no log row; every failure is silent
/**
* @param {{ tab?: { id?: number }, frameId?: number, url?: string, id?: string } | undefined} sender
diff --git a/src/background.js b/src/background.js
index aba7cc2..354b8ee 100644
--- a/src/background.js
+++ b/src/background.js
@@ -9,7 +9,7 @@ import { generateAlphanumericPassword, generateApplePassword } from "./password-
import { otpAuthSecret, parseOtpAuth } from "./otpauth.js";
import { parseSetupInput, totpHandoff, withAccount } from "./totp-setup.js";
import { passwordSearchSteps } from "./session/password-search.js";
-import { listOtpEntries } from "./session/otp-list.js";
+import { listOtpEntries, totpRowMatches } from "./session/otp-list.js";
import { registrableDomain, siteLookupHosts } from "./session/site-domain.js";
import { orderByUse, recordUse } from "./session/mru.js";
import { pickSaveTarget, tryAutoSave } from "./save-target.js";
@@ -17,7 +17,7 @@ import { addToAllowlist, agentHostFor, agentOfferFor } from "./session/agent-all
import { frameUrlsFor } from "./session/frame-urls.js";
import { orderByPageUsername } from "./session/username-match.js";
import { scrubUrl } from "./report-scrub.js";
-import { initAgent, loginSavedFor, pickAllowedFrames, pickCodeFrames } from "./agent.js";
+import { initAgent, loginSavedFor, onSiteOrSubdomain, pickAllowedFrames, pickCodeFrames } from "./agent.js";
import { UPDATE_PAGE, availableUpdate, checkForUpdate, dismissUpdate, takeUpdatedTo } from "./update/check.js";
import { getEffectiveSettings } from "./managed.js";
import { reloadIfStale } from "./update/stale.js";
@@ -2001,6 +2001,51 @@ async function submitPin(pin) {
return { ok: true, state };
}
+// agent verify_code on a non-Apple site: the code Apple Passwords offers for this tab, picked here; the value goes only to the caller's fill
+/**
+ * @param {{ id?: number, url?: string }} tab
+ * @param {{ frameId: number, host: string }} frame
+ * @param {string} [username]
+ * @returns {Promise<{ ok: boolean, code?: string, source?: string, usernames?: string[], error?: string }>}
+ */
+async function vaultCodeForAgent(tab, frame, username) {
+ if (!client.ready || tab.id == null || !tab.url) return { ok: false, error: "needs_user" };
+ const host = frame.host;
+ /** @type {any[]} */
+ let entries;
+ try {
+ const r = await listOtpEntries(client, { tabId: tab.id, frameId: frame.frameId, frameUrls: frameUrlsFor({ url: tab.url, tab }), platform: await platformReady });
+ entries = r.entries;
+ if (!entries.length && r.requiresAuth) return { ok: false, error: "needs_user" };
+ } catch {
+ return { ok: false, error: "needs_user" };
+ }
+ // a row with no domain does not count for a totp
+ const totps = entries.filter((e) => e.source === "totp" && e.domain && onSiteOrSubdomain(host, String(e.domain).toLowerCase().replace(/^www\./, "")));
+ /** @type {any} */
+ let pick = null;
+ if (totps.length) {
+ if (username) pick = totps.find((e) => totpRowMatches(e, username));
+ else if (totps.length === 1) pick = totps[0];
+ if (!pick) return username ? { ok: false, error: "no_code" } : { ok: false, error: "several_codes", usernames: totps.map((e) => e.username) };
+ } else {
+ const others = entries.filter((e) => e.source !== "totp" && (!e.domain || onSiteOrSubdomain(host, String(e.domain).toLowerCase().replace(/^www\./, ""))));
+ if (others.length > 1) return { ok: false, error: "several_codes" };
+ if (!others.length) return { ok: false, error: "no_code" };
+ return typeof others[0].code === "string" ? { ok: true, code: others[0].code, source: "messages" } : { ok: false, error: "reader_failed" };
+ }
+ // the value rotates: read it now
+ try {
+ const fresh = await client.readOneTimeCode(tab.id, frame.frameId, frameUrlsFor({ url: tab.url, tab }), pick.username);
+ const hit =
+ fresh.find((/** @type {any} */ e) => e.source === "totp" && e.username === pick.username && e.domain === pick.domain) || fresh.find((/** @type {any} */ e) => e.source === "totp");
+ if (!hit?.code) return { ok: false, error: "no_code" };
+ return { ok: true, code: hit.code, source: "totp" };
+ } catch {
+ return { ok: false, error: "needs_user" };
+ }
+}
+
const agent = initAgent({
client,
pairStart: startPairing,
@@ -2035,6 +2080,7 @@ const agent = initAgent({
return false;
}
},
+ vaultCode: vaultCodeForAgent,
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) =>
diff --git a/test-harness/automation/unit.test.ts b/test-harness/automation/unit.test.ts
index 15e28ae..81224c3 100644
--- a/test-harness/automation/unit.test.ts
+++ b/test-harness/automation/unit.test.ts
@@ -257,7 +257,7 @@ ok("isCodeHost: exact sign-in hosts only", ["appleid.apple.com", "account.apple.
}
ok("settings: agentCodeReader not in SETTINGS_DEFAULTS, so migrateSettingsToSync leaves it", !("agentCodeReader" in SETTINGS_DEFAULTS) && !String(migrateSettingsToSync).includes("agentCodeReader"));
{
- const calls: any = { read: 0, probe: 0, fill: [] as any[], notify: [] as any[] };
+ const calls: any = { vault: [] as any[], read: 0, probe: 0, fill: [] as any[], notify: [] as any[] };
const frame = { frameId: 3, host: "idmsa.apple.com" };
const base = (over: any = {}) => ({
client: { ready: false },
@@ -289,11 +289,59 @@ ok("settings: agentCodeReader not in SETTINGS_DEFAULTS, so migrateSettingsToSync
r = await vc({}, { platform: async () => "mac" });
ok("verify_code: platform() resolves mac -> the read runs", r.ok === true && calls.read === 1);
r = await vc({}, { getSettings: async () => ({ agentSignIn: true, agentAllowlist: ["github.com"], agentAllowAll: true }) });
- ok("verify_code: not allowlisted, allowAll on -> not_allowed", r.error === "not_allowed" && !r.reason && calls.probe === 0 && calls.read === 0);
- r = await vc({}, { getSettings: async () => ({ agentSignIn: true, agentAllowlist: ["github.com"] }), getTab: async () => ({ id: 1, url: "https://github.com/login" }) });
- ok("verify_code: allowlisted non-Apple host -> not_apple_site", r.error === "not_allowed" && r.reason === "not_apple_site" && calls.read === 0);
- r = await vc({}, { getTab: async () => ({ id: 1, url: "https://support.apple.com/" }) });
- ok("verify_code: allowlisted support.apple.com -> not_apple_site, probe not called", r.reason === "not_apple_site" && calls.probe === 0);
+ ok("verify_code: Apple host not allowlisted, allowAll on -> not_allowed (Apple hosts keep the allowlist)", r.error === "not_allowed" && !r.reason && calls.probe === 0 && calls.read === 0);
+ const all = { agentSignIn: true, agentAllowlist: [], agentAllowAll: true };
+ const gh = { getTab: async () => ({ id: 1, url: "https://github.com/sessions/verified-device" }) };
+ const vault = (over: any = {}) => ({ ...gh, getSettings: async () => all, vaultCode: async (...a: any[]) => { calls.vault.push(a); return { ok: true, code: "704129", source: "totp" }; }, ...over });
+ calls.vault = [];
+ r = await vc({}, vault({ getSettings: async () => ({ agentSignIn: true, agentAllowlist: ["github.com"] }) }));
+ ok("verify_code: allowlisted non-Apple host -> vault path, readCode never called", r.ok === true && r.domain === "github.com" && r.source === "totp" && r.filled === true && calls.read === 0 && calls.vault.length === 1 && calls.fill[0][2] === "704129" && !JSON.stringify(r).includes("704129"));
+ let probed: any = null;
+ r = await vc({}, vault({ probeCodeField: async (_t: any, f: any) => { probed = f; return f[0]; } }));
+ ok("verify_code: allowAll, non-Apple https host -> vault path, probes the top frame only", r.ok === true && calls.read === 0 && calls.fill.length === 1 && JSON.stringify(probed) === JSON.stringify([{ frameId: 0, host: "github.com" }]));
+ calls.vault = [];
+ r = await vc({}, vault({ getSettings: async () => ({ agentSignIn: true, agentAllowlist: [] }) }));
+ ok("verify_code: non-Apple host not allowlisted, allowAll off -> not_allowed", r.error === "not_allowed" && !r.reason && calls.probe === 0 && calls.vault.length === 0);
+ r = await vc({}, vault({ getTab: async () => ({ id: 1, url: "http://github.com/" }) }));
+ const loc = await vc({}, vault({ getTab: async () => ({ id: 1, url: "https://localhost:3000/" }), isLocalDevHost: () => true }));
+ const blk = await vc({}, vault({ getSettings: async () => ({ ...all, blockedDomains: ["github.com"] }) }));
+ const nofill = await vc({}, vault({ isFillUrlAllowed: async () => false }));
+ ok("verify_code: allowAll refuses http, local dev host, blocked domain, fill-disallowed url", [r, loc, blk, nofill].every((x) => x.error === "not_allowed") && calls.vault.length === 0 && calls.probe === 0);
+ r = await vc({}, vault({ getTab: async () => ({ id: 1, url: "https://support.apple.com/" }) }));
+ ok("verify_code: support.apple.com (not an Apple sign-in host) -> vault path, readCode not called", r.ok === true && calls.read === 0 && calls.vault.length === 1);
+ r = await vc({}, vault({ vaultCode: undefined }));
+ ok("verify_code: no vaultCode dep -> reader_missing", r.error === "reader_missing" && calls.read === 0);
+ r = await vc({}, vault({ vaultCode: async () => ({ ok: false, error: "no_code" }) }));
+ ok("verify_code: no_code carries a Keytray hint", r.error === "no_code" && /Keytray/.test(r.hint) && calls.fill.length === 0);
+ r = await vc({}, vault({ vaultCode: async () => ({ ok: false, error: "several_codes", usernames: ["a@x.com", "b@x.com"] }) }));
+ ok("verify_code: several_codes lists usernames, no values", r.error === "several_codes" && r.usernames.length === 2 && !/\d{4}/.test(JSON.stringify(r)));
+ calls.vault = [];
+ r = await vc({ username: "b@x.com" }, vault());
+ ok("verify_code: username reaches vaultCode", calls.vault[0][2] === "b@x.com" && r.ok === true);
+ calls.vault = [];
+ r = await vc({}, vault());
+ ok("verify_code: no username -> undefined", calls.vault[0][2] === undefined);
+ r = await vc({}, vault({ vaultCode: async () => ({ ok: false, error: "needs_user" }) }));
+ ok("verify_code: vault needs_user passes through", r.error === "needs_user");
+ r = await vc({}, vault({ vaultCode: async () => ({ ok: false, error: "weird" }) }));
+ ok("verify_code: other vault error -> reader_failed", r.error === "reader_failed");
+ const bad = [];
+ for (const c of ["123", "12345678901", "12ab56"]) bad.push(await vc({}, vault({ vaultCode: async () => ({ ok: true, code: c, source: "totp" }) })));
+ ok("verify_code: vault code not 4-10 digits -> reader_failed, fillCode not called", bad.every((x) => x.error === "reader_failed") && calls.fill.length === 0);
+ r = await vc({}, vault({ vaultCode: async () => ({ ok: true, code: "0481", source: "messages" }) }));
+ ok("verify_code: messages source and 4 digits accepted", r.ok === true && r.source === "messages" && calls.fill[0][2] === "0481");
+ calls.vault = [];
+ r = await vc({}, vault({ probeCodeField: async () => null }));
+ ok("verify_code: vault path no field -> no_field, vaultCode not called", r.error === "no_field" && calls.vault.length === 0);
+ {
+ const lim2 = createLimiter();
+ calls.vault = [];
+ const x = [await vc({}, vault(), lim2, 0), await vc({}, {}, lim2, 1), await vc({}, vault(), lim2, 2)];
+ r = await vc({}, vault(), lim2, 3);
+ ok("verify_code: Apple and vault paths share the 3 per 10 min limit", x.every((y) => y.ok) && r.error === "rate_limited" && calls.vault.length === 2);
+ }
+ r = await vc({}, vault({ codeReaderOn: async () => calls.vault.length === 0 }));
+ ok("verify_code: switch off before fill (vault path) -> code dropped", r.reason === "code_reader_off" && calls.fill.length === 0);
r = await vc({ site: "github.com" });
ok("verify_code: site mismatch", r.error === "not_allowed" && r.reason === "site_mismatch" && calls.read === 0);
ok("verify_code: site match passes", (await vc({ site: "apple.com" })).ok === true);