Skip to content
Open
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
20 changes: 18 additions & 2 deletions docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ Off by default. In Settings, on the Agents tab, the user can turn on Allow every

- the tab must be `https:`; plain HTTP is refused even if Fill and save on HTTP pages is on, and so are `localhost`, `127.0.0.1`, `[::1]`, `.localhost` and `.test` hosts;
- a site in the user's blocked domains is refused (on listed sites too);
- `logins` and `sign_in` only see logins saved for the tab's own site, a subdomain of it, or its `www.` form. A login saved only for another domain, such as a college's SSO domain, is not offered;
- `logins` and `sign_in` only see logins saved for the tab's own site, a subdomain of it, or its `www.` form. A login saved only for another domain, such as a college's SSO domain, is not offered. A login saved for a sibling host on the same site (for example `billing.example.com` when the tab is on `auth.example.com`) is not offered either; on a miss it is listed in `near`, for information only, and never filled;
- the password is read fresh each time and refused (`not_allowed`) unless the record read is itself saved for the site;
- only the page's own frames on the same origin are filled, never an allowlisted frame from another site;
- each password read still needs the user's approval in Apple's Passwords.
Expand All @@ -149,6 +149,16 @@ Success:

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

### Misses: `lookedUp`, `near`, `nearSites`

When nothing is offered (`logins` with an empty `usernames`, or `sign_in` ending in `no_login`, whether the site has no login or none matches `username`), the reply may say why. These fields never appear on a success, never carry a password or code, and nothing named in them is ever filled:

- `lookedUp`: the hosts PassBridge asked Apple about, the tab's host first.
- `near`: with Allow every site (*), logins that were found but not offered because they are saved for another host of the same registrable domain, as `[{"site":"billing.example.com","usernames":["octocat"]}]`. Omitted when there are none.
- `nearSites`: sites with a similar spelling (two letters swapped or one dropped in the site name, with and without `www.`) that do have a login. Site names only, no usernames. PassBridge makes at most 12 extra lookups for this, only on a miss, and each asks only for usernames. A spelling is only asked about when an agent could be served there anyway: never a blocked or local host, and only an allowlisted one unless Allow every site (*) is on. These lookups have their own budget of 3 misses per 10 minutes, apart from the `sign_in` limit; past it the reply has no `nearSites`. Omitted when there are none.

`sign_in` with a `username` that is not saved, on a site that has other logins, also carries `usernames`.

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,7 +174,7 @@ Failure: `{"id":"…","ok":false,"error":"<code>"}`. `choose_login` and `usernam
| `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` |
| `no_login` | no saved login for the site, or none matching `username`; may carry `lookedUp`, `near`, `nearSites` (see Misses) |
| `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) |
Expand All @@ -178,6 +188,12 @@ Failure: `{"id":"…","ok":false,"error":"<code>"}`. `choose_login` and `usernam
The reference CLI: `status`, `pair-start`, `pair-pin` (reads the 6 digits as one line from stdin, never from the command line, for example `printf '%s
' 123456 | python3 passbridge-agent-cli.py pair-pin`), `logins <tabId>`, `sign_in <tabId> [username]`, and `save <tabId> <username>` or `save --url <https-url> <username>`, which reads the password from stdin (never from the command line), for example `printf '%s' "$PW" | python3 passbridge-agent-cli.py save 12 octocat`, or `... save --url https://github.com/login octocat`. `verify-code <tabId> [site]` runs `verify_code` (macOS and Windows only).

`logins` and `sign_in` also take, anywhere after the `tabId`, `--site <host>` (sent as `site`, so a tab that navigated away is refused) and `--wait <seconds>` (a whole number up to 600; a missing or bad value is a usage error, exit 2). With `--wait N`, `logins` asks again every 10 s (`PASSBRIDGE_WAIT_STEP` sets the step in seconds, for tests) until a username is listed or N seconds have passed, and prints the last reply. `sign_in --wait N` does the same with `logins` first, until some login is listed (or the named `username`, matched without regard to case), then sends `sign_in` once; if the time runs out first, it prints the last `logins` reply (with its miss fields), exit 1, and sends no `sign_in`. A `logins` reply that is not `ok` is printed at once, exit 1, and no `sign_in` is sent. Each request has its own `id`. Without `--wait` one request is sent.

## Sync

PassBridge keeps no copy of the login list: every lookup asks Apple's helper live. Apple syncs logins between devices on its own schedule and offers no way to trigger a sync or to read when one last ran, so a login saved on another device a few minutes ago can be missing here until Apple copies it. `--wait` covers that: it keeps asking until the login appears or the time is up.

The reference CLI adds two codes of its own, without an `id`: `no_host`, when it can't connect, and `no_reply`, when the connection closed with no answer. Wait at least 90 s for a reply, because a Touch ID prompt can take that long. The CLI waits 100 s.

## Removed
Expand Down
74 changes: 71 additions & 3 deletions native/passbridge-agent-cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import socket
import subprocess
import sys
import time
import uuid

USAGE = "usage: passbridge-agent-cli.py status | pair-start | pair-pin (pin on stdin) | logins <tabId> | sign_in <tabId> [username] | save <tabId> <username> | verify-code <tabId> [site] [username] | unlock | save --url <https-url> <username> (save reads the password from stdin)"
USAGE = "usage: passbridge-agent-cli.py status | pair-start | pair-pin (pin on stdin) | logins <tabId> [--site <host>] [--wait <seconds, max 600>] | sign_in <tabId> [username] [--site <host>] [--wait <seconds, max 600>] | save <tabId> <username> | verify-code <tabId> [site] [username] | unlock | save --url <https-url> <username> (save reads the password from stdin)"

MAX_WAIT = 600
WINDOWS = os.name == "nt"
if WINDOWS:
_default = os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~"), "PassBridge")
Expand Down Expand Up @@ -86,7 +88,32 @@ def main(argv):
code = wsl_reexec(argv)
if code is not None:
return code
wait = 0
site = None
if argv[0] in ("logins", "sign_in"):
# --site <host> and --wait <seconds> may come anywhere after the tabId
rest = []
i = 0
while i < len(argv):
a = argv[i]
if i >= 2 and a in ("--site", "--wait"):
val = argv[i + 1] if i + 1 < len(argv) else None
bad_wait = a == "--wait" and not (val and val.isascii() and val.isdigit() and int(val) <= MAX_WAIT)
if val is None or bad_wait or (a == "--site" and not val):
print(USAGE, file=sys.stderr)
return 2
if a == "--wait":
wait = int(val)
else:
site = val
i += 2
continue
rest.append(a)
i += 1
argv = rest
req = {"id": uuid.uuid4().hex, "op": argv[0].replace("-", "_")}
if site:
req["site"] = site
pairing = argv[0] in ("pair-start", "pair-pin", "unlock")
if argv[0] == "pair-pin":
req["pin"] = sys.stdin.readline().strip()
Expand Down Expand Up @@ -117,15 +144,56 @@ def main(argv):
if not req["password"]:
print("the password must come on stdin", file=sys.stderr)
return 2
line = (ask_pipe if WINDOWS else ask_socket)(req)
ask = ask_pipe if WINDOWS else ask_socket
if wait:
# a login saved on another device can take minutes to reach this Mac: poll the username list until it shows up
try:
step = max(0.05, float(os.environ.get("PASSBRIDGE_WAIT_STEP") or 10))
except ValueError:
step = 10.0
want = req.get("username")
probe = dict(req, op="logins")
probe.pop("username", None)
start = time.monotonic()
while True:
probe["id"] = uuid.uuid4().hex
raw = ask(probe)
try:
r = json.loads(raw) if raw else None
except ValueError:
r = None
if r is None:
return finish(raw)
names = [str(n).strip().lower() for n in (r.get("usernames") or [])]
found = bool(names) and (not want or str(want).strip().lower() in names)
if not r.get("ok") or found or time.monotonic() - start >= wait:
break
time.sleep(step)
# logins prints its last reply; a failed read stops before any sign_in is sent
if req["op"] == "logins" or not r.get("ok"):
return finish(raw)
if not found:
# time ran out: the last logins reply says what was looked up; no sign_in is sent
print(raw.decode().strip())
return 1
req["id"] = uuid.uuid4().hex
return finish(ask(req))


def finish(line):
if line is None:
print(json.dumps({"ok": False, "error": "no_host"}))
return 1
if not line:
print(json.dumps({"ok": False, "error": "no_reply"}))
return 1
try:
reply = json.loads(line)
except ValueError:
print(json.dumps({"ok": False, "error": "no_reply"}))
return 1
print(line.decode().strip())
return 0 if json.loads(line).get("ok") else 1
return 0 if isinstance(reply, dict) and reply.get("ok") else 1


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion scripts/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const AUTO = join(dirname(fileURLToPath(import.meta.url)), "..", "test-harness", "automation");
const PY_SUITES = ["native-hosts.test.py", "updater.test.py", "agent-relay.test.py", "agent-cli-wsl.test.py", "policy-profile.test.py"];
const PY_SUITES = ["native-hosts.test.py", "updater.test.py", "agent-relay.test.py", "agent-cli-wsl.test.py", "agent-cli-wait.test.py","policy-profile.test.py"];
const SUITES = ["unit.test.ts", "pin-session.test.ts", "windows-host.test.ts", "windows-fixtures.test.ts", "i18n.test.ts", "otp-list.test.ts", "mru.test.ts", "fake-helper.test.ts"];

// the Windows Store "python3" stub exits non-zero, so ask each candidate for its major version
Expand Down
85 changes: 80 additions & 5 deletions src/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { SETTINGS_AREA, getSettings, hostBlocked } from "./settings.js";
import { hostOfSite, siteHosts } from "./session/password-search.js";
import { usernameMatchesPage } from "./session/username-match.js";
import { registrableDomain, siteLookupHosts } from "./session/site-domain.js";

/**
* Injected collaborators. Results are `any` where they are owned by background.js or the vault (shapes not typed there).
Expand All @@ -28,6 +29,8 @@ import { usernameMatchesPage } from "./session/username-match.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 {{ take: (now?: number) => boolean }} [probeLimiter] budget for typo probes (tests); a module limiter otherwise
* @property {(tabId: number | undefined, hosts: string[]) => Promise<string[]>} [probeLoginHosts] the hosts (of those asked) that have at least one non-passkey login; names only
* @property {(tab: any) => Promise<{ username?: string, fixed?: boolean } | null>} [pageUsername] the account the page already shows; fixed when the fill cannot change it
*/

Expand Down Expand Up @@ -206,6 +209,75 @@ export function sanitizeReply(value) {
* @param {unknown} b
*/
const same = (a, b) => String(a || "").trim().toLowerCase() === String(b || "").trim().toLowerCase();
// near-miss hosts: the registrable domain with its main label mistyped (one swap or one letter dropped), bare and www.
// at most 12, all derived from the tab host. only used to tell the caller a login may be saved under another spelling
/**
* @param {unknown} host
* @returns {string[]}
*/
export function typoHosts(host) {
const h = String(host || "").toLowerCase().replace(/\.$/, "");
const reg = registrableDomain(h);
if (!reg || !reg.includes(".") || /^\d{1,3}(\.\d{1,3}){3}$/.test(reg) || reg.includes(":") || reg.startsWith("[")) return [];
const dot = reg.indexOf(".");
const main = reg.slice(0, dot);
const suffix = reg.slice(dot + 1);
/** @type {string[]} */
const variants = [];
const add = (/** @type {string} */ v) => {
if (v && v !== main && !variants.includes(v)) variants.push(v);
};
for (let i = 0; i < main.length - 1; i++) add(main.slice(0, i) + main[i + 1] + main[i] + main.slice(i + 2));
for (let i = 0; i < main.length; i++) {
const v = main.slice(0, i) + main.slice(i + 1);
if (v.length >= 2 && !v.startsWith("-") && !v.endsWith("-")) add(v);
}
const bare = variants.map((v) => `${v}.${suffix}`);
return [...bare, ...bare.map((b) => `www.${b}`)].slice(0, 12);
}

// typo probes on a miss: at most 3 per 10 minutes, apart from the sign_in budget
const probeLimiter = createLimiter(3);

/**
* What to tell a caller whose lookup found nothing: the hosts asked, sibling logins that were not offered, and
* misspelled sites that do have a login. Names only, never a password.
* @param {string} host
* @param {any} tab
* @param {any[]} all every login found, before the every-site filter
* @param {any[]} kept the logins that were offered
* @param {AgentDeps} deps
* @param {any} settings
* @param {boolean} everySite
* @param {number} now
*/
async function missInfo(host, tab, all, kept, deps, settings, everySite, now) {
/** @type {Record<string, unknown>} */
const out = { lookedUp: siteLookupHosts(host) };
const reg = registrableDomain(host);
/** @type {{ site: string, usernames: string[] }[]} */
const near = [];
for (const l of all) {
if (kept.includes(l)) continue;
const site = siteHosts(l.saved).map((s) => String(s).toLowerCase()).find((s) => reg && registrableDomain(s) === reg && !hostBlocked(s, settings.blockedDomains));
if (!site) continue;
let g = near.find((n) => n.site === site);
if (!g) near.push((g = { site, usernames: [] }));
if (!g.usernames.some((u) => same(u, l.username))) g.usernames.push(l.username);
}
if (near.length) out.near = near;
// only hosts the agent could be served on anyway: never a blocked or dev host, and on the allowlist unless every-site is on.
// its own budget, so a caller looping on misses cannot keep Apple's helper busy
const probe = typoHosts(host).filter((h) => !hostBlocked(h, settings.blockedDomains) && !deps.isLocalDevHost(h) && (everySite || hostAllowed(h, settings.agentAllowlist)));
if (deps.probeLoginHosts && probe.length && (deps.probeLimiter || probeLimiter).take(now)) {
try {
const hits = await deps.probeLoginHosts(tab.id, probe);
if (Array.isArray(hits) && hits.length) out.nearSites = hits.filter((h) => typeof h === "string");
} catch {}
}
return out;
}

/**
* @param {string} error
* @param {Record<string, unknown>} [extra]
Expand Down Expand Up @@ -511,8 +583,8 @@ export async function handleAgentRequest(msg, deps, limiter, now = Date.now()) {
if (!deps.client.ready) return done(fail("needs_user"));

try {
let found = await deps.siteLogins(tab.id, tab.url);
if (everySite) found = found.filter((l) => loginSavedFor(host, l.saved));
const all = await deps.siteLogins(tab.id, tab.url);
const found = everySite ? all.filter((l) => loginSavedFor(host, l.saved)) : all;
const logins = deps.uniqueByUsername(found);
const names = logins.map((l) => l.username);
if (op === "save") {
Expand All @@ -524,10 +596,13 @@ export async function handleAgentRequest(msg, deps, limiter, now = Date.now()) {
deps.notifySaved?.(host, saveName);
return done({ ok: true, domain: host, username: saveName });
}
if (op === "logins") return done({ ok: true, domain: host, usernames: names });
if (op === "logins") {
if (names.length) return done({ ok: true, domain: host, usernames: names });
return done({ ok: true, domain: host, usernames: names, ...(await missInfo(host, tab, all, found, deps, settings, everySite, now)) });
}

if (op === "sign_in") {
if (!names.length) return done(fail("no_login"));
if (!names.length) return done(fail("no_login", await missInfo(host, tab, all, found, deps, settings, everySite, now)));
// a page that shows a fixed account (a password-only step) only gets that account's password
let fixedName = "";
try {
Expand All @@ -542,7 +617,7 @@ export async function handleAgentRequest(msg, deps, limiter, now = Date.now()) {
username = pool[0];
} else {
const hit = names.find((n) => same(n, username));
if (!hit) return done(fail("no_login"));
if (!hit) return done(fail("no_login", { usernames: names, ...(await missInfo(host, tab, all, found, deps, settings, everySite, now)) }));
if (fixedName && !usernameMatchesPage(hit, fixedName)) return done(fail("username_mismatch", { usernames: names }));
username = hit;
}
Expand Down
12 changes: 12 additions & 0 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -2056,6 +2056,18 @@ const agent = initAgent({
isFillUrlAllowed,
isLocalDevHost,
siteLogins,
// usernames only, one lookup per host, never a password
probeLoginHosts: async (tabId, hosts) => {
/** @type {string[]} */
const out = [];
for (const h of hosts) {
try {
const list = await client.getLoginNamesForURL(tabId, `https://${h}/`);
if ((list || []).some((/** @type {any} */ l) => !isPasskeyLogin(l))) out.push(h);
} catch {}
}
return out;
},
uniqueByUsername,
fillLoginOnTab,
saveLogin: (tabId, url, username, password) => client.saveLogin(tabId, url, username, password, { reportTimeout: true }),
Expand Down
Loading
Loading