//! JavaScript that Nacre puts into pages, and the messages it sends back. //! //! Page -> browser: the bridge script keeps its own reference to `console.log` and logs //! `{"t": type, "d": data}`. `Hub::show_console_message` picks those lines out; the token is //! random per run and lives only inside the script's closure, so pages can't forge messages. //! Browser -> page: `WebView::evaluate_javascript` calling functions on `window.__nacre`. //! //! Servo injects user scripts into every document before the page's own scripts run. Settings //! that change them take effect on the next page load (Servo's rule for user content). use serde::Deserialize; use serde_json::Value; use crate::util; /// A message from a page. #[derive(Debug, Clone, Deserialize)] pub struct PageMessage { #[serde(rename = "t")] pub kind: String, #[serde(rename = "d", default)] pub data: Value, } /// Parse a console line; `None` if it isn't one of ours. pub fn parse_message(token: &str, line: &str) -> Option { let rest = line.strip_prefix(token)?; serde_json::from_str(rest).ok() } /// Settings the injected scripts need. pub struct Options<'a> { pub token: &'a str, pub privacy_mode: bool, pub seed: &'a str, pub dnt: bool, pub force_dark: bool, pub smooth_scroll: bool, pub preload: bool, pub save_data: bool, pub cosmetic: bool, pub animate_removal: bool, pub youtube_ads: bool, pub autofill: bool, pub spell: bool, pub google_signin: bool, } /// All scripts, in the order they are added to the user content manager. /// /// Nacre's own scripts run inside one closure with the private `__send`, so pages can call the /// functions on `window.__nacre` (find, media controls, ...) but can never send a message as Nacre. pub fn page_scripts(o: &Options) -> Vec { let mut modules: Vec = vec![MEDIA_JS.to_owned(), FIND_JS.to_owned(), PIP_JS.to_owned(), META_JS.to_owned()]; if o.dnt { modules.push(DNT_JS.to_owned()); } if o.privacy_mode { modules.push(PRIVACY_JS.replace("__SEED__", &util::js_string(o.seed))); } if o.force_dark { modules.push(FORCE_DARK_JS.to_owned()); } if o.smooth_scroll { modules.push(SMOOTH_JS.to_owned()); } if o.preload { modules.push(PRELOAD_JS.to_owned()); } if o.save_data { modules.push(SAVE_DATA_JS.to_owned()); } if o.cosmetic { modules.push(COSMETIC_JS.replace("__ANIMATE__", if o.animate_removal { "true" } else { "false" })); } if o.autofill { modules.push(AUTOFILL_JS.to_owned()); } if o.spell { modules.push(SPELL_JS.to_owned()); } if o.google_signin { modules.push(GOOGLE_SIGNIN_JS.to_owned()); } let mut combined = String::from("(() => {\n"); combined.push_str(&BRIDGE_JS.replace("__TOKEN__", &util::js_string(o.token))); for module in modules { combined.push_str("\ntry {\n"); combined.push_str(&module); combined.push_str("\n} catch (e) {}\n"); } combined.push_str("\n})();"); let mut out = vec![combined]; if o.youtube_ads { out.push(crate::adblock::YOUTUBE_JS.to_owned()); } out } /// The bridge: `__send(type, data)` for the other scripts, plus link/download hooks. const BRIDGE_JS: &str = r#"if (window.__nacre) return; const TOKEN = __TOKEN__; const log = console.log.bind(console); const stringify = JSON.stringify; // Private to Nacre's scripts: pages run later and can't reach it, or swap what it uses. const __send = (t, d) => { try { log(TOKEN + stringify({ t, d: d === undefined ? null : d })); } catch (e) {} }; Object.defineProperty(window, '__nacre', { value: {}, writable: false, configurable: false, enumerable: false }); // and links the user asked to save: Servo can't download, Nacre does. document.addEventListener('click', e => { const a = e.target && e.target.closest && e.target.closest('a[download]'); if (!a || !a.href || e.defaultPrevented) return; e.preventDefault(); __send('download', { url: a.href, name: a.getAttribute('download') || '' }); }, true); // Remember what was right-clicked, for the context menu (word under the cursor, selection, media). document.addEventListener('contextmenu', e => { const t = e.target; const sel = String(getSelection() || ''); const media = t && t.closest && t.closest('video,audio'); let word = ''; try { const r = document.caretRangeFromPoint ? document.caretRangeFromPoint(e.clientX, e.clientY) : null; if (r && r.startContainer.nodeType === 3) { const s = r.startContainer.data, i = r.startOffset; const m = /[\p{L}'’-]*$/u.exec(s.slice(0, i))[0] + /^[\p{L}'’-]*/u.exec(s.slice(i))[0]; word = m; } } catch (e) {} const field = t && t.closest && t.closest('input,textarea,[contenteditable=""],[contenteditable=true]'); __send('context', { selection: sel.slice(0, 2000), word, editable: !!field, media: media ? { src: media.currentSrc || media.src || '', kind: media.tagName.toLowerCase() } : null, x: e.clientX, y: e.clientY }); }, true); addEventListener('DOMContentLoaded', () => __send('ready', { title: document.title }), { once: true }); "#; /// Media state for the media button, Discord and the visualizer; actions from the browser. const MEDIA_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.media) return; const H = {}; try { const ms = navigator.mediaSession, set = ms.setActionHandler.bind(ms); ms.setActionHandler = (a, f) => { H[a] = f; return set(a, f); }; } catch (e) {} const A = new WeakMap(); let ctx = null; const pick = () => { const els = [...document.querySelectorAll('video,audio')]; return els.find(e => !e.paused) || els.find(e => e.currentTime > 0) || els[0] || null; }; const creator = () => { const a = document.querySelector('ytd-watch-metadata ytd-channel-name a, #owner ytd-channel-name a,' + ' ytmusic-player-bar .byline a, .content-info-wrapper .byline a, a[href*="/channel/"], a[rel=author]'); return a && a.href && a.href.startsWith('https://') ? a.href : ''; }; // Players with their own shuffle button (YouTube Music, Spotify, SoundCloud and others that label it). const shuf = () => document.querySelector('ytmusic-player-bar .shuffle, [data-testid=control-button-shuffle],' + ' button.shuffleControl, button[aria-label*="huffle"], [role=button][aria-label*="huffle"]'); const state = () => { const m = pick(), md = navigator.mediaSession && navigator.mediaSession.metadata, sh = shuf(); if (!m && !md) return null; let art = ''; if (md && md.artwork && md.artwork.length) { const a = [...md.artwork].sort((x, y) => (parseInt(y.sizes) || 0) - (parseInt(x.sizes) || 0))[0]; try { art = new URL(a.src, location.href).href; } catch (e) {} } return { title: (md && md.title) || document.title, artist: (md && md.artist) || '', album: (md && md.album) || '', art: art || (m && m.poster) || '', position: m ? m.currentTime : 0, duration: m && isFinite(m.duration) ? m.duration : 0, paused: m ? m.paused : !(navigator.mediaSession && navigator.mediaSession.playbackState === 'playing'), muted: m ? m.muted : false, loop: m ? m.loop : false, has_next: !!H.nexttrack, has_prev: !!H.previoustrack, creator_url: creator(), ad: !!document.querySelector('#movie_player.ad-showing, ytmusic-player.ad-showing'), is_video: !!(m && m.tagName === 'VIDEO'), has_shuffle: !!sh, shuffle: !!sh && (sh.getAttribute('aria-pressed') === 'true' || sh.getAttribute('aria-checked') === 'true' || sh.classList.contains('m-active')) }; }; let last = '', timer = 0; const report = () => { timer = 0; const s = state(); const k = JSON.stringify(s && Object.assign({}, s, { position: Math.round((s.position || 0) / 5) })); if (k !== last) { last = k; __send('media', s); } }; const soon = () => { if (!timer) timer = setTimeout(report, 300); }; for (const ev of ['play', 'pause', 'ended', 'loadedmetadata', 'seeked', 'volumechange', 'emptied']) document.addEventListener(ev, soon, true); setInterval(() => { const m = pick(); if (m && !m.paused) report(); }, 5000); window.__nacre.media = { state, act(a, v) { const m = pick(); if (a === 'toggle') { if (m) m.paused ? m.play() : m.pause(); } else if (a === 'play') { if (m) m.play(); } else if (a === 'pause') { if (m) m.pause(); } else if (a === 'next') { if (H.nexttrack) H.nexttrack({ action: 'nexttrack' }); else if (m) m.currentTime = m.duration; } else if (a === 'prev') { if (H.previoustrack && (!m || m.currentTime < 3)) H.previoustrack({ action: 'previoustrack' }); else if (m) m.currentTime = 0; } else if (a === 'seek' && m) m.currentTime = v; else if (a === 'skip' && m) m.currentTime = Math.max(0, m.currentTime + v); else if (a === 'loop' && m) m.loop = !m.loop; else if (a === 'shuffle') { const b = shuf(); if (b) b.click(); } else if (a === 'mute') document.querySelectorAll('video,audio').forEach(e => e.muted = !!v); else if (a === 'volume' && m) { m.volume = Math.min(1, Math.max(0, v)); m.muted = false; } setTimeout(report, 50); return state(); }, // Real levels: a Web Audio analyser on the playing element (bands log-spaced, bass first). levels(n) { const m = pick(); if (!m || m.paused) return null; let a = A.get(m); if (!a) { if (A.pending) return null; const src = m.currentSrc || ''; let same = src.startsWith('blob:') || src.startsWith('data:'); try { same = same || new URL(src, location.href).origin === location.origin || !!m.crossOrigin; } catch (e) {} if (!same || typeof AudioContext === 'undefined') return null; // cross-origin media would be silenced ctx = ctx || new AudioContext(); A.pending = true; ctx.resume().then(() => { A.pending = false; if (ctx.state !== 'running' || A.get(m)) return; try { const s = ctx.createMediaElementSource(m), an = ctx.createAnalyser(); an.fftSize = 4096; an.smoothingTimeConstant = 0.55; s.connect(an); an.connect(ctx.destination); A.set(m, { an, buf: new Uint8Array(an.frequencyBinCount) }); } catch (e) { A.set(m, { failed: 1 }); } }).catch(() => { A.pending = false; }); return null; } if (a.failed) return null; a.an.getByteFrequencyData(a.buf); const hz = ctx.sampleRate / 2 / a.buf.length, out = []; for (let i = 0; i < n; i++) { const f0 = 35 * Math.pow(16000 / 35, i / n), f1 = 35 * Math.pow(16000 / 35, (i + 1) / n); let s = 0, c = 0; for (let b = Math.floor(f0 / hz); b <= Math.ceil(f1 / hz) && b < a.buf.length; b++) { s += a.buf[b]; c++; } const v = c ? s / c / 255 : 0; out.push(Math.round(Math.min(1, Math.pow(v, 1.6) * (1 + i / n * 0.8)) * 100) / 100); } return out; } }; })();"#; /// Find in page: highlights every match, steps through them, reports "n of m". const FIND_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.find) return; let marks = [], cur = -1, lastQ = '', lastCase = false; const clear = () => { for (const m of marks) { const p = m.parentNode; if (!p) continue; p.replaceChild(document.createTextNode(m.textContent), m); p.normalize(); } marks = []; cur = -1; }; const css = () => { if (document.getElementById('__nacre_find_css')) return; const s = document.createElement('style'); s.id = '__nacre_find_css'; s.textContent = 'mark[data-nacre-find]{background:#ffd54f!important;color:#000!important;border-radius:2px}' + 'mark[data-nacre-find].cur{background:#ff9800!important}'; (document.head || document.documentElement).appendChild(s); }; const search = (q, cs) => { clear(); if (!q) return; css(); const needle = cs ? q : q.toLowerCase(); const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, { acceptNode: n => { const p = n.parentElement; if (!p || /^(SCRIPT|STYLE|NOSCRIPT|TEXTAREA|INPUT)$/.test(p.tagName)) return NodeFilter.FILTER_REJECT; const st = getComputedStyle(p); if (st.display === 'none' || st.visibility === 'hidden') return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; } }); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); for (const node of nodes) { const text = cs ? node.data : node.data.toLowerCase(); let i = text.indexOf(needle); if (i < 0) continue; let n = node; while (i >= 0 && marks.length < 5000) { const hit = n.splitText(i); const after = hit.splitText(q.length); const m = document.createElement('mark'); m.setAttribute('data-nacre-find', ''); hit.parentNode.replaceChild(m, hit); m.appendChild(hit); marks.push(m); n = after; const t = cs ? n.data : n.data.toLowerCase(); i = t.indexOf(needle); } } }; const go = i => { if (!marks.length) return; if (cur >= 0 && marks[cur]) marks[cur].classList.remove('cur'); cur = (i + marks.length) % marks.length; marks[cur].classList.add('cur'); marks[cur].scrollIntoView({ block: 'center', inline: 'nearest' }); }; window.__nacre.find = { run(q, cs, dir) { if (q !== lastQ || cs !== lastCase || !marks.length || !marks[0].isConnected) { search(q, cs); lastQ = q; lastCase = cs; go(0); } else go(cur + (dir < 0 ? -1 : 1)); const r = { count: marks.length, index: marks.length ? cur + 1 : 0 }; __send('find', r); return r; }, stop() { clear(); lastQ = ''; } }; })();"#; /// Picture-in-picture. The tab's own page hands over its video (`take`, later `resume`); a second web view /// with its own painter loads the same page and shows only that video (`start`, D-008). const PIP_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.pip) return; const pick = () => { const vs = [...document.querySelectorAll('video')].filter(v => v.readyState > 0); const area = v => v.offsetWidth * v.offsetHeight; return vs.filter(v => !v.paused).sort((a, b) => area(b) - area(a))[0] || vs.sort((a, b) => area(b) - area(a))[0] || null; }; window.__nacre.pip = { take() { const v = pick(); if (!v) return null; window.__nacrePipV = v; const r = { w: v.videoWidth || 16, h: v.videoHeight || 9, t: v.currentTime, paused: v.paused }; v.pause(); return r; }, resume(t, play) { const v = window.__nacrePipV; window.__nacrePipV = null; if (!v || !v.isConnected) return; try { v.currentTime = t; } catch (e) {} if (play) v.play().catch(() => {}); }, // The page may build its video late (players): keep looking for up to 30 s. start(t, play, tries) { const pip = window.__nacre.pip; if (!pip.enter()) { if ((tries || 0) < 150) setTimeout(() => pip.start(t, play, (tries || 0) + 1), 200); return; } // Servo 0.7 freezes a playing video that is seeked and then play()ed: pause before the seek. const v = window.__nacrePipV; v.pause(); try { v.currentTime = t; } catch (e) {} if (play) v.play().catch(() => {}); else v.pause(); }, enter() { const v = pick(); if (!v) return null; window.__nacrePipV = v; v.setAttribute('data-nacre-pip', ''); if (!document.getElementById('__nacre_pip_css')) { const st = document.createElement('style'); st.id = '__nacre_pip_css'; st.textContent = 'video[data-nacre-pip]{position:fixed!important;inset:0!important;margin:0!important;width:100vw!important;height:100vh!important;' + 'max-width:none!important;max-height:none!important;object-fit:contain!important;background:#000!important;z-index:2147483647!important;transform:none!important}' + 'html.__nacre_pip,html.__nacre_pip body{overflow:hidden!important}'; (document.head || document.documentElement).appendChild(st); } document.documentElement.classList.add('__nacre_pip'); return { w: v.videoWidth || 16, h: v.videoHeight || 9, paused: v.paused }; }, state() { const v = window.__nacrePipV; if (!v || !v.isConnected) return null; return { t: v.currentTime, d: isFinite(v.duration) ? v.duration : 0, paused: v.paused, muted: v.muted, vol: v.volume, w: v.videoWidth, h: v.videoHeight }; }, act(what, arg) { const v = window.__nacrePipV; if (!v) return; if (what === 'toggle') v.paused ? v.play() : v.pause(); else if (what === 'skip') v.currentTime = Math.max(0, v.currentTime + arg); else if (what === 'to') v.currentTime = arg; else if (what === 'mute') v.muted = !v.muted; else if (what === 'vol') { v.volume = Math.min(1, Math.max(0, arg)); v.muted = false; } } }; })();"#; /// Page details the browser uses: theme colour (website colours), name and icons (install as app, /// Discord), and the login form state. const META_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.meta) return; const meta = p => (document.querySelector(`meta[property="${p}"], meta[name="${p}"]`) || {}).content || ''; const collect = () => { const size = l => Math.max(0, ...((l.sizes && l.sizes.value) || '').split(' ').map(s => parseInt(s) || 0)); const icons = [...document.querySelectorAll('link[rel~="icon"], link[rel="apple-touch-icon"], link[rel="apple-touch-icon-precomposed"]')] .map(l => ({ href: l.href, size: size(l) })).filter(i => /^https?:/.test(i.href)).sort((a, b) => b.size - a.size); const man = document.querySelector('link[rel="manifest"]'); let bg = ''; try { const b = document.body && getComputedStyle(document.body).backgroundColor; bg = b || ''; } catch (e) {} return { theme_color: meta('theme-color'), background: bg, site_name: meta('og:site_name') || meta('application-name'), image: meta('og:image'), icons: icons.slice(0, 8), manifest: man ? man.href : '', title: document.title, description: meta('description').slice(0, 300), lang: document.documentElement.lang || '' }; }; window.__nacre.meta = collect; const sendMeta = () => __send('meta', collect()); addEventListener('load', sendMeta, { once: true }); // Sites change theme-color as you navigate inside them. addEventListener('load', () => { const m = document.querySelector('meta[name="theme-color"]'); if (m) new MutationObserver(sendMeta).observe(m, { attributes: true }); }, { once: true }); })();"#; const DNT_JS: &str = r#"(() => { try { Object.defineProperty(Navigator.prototype, 'globalPrivacyControl', { get: () => true, configurable: true }); Object.defineProperty(Navigator.prototype, 'doNotTrack', { get: () => '1', configurable: true }); } catch (e) {} })();"#; /// Privacy mode: fingerprint noise seeded per site and per run, common values for the rest. const PRIVACY_JS: &str = r#"(() => { if (window.__nacrePriv) return; window.__nacrePriv = 1; const SEED = __SEED__ + location.hostname; let h = 2166136261; for (let i = 0; i < SEED.length; i++) { h ^= SEED.charCodeAt(i); h = Math.imul(h, 16777619); } const rnd = () => { h ^= h << 13; h ^= h >>> 17; h ^= h << 5; return ((h >>> 0) % 1000) / 1000; }; const def = (o, k, v) => { try { Object.defineProperty(o, k, { get: () => v, configurable: true }); } catch (e) {} }; def(Navigator.prototype, 'hardwareConcurrency', 8); def(Navigator.prototype, 'deviceMemory', 8); const round = (v, step) => Math.ceil(v / step) * step; try { const s = screen; const w = round(s.width, 200), hgt = round(s.height, 100); def(Screen.prototype, 'width', w); def(Screen.prototype, 'height', hgt); def(Screen.prototype, 'availWidth', w); def(Screen.prototype, 'availHeight', hgt); def(Screen.prototype, 'colorDepth', 24); def(Screen.prototype, 'pixelDepth', 24); } catch (e) {} // Canvas: flip the lowest bit of a few pixels, the same pixels every time on this site. const noise = (ctx, w, hh) => { try { if (!w || !hh) return; const img = ctx.getImageData(0, 0, w, hh); for (let i = 0; i < 12; i++) { const p = Math.floor(rnd() * w * hh) * 4; img.data[p] ^= 1; img.data[p + 1] ^= 1; } ctx.putImageData(img, 0, 0); } catch (e) {} }; const toURL = HTMLCanvasElement.prototype.toDataURL; HTMLCanvasElement.prototype.toDataURL = function () { const c = this.getContext && this.getContext('2d'); if (c) noise(c, this.width, this.height); return toURL.apply(this, arguments); }; const toBlob = HTMLCanvasElement.prototype.toBlob; if (toBlob) HTMLCanvasElement.prototype.toBlob = function () { const c = this.getContext && this.getContext('2d'); if (c) noise(c, this.width, this.height); return toBlob.apply(this, arguments); }; const gid = CanvasRenderingContext2D.prototype.getImageData; CanvasRenderingContext2D.prototype.getImageData = function () { const d = gid.apply(this, arguments); for (let i = 0; i < Math.min(8, d.data.length / 4); i++) { const p = Math.floor(rnd() * d.data.length / 4) * 4; d.data[p] ^= 1; } return d; }; for (const G of [window.WebGLRenderingContext, window.WebGL2RenderingContext]) { if (!G) continue; const gp = G.prototype.getParameter; G.prototype.getParameter = function (p) { if (p === 37445) return 'Intel Inc.'; if (p === 37446) return 'Intel Iris OpenGL Engine'; return gp.apply(this, arguments); }; } try { const gc = AudioBuffer.prototype.getChannelData; AudioBuffer.prototype.getChannelData = function () { const d = gc.apply(this, arguments); for (let i = 0; i < d.length; i += 100) d[i] += (rnd() - 0.5) * 1e-7; return d; }; } catch (e) {} })();"#; /// Dark pages for sites that have no dark style of their own. const FORCE_DARK_JS: &str = r#"(() => { const add = () => { if (document.getElementById('__nacre_dark')) return; const dark = matchMedia && matchMedia('(prefers-color-scheme: dark)').matches; let bg = 'rgb(255, 255, 255)'; try { bg = getComputedStyle(document.body || document.documentElement).backgroundColor; } catch (e) {} const m = /rgba?\((\d+), (\d+), (\d+)/.exec(bg); if (m && (+m[1] + +m[2] + +m[3]) / 3 < 110) return; // already dark const s = document.createElement('style'); s.id = '__nacre_dark'; s.textContent = 'html{filter:invert(1) hue-rotate(180deg)!important;background:#fff!important}' + 'img,video,picture,canvas,iframe,svg image,[style*="background-image"]{filter:invert(1) hue-rotate(180deg)!important}'; (document.head || document.documentElement).appendChild(s); void dark; }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', add, { once: true }); else add(); })();"#; const SMOOTH_JS: &str = r#"(() => { const s = document.createElement('style'); s.textContent = 'html{scroll-behavior:smooth}'; const add = () => (document.head || document.documentElement).appendChild(s); if (document.documentElement) add(); else addEventListener('DOMContentLoaded', add, { once: true }); })();"#; /// "Preload pages": tell the browser which hosts the page links to, so their names are looked up early. const PRELOAD_JS: &str = r#"(() => { if (!window.__nacre) return; addEventListener('load', () => setTimeout(() => { const hosts = new Set(); for (const a of document.querySelectorAll('a[href^="http"]')) { try { const h = new URL(a.href).hostname; if (h !== location.hostname) hosts.add(h); } catch (e) {} if (hosts.size >= 24) break; } if (hosts.size) __send('preload', [...hosts]); }, 1500), { once: true }); })();"#; const SAVE_DATA_JS: &str = r#"(() => { try { const c = navigator.connection; if (c) Object.defineProperty(c, 'saveData', { get: () => true }); document.addEventListener('DOMContentLoaded', () => { for (const v of document.querySelectorAll('video[autoplay],video[preload]')) { v.preload = 'none'; } }, { once: true }); } catch (e) {} })();"#; /// Cosmetic filtering: the page's classes and ids go to the browser, which answers with selectors. /// Removal can animate (squish) for visible elements. const COSMETIC_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.cosmetic) return; const ANIMATE = __ANIMATE__; const seen = new Set(); let pending = new Set(), timer = 0, style = null, rules = ''; const flush = () => { timer = 0; if (!pending.size) return; const classes = [], ids = []; for (const k of pending) (k[0] === '.' ? classes : ids).push(k.slice(1)); pending = new Set(); __send('cosmetic_ids', { classes, ids }); }; const scan = root => { const els = root.querySelectorAll ? root.querySelectorAll('[class],[id]') : []; for (const el of [root, ...els]) { if (!el.getAttribute) continue; const id = el.id; if (id && !seen.has('#' + id)) { seen.add('#' + id); pending.add('#' + id); } const cl = el.classList; if (cl) for (const c of cl) if (!seen.has('.' + c)) { seen.add('.' + c); pending.add('.' + c); } } if (pending.size && !timer) timer = setTimeout(flush, 120); }; window.__nacre.cosmetic = { hide(selectors) { if (!selectors || !selectors.length) return 0; if (!style) { style = document.createElement('style'); style.id = '__nacre_cosmetic'; (document.head || document.documentElement).appendChild(style); } let removed = 0; for (const sel of selectors) { try { for (const el of document.querySelectorAll(sel)) { if (el.__nacreGone) continue; el.__nacreGone = 1; removed++; const r = el.getBoundingClientRect(); if (ANIMATE && r.width * r.height > 0 && r.bottom > 0 && r.top < innerHeight) { el.style.transition = 'opacity .25s, transform .25s'; el.style.transformOrigin = 'center'; el.style.opacity = '0'; el.style.transform = 'scale(.92)'; setTimeout(() => el.style.setProperty('display', 'none', 'important'), 260); } else el.style.setProperty('display', 'none', 'important'); } } catch (e) { continue; } rules += sel + '{display:none!important}\n'; } style.textContent = rules; if (removed) __send('cosmetic_removed', removed); return removed; } }; const start = () => { scan(document.documentElement); new MutationObserver(ms => { for (const m of ms) { if (m.type === 'attributes') scan(m.target); else for (const n of m.addedNodes) if (n.nodeType === 1) scan(n); } }) .observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'id'] }); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true }); else start(); })();"#; /// Password capture and autofill. const AUTOFILL_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.fill || !/^https?:$/.test(location.protocol)) return; const visible = el => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }; const userFieldFor = pw => { const form = pw.form || document; const fields = [...form.querySelectorAll('input:not([type=hidden]):not([type=password]):not([type=submit]):not([type=checkbox]):not([type=radio]):not([type=button])')].filter(visible); const before = fields.filter(f => f.compareDocumentPosition(pw) & Node.DOCUMENT_POSITION_FOLLOWING); return before.reverse().find(f => /user|mail|login|name|phone|account/i.test(f.name + f.id + f.autocomplete + f.type)) || before[0] || null; }; const pwFields = () => [...document.querySelectorAll('input[type=password]')].filter(visible); const setValue = (el, v) => { const proto = Object.getPrototypeOf(el); const d = Object.getOwnPropertyDescriptor(proto, 'value'); if (d && d.set) d.set.call(el, v); else el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); }; let reported = false; const announce = () => { const pws = pwFields(); if (!pws.length || reported) return; reported = true; const r = pws[0].getBoundingClientRect(); __send('login_form', { url: location.href, x: r.left, y: r.bottom, w: r.width, new_password: pws.length > 1 || /new/i.test(pws[0].autocomplete) }); }; const capture = form => { const pws = [...(form || document).querySelectorAll('input[type=password]')].filter(p => p.value); if (!pws.length) return; const pw = pws[pws.length - 1]; const user = userFieldFor(pws[0]); __send('login_submit', { url: location.href, username: user ? user.value : '', password: pw.value }); }; document.addEventListener('submit', e => capture(e.target), true); // Sites that log in with a button and fetch() instead of a real form submit. document.addEventListener('click', e => { const b = e.target && e.target.closest && e.target.closest('button,input[type=submit],[role=button]'); if (b && pwFields().some(p => p.value)) capture(b.form || document); }, true); document.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target && e.target.type === 'password' && e.target.value) capture(e.target.form || document); }, true); document.addEventListener('focusin', e => { const t = e.target; if (!t || t.tagName !== 'INPUT') return; if (t.type === 'password' || (pwFields().length && userFieldFor(pwFields()[0]) === t)) { const r = t.getBoundingClientRect(); __send('login_focus', { url: location.href, x: r.left, y: r.bottom, w: r.width }); } else if (/address|street|postal|zip|city|country|tel|email|cc-|card/i.test(t.autocomplete + t.name + t.id)) { const r = t.getBoundingClientRect(); __send('form_focus', { kind: /cc-|card/i.test(t.autocomplete + t.name + t.id) ? 'card' : 'address', x: r.left, y: r.bottom, w: r.width }); } }, true); const watch = () => { announce(); new MutationObserver(() => { if (!reported) announce(); }).observe(document.documentElement, { subtree: true, childList: true }); }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watch, { once: true }); else watch(); window.__nacre.fill = { login(username, password) { const pws = pwFields(); if (!pws.length) return false; const user = userFieldFor(pws[0]); if (user && username) setValue(user, username); setValue(pws[0], password); if (pws.length > 1 && /new|confirm/i.test(pws[1].autocomplete + pws[1].name)) setValue(pws[1], password); return true; }, password(value) { const pws = pwFields().filter(p => !p.value || p === document.activeElement); for (const p of pws) setValue(p, value); return pws.length; }, address(a) { const map = { name: /^name$|full.?name|cc-name/i, organization: /organi[sz]ation|company/i, street: /street|address-line1|address1|^address$/i, city: /city|address-level2|locality/i, region: /state|region|province|address-level1/i, postal_code: /postal|zip/i, country: /country/i, phone: /tel|phone/i, email: /e-?mail/i }; let n = 0; for (const el of document.querySelectorAll('input,select,textarea')) { if (!visible(el) || el.value) continue; const key = el.autocomplete + ' ' + el.name + ' ' + el.id; for (const [k, re] of Object.entries(map)) if (re.test(key) && a[k]) { setValue(el, a[k]); n++; break; } } return n; }, card(c) { let n = 0; for (const el of document.querySelectorAll('input,select')) { if (!visible(el) || el.value) continue; const key = el.autocomplete + ' ' + el.name + ' ' + el.id; const v = /cc-number|card.?num/i.test(key) ? c.number : /cc-name|name.?on/i.test(key) ? c.name : /cc-exp-month|exp.?month/i.test(key) ? String(c.exp_month).padStart(2, '0') : /cc-exp-year|exp.?year/i.test(key) ? String(c.exp_year) : /cc-exp\b|expir/i.test(key) ? String(c.exp_month).padStart(2, '0') + '/' + String(c.exp_year).slice(-2) : null; if (v) { setValue(el, v); n++; } } return n; } }; })();"#; /// Spell check: words typed in text fields go to the browser; misspelled ones come back and get a /// wavy underline drawn in an overlay that mirrors the field. const SPELL_JS: &str = r#"(() => { if (!window.__nacre || window.__nacre.spell) return; const css = () => { if (document.getElementById('__nacre_spell_css')) return; const s = document.createElement('style'); s.id = '__nacre_spell_css'; s.textContent = '.__nacre_spell_mirror{position:absolute;pointer-events:none;color:transparent!important;overflow:hidden;white-space:pre-wrap;word-wrap:break-word;z-index:2147483646}' + '.__nacre_spell_mirror u{text-decoration:underline wavy #e53935;text-decoration-skip-ink:none;color:transparent}'; (document.head || document.documentElement).appendChild(s); }; let field = null, mirror = null, timer = 0, bad = new Set(); const isText = el => el && ((el.tagName === 'TEXTAREA') || (el.tagName === 'INPUT' && /^(text|search|)$/.test(el.type))) && el.spellcheck !== false; const words = t => (t.match(/[\p{L}][\p{L}'’]*/gu) || []).slice(0, 400); const esc = s => s.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])); const draw = () => { if (!field || !mirror) return; const st = getComputedStyle(field), r = field.getBoundingClientRect(); for (const p of ['font', 'letterSpacing', 'lineHeight', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'borderTopWidth', 'borderLeftWidth', 'textAlign', 'textIndent', 'wordSpacing', 'boxSizing']) mirror.style[p] = st[p]; mirror.style.borderStyle = 'solid'; mirror.style.borderColor = 'transparent'; Object.assign(mirror.style, { left: (r.left + scrollX) + 'px', top: (r.top + scrollY) + 'px', width: r.width + 'px', height: r.height + 'px' }); if (field.tagName === 'INPUT') mirror.style.whiteSpace = 'pre'; mirror.innerHTML = esc(field.value).replace(/[\p{L}][\p{L}'’]*/gu, w => bad.has(w) ? '' + w + '' : w); mirror.scrollTop = field.scrollTop; mirror.scrollLeft = field.scrollLeft; }; const check = () => { timer = 0; if (!field) return; __send('spell', [...new Set(words(field.value))]); }; document.addEventListener('focusin', e => { if (!isText(e.target)) return; field = e.target; css(); if (!mirror) { mirror = document.createElement('div'); mirror.className = '__nacre_spell_mirror'; } document.body && document.body.appendChild(mirror); check(); }, true); document.addEventListener('focusout', e => { if (e.target === field) { field = null; if (mirror) mirror.remove(); } }, true); document.addEventListener('input', e => { if (e.target !== field) return; draw(); if (!timer) timer = setTimeout(check, 400); }, true); document.addEventListener('scroll', () => draw(), true); window.__nacre.spell = { mark(list) { bad = new Set(list || []); draw(); }, replace(word, by) { const el = field || document.activeElement; if (!el || !('value' in el)) return; el.value = el.value.replace(new RegExp('(^|[^\\p{L}])' + word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![\\p{L}])', 'u'), (m, p) => p + by); el.dispatchEvent(new Event('input', { bubbles: true })); } }; })();"#; /// Google refuses sign-in from browsers it doesn't know; on its sign-in pages Nacre looks like /// Firefox (the user agent pref is switched by the browser; this covers the JavaScript side). const GOOGLE_SIGNIN_JS: &str = r#"(() => { if (!/(^|\.)accounts\.google\.com$/.test(location.hostname)) return; const ua = 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0'; try { Object.defineProperty(Navigator.prototype, 'userAgent', { get: () => ua, configurable: true }); Object.defineProperty(Navigator.prototype, 'appVersion', { get: () => '5.0 (X11)', configurable: true }); Object.defineProperty(Navigator.prototype, 'vendor', { get: () => '', configurable: true }); } catch (e) {} })();"#; /// The Firefox user agent used on Google's sign-in pages. pub const FIREFOX_UA: &str = "Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0"; /// Small helpers for browser -> page calls. pub fn call(path: &str, args: &[Value]) -> String { let args: Vec = args.iter().map(Value::to_string).collect(); format!("(() => {{ try {{ const f = window.__nacre && window.__nacre.{path}; return f ? f({}) : null; }} catch (e) {{ return null; }} }})()", args.join(",")) } /// A page that sends the tab somewhere else at once (used where a 30x can't be returned). pub fn redirect_page(to: &str, note: &str) -> Vec { format!( "{}

{}

", util::html_escape(note), util::html_escape(to), util::js_string(to), util::html_escape(note) ) .into_bytes() } #[cfg(test)] mod tests { use super::*; #[test] fn messages() { let m = parse_message("abc", r#"abc{"t":"media","d":{"title":"x"}}"#).unwrap(); assert_eq!(m.kind, "media"); assert!(parse_message("abc", "hello").is_none()); assert_eq!(call("find.run", &[Value::from("a"), Value::from(false), Value::from(1)]).contains(r#"f("a",false,1)"#), true); } }