Files
CustosPublic/extension/content.js
T

174 lines
8.3 KiB
JavaScript

// 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 and the
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens.
(() => {
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.',
locked: 'Custos is locked. Unlock it, then try again.',
denied: 'Custos did not allow this browser to use your logins.',
not_found: 'That login is no longer in Custos.',
no_match: 'That login does not belong to this site.',
no_answer: 'Custos did not answer.',
};
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
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 };
}
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
function put(el, value) {
if (!el || 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 }));
}
async function fill(id, near) {
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
if (!r?.ok) return say(r?.error);
const f = fieldsAround(near);
put(f.user, r.username);
put(f.pass, r.password);
if (f.otp) put(f.otp, r.totp);
return null;
}
// ---- the button and the list ----
const host = document.createElement('custos-fill');
const root = host.attachShadow({ mode: 'closed' });
root.innerHTML = `
<style>
:host { all: initial; }
.chip, .menu { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
.menu { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
color: inherit; text-align: left; cursor: pointer; font: inherit; }
button.login:hover, button.login:focus-visible { background: #262b33; outline: none; }
.title { font-weight: 600; }
.user { color: #9aa3b1; font-size: 12px; }
.note { padding: 6px 8px; color: #c9d1dc; }
[hidden] { display: none !important; }
</style>
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5l5 2v4c0 3.2-2.1 5.8-5 7-2.9-1.2-5-3.8-5-7v-4z"
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>`;
const chip = root.querySelector('.chip');
const menu = root.querySelector('.menu');
let field = null;
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(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
menu.hidden = false;
}
async function open() {
const target = field;
note('Asking Custos…');
const r = await chrome.runtime.sendMessage({ 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 head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
const items = r.logins.map((l) => {
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' });
b.setAttribute('role', 'menuitem');
b.append(
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
);
b.addEventListener('click', async () => {
const why = await fill(l.id, target);
if (why) note(why);
else hide();
});
return b;
});
menu.replaceChildren(head, ...items);
items[0]?.focus();
}
chip.addEventListener('click', () => (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 el = e.target;
if (!(el instanceof HTMLInputElement) || !visible(el)) return;
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return;
if (!host.isConnected) document.documentElement.append(host);
field = el;
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);
// The popup's choice, in the top frame: fill the page's login form.
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
if (sender.id !== chrome.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;
});
})();