202 lines
8.5 KiB
JavaScript
202 lines
8.5 KiB
JavaScript
// 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.',
|
|
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: 'Custos fills only web pages (https, or this computer).',
|
|
no_totp: 'That login has no 2FA code in Custos.',
|
|
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;
|
|
}
|
|
|
|
const GLOBE =
|
|
'<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M2 8h12M8 2c1.8 2 1.8 10 0 12M8 2c-1.8 2-1.8 10 0 12" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>';
|
|
|
|
/** 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(
|
|
`<svg class="ring" viewBox="0 0 22 22" aria-hidden="true"><circle class="track" cx="11" cy="11" r="${r}" fill="none" stroke-width="2"/>` +
|
|
`<circle cx="11" cy="11" r="${r}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="${c}" ` +
|
|
`stroke-dashoffset="${c * (1 - done)}" transform="rotate(-90 11 11)"/><text x="11" y="14" text-anchor="middle">${left}</text></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) {
|
|
box.replaceChildren();
|
|
return;
|
|
}
|
|
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 = 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…';
|
|
$('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' });
|
|
box.hidden = true;
|
|
});
|
|
}
|
|
|
|
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' });
|
|
theme(r);
|
|
const host = r?.origin ? new URL(r.origin).host : '';
|
|
if (host) {
|
|
$('site').textContent = host;
|
|
$('fav').textContent = host.replace(/^www\./, '').charAt(0).toUpperCase();
|
|
}
|
|
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)}`;
|
|
}
|
|
|
|
void show();
|
|
void connection();
|