// 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 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) => { 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 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); 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 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); 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); } /** 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); 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 = ` `; // 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'); 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; 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( 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' }), ...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))); // 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(); 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 ? (SAVED[r.saved] ?? SAVED.new) : 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: 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 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 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. 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 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 || 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; }); })();