// ==UserScript== // @name 通用广告无感过滤助手 // @namespace js-hub/ad-filter-hub // @version 1.0.15 // @description document-start 移动网页干扰过滤内核:事件决策、资源插入拦截、可逆 DOM 修饰、站点降级与健康熔断;零 UI、零网络请求。 // @author EFate // @copyright 2026 EFate // @license MIT // @match *://*/* // @match https://bxs.lozhy.top/* // @match https://cn8.91short.com/* // @include *://*/* // @run-at document-start // @grant none // @icon data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2232%22%20height%3D%2232%22%20viewBox%3D%220%200%2032%2032%22%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20aria-hidden%3D%22true%22%3E%3Crect%20x%3D%221.5%22%20y%3D%221.5%22%20width%3D%2229%22%20height%3D%2229%22%20rx%3D%229%22%20fill%3D%22%23080d10%22%20stroke%3D%22%23263641%22%20stroke-width%3D%221%22%2F%3E%3Cg%20fill%3D%22none%22%20stroke%3D%22%235bd68f%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M16%205.8%2024%209.2v6.1c0%204.7-3.2%207.9-8%209.4-4.8-1.5-8-4.7-8-9.4V9.2z%22%2F%3E%3Cpath%20d%3D%22M11%2012h10l-3.4%204.1v4.2l-3.2%201.5v-5.7z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E // ==/UserScript== (function (root, factory) { 'use strict'; const api = factory(); if (typeof module === 'object' && module && module.exports) { module.exports = api; } else if (root) { root.AD_FILTER_HUB = api; } })(typeof globalThis !== 'undefined' ? globalThis : this, function () { 'use strict'; var VERSION = '1.0.15'; var ZERO_INJECTION = true; var SCRIPT_ICON = String.raw``; var STYLE_ID = 'afh-style'; var MARK_STATE = 'data-afh-state'; var MARK_RULE = 'data-afh-rule'; var MARK_PROCESSED = 'data-afh-processed'; var MARK_BLOCKED = 'data-afh-blocked'; var AUDIT_LIMIT = 200; var MAX_BATCH = 120; var MAX_INITIAL = 240; var MAX_SUBTREE = 160; var MODES = { NORMAL: 'NORMAL', CONSERVATIVE: 'CONSERVATIVE', SAFE: 'SAFE', BYPASS: 'BYPASS' }; var ACTIONS = { ALLOW: 'ALLOW', BLOCK_INSERTION: 'BLOCK_INSERTION', BLOCK_POPUP: 'BLOCK_POPUP', CANCEL_NAVIGATION: 'CANCEL_NAVIGATION', HIDE_ELEMENT: 'HIDE_ELEMENT', RESTORE_ELEMENT: 'RESTORE_ELEMENT', OBSERVE_ONLY: 'OBSERVE_ONLY', ENTER_SAFE_MODE: 'ENTER_SAFE_MODE', BYPASS: 'BYPASS' }; var RESOURCE_TYPES = { SCRIPT: 'script', IFRAME: 'iframe', IMAGE: 'image', MEDIA: 'media', VIDEO: 'video', AUDIO: 'audio', STYLESHEET: 'stylesheet', FONT: 'font', FETCH: 'fetch', XHR: 'xhr', BEACON: 'beacon', WEBSOCKET: 'websocket', EVENTSOURCE: 'eventsource', NAVIGATION: 'navigation', DOCUMENT: 'document', POPUP: 'popup', UNKNOWN: 'unknown' }; var EVENT_TYPES = { RESOURCE_INSERT: 'RESOURCE_INSERT', RESOURCE_ATTRIBUTE_CHANGE: 'RESOURCE_ATTRIBUTE_CHANGE', WINDOW_OPEN: 'WINDOW_OPEN', LINK_CLICK: 'LINK_CLICK', FORM_SUBMIT: 'FORM_SUBMIT', NAVIGATION_ATTEMPT: 'NAVIGATION_ATTEMPT', DOM_NODE_ADDED: 'DOM_NODE_ADDED', COSMETIC_MATCH: 'COSMETIC_MATCH', HEALTH_FAILURE: 'HEALTH_FAILURE' }; var DEFAULT_HEALTH = { minTextRatio: 0.35, minLinkRatio: 0.25, minTextForTextCheck: 200, minLinksForLinkCheck: 8, maxHidesPerBatch: 80 }; var PROTECTED_SELECTORS = [ 'html', 'head', 'body', 'main', '[role="main"]', '#app', '#root', '#__next', '#__nuxt', '#main', 'video', 'audio', 'canvas', '.dplayer', '.player', '.video-js', '#player', '[data-player]', 'iframe[src^="/embed/"]', 'iframe[src*="player"]', 'iframe[src*="embed"]' ]; var GLOBAL_HIDE_SELECTORS = [ '.xqbj-component-ssp-float-icon', '.xqbj-component-ssp-popup-icon-container', '.hg-ssp-floating', '.exo-native-widget-item', '.post-card-ads', '.home-benefits-float', 'img[class*="imgad"]', 'img[data-id^="ad"]', 'iframe[src*="HereByAD"]', 'iframe[id="HereByAD1"]', 'iframe[src*="tsyndicate.com"]', 'iframe[src*="forkedspare.com"]' ]; var GLOBAL_CSS_SELECTORS = [ '.xqbj-component-ssp-float-icon', '.xqbj-component-ssp-popup-icon-container', '.hg-ssp-floating', '.exo-native-widget-item', '.post-card-ads', '.home-benefits-float', 'img[class*="imgad"]', 'img[data-id^="ad"]', 'iframe[src*="HereByAD"]', 'iframe[id="HereByAD1"]', 'iframe[src*="tsyndicate.com"]', 'iframe[src*="forkedspare.com"]' ]; var STRONG_AD_PATH_PATTERNS = [ /\/api\/sdk\/ad\//i, /\/flink\/url\.php/i, /\/click\.php/i, /\/popunder(?:\/|\.|$)/i, /\/prebid(?:\/|\.|$)/i, /\/vast(?:\/|\.|$)/i, /\/vmap(?:\/|\.|$)/i ]; var GLOBAL_BLOCK_RULES = [ { id: 'net-clickadu', hostSuffixes: ['clickadu.io'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-juicyads', hostSuffixes: ['juicyads.com'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-tsyndicate', hostSuffixes: ['tsyndicate.com'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-forkedspare', hostSuffixes: ['forkedspare.com'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-doubleclick', hostSuffixes: ['doubleclick.net'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-googlesyndication', hostSuffixes: ['googlesyndication.com'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-google-adservice', hostSuffixes: ['adservice.google.com'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup'] }, { id: 'net-popads', hostSuffixes: ['popads.net'], resourceTypes: ['script','iframe','fetch','xhr','beacon','popup'] }, { id: 'net-propellerads', hostSuffixes: ['propellerads.com'], resourceTypes: ['script','iframe','fetch','xhr','beacon','popup'] }, { id: 'net-sexymeet', hostSuffixes: ['sexymeet.tv'], resourceTypes: ['script','iframe','fetch','xhr','beacon','popup'] }, { id: 'path-api-ad', pathIncludes: ['/api/sdk/ad/'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon'] }, { id: 'path-flink', pathIncludes: ['/flink/url.php'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup','navigation'] }, { id: 'path-click-php', pathIncludes: ['/click.php'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup','navigation'] }, { id: 'url-herebyad', urlIncludes: ['HereByAD'], resourceTypes: ['script','iframe'] } ]; var DEFAULT_PROFILE = { id: 'global-balanced', hosts: [], mode: MODES.NORMAL, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: [], cssSelectors: [], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }; var SITE_PROFILES = [ { id: 'xen-safe', hosts: ['xen.wtos.top'], mode: MODES.SAFE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: [], cssSelectors: [], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: ['css', 'dom'], healthCriteria: {} }, { id: 'lozhy-safe', hosts: ['bxs.lozhy.top', 'lso.lozhy.top'], mode: MODES.SAFE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: [], cssSelectors: [], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: ['css', 'dom'], healthCriteria: {} }, { id: '51-video', hosts: ['d2jj9xdphpyf9i.cloudfront.net', '51sptv.com'], mode: MODES.NORMAL, version: '1.0.0', allowResources: [], blockResources: [{ id: '51-path-ad', pathIncludes: ['/api/sdk/ad/'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon'] }], hideSelectors: ['.xqbj-component-ssp-float-icon', '.xqbj-component-ssp-popup-icon-container', 'article.ad-item', 'a.xqbj-component-ssp-list-item'], cssSelectors: ['.xqbj-component-ssp-float-icon', '.xqbj-component-ssp-popup-icon-container'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'qinav', hosts: ['qinav.com'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [{ id: 'qinav-player', urlIncludes: ['/embed/'], resourceTypes: ['iframe'] }], blockResources: [], hideSelectors: [], cssSelectors: [], protectSelectors: ['iframe[src^="/embed/"]'], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'xanimu', hosts: ['xanimu.ws', 'xanimu.one', 'xanimu.art', 'xanimu.net', 'xanimu.top', 'xanimu.sbs'], mode: MODES.NORMAL, version: '1.0.0', allowResources: [{ id: 'xanimu-player', urlIncludes: ['/embed/', '/player/'], resourceTypes: ['iframe'] }], blockResources: [], hideSelectors: ['iframe[src*="HereByAD"]', 'iframe[src*="forkedspare.com"]', '.exo-native-widget-item'], cssSelectors: ['iframe[src*="HereByAD"]', 'iframe[src*="forkedspare.com"]', '.exo-native-widget-item'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'huangguo-drama', hosts: ['ipycpknh.cc'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['.hg-ssp-floating', 'a.hg-hero__cover-link[rel~="sponsored"]', 'a[rel~="sponsored"]'], cssSelectors: ['.hg-ssp-floating'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'liz-drama', hosts: ['liz04.com'], mode: MODES.NORMAL, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['.ad-placement', '.ad-configured', 'img.ad-placement__image'], cssSelectors: ['.ad-configured', 'img.ad-placement__image'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'mrds-daily', hosts: ['mrds66.cc'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['.popup-container', '.post-card-ads', 'a[rel~="sponsored"]'], cssSelectors: ['.post-card-ads'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'laimei', hosts: ['wwwlameicom1.com'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['.home-banner-carousel', '.home-benefits-float', 'a.home-banner[href*="channelCode"]'], cssSelectors: ['.home-benefits-float'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'rouman', hosts: ['roum29.xyz', 'rouman5.com'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['iframe[src*="tsyndicate.com"]'], cssSelectors: ['iframe[src*="tsyndicate.com"]'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'rousewu', hosts: ['rousewu.cc'], mode: MODES.SAFE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: [], cssSelectors: [], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: ['css', 'dom'], healthCriteria: {} }, { id: 'qpv-wall', hosts: ['qpv.yzfnb8.pics'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [{ id: 'qpv-cover', resourceTypes: ['image'], pathIncludes: ['/pic/'] }], blockResources: [{ id: 'qpv-flink', pathIncludes: ['/000/flink/url.php'], resourceTypes: ['script','iframe','image','fetch','xhr','beacon','popup','navigation'] }], hideSelectors: ['img[src^="http"][src$=".gif"]', '.u702fe.TypeB_u17f6c', '.u702fe.TypeA_u82adc', '.ua220d.TypeB_u0d6fc', '.ua220d.TypeA_u34a89', 'a.btn-danger.btn-lg[href^="http"]', 'a[href*="/000/flink/url.php"]'], cssSelectors: ['img[src^="http"][src$=".gif"]'], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} }, { id: 'cn8-91short', hosts: ['cn8.91short.com'], mode: MODES.CONSERVATIVE, version: '1.0.0', allowResources: [], blockResources: [], hideSelectors: ['img.imgad33', 'img[data-id^="ad"]'], cssSelectors: [], protectSelectors: [], behaviorRules: { blockUnsolicitedPopups: true, blockExtraPopups: true }, disabledModules: [], healthCriteria: {} } ]; var SITE_PROFILE_INDEX = {}; for (var profileIndex = 0; profileIndex < SITE_PROFILES.length; profileIndex++) { var profileEntry = SITE_PROFILES[profileIndex]; for (var hostIndex = 0; hostIndex < profileEntry.hosts.length; hostIndex++) { SITE_PROFILE_INDEX[normalizeHost(profileEntry.hosts[hostIndex])] = profileEntry; } } function normalizeHost(input) { if (!input) return ''; var value = String(input).trim().toLowerCase(); if (/^https?:\/\//i.test(value)) { try { value = new URL(value).hostname; } catch (e) { /* keep literal */ } } value = value.split(':')[0].split('/')[0].replace(/\.$/, ''); return value.replace(/^(www|m)\./, ''); } function getSiteKey(host) { var normalized = normalizeHost(host); var parts = normalized.split('.'); if (parts.length <= 2) return normalized; var secondLevel = parts[parts.length - 2]; if (['co','com','net','org','gov','ac','edu'].indexOf(secondLevel) >= 0) { return parts.slice(-3).join('.'); } return parts.slice(-2).join('.'); } function isThirdParty(targetHost, pageHost) { var target = getSiteKey(targetHost); var page = getSiteKey(pageHost); return Boolean(target && page && target !== page); } function normalizeUrl(raw, base) { if (!raw) return null; var value = String(raw).trim(); if (!value || value === '#' || value === 'about:blank' || value.indexOf('javascript:') === 0) return null; if (value.indexOf('//') === 0) value = 'https:' + value; try { return new URL(value, base || (typeof location !== 'undefined' ? location.href : undefined)); } catch (e) { return null; } } function findSiteProfile(host) { var normalized = normalizeHost(host); if (!normalized) return DEFAULT_PROFILE; if (SITE_PROFILE_INDEX[normalized]) return SITE_PROFILE_INDEX[normalized]; for (var i = 0; i < SITE_PROFILES.length; i++) { var profile = SITE_PROFILES[i]; for (var j = 0; j < profile.hosts.length; j++) { var ruleHost = normalizeHost(profile.hosts[j]); if (ruleHost && normalized.endsWith('.' + ruleHost)) return profile; } } return DEFAULT_PROFILE; } function matchesHostList(host, rule) { var normalized = normalizeHost(host); if (!normalized || !rule) return false; if (rule.hosts && rule.hosts.some(function (item) { return normalizeHost(item) === normalized; })) return true; if (rule.hostSuffixes && rule.hostSuffixes.some(function (item) { var suffix = normalizeHost(item); return normalized === suffix || normalized.endsWith('.' + suffix); })) return true; return false; } function matchesUrlRule(url, rule) { if (!url || !rule) return false; var href = String(url); if (rule.pathIncludes && rule.pathIncludes.some(function (part) { return href.indexOf(part) >= 0; })) return true; if (rule.urlIncludes && rule.urlIncludes.some(function (part) { return href.indexOf(part) >= 0; })) return true; if (rule.pathPatterns && rule.pathPatterns.some(function (pattern) { return pattern.test(href); })) return true; if (!rule.pathIncludes && !rule.urlIncludes && !rule.pathPatterns) return true; return false; } function matchesResourceRule(ctx, rule) { if (!ctx || !rule) return false; if (rule.resourceTypes && rule.resourceTypes.indexOf(ctx.resourceType) < 0) return false; if (rule.hosts || rule.hostSuffixes) { if (!matchesHostList(ctx.targetHost, rule)) return false; } if (rule.pathIncludes || rule.urlIncludes || rule.pathPatterns) { if (!matchesUrlRule(ctx.targetUrl, rule)) return false; } if (rule.firstParty && ctx.isThirdParty) return false; if (rule.thirdParty && !ctx.isThirdParty) return false; return true; } function matchRuleList(ctx, rules) { for (var i = 0; i < (rules || []).length; i++) { if (matchesResourceRule(ctx, rules[i])) return rules[i]; } return null; } function createContext(input) { var data = input || {}; var targetUrl = data.targetUrl || null; var parsed = targetUrl ? normalizeUrl(targetUrl, data.baseUrl) : null; var targetHost = data.targetHost || (parsed && parsed.hostname) || ''; var pageUrl = data.pageUrl || (typeof location !== 'undefined' ? location.href : ''); var pageHost = normalizeHost(data.pageHost || (pageUrl ? normalizeUrl(pageUrl) && normalizeUrl(pageUrl).hostname : '')); var resourceType = data.resourceType || RESOURCE_TYPES.UNKNOWN; var profile = data.siteProfile || findSiteProfile(pageHost); return { eventType: data.eventType || EVENT_TYPES.DOM_NODE_ADDED, pageUrl: pageUrl, pageHost: pageHost, targetUrl: parsed ? parsed.href : (targetUrl || ''), targetHost: normalizeHost(targetHost), resourceType: resourceType, element: data.element || null, initiator: data.initiator || null, isThirdParty: isThirdParty(normalizeHost(targetHost), pageHost), isTopNavigation: Boolean(data.isTopNavigation), frameDepth: Number(data.frameDepth || 0), userGesture: data.userGesture || null, siteProfile: profile, evidence: data.evidence || [], timestamp: Date.now() }; } function isStrongAdPath(url) { if (!url) return false; return STRONG_AD_PATH_PATTERNS.some(function (pattern) { return pattern.test(url); }); } function isAlwaysAllowedContext(ctx) { if (!ctx) return true; if (ctx.resourceType === RESOURCE_TYPES.DOCUMENT || ctx.resourceType === RESOURCE_TYPES.NAVIGATION) return true; if (ctx.resourceType === RESOURCE_TYPES.MEDIA || ctx.resourceType === RESOURCE_TYPES.VIDEO || ctx.resourceType === RESOURCE_TYPES.AUDIO) return true; if (ctx.resourceType === RESOURCE_TYPES.STYLESHEET || ctx.resourceType === RESOURCE_TYPES.FONT) return true; if (/^(blob:|data:|about:)/i.test(ctx.targetUrl || '')) return true; if (/(?:\/embed\/|\/player\/|(?:^|[\/.])m3u8(?:[?#]|$)|\.mp4(?:[?#]|$))/i.test(ctx.targetUrl || '')) return true; return false; } function evaluateNetwork(ctx) { if (!ctx) return { action: ACTIONS.ALLOW, ruleId: 'default-allow', confidence: 'none', reversible: true, reason: 'missing-context', riskLevel: 'low', fallback: ACTIONS.ALLOW }; var profile = ctx.siteProfile || findSiteProfile(ctx.pageHost); var mode = profile.mode || MODES.NORMAL; if (mode === MODES.BYPASS) return { action: ACTIONS.BYPASS, ruleId: 'site-bypass', confidence: 'rule', reversible: true, reason: 'site-bypass', riskLevel: 'low', fallback: ACTIONS.ALLOW }; if (isAlwaysAllowedContext(ctx)) return { action: ACTIONS.ALLOW, ruleId: 'content-protection', confidence: 'strong', reversible: true, reason: 'protected-resource-type', riskLevel: 'low', fallback: ACTIONS.ALLOW }; var allow = matchRuleList(ctx, profile.allowResources || []); if (allow) return { action: ACTIONS.ALLOW, ruleId: allow.id || 'site-allow', confidence: 'strong', reversible: true, reason: 'site-allow', riskLevel: 'low', fallback: ACTIONS.ALLOW }; if (ctx.isTopNavigation) return { action: ACTIONS.ALLOW, ruleId: 'top-navigation', confidence: 'strong', reversible: true, reason: 'top-navigation', riskLevel: 'low', fallback: ACTIONS.ALLOW }; var siteBlock = matchRuleList(ctx, profile.blockResources || []); if (siteBlock) return { action: ctx.resourceType === RESOURCE_TYPES.POPUP ? ACTIONS.BLOCK_POPUP : ACTIONS.BLOCK_INSERTION, ruleId: siteBlock.id || 'site-block', confidence: 'strong', reversible: true, reason: 'site-block', riskLevel: 'medium', fallback: ACTIONS.OBSERVE_ONLY }; var globalBlock = matchRuleList(ctx, GLOBAL_BLOCK_RULES); if (globalBlock) return { action: ctx.resourceType === RESOURCE_TYPES.POPUP ? ACTIONS.BLOCK_POPUP : ACTIONS.BLOCK_INSERTION, ruleId: globalBlock.id, confidence: 'strong', reversible: true, reason: 'global-block', riskLevel: 'medium', fallback: ACTIONS.OBSERVE_ONLY }; if (ctx.resourceType === RESOURCE_TYPES.POPUP) { var gesture = ctx.userGesture || {}; var popupCount = Number(gesture.popupCount || 0); if (profile.behaviorRules && profile.behaviorRules.blockUnsolicitedPopups && !gesture.isTrusted && ctx.isThirdParty) return { action: ACTIONS.BLOCK_POPUP, ruleId: 'popup-unsolicited', confidence: 'strong', reversible: true, reason: 'unsolicited-third-party-popup', riskLevel: 'medium', fallback: ACTIONS.ALLOW }; if (profile.behaviorRules && profile.behaviorRules.blockExtraPopups && popupCount > 0) return { action: ACTIONS.BLOCK_POPUP, ruleId: 'popup-extra', confidence: 'strong', reversible: true, reason: 'extra-popup-same-gesture', riskLevel: 'medium', fallback: ACTIONS.ALLOW }; } if (isStrongAdPath(ctx.targetUrl) && ctx.isThirdParty) return { action: ACTIONS.BLOCK_INSERTION, ruleId: 'path-strong-ad', confidence: 'strong', reversible: true, reason: 'strong-ad-path', riskLevel: 'medium', fallback: ACTIONS.OBSERVE_ONLY }; if (ctx.isThirdParty && (ctx.resourceType === RESOURCE_TYPES.SCRIPT || ctx.resourceType === RESOURCE_TYPES.IFRAME)) return { action: ACTIONS.OBSERVE_ONLY, ruleId: 'third-party-observe', confidence: 'weak', reversible: true, reason: 'third-party-without-strong-evidence', riskLevel: 'low', fallback: ACTIONS.ALLOW }; return { action: ACTIONS.ALLOW, ruleId: 'default-allow', confidence: 'none', reversible: true, reason: 'no-strong-evidence', riskLevel: 'low', fallback: ACTIONS.ALLOW }; } function getResourceTypeForElement(el) { if (!el || !el.tagName) return RESOURCE_TYPES.UNKNOWN; var tag = String(el.tagName).toLowerCase(); if (tag === 'script') return RESOURCE_TYPES.SCRIPT; if (tag === 'iframe') return RESOURCE_TYPES.IFRAME; if (tag === 'img') return RESOURCE_TYPES.IMAGE; if (tag === 'video') return RESOURCE_TYPES.VIDEO; if (tag === 'audio') return RESOURCE_TYPES.AUDIO; if (tag === 'source') return el.parentElement && String(el.parentElement.tagName).toLowerCase() === 'video' ? RESOURCE_TYPES.VIDEO : RESOURCE_TYPES.MEDIA; if (tag === 'link') return RESOURCE_TYPES.STYLESHEET; if (tag === 'object' || tag === 'embed') return RESOURCE_TYPES.IFRAME; if (tag === 'a') return RESOURCE_TYPES.NAVIGATION; return RESOURCE_TYPES.UNKNOWN; } function getElementUrl(el) { if (!el || !el.getAttribute) return ''; return el.getAttribute('src') || el.getAttribute('href') || el.getAttribute('data') || el.getAttribute('poster') || ''; } function matchesAny(el, selectors) { if (!el || typeof el.matches !== 'function' || !selectors || !selectors.length) return false; for (var i = 0; i < selectors.length; i++) { try { if (el.matches(selectors[i])) return true; } catch (e) { /* an invalid site selector must not stop the runtime */ } } return false; } function textOf(el) { return el && typeof el.textContent === 'string' ? el.textContent.replace(/\s+/g, ' ').trim() : ''; } function isProtectedElement(el) { if (!el || typeof el.matches !== 'function') return false; return matchesAny(el, PROTECTED_SELECTORS); } function hasProtectedContent(el) { if (!el || typeof el.querySelector !== 'function') return false; try { if (el.querySelector('video, audio, canvas, main, [role="main"], nav, form, .dplayer, .player, .video-js, #player, [data-player], iframe[src^="/embed/"], iframe[src*="player"], iframe[src*="embed"]')) return true; var interactive = el.querySelectorAll ? el.querySelectorAll('a, button, input, textarea, select').length : 0; var blocks = el.querySelectorAll ? el.querySelectorAll('header, nav, main, section, article, form').length : 0; if (interactive >= 5 || blocks >= 2) return true; if (textOf(el).length >= 300 && interactive >= 3) return true; } catch (e) { return true; } return false; } function isHighRiskContainer(el) { if (!el || !el.tagName) return true; var tag = String(el.tagName).toLowerCase(); if (['html','head','body','main','section','article','header','footer','form','nav'].indexOf(tag) >= 0) return true; try { if (el.matches('#app, #root, #main, [role="main"], [data-reactroot], #__next, #__nuxt, .app, .app-root, .layout, .page, .site, .shell, .site-shell, .page-shell')) return true; } catch (e) { return true; } return false; } function evaluateElement(el, profile, pageHost) { if (!el || el.nodeType !== 1) return { action: ACTIONS.ALLOW, ruleId: 'not-element', confidence: 'none', reversible: true, reason: 'not-element', riskLevel: 'low', fallback: ACTIONS.ALLOW }; var mode = profile.mode || MODES.NORMAL; if (mode === MODES.BYPASS) return { action: ACTIONS.BYPASS, ruleId: 'site-bypass', confidence: 'rule', reversible: true, reason: 'site-bypass', riskLevel: 'low', fallback: ACTIONS.ALLOW }; if (isProtectedElement(el) || hasProtectedContent(el)) return { action: ACTIONS.ALLOW, ruleId: 'content-protection', confidence: 'strong', reversible: true, reason: 'protected-element', riskLevel: 'low', fallback: ACTIONS.ALLOW }; if (mode === MODES.SAFE) return { action: ACTIONS.OBSERVE_ONLY, ruleId: 'site-safe', confidence: 'rule', reversible: true, reason: 'site-safe-no-dom', riskLevel: 'low', fallback: ACTIONS.ALLOW }; var siteMatch = matchesAny(el, profile.hideSelectors || []); if (siteMatch) return { action: ACTIONS.HIDE_ELEMENT, ruleId: 'site-hide', confidence: 'strong', reversible: true, reason: 'site-exact-selector', riskLevel: isHighRiskContainer(el) ? 'high' : 'medium', fallback: ACTIONS.RESTORE_ELEMENT }; if (matchesAny(el, GLOBAL_HIDE_SELECTORS)) { if (isHighRiskContainer(el)) return { action: ACTIONS.OBSERVE_ONLY, ruleId: 'global-container-guard', confidence: 'medium', reversible: true, reason: 'global-rule-hit-high-risk-container', riskLevel: 'high', fallback: ACTIONS.ALLOW }; return { action: ACTIONS.HIDE_ELEMENT, ruleId: 'global-hide', confidence: 'strong', reversible: true, reason: 'global-exact-selector', riskLevel: 'medium', fallback: ACTIONS.RESTORE_ELEMENT }; } var resourceType = getResourceTypeForElement(el); var decision = evaluateNetwork(createContext({ eventType: EVENT_TYPES.COSMETIC_MATCH, pageHost: pageHost, targetUrl: getElementUrl(el), resourceType: resourceType, element: el, siteProfile: profile })); if (decision.action === ACTIONS.BLOCK_INSERTION) return { action: ACTIONS.HIDE_ELEMENT, ruleId: decision.ruleId, confidence: decision.confidence, reversible: true, reason: 'resource-evidence', riskLevel: 'medium', fallback: ACTIONS.RESTORE_ELEMENT }; return decision; } function buildStyle(profile) { var active = profile || DEFAULT_PROFILE; if (active.mode === MODES.SAFE || active.mode === MODES.BYPASS) return ''; var selectors = GLOBAL_CSS_SELECTORS.slice(); for (var i = 0; i < (active.cssSelectors || []).length; i++) { if (selectors.indexOf(active.cssSelectors[i]) < 0) selectors.push(active.cssSelectors[i]); } var css = selectors.map(function (selector) { return selector + '{display:none!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;}'; }).join('\n'); return css + '\n[data-afh-state="hidden"]{display:none!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;}'; } function isVisible(el, win) { if (!el || !el.isConnected) return false; var style; try { style = win && win.getComputedStyle ? win.getComputedStyle(el) : null; } catch (e) { style = null; } if (style && (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')) return false; if (el.getAttribute && el.getAttribute(MARK_STATE) === 'hidden') return false; return true; } function countVisible(win, nodes, max) { var count = 0; var limit = Math.min(nodes.length, max || 400); for (var i = 0; i < limit; i++) if (isVisible(nodes[i], win)) count++; return count; } function visibleText(doc, body) { if (!body) return ''; if (!doc || typeof doc.createTreeWalker !== 'function') return body.textContent || ''; var parts = []; try { var walker = doc.createTreeWalker(body, 4, null, false); var node = walker.nextNode(); while (node) { var parent = node.parentElement; var hidden = false; while (parent) { if (parent.getAttribute && parent.getAttribute(MARK_STATE) === 'hidden') { hidden = true; break; } parent = parent.parentElement; } if (!hidden && node.nodeValue) parts.push(node.nodeValue); node = walker.nextNode(); } } catch (e) { return body.textContent || ''; } return parts.join(' ').replace(/s+/g, ' ').trim(); } function captureHealth(doc, win) { var body = doc && doc.body; var text = visibleText(doc, body); var mainNodes = doc ? doc.querySelectorAll('main, [role="main"], #app, #root') : []; var links = doc ? doc.querySelectorAll('a') : []; var media = doc ? doc.querySelectorAll('video, audio, canvas, .dplayer, .player, iframe[src^="/embed/"], iframe[src*="player"]') : []; var controls = doc ? doc.querySelectorAll('button, input, textarea, select') : []; var mainVisible = false; for (var i = 0; i < mainNodes.length; i++) { if (isVisible(mainNodes[i], win)) { mainVisible = true; break; } } return { textLength: text.replace(/\s+/g, ' ').trim().length, linkCount: countVisible(win, links, 500), mediaCount: countVisible(win, media, 120), controlCount: countVisible(win, controls, 200), mainVisible: mainVisible, bodyVisible: Boolean(body && isVisible(body, win)), timestamp: Date.now() }; } function healthFailure(before, after, transaction, profile) { if (!before || !after) return null; var criteria = Object.assign({}, DEFAULT_HEALTH, (profile && profile.healthCriteria) || {}); if (before.bodyVisible && !after.bodyVisible) return 'body-hidden'; if (before.mainVisible && !after.mainVisible) return 'main-hidden'; if (before.textLength >= criteria.minTextForTextCheck && after.textLength < before.textLength * criteria.minTextRatio) return 'text-collapse'; if (before.linkCount >= criteria.minLinksForLinkCheck && after.linkCount < before.linkCount * criteria.minLinkRatio) return 'link-collapse'; if (transaction && transaction.records.length > criteria.maxHidesPerBatch) return 'batch-too-large'; return null; } function createAudit(pageHost) { var entries = []; return { push: function (entry) { entries.push(Object.assign({ time: Date.now(), pageHost: pageHost }, entry || {})); if (entries.length > AUDIT_LIMIT) entries.splice(0, entries.length - AUDIT_LIMIT); }, all: function () { return entries.slice(); }, recent: function (limit) { return entries.slice(-Number(limit || 20)); } }; } function createRuntime(env, profile) { return { env: env, win: env.window, doc: env.document, pageHost: normalizeHost(env.location && env.location.hostname), profile: profile || DEFAULT_PROFILE, mode: (profile && profile.mode) || MODES.NORMAL, styleEl: null, observer: null, queue: [], queued: new Set(), records: [], transactions: [], stats: { blockedInsertions: 0, blockedPopups: 0, hidden: 0, observed: 0, restored: 0, safeSwitches: 0 }, audit: createAudit(normalizeHost(env.location && env.location.hostname)), started: false, destroyed: false, baseline: null, lastGesture: null }; } function audit(runtime, eventType, target, decision, transactionId, result) { if (!runtime || !runtime.audit) return; runtime.audit.push({ eventType: eventType, target: String(target || '').slice(0, 500), action: decision && decision.action || ACTIONS.OBSERVE_ONLY, ruleId: decision && decision.ruleId || 'unknown', confidence: decision && decision.confidence || 'none', risk: decision && decision.riskLevel || 'low', transactionId: transactionId || '', result: result || 'recorded' }); } function applyHide(runtime, el, decision, transaction) { if (!el || el.nodeType !== 1 || el.getAttribute(MARK_STATE) === 'hidden') return false; var record = { el: el, originalState: el.getAttribute(MARK_STATE), originalRule: el.getAttribute(MARK_RULE), originalProcessed: el.getAttribute(MARK_PROCESSED), ruleId: decision.ruleId || 'unknown', transactionId: transaction.id }; el.setAttribute(MARK_STATE, 'hidden'); el.setAttribute(MARK_RULE, record.ruleId); el.setAttribute(MARK_PROCESSED, '1'); transaction.records.push(record); runtime.records.push(record); runtime.stats.hidden++; return true; } function restoreRecord(runtime, record) { if (!record || !record.el || !record.el.removeAttribute) return false; if (record.originalState === null) record.el.removeAttribute(MARK_STATE); else record.el.setAttribute(MARK_STATE, record.originalState); if (record.originalRule === null) record.el.removeAttribute(MARK_RULE); else record.el.setAttribute(MARK_RULE, record.originalRule); if (record.originalProcessed === null) record.el.removeAttribute(MARK_PROCESSED); else record.el.setAttribute(MARK_PROCESSED, record.originalProcessed); runtime.stats.restored++; return true; } function rollbackTransaction(runtime, transaction) { if (!transaction || transaction.rolledBack) return; for (var i = transaction.records.length - 1; i >= 0; i--) restoreRecord(runtime, transaction.records[i]); transaction.rolledBack = true; audit(runtime, EVENT_TYPES.HEALTH_FAILURE, transaction.id, { action: ACTIONS.RESTORE_ELEMENT, ruleId: 'health-rollback', confidence: 'strong', riskLevel: 'high' }, transaction.id, 'rolled-back'); } function switchSafe(runtime, reason) { if (!runtime || runtime.mode === MODES.SAFE) return; runtime.mode = MODES.SAFE; runtime.stats.safeSwitches++; if (runtime.observer && runtime.observer.disconnect) runtime.observer.disconnect(); runtime.observer = null; if (runtime.styleEl && runtime.styleEl.parentNode) runtime.styleEl.parentNode.removeChild(runtime.styleEl); runtime.styleEl = null; for (var i = runtime.records.length - 1; i >= 0; i--) restoreRecord(runtime, runtime.records[i]); runtime.records.length = 0; audit(runtime, EVENT_TYPES.HEALTH_FAILURE, reason || 'health', { action: ACTIONS.ENTER_SAFE_MODE, ruleId: 'health-safe', confidence: 'strong', riskLevel: 'high' }, '', 'safe-mode'); } var RESOURCE_SELECTOR = 'script,iframe,img,link,source,video,audio,object,embed'; function candidateSelectors(profile) { var selectors = []; var source = (profile && profile.hideSelectors || []).concat(GLOBAL_HIDE_SELECTORS); for (var i = 0; i < source.length; i++) { if (selectors.indexOf(source[i]) < 0) selectors.push(source[i]); } selectors.push(RESOURCE_SELECTOR); return selectors; } function candidateSelector(profile) { return candidateSelectors(profile).join(','); } function collectCandidates(root, profile, limit) { var result = []; var seen = new Set(); var selectors = candidateSelectors(profile); var max = limit || MAX_SUBTREE; function add(el) { if (!el || el.nodeType !== 1 || seen.has(el) || result.length >= max) return; seen.add(el); result.push(el); } if (root && root.nodeType === 1 && root.matches) { for (var r = 0; r < selectors.length; r++) { try { if (root.matches(selectors[r])) { add(root); break; } } catch (e) { } } } if (root && root.querySelectorAll) { for (var i = 0; i < selectors.length && result.length < max; i++) { try { var nodes = root.querySelectorAll(selectors[i]); for (var j = 0; j < nodes.length && result.length < max; j++) add(nodes[j]); } catch (e) { /* a bad site selector must not hide the rest */ } } } return result; } function runTransaction(runtime, candidates) { if (!runtime || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return { records: [], skipped: true }; var tx = { id: 'tx-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7), records: [], rules: [], beforeHealth: captureHealth(runtime.doc, runtime.win), afterHealth: null, rolledBack: false }; for (var i = 0; i < candidates.length; i++) { var el = candidates[i]; if (!el || !el.isConnected) continue; var decision = evaluateElement(el, runtime.profile, runtime.pageHost); if (decision.action === ACTIONS.HIDE_ELEMENT) { if (applyHide(runtime, el, decision, tx)) { if (tx.rules.indexOf(decision.ruleId) < 0) tx.rules.push(decision.ruleId); audit(runtime, EVENT_TYPES.COSMETIC_MATCH, el.id || el.tagName, decision, tx.id, 'hidden'); } } else if (decision.action === ACTIONS.OBSERVE_ONLY) { runtime.stats.observed++; } } tx.afterHealth = captureHealth(runtime.doc, runtime.win); var failure = healthFailure(tx.beforeHealth, tx.afterHealth, tx, runtime.profile); if (failure) { rollbackTransaction(runtime, tx); switchSafe(runtime, failure); return tx; } if (tx.records.length) runtime.transactions.push(tx); return tx; } function enqueueNode(runtime, node) { if (!runtime || !node || node.nodeType !== 1 || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return; if (runtime.queued.has(node)) return; runtime.queued.add(node); runtime.queue.push(node); if (runtime.queue.length > MAX_BATCH * 3) { switchSafe(runtime, 'queue-overflow'); } } function flushQueue(runtime) { if (!runtime || runtime.destroyed || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return; var batch = []; while (runtime.queue.length && batch.length < MAX_BATCH) { var node = runtime.queue.shift(); runtime.queued.delete(node); if (!node.isConnected) continue; batch.push(node); } if (!batch.length) return; var candidates = []; var seen = new Set(); for (var i = 0; i < batch.length; i++) { var list = collectCandidates(batch[i], runtime.profile, MAX_SUBTREE); for (var j = 0; j < list.length; j++) { if (!seen.has(list[j])) { seen.add(list[j]); candidates.push(list[j]); } if (candidates.length >= MAX_BATCH) break; } if (candidates.length >= MAX_BATCH) break; } if (candidates.length) runTransaction(runtime, candidates); if (runtime.queue.length) scheduleFlush(runtime); } function scheduleFlush(runtime) { if (runtime.flushScheduled) return; runtime.flushScheduled = true; var defer = typeof queueMicrotask === 'function' ? queueMicrotask : function (fn) { Promise.resolve().then(fn); }; defer(function () { runtime.flushScheduled = false; flushQueue(runtime); }); } function startObserver(runtime) { if (!runtime || runtime.observer || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return false; var Observer = runtime.win && runtime.win.MutationObserver; if (!Observer || !runtime.doc || !runtime.doc.documentElement) return false; runtime.observer = new Observer(function (mutations) { if (runtime.mode === MODES.SAFE || runtime.destroyed) return; for (var i = 0; i < mutations.length; i++) { var mutation = mutations[i]; if (mutation.type === 'childList') { for (var j = 0; j < mutation.addedNodes.length; j++) { if (mutation.addedNodes[j] && mutation.addedNodes[j].nodeType === 1) enqueueNode(runtime, mutation.addedNodes[j]); } } else if (mutation.type === 'attributes' && mutation.target && mutation.target.nodeType === 1) { enqueueNode(runtime, mutation.target); } } scheduleFlush(runtime); }); runtime.observer.observe(runtime.doc.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src', 'href', 'class', 'id'] }); return true; } function initialSweep(runtime) { if (!runtime || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return 0; runtime.baseline = captureHealth(runtime.doc, runtime.win); var candidates = collectCandidates(runtime.doc, runtime.profile, MAX_INITIAL); if (candidates.length) runTransaction(runtime, candidates); return candidates.length; } function scheduleHealthChecks(runtime) { if (!runtime || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return; var check = function () { if (runtime.destroyed || runtime.mode === MODES.SAFE) return; var after = captureHealth(runtime.doc, runtime.win); var failure = healthFailure(runtime.baseline, after, null, runtime.profile); if (failure) switchSafe(runtime, failure); }; if (runtime.win && runtime.win.setTimeout) { runtime.win.setTimeout(check, 1800); runtime.win.setTimeout(check, 4500); } } function gestureSnapshot(runtime, target) { var gesture = runtime && runtime.lastGesture; if (!gesture) return { isTrusted: false, type: 'none', time: 0, target: null, href: '', popupCount: 0 }; var fresh = Date.now() - gesture.time <= 1500; return { isTrusted: Boolean(fresh && gesture.isTrusted), type: gesture.type, time: gesture.time, target: target || gesture.target, href: gesture.href, popupCount: gesture.popupCount || 0 }; } function rememberGesture(runtime, event) { var target = event && event.target; var anchor = target && target.closest ? target.closest('a[href]') : null; runtime.lastGesture = { isTrusted: event && event.isTrusted !== false, type: event && event.type || 'click', time: Date.now(), target: target || null, href: anchor && anchor.getAttribute('href') || '', popupCount: 0 }; return runtime.lastGesture; } function evaluateAnchorClick(runtime, anchor) { var href = anchor && anchor.getAttribute && anchor.getAttribute('href') || ''; var ctx = createContext({ eventType: EVENT_TYPES.LINK_CLICK, pageHost: runtime.pageHost, targetUrl: href, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: RESOURCE_TYPES.POPUP, element: anchor, siteProfile: runtime.profile, userGesture: gestureSnapshot(runtime, anchor) }); var decision = evaluateNetwork(ctx); if (decision.action === ACTIONS.BLOCK_INSERTION || decision.action === ACTIONS.BLOCK_POPUP) return Object.assign({}, decision, { action: ACTIONS.CANCEL_NAVIGATION }); return decision; } function installClickTracker(runtime) { var doc = runtime.doc; if (!doc || typeof doc.addEventListener !== 'function' || runtime.clickInstalled) return; runtime.clickInstalled = true; var remember = function (event) { rememberGesture(runtime, event); }; doc.addEventListener('pointerdown', remember, true); doc.addEventListener('touchstart', remember, true); doc.addEventListener('click', function (event) { if (runtime.destroyed || runtime.mode === MODES.BYPASS) return; rememberGesture(runtime, event); var target = event && event.target; var anchor = target && target.closest ? target.closest('a[href]') : null; if (!anchor) return; var decision = evaluateAnchorClick(runtime, anchor); if (decision.action === ACTIONS.CANCEL_NAVIGATION) { event.preventDefault(); audit(runtime, EVENT_TYPES.LINK_CLICK, anchor.getAttribute('href'), decision, '', 'navigation-cancelled'); } }, true); } function installOpenGuard(runtime) { var win = runtime.win; if (!win || typeof win.open !== 'function' || win.open.__afhWrapped) return; var nativeOpen = win.open; function wrappedOpen(url) { if (runtime.destroyed || runtime.mode === MODES.BYPASS) return nativeOpen.apply(this, arguments); var decision = evaluateNetwork(createContext({ eventType: EVENT_TYPES.WINDOW_OPEN, pageHost: runtime.pageHost, targetUrl: url, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: RESOURCE_TYPES.POPUP, siteProfile: runtime.profile, userGesture: gestureSnapshot(runtime, null) })); if (decision.action === ACTIONS.BLOCK_POPUP || decision.action === ACTIONS.BLOCK_INSERTION) { runtime.stats.blockedPopups++; audit(runtime, EVENT_TYPES.WINDOW_OPEN, url, Object.assign({}, decision, { action: ACTIONS.BLOCK_POPUP }), '', 'popup-blocked'); return null; } var result = nativeOpen.apply(this, arguments); if (runtime.lastGesture && Date.now() - runtime.lastGesture.time <= 1500) runtime.lastGesture.popupCount = Number(runtime.lastGesture.popupCount || 0) + 1; return result; } wrappedOpen.__afhWrapped = true; try { win.open = wrappedOpen; } catch (e) { runtime.audit.push({ eventType: 'ERROR', action: 'WARN', ruleId: 'open-guard', result: 'install-failed' }); } } function shouldBlockInsertion(runtime, node, initiator) { if (!runtime || runtime.destroyed || !node || node.nodeType !== 1 || runtime.mode === MODES.BYPASS) return false; var type = getResourceTypeForElement(node); if (type === RESOURCE_TYPES.UNKNOWN) return false; var url = getElementUrl(node); if (!url) return false; var decision = evaluateNetwork(createContext({ eventType: EVENT_TYPES.RESOURCE_INSERT, pageHost: runtime.pageHost, targetUrl: url, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: type, element: node, initiator: initiator || null, siteProfile: runtime.profile })); return decision.action === ACTIONS.BLOCK_INSERTION; } function markBlocked(runtime, node, target) { try { node.setAttribute(MARK_BLOCKED, '1'); } catch (e) { } runtime.stats.blockedInsertions++; audit(runtime, EVENT_TYPES.RESOURCE_INSERT, target, { action: ACTIONS.BLOCK_INSERTION, ruleId: 'resource-rule', confidence: 'strong', riskLevel: 'medium' }, '', 'insertion-blocked'); } function findPropertyDescriptor(proto, prop) { var current = proto; while (current) { var descriptor = Object.getOwnPropertyDescriptor(current, prop); if (descriptor) return descriptor; current = Object.getPrototypeOf(current); } return null; } function patchResourceProperty(runtime, ctorName, prop, queue) { var win = runtime.win; var ctor = win && win[ctorName]; var proto = ctor && ctor.prototype; if (!proto) return; var descriptor = findPropertyDescriptor(proto, prop); if (!descriptor || typeof descriptor.set !== 'function' || descriptor.set.__afhWrapped) return; var wrapped = function (value) { if (queue.shouldBlock(this, value)) { queue.mark(this, value); return; } return descriptor.set.call(this, value); }; wrapped.__afhWrapped = true; try { Object.defineProperty(proto, prop, { configurable: true, enumerable: descriptor.enumerable, get: descriptor.get, set: wrapped }); } catch (e) { } } function installResourceGuards(runtime) { var win = runtime.win; if (!win || !win.Node || !win.Node.prototype || runtime.nodeGuardsInstalled) return; runtime.nodeGuardsInstalled = true; var nodeProto = win.Node.prototype; var nativeAppend = nodeProto.appendChild; var nativeInsert = nodeProto.insertBefore; var nativeReplace = nodeProto.replaceChild; nodeProto.appendChild = function (node) { if (shouldBlockInsertion(runtime, node, this)) { markBlocked(runtime, node, getElementUrl(node)); return node; } return nativeAppend.apply(this, arguments); }; nodeProto.insertBefore = function (node) { if (shouldBlockInsertion(runtime, node, this)) { markBlocked(runtime, node, getElementUrl(node)); return node; } return nativeInsert.apply(this, arguments); }; nodeProto.replaceChild = function (node) { if (shouldBlockInsertion(runtime, node, this)) { markBlocked(runtime, node, getElementUrl(node)); return node; } return nativeReplace.apply(this, arguments); }; var elementProto = win.Element && win.Element.prototype; if (elementProto && elementProto.setAttribute && !elementProto.setAttribute.__afhWrapped) { var nativeSetAttribute = elementProto.setAttribute; elementProto.setAttribute = function (name, value) { var attr = String(name || '').toLowerCase(); if (['src','href','data','poster'].indexOf(attr) >= 0 && !this.isConnected && shouldBlockInsertion(runtime, this, this.parentNode)) { markBlocked(runtime, this, value); return; } return nativeSetAttribute.apply(this, arguments); }; elementProto.setAttribute.__afhWrapped = true; } var queue = { shouldBlock: function (el, value) { var type = getResourceTypeForElement(el); return Boolean(value) && evaluateNetwork(createContext({ eventType: EVENT_TYPES.RESOURCE_INSERT, pageHost: runtime.pageHost, targetUrl: value, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: type, element: el, siteProfile: runtime.profile })).action === ACTIONS.BLOCK_INSERTION; }, mark: function (el, value) { markBlocked(runtime, el, value); } }; [['HTMLScriptElement','src'],['HTMLIFrameElement','src'],['HTMLImageElement','src'],['HTMLLinkElement','href'],['HTMLSourceElement','src'],['HTMLVideoElement','poster'],['HTMLObjectElement','data'],['HTMLEmbedElement','src']].forEach(function (item) { patchResourceProperty(runtime, item[0], item[1], queue); }); } function installRequestGuards(runtime) { var win = runtime.win; if (!win) return; if (typeof win.fetch === 'function' && !win.fetch.__afhWrapped) { var nativeFetch = win.fetch; var wrappedFetch = function (input) { if (runtime.destroyed || runtime.mode === MODES.BYPASS) return nativeFetch.apply(this, arguments); var url = typeof input === 'string' ? input : input && input.url; var decision = evaluateNetwork(createContext({ eventType: EVENT_TYPES.RESOURCE_INSERT, pageHost: runtime.pageHost, targetUrl: url, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: RESOURCE_TYPES.FETCH, siteProfile: runtime.profile })); if (decision.action === ACTIONS.BLOCK_INSERTION) { runtime.stats.blockedInsertions++; audit(runtime, EVENT_TYPES.RESOURCE_INSERT, url, decision, '', 'fetch-blocked'); if (typeof win.Response === 'function') return Promise.resolve(new win.Response(null, { status: 204, statusText: 'No Content' })); return Promise.resolve({ ok: true, status: 204, text: function () { return Promise.resolve(''); } }); } return nativeFetch.apply(this, arguments); }; wrappedFetch.__afhWrapped = true; try { win.fetch = wrappedFetch; } catch (e) { } } if (win.navigator && typeof win.navigator.sendBeacon === 'function' && !win.navigator.sendBeacon.__afhWrapped) { var nativeBeacon = win.navigator.sendBeacon; var wrappedBeacon = function (url) { if (runtime.destroyed || runtime.mode === MODES.BYPASS) return nativeBeacon.apply(this, arguments); var decision = evaluateNetwork(createContext({ eventType: EVENT_TYPES.RESOURCE_INSERT, pageHost: runtime.pageHost, targetUrl: url, baseUrl: runtime.doc.baseURI || runtime.win.location.href, resourceType: RESOURCE_TYPES.BEACON, siteProfile: runtime.profile })); if (decision.action === ACTIONS.BLOCK_INSERTION) { runtime.stats.blockedInsertions++; audit(runtime, EVENT_TYPES.RESOURCE_INSERT, url, decision, '', 'beacon-blocked'); return true; } return nativeBeacon.apply(this, arguments); }; wrappedBeacon.__afhWrapped = true; try { win.navigator.sendBeacon = wrappedBeacon; } catch (e) { } } } function installEarlyGuards(runtime) { installClickTracker(runtime); installOpenGuard(runtime); installResourceGuards(runtime); installRequestGuards(runtime); } function environmentCapabilities(env) { var win = env && env.window; var doc = env && env.document; return { canPatchPageWindow: Boolean(win && win.Node && win.Element && win.Node.prototype), canUseUnsafeWindow: Boolean(win), canPersistSettings: false, canInjectStyle: Boolean(doc && doc.createElement), canObserveDOM: Boolean(win && win.MutationObserver && doc), canAccessOpenShadowRoot: Boolean(doc && doc.documentElement && 'shadowRoot' in doc.documentElement), canExecuteAtDocumentStart: true }; } function injectStyle(runtime) { if (!runtime || runtime.styleEl || runtime.mode === MODES.SAFE || runtime.mode === MODES.BYPASS) return false; if (runtime.profile.disabledModules && runtime.profile.disabledModules.indexOf('css') >= 0) return false; var doc = runtime.doc; if (!doc || !doc.documentElement || !doc.createElement) return false; var style = doc.createElement('style'); style.id = STYLE_ID; style.textContent = buildStyle(runtime.profile); (doc.head || doc.documentElement).appendChild(style); runtime.styleEl = style; return true; } function startDocument(runtime) { if (!runtime || runtime.started || runtime.destroyed || !runtime.doc || !runtime.doc.documentElement) return false; runtime.started = true; if (runtime.mode === MODES.BYPASS) return false; var begin = function () { if (runtime.destroyed || runtime.documentStarted || !runtime.doc || !runtime.doc.body) return; runtime.documentStarted = true; if (runtime.mode !== MODES.SAFE) { injectStyle(runtime); initialSweep(runtime); startObserver(runtime); scheduleHealthChecks(runtime); } }; if (runtime.doc.body) begin(); else if (typeof runtime.doc.addEventListener === 'function') runtime.doc.addEventListener('DOMContentLoaded', begin, { once: true }); return true; } function install(env) { var win = env && env.window ? env.window : (typeof window !== 'undefined' ? window : null); var doc = env && env.document ? env.document : (win && win.document); if (!win || !doc) return false; if (win.__afhRuntime) return false; var loc = env && env.location ? env.location : win.location; var host = normalizeHost(loc && loc.hostname); var profile = findSiteProfile(host); var runtime = createRuntime({ window: win, document: doc, location: loc || {} }, profile); runtime.capabilities = environmentCapabilities({ window: win, document: doc }); win.__afhRuntime = runtime; if (runtime.mode !== MODES.BYPASS) installEarlyGuards(runtime); if (doc.documentElement) startDocument(runtime); else if (typeof doc.addEventListener === 'function') { var start = function () { if (doc.documentElement) { if (typeof doc.removeEventListener === 'function') doc.removeEventListener('readystatechange', start); startDocument(runtime); } }; doc.addEventListener('readystatechange', start); var EarlyObserver = win.MutationObserver; if (EarlyObserver) { try { var early = new EarlyObserver(function () { if (doc.documentElement) { if (early.disconnect) early.disconnect(); startDocument(runtime); } }); early.observe(doc, { childList: true }); runtime.earlyObserver = early; } catch (e) { } } } return true; } function mountWhenReady(env) { return install(env); } function getRuntime(win) { var target = win || (typeof window !== 'undefined' ? window : null); return target && target.__afhRuntime || null; } function diagnostics(win) { var runtime = getRuntime(win); if (!runtime) return { running: false }; return { running: !runtime.destroyed, mode: runtime.mode, profile: runtime.profile.id, profileVersion: runtime.profile.version, capabilities: runtime.capabilities, stats: Object.assign({}, runtime.stats), recentAudit: runtime.audit.recent(20), baseline: runtime.baseline }; } function stop(win) { var runtime = getRuntime(win); if (!runtime) return false; runtime.destroyed = true; if (runtime.observer && runtime.observer.disconnect) runtime.observer.disconnect(); if (runtime.earlyObserver && runtime.earlyObserver.disconnect) runtime.earlyObserver.disconnect(); if (runtime.styleEl && runtime.styleEl.parentNode) runtime.styleEl.parentNode.removeChild(runtime.styleEl); for (var i = runtime.records.length - 1; i >= 0; i--) restoreRecord(runtime, runtime.records[i]); runtime.records.length = 0; runtime.observer = null; runtime.styleEl = null; if (win) { try { delete win.__afhRuntime; } catch (e) { win.__afhRuntime = null; } } return true; } function setMode(mode, win) { var runtime = getRuntime(win); if (!runtime || !MODES[mode]) return false; if (mode === MODES.BYPASS) return stop(win); if (mode === MODES.SAFE) switchSafe(runtime, 'manual-safe'); else runtime.mode = mode; return true; } if (typeof window !== 'undefined' && typeof document !== 'undefined') { install({ window: window, document: document, location: window.location }); } return { VERSION: VERSION, ZERO_INJECTION: ZERO_INJECTION, STYLE_ID: STYLE_ID, MARK_STATE: MARK_STATE, MARK_RULE: MARK_RULE, MARK_PROCESSED: MARK_PROCESSED, MARK_BLOCKED: MARK_BLOCKED, MODES: MODES, ACTIONS: ACTIONS, RESOURCE_TYPES: RESOURCE_TYPES, EVENT_TYPES: EVENT_TYPES, GLOBAL_HIDE_SELECTORS: GLOBAL_HIDE_SELECTORS, GLOBAL_CSS_SELECTORS: GLOBAL_CSS_SELECTORS, GLOBAL_BLOCK_RULES: GLOBAL_BLOCK_RULES, PROTECTED_SELECTORS: PROTECTED_SELECTORS, SITE_PROFILES: SITE_PROFILES, DEFAULT_PROFILE: DEFAULT_PROFILE, normalizeHost: normalizeHost, getSiteKey: getSiteKey, isThirdParty: isThirdParty, normalizeUrl: normalizeUrl, findSiteProfile: findSiteProfile, createContext: createContext, evaluateNetwork: evaluateNetwork, evaluateElement: evaluateElement, buildStyle: buildStyle, isProtectedElement: isProtectedElement, hasProtectedContent: hasProtectedContent, isHighRiskContainer: isHighRiskContainer, captureHealth: captureHealth, healthFailure: healthFailure, createRuntime: createRuntime, applyHide: applyHide, rollbackTransaction: rollbackTransaction, switchSafe: switchSafe, collectCandidates: collectCandidates, runTransaction: runTransaction, install: install, mountWhenReady: mountWhenReady, startDocument: startDocument, diagnostics: diagnostics, setMode: setMode, stop: stop, getRuntime: getRuntime }; });