diff --git a/crates/custos-native/src/main.rs b/crates/custos-native/src/main.rs index 26b8ae6..fd03e21 100644 --- a/crates/custos-native/src/main.rs +++ b/crates/custos-native/src/main.rs @@ -1,13 +1,14 @@ //! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Firefox, Edge or Chrome //! starts it when the extension connects, and talks to it over stdin/stdout in native messaging frames. It -//! forwards five requests to the desktop Custos over its Domi pipe and returns the answers: +//! forwards six requests to the desktop Custos over its Domi pipe and returns the answers: //! -//! - `browser_status`: is Custos running, and this connection's match code; +//! - `browser_status`: is Custos running, this connection's match code, and Custos's theme; //! - `browser_match { origin, top }`: the logins for a frame (title, username, has 2FA; never a password); //! - `browser_fill { id, origin, top }`: one login's username, password and 2FA code, when it matches; //! - `browser_totp { id, origin, top }`: only the 2FA code, for the popup; //! - `browser_save { origin, top, username, password, title }`: offer a new login (or a changed password); -//! Custos shows a card and stores it only on *Save*. +//! Custos shows a card and stores it only on *Save*; +//! - `browser_generate { origin, top }`: a new password for a sign-up or change-password form, stored nowhere. //! //! The host adds nothing and decides nothing: Custos checks the origins against the login and asks the user //! once whether this host may use web logins. It forwards only those requests, rebuilt from their known fields, @@ -25,7 +26,7 @@ use serde_json::{Value, json}; use zeroize::Zeroizing; const PIPE: &str = r"\\.\pipe\custos-domi"; -const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill", "browser_totp", "browser_save"]; +const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill", "browser_totp", "browser_save", "browser_generate"]; /// The connection: who started the host, and its session. struct Conn { @@ -310,6 +311,13 @@ mod tests { assert!(save.get("extra").is_none()); // The browser's name: Firefox from the arguments, whatever the extension says; Chromium names itself. let f = conn(Browser::Firefox); + assert_eq!( + rebuild(br#"{"op":"browser_generate","origin":"https://a.cz","top":"https://a.cz","length":4,"id":"x"}"#, &c).unwrap(), + json!({ "op": "browser_generate", "origin": "https://a.cz", "top": "https://a.cz", "app": "Custos for your browser", + "browser": "chromium", "session": c.session }), + "a new password is asked for by origin only; the extension chooses nothing else", + ); + assert_eq!(rebuild(br#"{"op":"browser_generate"}"#, &c), Err("bad_request")); assert_eq!(rebuild(br#"{"op":"browser_status","browser":"chrome"}"#, &f).unwrap()["browser"], "firefox"); assert_eq!(rebuild(br#"{"op":"browser_status","browser":"lynx"}"#, &c).unwrap()["browser"], "chromium"); // Custos's other Domi requests never pass through the browser's host. diff --git a/docs/BROWSER.md b/docs/BROWSER.md index 88d4caa..163c954 100644 --- a/docs/BROWSER.md +++ b/docs/BROWSER.md @@ -54,11 +54,12 @@ answer carries it back. The host adds `app`, `browser` (`firefox` from its argum | Extension → host | Answer | |:--|:--| -| `{"op":"browser_status"}` | `{"ok":true,"code":"123456"}`: the session's match code | -| `{"op":"browser_match","origin","top"}` | `{"ok":true,"logins":[{"id","title","username","totp"}]}` (`totp`: it has a 2FA code); never a secret | +| `{"op":"browser_status"}` | `{"ok":true,"code":"123456","theme"}`: the session's match code; Custos's theme, `auto`/`light`/`dark` | +| `{"op":"browser_match","origin","top"}` | `{"ok":true,"logins":[{"id","title","username","totp"}],"theme"}` (`totp`: it has a 2FA code); never a secret | | `{"op":"browser_fill","id","origin","top"}` | `{"ok":true,"username","password","totp"}` only if that login may go into that frame of that page, else `no_match` | | `{"op":"browser_totp","id","origin","top"}` | `{"ok":true,"totp","remaining"}` (seconds left) under the same rule; `no_totp` without one | | `{"op":"browser_save","origin","top","username","password"[,"title"]}` | after Custos's card: `{"ok":true,"saved":"new"/"updated"/"unchanged"}`, or `refused` | +| `{"op":"browser_generate","origin","top"}` | `{"ok":true,"password","bits"}`: a new password for a sign-up or change-password form, from `custos-gen` (20 characters, every kind required); stored nowhere | Limits: `origin`, `top` ≤ 2 KiB, `id` ≤ 128 bytes, `username` ≤ 1 KiB, `password` 1 byte to 4 KiB, `title` ≤ 200 bytes. Errors the extension turns into a sentence: `not_connected` (no host registered), `not_allowed` @@ -77,7 +78,27 @@ Limits: `origin`, `top` ≤ 2 KiB, `id` ≤ 128 bytes, `username` ≤ 1 KiB, `pa - `browser_save` always shows a card (*Save* / *Don't save*): a new *Web login* for the origin, or, when a login of that site has the same username, its new password. An identical login is `unchanged`, without a card. - Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then - answers `locked`. + answers `locked`, also to `browser_generate`. +- `browser_generate` needs the same grant and a web page, stores nothing and writes no audit line: the password + is kept only if the page's form is sent and the person says *Save* on the card. + +## The popup and the page + +- The popup (the 2026-12 redesign, layout C) shows the active tab's site, its logins first, each with **Fill** and + its 2FA code inline (at most three codes at once; each is a `browser_totp`, so each is in the audit), then a + pending save offer (*Save to Custos*, or *Update* when Custos has that username for the site), and on a page with + a sign-up or change-password form **A new password for this site** with *Fill*. The new password is shown in + the popup's own page only; *Fill* hands it to the tab's top frame, which takes it only if it is still on the + origin it was made for. The popup's requests (`*-tab`) are answered only for the extension's own pages, never + for a content script. +- In the page, a new-password field (marked `new-password`, named new/confirm/repeat, or the two last password + fields of a form) gets **Use a new password** first in Custos's menu. Custos makes it; it goes into that form's + new-password fields (the password and its repeat). Sending the form offers to save it, like a password typed + by hand; a change-password form saves the new password, not the current one, and with no username on the form + a site with one login updates that login. +- Colours are @domi/ui's custos room (dark; parchment in the light theme), copied into the CSS because the + extension has no build step. The popup and the in-page menu follow Custos's theme (`theme` in the answers), + and the system's until Custos has answered. ## Registration and the extension ids @@ -123,8 +144,9 @@ node tools/extension-test.mjs `custos-browser` covers origin parsing, look-alikes (punycode twins, extra labels, userinfo, encoded dots, backslashes, odd ports), public suffixes, frames and their pages, ports and schemes, bare names and IPs, -best-of-several, the callers and the frames. `custos-native` covers that only the five ops pass, rebuilt from +best-of-several, the callers and the frames. `custos-native` covers that only the six ops pass, rebuilt from known fields, and that another extension gets `not_allowed` without reaching Custos. `tools/extension-test.mjs` runs the background script against a fake browser: origins from the browser and never from the message, frames, -sandboxed and blank frames, other extensions, a locked Custos, and a login offered for saving that never comes back -out. The desktop repo has the pipe tests and the end-to-end runs in each browser. +sandboxed and blank frames, other extensions, a locked Custos, a login offered for saving that never comes back +out, a new password asked for by origin only, the popup's requests refused to content scripts, *Update* offers, +and that nothing is ever written to the console. The desktop repo has the pipe tests and the end-to-end runs in each browser. diff --git a/extension/background.js b/extension/background.js index 801b47f..43e40fc 100644 --- a/extension/background.js +++ b/extension/background.js @@ -103,7 +103,22 @@ function showBadge(tabId) { api.tabs.onRemoved.addListener((tabId) => offers.delete(tabId)); /** What the popup and the page may see of an offer: never its password. */ -const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username } : null); +const offerView = (o) => (o ? { host: new URL(o.origin).host, username: o.username, update: o.update } : null); + +/** + * Whether Custos already has this login of the site (the offer then says Update), and the username a form without + * one means: a change-password form of a site with one login changes that login. Custos's card decides either way; + * a locked or unsure Custos just makes it a new one here. + */ +async function known(at, username) { + const r = await ask({ op: 'browser_match', ...at }); + const logins = r?.ok && Array.isArray(r.logins) ? r.logins : []; + if (!username && logins.length === 1 && typeof logins[0].username === 'string') return { username: logins[0].username, update: true }; + return { username, update: logins.some((l) => l.username === username) }; +} + +/** A message from the extension's own pages (the popup), not from a content script in some page. */ +const fromPopup = (sender) => !sender.tab && typeof sender.url === 'string' && sender.url.startsWith(api.runtime.getURL('')); async function save(tabId) { const o = offerFor(tabId); @@ -146,14 +161,22 @@ async function handle(msg, sender) { if (!at || tabId == null || typeof msg.password !== 'string' || !msg.password || msg.password.length > 4096) { return { ok: false, error: 'bad_request' }; } - const username = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : ''; + const typed = typeof msg.username === 'string' ? msg.username.slice(0, 1024) : ''; const title = new URL(at.origin).host; - offers.set(tabId, { ...at, username, password: msg.password, title, at: Date.now() }); + // Kept at once (the page may be going away), then told whether it is an update. + const offer = { ...at, username: typed, password: msg.password, title, update: false, at: Date.now() }; + offers.set(tabId, offer); showBadge(tabId); - // The open connection keeps a service worker (Edge, Chrome) alive, and the offer with it. - void ask({ op: 'browser_status' }); + // The open connection also keeps a service worker (Edge, Chrome) alive, and the offer with it. + Object.assign(offer, await known(at, typed)); return { ok: true, offer: offerView(offers.get(tabId)) }; } + case 'generate': { + // A sign-up or change-password field asks for a new password: by its frame's origin, nothing else. + const at = placeOf(sender); + if (!at) return { ok: false, error: 'no_match' }; + return ask({ op: 'browser_generate', ...at }); + } case 'pending-save': { // The top page of the tab that sent the form, on the same site, asks whether to show the offer. const at = placeOf(sender); @@ -171,6 +194,20 @@ async function handle(msg, sender) { showBadge(sender.tab.id); } return { ok: true }; + case 'match-tab': + case 'totp-tab': + case 'generate-tab': + case 'save-tab': + case 'dismiss-tab': + return fromPopup(sender) ? popupAsks(msg) : { ok: false, error: 'bad_request' }; + default: + return { ok: false, error: 'bad_request' }; + } +} + +/** The popup's requests: always about the active tab's page. */ +async function popupAsks(msg) { + switch (msg.kind) { case 'match-tab': { // From the popup: the logins for the active tab's page, and any login offered for saving there. const tab = await activeTab(); @@ -186,6 +223,13 @@ async function handle(msg, sender) { if (!origin || typeof msg.id !== 'string') return { ok: false, error: 'no_match' }; return ask({ op: 'browser_totp', id: msg.id, origin, top: origin }); } + case 'generate-tab': { + // A new password for the active page, shown in the popup; its Fill hands it to that page's top frame. + const tab = await activeTab(); + const origin = tab && originOf(tab.url); + if (!origin) return { ok: false, error: 'no_match' }; + return { ...(await ask({ op: 'browser_generate', origin, top: origin })), origin, tab: tab.id }; + } case 'save-tab': { const tab = await activeTab(); return tab ? save(tab.id) : { ok: false, error: 'gone' }; diff --git a/extension/content.js b/extension/content.js index af815ae..d0c8799 100644 --- a/extension/content.js +++ b/extension/content.js @@ -19,6 +19,11 @@ gone: 'That offer has expired.', }; const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; + const SAVED = { new: 'Saved to Custos.', updated: 'Updated in Custos.', unchanged: 'Custos already has this login.' }; + const offerText = (o) => + o.update + ? `Update the password of ${o.username || 'your login'} on ${o.host} in Custos?` + : `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host} to Custos?`; const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' })); const visible = (el) => { @@ -32,6 +37,32 @@ (el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`)); const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`); + /** + * The fields of a sign-up or change-password form that take a new password (and its repeat), around `near` (a + * field, or the whole page): the ones the page marks `new-password` or names new/confirm/repeat; else, in a form + * with two password fields, both (a password and its repeat), and with three, the last two (the current one first). + */ + function newPasswordFields(near) { + const scope = near?.form ?? near?.closest?.('form') ?? document; + const pws = [...scope.querySelectorAll('input[type=password]')].filter(visible); + const marked = pws.filter( + (el) => el.autocomplete === 'new-password' || /(^|[^a-z])(new|confirm|repeat|again|retype)/i.test(`${el.name} ${el.id}`), + ); + if (marked.length) return marked; + if (pws.length === 2 && pws.every((el) => el.autocomplete !== 'current-password')) return pws; + if (pws.length === 3) return pws.slice(1); + return []; + } + + /** The new-password fields of the first form on the page that has any. */ + function firstNewFields() { + for (const f of [...document.forms, null]) { + const found = newPasswordFields(f ? (f.querySelector('input[type=password]') ?? f) : null); + if (found.length) return found; + } + return []; + } + /** The username field of a password field: the one the page marks, else the last text field before it. */ function usernameFor(pw) { const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible); @@ -51,7 +82,8 @@ return { user, pass, otp }; } - // Fields Custos filled and the person has not typed in since: a form sent with them is not offered for saving. + // Fields Custos filled from a saved login and the person has not typed in since: a form sent with them is not + // offered for saving. A new password Custos made is not among them: sending that form offers to save it. const filledByCustos = new WeakSet(); document.addEventListener('input', (e) => e.isTrusted && filledByCustos.delete(e.target), true); @@ -65,6 +97,24 @@ filledByCustos.add(el); } + /** A new password into every field that takes it (the password and its repeat). */ + function putNew(fields, password) { + for (const el of fields) { + put(el, password); + filledByCustos.delete(el); + } + } + + /** Asks Custos for a new password and puts it into the form's new-password fields around `near`. */ + async function fillNew(near) { + const fields = newPasswordFields(near); + if (!fields.length) return 'This form has no field for a new password.'; + const r = await send({ kind: 'generate' }); + if (!r?.ok || typeof r.password !== 'string') return say(r?.error); + putNew(fields, r.password); + return null; + } + /** Fills login `id` around `near`. Only what the page has fields for is asked for: a 2FA page gets the code only. */ async function fill(id, near) { const f = fieldsAround(near); @@ -88,34 +138,60 @@ const root = host.attachShadow({ mode: 'closed' }); root.innerHTML = ` - `; + `; + // Every part sits in one box that carries the theme. + const ui = document.createElement('div'); + ui.className = 'ui'; + ui.append(...[...root.children].filter((c) => c.tagName !== 'STYLE')); + root.append(ui); + /** Custos's theme, from any answer that carries it: `light`, `dark`, or `auto` (the system's). */ + function theme(r) { + if (r?.theme === 'light' || r?.theme === 'dark') ui.dataset.domiTheme = r.theme; + else if (r?.theme === 'auto') delete ui.dataset.domiTheme; + } const chip = root.querySelector('.chip'); const menu = root.querySelector('.menu'); const offerBox = root.querySelector('.offer'); @@ -149,9 +225,13 @@ note('Asking Custos…'); const r = await send({ kind: 'match' }); if (field !== target) return; - if (!r?.ok) return note(say(r?.error)); - if (!r.logins.length) return note('Custos has no login for this site.'); - const items = r.logins.map((l) => { + theme(r); + // A sign-up or change-password field: a new password from Custos comes first. + const fresh = newPasswordFields(target).includes(target) ? [newItem(target)] : []; + if (!r?.ok && !fresh.length) return note(say(r?.error)); + const logins = r?.ok ? r.logins : []; + if (!logins.length && !fresh.length) return note('Custos has no login for this site.'); + const items = logins.map((l) => { const b = el('button', { className: 'login', type: 'button' }); b.setAttribute('role', 'menuitem'); b.append( @@ -166,8 +246,25 @@ }); return b; }); - menu.replaceChildren(el('div', { className: 'head', textContent: 'Custos' }), ...items); - items[0]?.focus(); + menu.replaceChildren(el('div', { className: 'head', textContent: 'CUSTOS' }), ...fresh, ...items); + (fresh[0] ?? items[0])?.focus(); + } + + /** "Use a new password": Custos makes one, and it goes into this form's new-password fields only. */ + function newItem(target) { + const b = el('button', { className: 'login new', type: 'button' }); + b.setAttribute('role', 'menuitem'); + b.append( + el('span', { className: 'title', textContent: 'Use a new password' }), + el('span', { className: 'user', textContent: 'Made by Custos. Sending the form offers to save it.' }), + ); + b.addEventListener('click', async (e) => { + if (!e.isTrusted) return; + const why = await fillNew(target); + if (why) note(why); + else hide(); + }); + return b; } chip.addEventListener('click', (e) => e.isTrusted && (menu.hidden ? void open() : (menu.hidden = true))); @@ -198,13 +295,14 @@ function showOffer(offer) { if (!offer || window.top !== window) return; attach(); - const yes = el('button', { type: 'button', className: 'primary', textContent: 'Save in Custos' }); + void send({ kind: 'status' }).then(theme); + const yes = el('button', { type: 'button', className: 'primary', textContent: offer.update ? 'Update' : 'Save to Custos' }); const no = el('button', { type: 'button', textContent: 'Not now' }); yes.addEventListener('click', async (e) => { if (!e.isTrusted) return; offerBox.replaceChildren(el('div', { className: 'note', textContent: 'Answer in Custos…' })); const r = await send({ kind: 'save' }); - const done = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error); + const done = r?.ok ? (SAVED[r.saved] ?? SAVED.new) : say(r?.error); offerBox.replaceChildren(el('div', { className: 'note', textContent: done })); setTimeout(() => (offerBox.hidden = true), 2500); }); @@ -214,18 +312,23 @@ offerBox.hidden = true; }); offerBox.replaceChildren( - el('div', { className: 'head', textContent: 'Custos' }), - el('div', { className: 'note', textContent: `Save the login${offer.username ? ` of ${offer.username}` : ''} for ${offer.host}?` }), + el('div', { className: 'head', textContent: 'CUSTOS' }), + el('div', { className: 'note', textContent: offerText(offer) }), Object.assign(el('div', { className: 'row' }), {}), ); offerBox.lastChild.append(no, yes); offerBox.hidden = false; } - /** A form is being sent: if it has a password the person typed (not one Custos filled), offer to save it. */ + /** + * A form is being sent: if it has a password the person typed or Custos just made (not a saved one Custos filled), + * offer to save it. On a sign-up or change-password form that is the new password, not the current one. + */ function sent(form) { const scope = form ? [...form.querySelectorAll('input')] : [...document.querySelectorAll('input')]; - const pass = scope.find((i) => i.type === 'password' && visible(i) && i.value); + const first = scope.find((i) => i.type === 'password' && visible(i)) ?? null; + const fresh = first ? newPasswordFields(first).find((i) => i.value) : undefined; + const pass = fresh ?? scope.find((i) => i.type === 'password' && visible(i) && i.value); if (!pass || filledByCustos.has(pass)) return; const user = usernameFor(pass); // Read once, handed to the background in memory, and not kept here. @@ -253,10 +356,25 @@ // After the sign-in page went away: the next page of the same site shows the offer. if (window.top === window) void send({ kind: 'pending-save' }).then((r) => r?.ok && showOffer(r.offer)); - // ---- the popup's choice, in the top frame: fill the page's login form, or only its 2FA field ---- + // ---- the popup's choices, in the top frame ---- + // `fill-now`: the page's login form, or only its 2FA field. `page-forms`: does the page take a new password? + // `fill-new`: the new password the popup shows, into those fields, only if this is still the page it was made for. api.runtime.onMessage.addListener((msg, sender, reply) => { - if (sender.id !== api.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false; - fill(msg.id, null).then((why) => reply({ ok: !why, error: why })); - return true; + if (sender.id !== api.runtime.id || sender.tab || window.top !== window) return false; + if (msg?.kind === 'fill-now' && typeof msg.id === 'string') { + fill(msg.id, null).then((why) => reply({ ok: !why, error: why })); + return true; + } + if (msg?.kind === 'page-forms') { + reply({ ok: true, newPassword: firstNewFields().length > 0 }); + return false; + } + if (msg?.kind === 'fill-new' && typeof msg.password === 'string' && msg.password && msg.origin === location.origin) { + const fields = firstNewFields(); + if (fields.length) putNew(fields, msg.password); + reply(fields.length ? { ok: true } : { ok: false, error: 'This page has no field for a new password.' }); + return false; + } + return false; }); })(); diff --git a/extension/popup.css b/extension/popup.css index ad50939..cd6f106 100644 --- a/extension/popup.css +++ b/extension/popup.css @@ -1,128 +1,364 @@ +/* + * The popup in @domi/ui's custos room (the redesign's layout C): its roles, copied here because the extension has + * no build step. Dark by default; parchment in the light theme. Custos's own theme (Light, Dark or Match Windows) + * decides, through `data-domi-theme` on ; until Custos has answered, the system's. + */ :root { color-scheme: dark; - --bg: #101216; - --panel: #15181d; - --hover: #262b33; - --line: #2b3038; - --fg: #e8ebf0; - --muted: #9aa3b1; - --accent: #c9d1dc; + --domi-bg: #08090b; + --domi-chrome: #0c0e11; + --domi-chrome-top: #12151a; + --domi-panel: #121519; + --domi-hover: #1a1e24; + --domi-line: #242930; + --domi-edge: #6b7581; + --domi-field: #060608; + --domi-fg: #eef1f4; + --domi-fg-2: #c4cbd3; + --domi-muted: #959fab; + --domi-accent: #d3dce5; + --domi-leaf-hi: #ffffff; + --domi-leaf-mid: #dfe5eb; + --domi-leaf-lo: #b7c1cc; + --domi-leaf-fg: #0a0c0f; + --domi-rim: #aab5c1; + --domi-second: #ee8344; + --domi-ok: #8fd3a2; + --domi-danger: #ff9d9d; + --digit: #8fb4ff; + --symbol: #ff9d9d; + --font-hand: 'Manrope Variable', 'Manrope', 'Segoe UI Variable Text', 'Segoe UI', system-ui, sans-serif; + --font-code: 'Cascadia Mono', Consolas, ui-monospace, monospace; +} +@media (prefers-color-scheme: light) { + :root:not([data-domi-theme='dark']) { + color-scheme: light; + --domi-bg: #f4efe4; + --domi-chrome: #ebe4d4; + --domi-chrome-top: #f7f2e8; + --domi-panel: #fbf8f1; + --domi-hover: #ece5d5; + --domi-line: #d8cdb6; + --domi-edge: #857a64; + --domi-field: #fffdf8; + --domi-fg: #1e1b16; + --domi-fg-2: #3e382e; + --domi-muted: #5e5647; + --domi-accent: #666e76; + --domi-leaf-hi: #6e777f; + --domi-leaf-mid: #666e76; + --domi-leaf-lo: #525a62; + --domi-leaf-fg: #ffffff; + --domi-rim: #666e76; + --domi-second: #b15003; + --domi-ok: #377a4e; + --domi-danger: #aa5153; + --digit: #2f55b0; + --symbol: #aa3b3d; + } +} +:root[data-domi-theme='light'] { + color-scheme: light; + --domi-bg: #f4efe4; + --domi-chrome: #ebe4d4; + --domi-chrome-top: #f7f2e8; + --domi-panel: #fbf8f1; + --domi-hover: #ece5d5; + --domi-line: #d8cdb6; + --domi-edge: #857a64; + --domi-field: #fffdf8; + --domi-fg: #1e1b16; + --domi-fg-2: #3e382e; + --domi-muted: #5e5647; + --domi-accent: #666e76; + --domi-leaf-hi: #6e777f; + --domi-leaf-mid: #666e76; + --domi-leaf-lo: #525a62; + --domi-leaf-fg: #ffffff; + --domi-rim: #666e76; + --domi-second: #b15003; + --domi-ok: #377a4e; + --domi-danger: #aa5153; + --digit: #2f55b0; + --symbol: #aa3b3d; +} + +* { + box-sizing: border-box; } body { - width: 320px; - margin: 0; - background: var(--bg); - color: var(--fg); - font: 13px/1.45 "Segoe UI", system-ui, sans-serif; -} -header { display: flex; - align-items: baseline; + flex-direction: column; + width: 360px; + min-height: 200px; + max-height: 600px; + margin: 0; + overflow-x: hidden; + background: var(--domi-bg); + color: var(--domi-fg); + font: 13px/1.45 var(--font-hand); +} +.grow { + flex: 1; +} +.muted { + color: var(--domi-muted); +} +.small { + font-size: 12px; +} + +/* the bar and its dentils */ +.bar { + display: flex; + align-items: center; gap: 10px; - padding: 12px 14px 10px; - border-bottom: 1px solid var(--line); - background: var(--panel); + height: 44px; + padding: 0 14px; + background: linear-gradient(180deg, var(--domi-chrome-top), var(--domi-chrome)); } .wordmark { - color: var(--accent); - font-size: 12px; + color: var(--domi-accent); + font-size: 11.5px; letter-spacing: 0.3em; } +.state { + color: var(--domi-muted); + font-size: 12px; +} +.dentils { + height: 3px; + background: repeating-linear-gradient( + 90deg, + var(--domi-accent) 0 7px, + color-mix(in srgb, var(--domi-accent) 25%, var(--domi-bg)) 7px 11px + ); +} +main { + flex: 1; + overflow-y: auto; + padding-bottom: 12px; +} + +/* the site */ .site { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 16px 10px; +} +.site-text { + display: grid; + min-width: 0; +} +.site-text b { overflow: hidden; - color: var(--muted); + font-size: 15px; white-space: nowrap; text-overflow: ellipsis; } -main { - padding: 8px; +.fav { + display: grid; + flex: none; + place-items: center; + width: 40px; + height: 40px; + border-radius: 12px; + background: var(--domi-panel); + border: 1px solid var(--domi-line); + color: var(--domi-fg); + font-size: 17px; + font-weight: 700; } .note { - margin: 6px 6px 10px; + margin: 4px 16px 10px; + color: var(--domi-fg-2); } + +/* the site's logins: each with Fill, and its 2FA code inline */ .logins { + display: grid; + gap: 8px; margin: 0; - padding: 0; + padding: 0 12px 12px; list-style: none; } -.logins button { - display: grid; - width: 100%; - padding: 8px 10px; - border: 0; - border-radius: 8px; - background: none; - color: inherit; - font: inherit; - text-align: left; - cursor: pointer; -} -.logins button:hover, -.logins button:focus-visible { - background: var(--hover); - outline: none; -} -.title { - font-weight: 600; -} -.user { - color: var(--muted); - font-size: 12px; -} -.logins li { +.login { display: flex; align-items: center; - gap: 6px; + gap: 10px; + padding: 10px; + border: 1px solid var(--domi-line); + border-radius: 12px; + background: var(--domi-panel); } -.logins button.login { +.login.first { + border-color: color-mix(in srgb, var(--domi-accent) 45%, var(--domi-line)); +} +.tile { + display: grid; + flex: none; + place-items: center; + width: 32px; + height: 32px; + border-radius: 10px; + background: var(--domi-hover); + color: var(--domi-accent); +} +.login .tx { + display: grid; flex: 1; min-width: 0; } -.logins button.code { - display: block; - width: auto; +.login .tx b, +.login .tx span { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} +.totp { + display: flex; flex: none; - padding: 4px 8px; - border: 1px solid var(--line); - color: var(--accent); + align-items: center; + gap: 6px; +} +.totp .code { + font: 600 15px/1 var(--font-code); font-variant-numeric: tabular-nums; - letter-spacing: 0.08em; + letter-spacing: 0.04em; +} +.ring { + width: 22px; + height: 22px; + color: var(--domi-accent); +} +.ring circle.track { + stroke: var(--domi-line); +} +.ring text { + fill: var(--domi-muted); + font: 600 8px var(--font-hand); +} + +/* buttons: struck leaves for the main action, quiet outlines for the rest */ +.btn { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + gap: 6px; + height: 30px; + padding: 0 14px; + border: 1px solid var(--domi-line); + border-radius: 10px; + background: var(--domi-panel); + color: var(--domi-fg); + font: 600 13px var(--font-hand); + cursor: pointer; +} +.btn:hover, +.btn:focus-visible { + border-color: var(--domi-rim); + outline: none; +} +.btn.primary { + border-color: var(--domi-leaf-lo); + background: linear-gradient(180deg, var(--domi-leaf-hi), var(--domi-leaf-mid) 55%, var(--domi-leaf-lo)); + color: var(--domi-leaf-fg); +} +.btn.quiet { + border-color: transparent; + background: none; + color: var(--domi-fg-2); +} +.btn.icon { + width: 30px; + padding: 0; +} +.btn:disabled { + opacity: 0.5; + cursor: default; +} + +/* cards: the save offer and the new password */ +.card { + display: grid; + gap: 8px; + margin: 0 12px 12px; + padding: 12px; + border: 1px solid var(--domi-line); + border-radius: 12px; + background: var(--domi-panel); } .offer { - margin: 4px 4px 10px; - padding: 10px; - border: 1px solid #c9a96e; - border-radius: 8px; + border-color: color-mix(in srgb, var(--domi-second) 60%, var(--domi-line)); } .offer p { - margin: 0 0 8px; + margin: 0; } .buttons { display: flex; justify-content: flex-end; gap: 8px; } -.buttons button { - padding: 5px 12px; - border: 1px solid var(--line); - border-radius: 7px; - background: var(--panel); - color: inherit; - font: inherit; - cursor: pointer; +.gen-head { + display: flex; + align-items: center; + gap: 8px; + color: var(--domi-fg-2); } -.buttons button.primary { - border-color: #c9a96e; +.gen .pw { + font: 500 15px/1.4 var(--font-code); + letter-spacing: 0.03em; + word-break: break-all; } +.pw .d { + color: var(--digit); +} +.pw .s { + color: var(--symbol); +} +.gen-ctl { + display: flex; + align-items: center; + gap: 6px; +} +.meter { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--domi-fg-2); + font-size: 12px; +} +.bars { + display: inline-flex; + gap: 3px; +} +.bars i { + width: 18px; + height: 4px; + border-radius: 2px; + background: var(--domi-line); +} +.bars i.on { + background: var(--domi-ok); +} +.gen p { + margin: 0; +} + footer { - display: grid; - gap: 2px; - padding: 8px 14px 12px; - border-top: 1px solid var(--line); - color: var(--muted); + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 14px; + border-top: 1px solid var(--domi-line); font-size: 12px; } .code-line { + flex: none; + color: var(--domi-muted); font-variant-numeric: tabular-nums; } [hidden] { diff --git a/extension/popup.html b/extension/popup.html index a7c150a..606da5e 100644 --- a/extension/popup.html +++ b/extension/popup.html @@ -1,5 +1,5 @@ - + Custos @@ -7,23 +7,48 @@ -
+
CUSTOS - + +
+
-
diff --git a/extension/popup.js b/extension/popup.js index f88d652..5ad6a11 100644 --- a/extension/popup.js +++ b/extension/popup.js @@ -1,7 +1,8 @@ -// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form -// (the top frame's content script asks for the secrets itself, so they go only where they belong). A login with -// 2FA can show its current code here. A login the page just sent can be saved in Custos. The footer shows this -// connection's match code, the one Custos shows on its card. +// The toolbar popup (the redesign's layout C, docs/BROWSER.md): the active tab's site, its logins first, each with +// Fill and its 2FA code inline; a login the page just sent, to save or update; on a sign-up or change-password page, +// a new password from Custos to fill in. A click on Fill has the top frame's content script ask for the secrets +// itself, so they go only where they belong. The footer shows this connection's match code, the one Custos's card +// shows. The look follows Custos's theme. const api = globalThis.browser ?? globalThis.chrome; const SENTENCES = { not_connected: 'Connect this browser in Custos first: Settings → Browser.', @@ -17,40 +18,82 @@ const SENTENCES = { no_answer: 'Custos did not answer.', gone: 'That offer has expired.', }; +const SAVED = { new: 'Saved to Custos.', updated: 'Updated in Custos.', unchanged: 'Custos already has this login.' }; +// Codes shown at once: a few logins at most; each one Custos notes in its audit. +const CODES_SHOWN = 3; const say = (code) => SENTENCES[code] ?? 'Custos could not do that.'; const send = (msg) => Promise.resolve(api.runtime.sendMessage(msg)).catch(() => ({ ok: false, error: 'not_running' })); +const toTab = (tab, msg) => Promise.resolve(api.tabs.sendMessage(tab, msg, { frameId: 0 })).catch(() => null); const $ = (id) => document.getElementById(id); const el = (tag, props) => Object.assign(document.createElement(tag), props); +const svg = (markup) => { + const t = document.createElement('template'); + t.innerHTML = markup; + return t.content.firstChild; +}; const note = $('note'); const list = $('logins'); +/** Custos's theme: `light`, `dark`, or `auto` (the system's, which the CSS already follows). */ +function theme(r) { + if (r?.theme === 'light' || r?.theme === 'dark') document.documentElement.dataset.domiTheme = r.theme; + else if (r?.theme === 'auto') delete document.documentElement.dataset.domiTheme; +} + function tell(text) { note.hidden = false; note.textContent = text; } -/** The 2FA code, shown until it changes; then the next one is asked for. */ -async function showCode(id, out) { +const GLOBE = + ''; + +/** The seconds left of a 2FA code, as a ring. */ +function ring(left, period = 30) { + const r = 9; + const c = 2 * Math.PI * r; + const done = Math.max(0, Math.min(1, left / period)); + return svg( + ``, + ); +} + +/** The 2FA code, shown until it changes; then the next one is asked for, while the popup is open. */ +async function showCode(id, box) { const r = await send({ kind: 'totp-tab', id }); + if (!box.isConnected) return; if (!r?.ok) { - out.textContent = say(r?.error); + box.replaceChildren(); return; } - out.textContent = `${r.totp.slice(0, 3)} ${r.totp.slice(3)}`; - out.title = `Changes in ${r.remaining} s`; - setTimeout(() => out.isConnected && showCode(id, out), Math.max(1, r.remaining) * 1000); + const code = el('span', { className: 'code', textContent: `${r.totp.slice(0, 3)} ${r.totp.slice(3)}` }); + code.setAttribute('aria-label', `2FA code ${r.totp.split('').join(' ')}`); + let left = Math.max(1, r.remaining); + const tick = () => { + if (!box.isConnected) return; + if (left <= 0) return void showCode(id, box); + box.replaceChildren(code, ring(left)); + left -= 1; + setTimeout(tick, 1000); + }; + tick(); } function offer(o) { if (!o) return; const box = $('offer'); box.hidden = false; - $('offer-text').textContent = `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host}?`; + $('offer-text').textContent = o.update + ? `Update the password of ${o.username || 'your login'} on ${o.host} in Custos?` + : `Save the login${o.username ? ` of ${o.username}` : ''} for ${o.host} to Custos?`; + $('offer-save').textContent = o.update ? 'Update' : 'Save to Custos'; $('offer-save').addEventListener('click', async () => { $('offer-text').textContent = 'Answer in Custos…'; - const r = await send({ kind: 'save-tab' }); - $('offer-text').textContent = r?.ok ? (r.saved === 'unchanged' ? 'Custos already has this login.' : 'Saved in Custos.') : say(r?.error); $('offer-buttons').hidden = true; + const r = await send({ kind: 'save-tab' }); + $('offer-text').textContent = r?.ok ? (SAVED[r.saved] ?? SAVED.new) : say(r?.error); }); $('offer-dismiss').addEventListener('click', async () => { await send({ kind: 'dismiss-tab' }); @@ -58,39 +101,99 @@ function offer(o) { }); } +function loginRow(l, tab, first) { + const li = el('li', { className: first ? 'login first' : 'login' }); + const tile = el('span', { className: 'tile' }); + tile.append(svg(GLOBE)); + const tx = el('div', { className: 'tx' }); + tx.append(el('b', { textContent: l.title }), el('span', { className: 'muted', textContent: l.username || '—' })); + const fill = el('button', { type: 'button', className: first ? 'btn primary' : 'btn', textContent: 'Fill' }); + fill.setAttribute('aria-label', `Fill ${l.title}`); + fill.addEventListener('click', async () => { + const done = await toTab(tab, { kind: 'fill-now', id: l.id }); + if (done?.ok) window.close(); + else tell(done?.error ?? 'This page has no login form Custos can fill.'); + }); + li.append(tile, tx); + if (l.totp) { + const box = el('span', { className: 'totp' }); + li.append(box); + if (list.querySelectorAll('.totp').length < CODES_SHOWN) void showCode(l.id, box); + } + li.append(fill); + return li; +} + +/** The new password, with its digits and symbols set apart so it reads. */ +function showPassword(out, pw) { + out.replaceChildren( + ...[...pw].map((c) => el('span', { className: /\d/.test(c) ? 'd' : /[A-Za-z]/.test(c) ? '' : 's', textContent: c })), + ); +} + +async function generator(tab, origin) { + const page = await toTab(tab, { kind: 'page-forms' }); + if (!page?.newPassword) return; + const box = $('gen'); + const out = $('gen-pw'); + const fillBtn = $('gen-fill'); + const gnote = $('gen-note'); + let current = null; + const make = async () => { + const r = await send({ kind: 'generate-tab' }); + if (!r?.ok || typeof r.password !== 'string' || r.origin !== origin) { + current = null; + box.hidden = true; + return; + } + current = r.password; + showPassword(out, current); + const strong = r.bits >= 100 ? 5 : r.bits >= 80 ? 4 : r.bits >= 60 ? 3 : r.bits >= 40 ? 2 : 1; + box.querySelectorAll('.bars i').forEach((i, n) => i.classList.toggle('on', n < strong)); + $('gen-strength').textContent = ['Weak', 'Weak', 'Fair', 'Good', 'Strong', 'Very strong'][strong]; + box.hidden = false; + }; + $('gen-again').addEventListener('click', () => void make()); + fillBtn.addEventListener('click', async () => { + if (!current) return; + const done = await toTab(tab, { kind: 'fill-new', password: current, origin }); + gnote.hidden = false; + gnote.textContent = done?.ok + ? 'Filled. When you send the form, Custos offers to save it.' + : (done?.error ?? 'This page has no field for a new password.'); + if (done?.ok) setTimeout(() => window.close(), 900); + }); + await make(); +} + async function show() { const r = await send({ kind: 'match-tab' }); - if (r?.origin) $('site').textContent = new URL(r.origin).host; - offer(r?.offer); - if (!r?.ok) return tell(say(r?.error)); - if (!r.logins.length) return tell('Custos has no login for this site.'); - note.hidden = true; - for (const l of r.logins) { - const li = el('li', {}); - const b = el('button', { type: 'button', className: 'login' }); - b.append(el('span', { className: 'title', textContent: l.title }), el('span', { className: 'user', textContent: l.username || '—' })); - b.addEventListener('click', async () => { - const done = await Promise.resolve(api.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 })).catch(() => null); - if (done?.ok) window.close(); - else tell(done?.error ?? 'This page has no login form Custos can fill.'); - }); - li.append(b); - if (l.totp) { - const code = el('button', { type: 'button', className: 'code', textContent: '2FA code' }); - code.addEventListener('click', () => { - code.disabled = true; - code.textContent = '…'; - void showCode(l.id, code); - }); - li.append(code); - } - list.append(li); + theme(r); + const host = r?.origin ? new URL(r.origin).host : ''; + if (host) { + $('site').textContent = host; + $('fav').textContent = host.replace(/^www\./, '').charAt(0).toUpperCase(); } - list.querySelector('button')?.focus(); + offer(r?.offer); + if (r?.origin && r.tab != null) void generator(r.tab, r.origin); + if (!r?.ok) { + $('state').hidden = r?.error !== 'locked'; + $('state').textContent = 'Locked'; + return tell(say(r?.error)); + } + $('state').hidden = false; + $('state').textContent = 'Unlocked'; + const n = r.logins.length; + $('count').textContent = n === 0 ? 'No login for this site' : n === 1 ? '1 login for this site' : `${n} logins for this site`; + if (!n) return tell('Custos has no login for this site.'); + note.hidden = true; + r.logins.forEach((l, i) => list.append(loginRow(l, r.tab, i === 0))); + list.querySelector('.btn')?.focus(); } async function connection() { const r = await send({ kind: 'status' }); + theme(r); if (r?.ok && typeof r.code === 'string') $('code').textContent = `Connection ${r.code.slice(0, 3)} ${r.code.slice(3)}`; } diff --git a/tools/extension-test.mjs b/tools/extension-test.mjs index 011ef68..0dae1ab 100644 --- a/tools/extension-test.mjs +++ b/tools/extension-test.mjs @@ -15,7 +15,7 @@ const code = fs.readFileSync(path.join(root, 'extension', 'background.js'), 'utf const ID = 'custos-test-id'; /** A fresh background with a fake API. `host(req)` answers the native host's requests. */ -function background(host) { +function background(host, console = globalThis.console) { const sent = []; let listener = null; const port = { @@ -28,7 +28,7 @@ function background(host) { }; const tabs = [{ id: 1, url: 'https://github.com/login', active: true }]; const api = { - runtime: { id: ID, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } }, + runtime: { id: ID, getURL: (p) => `chrome-extension://${ID}/${p}`, connectNative: () => port, onMessage: { addListener: (f) => (listener = f) } }, tabs: { query: async () => tabs, onRemoved: { addListener: () => {} } }, action: { setBadgeText: async () => {}, setBadgeBackgroundColor: async () => {} }, }; @@ -104,9 +104,9 @@ test('a login offered for saving never comes back out, and goes only to Custos', const b = background((m) => (m.op === 'browser_save' ? { ok: true, saved: 'new' } : { ok: true, code: '123456' })); const at = top('https://github.com/login'); const offered = await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at); - assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark' } }); + assert.deepEqual(offered, { ok: true, offer: { host: 'github.com', username: 'mark', update: false } }); // Another page of the site in the same tab sees the offer, without the password; a frame or another site does not. - assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark' } }); + assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://github.com/home')), { ok: true, offer: { host: 'github.com', username: 'mark', update: false } }); assert.deepEqual(await b.call({ kind: 'pending-save' }, frame('https://github.com/x', 'https://github.com/')), { ok: true, offer: null }); assert.deepEqual(await b.call({ kind: 'pending-save' }, top('https://evil.net/')), { ok: true, offer: null }); const popup = await b.call({ kind: 'match-tab' }, { url: `chrome-extension://${ID}/popup.html` }); @@ -127,6 +127,59 @@ test('an offer needs a password, from a web page', async () => { assert.equal((await b.call({ kind: 'offer-save', username: 'm', password: 'x'.repeat(4097) }, top('https://a.cz/'))).ok, false); }); +test('a new password is asked for by origin only, and goes back only to the frame that asked', async () => { + const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw', bits: 128 } : { ok: true })); + const r = await b.call({ kind: 'generate', length: 4, origin: 'https://bank.cz' }, frame('https://accounts.example/signup', 'https://example.com/')); + assert.deepEqual(r, { ok: true, password: 'Gen-3rated!pw', bits: 128, seq: 1 }); + assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top, m.length]), [['browser_generate', 'https://accounts.example', 'https://example.com', undefined]]); + for (const s of [{ ...top('https://a.cz/'), origin: 'null' }, top('about:blank'), top('file:///x.html')]) { + assert.deepEqual(await b.call({ kind: 'generate' }, s), { ok: false, error: 'no_match' }); + } + assert.equal(b.sent.length, 1); +}); + +test('the popup’s requests come only from the extension’s own pages, never from a content script', async () => { + const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw', bits: 128 } : { ok: true, totp: '123456', logins: [] })); + const popup = { url: `chrome-extension://${ID}/popup.html` }; + for (const kind of ['match-tab', 'totp-tab', 'generate-tab', 'save-tab', 'dismiss-tab']) { + assert.deepEqual(await b.call({ kind, id: 'a' }, frame('https://evil.net/ad', 'https://github.com/')), { ok: false, error: 'bad_request' }, kind); + assert.deepEqual(await b.call({ kind, id: 'a' }, top('https://github.com/')), { ok: false, error: 'bad_request' }, kind); + } + assert.equal(b.sent.length, 0); + const g = await b.call({ kind: 'generate-tab' }, popup); + assert.deepEqual([g.password, g.origin], ['Gen-3rated!pw', 'https://github.com']); + assert.deepEqual(b.sent.map((m) => [m.op, m.origin, m.top]), [['browser_generate', 'https://github.com', 'https://github.com']]); +}); + +test('an offer says Update when Custos has that login, and a change-password form finds its one login', async () => { + const logins = [{ id: 'a', title: 'GitHub', username: 'mark', totp: false }]; + const b = background((m) => (m.op === 'browser_match' ? { ok: true, logins } : { ok: true, saved: 'updated' })); + const at = top('https://github.com/settings/password'); + assert.deepEqual(await b.call({ kind: 'offer-save', username: 'mark', password: 'new-pw-1' }, at), { ok: true, offer: { host: 'github.com', username: 'mark', update: true } }); + // No username on the form, and one login for the site: that login is the one that changes. + assert.deepEqual(await b.call({ kind: 'offer-save', username: '', password: 'new-pw-2' }, at), { ok: true, offer: { host: 'github.com', username: 'mark', update: true } }); + assert.deepEqual(await b.call({ kind: 'offer-save', username: 'petra', password: 'new-pw-3' }, at), { ok: true, offer: { host: 'github.com', username: 'petra', update: false } }); + // A locked Custos cannot say: it is offered as new, and Custos's card decides. + const locked = background((m) => (m.op === 'browser_match' ? { ok: false, error: 'locked' } : { ok: true })); + assert.deepEqual(await locked.call({ kind: 'offer-save', username: '', password: 'p' }, at), { ok: true, offer: { host: 'github.com', username: '', update: false } }); +}); + +test('nothing is ever written to the console, and no script of the extension can', async () => { + const said = []; + const quiet = new Proxy({}, { get: () => (...a) => said.push(a) }); + const b = background((m) => (m.op === 'browser_generate' ? { ok: true, password: 'Gen-3rated!pw' } : { ok: true, logins: [], saved: 'new' }), quiet); + const at = top('https://github.com/login'); + await b.call({ kind: 'offer-save', username: 'mark', password: 'hunter2-secret' }, at); + await b.call({ kind: 'save' }, at); + await b.call({ kind: 'generate' }, at); + await b.call({ kind: 'fill', id: 'a' }, at); + await b.call({ kind: 'nonsense' }, at); + assert.deepEqual(said, []); + for (const f of fs.readdirSync(path.join(root, 'extension')).filter((f) => f.endsWith('.js'))) { + assert.ok(!/\bconsole\s*\.|\bdebugger\b/.test(fs.readFileSync(path.join(root, 'extension', f), 'utf8')), f); + } +}); + let failed = 0; for (const [name, f] of tests) { try {