// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this // frame's site, and fills the one the person picks. Nothing is filled without a click. The button, the list and // the save offer live in a closed shadow root, out of the page's reach; logins are asked for only when the list // opens, and a secret goes only into the field it is for. (() => { const api = globalThis.browser ?? globalThis.chrome; const SENTENCES = { not_connected: 'Connect this browser in Custos first: Settings → Browser.', not_running: 'Custos is not running. Start it, then try again.', not_custos: 'Something other than Custos answered. Nothing was sent.', not_allowed: 'This copy of the extension is not the one Custos knows.', locked: 'Custos is locked. Unlock it, then try again.', denied: 'Custos did not allow this browser to use your logins.', refused: 'Not saved.', not_found: 'That login is no longer in Custos.', no_match: 'That login does not belong to this site.', no_totp: 'That login has no 2FA code in Custos.', no_answer: 'Custos did not answer.', gone: 'That offer has expired.', }; 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 visible = (el) => { const r = el.getBoundingClientRect(); const s = getComputedStyle(el); return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly; }; const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type); const isOtp = (el) => el instanceof HTMLInputElement && (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 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); const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete)); if (marked) return marked; for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i]; return null; } /** The fields a login fills, around `near` (the focused field) or on the whole page. */ function fieldsAround(near) { const all = [...document.querySelectorAll('input')].filter(visible); const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null; const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all; const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null; const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null); 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. const filledByCustos = new WeakSet(); document.addEventListener('input', (e) => e.isTrusted && filledByCustos.delete(e.target), true); const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set; function put(el, value) { if (!el || !el.isConnected || typeof value !== 'string' || !value) return; el.focus(); setValue.call(el, value); el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); filledByCustos.add(el); } /** 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); if (!f.pass && !f.user && f.otp) { const r = await send({ kind: 'totp', id }); if (!r?.ok) return say(r?.error); put(f.otp, r.totp); return null; } const r = await send({ kind: 'fill', id }); if (!r?.ok) return say(r?.error); put(f.user, r.username); put(f.pass, r.password); if (f.otp) put(f.otp, r.totp); return null; } // ---- the button, the list and the save offer ---- const host = document.createElement('custos-fill'); const root = host.attachShadow({ mode: 'closed' }); root.innerHTML = `
`; const chip = root.querySelector('.chip'); const menu = root.querySelector('.menu'); const offerBox = root.querySelector('.offer'); let field = null; const attach = () => host.isConnected || document.documentElement.append(host); const el = (tag, props) => Object.assign(document.createElement(tag), props); function place() { if (!field || !field.isConnected) return hide(); const r = field.getBoundingClientRect(); chip.style.left = `${Math.max(0, r.right - 28)}px`; chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`; menu.style.left = `${Math.max(4, r.left)}px`; menu.style.top = `${r.bottom + 4}px`; } function hide() { chip.hidden = true; menu.hidden = true; field = null; } function note(text) { menu.replaceChildren(el('div', { className: 'note', textContent: text })); menu.hidden = false; } async function open() { const target = field; 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) => { const b = el('button', { className: 'login', type: 'button' }); b.setAttribute('role', 'menuitem'); b.append( el('span', { className: 'title', textContent: l.title }), el('span', { className: 'user', textContent: (l.username || '—') + (l.totp ? ' · 2FA' : '') }), ); b.addEventListener('click', async (e) => { if (!e.isTrusted) return; const why = await fill(l.id, target); if (why) note(why); else hide(); }); return b; }); menu.replaceChildren(el('div', { className: 'head', textContent: 'Custos' }), ...items); items[0]?.focus(); } chip.addEventListener('click', (e) => e.isTrusted && (menu.hidden ? void open() : (menu.hidden = true))); // A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it. host.addEventListener('mousedown', (e) => e.preventDefault()); document.addEventListener( 'focusin', (e) => { const t = e.target; if (!(t instanceof HTMLInputElement) || !visible(t)) return; if (t.type !== 'password' && !isOtp(t) && !(isText(t) && fieldsAround(t).pass) && !isUserName(t)) return; attach(); field = t; menu.hidden = true; chip.hidden = false; place(); }, true, ); document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true); document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true); window.addEventListener('scroll', place, true); window.addEventListener('resize', place); // ---- saving a login the person typed ---- function showOffer(offer) { if (!offer || window.top !== window) return; attach(); const yes = el('button', { type: 'button', className: 'primary', textContent: 'Save in 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); offerBox.replaceChildren(el('div', { className: 'note', textContent: done })); setTimeout(() => (offerBox.hidden = true), 2500); }); no.addEventListener('click', (e) => { if (!e.isTrusted) return; void send({ kind: 'dismiss-save' }); 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}?` }), 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. */ function sent(form) { const scope = form ? [...form.querySelectorAll('input')] : [...document.querySelectorAll('input')]; const pass = 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. void send({ kind: 'offer-save', username: user?.value ?? '', password: pass.value }).then((r) => r?.ok && showOffer(r.offer)); } document.addEventListener('submit', (e) => e.isTrusted && sent(e.target instanceof HTMLFormElement ? e.target : null), true); // Pages that sign in by script never send a form: a click on their button, or Enter in the password, counts. document.addEventListener( 'click', (e) => { if (!e.isTrusted) return; const b = e.target instanceof Element ? e.target.closest('button, input[type=submit]') : null; if (!b || b.form?.querySelector('input[type=password]') == null || (b.type && b.type !== 'submit')) return; sent(b.form); }, true, ); document.addEventListener( 'keydown', (e) => e.isTrusted && e.key === 'Enter' && e.target instanceof HTMLInputElement && e.target.type === 'password' && !e.target.form && sent(null), true, ); // 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 ---- 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; }); })();