-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.min.js
1 lines (1 loc) · 100 KB
/
filter.min.js
1
class e{constructor(){this.action=1,this.keywordAction=1,this.rating=null,this.keywordRating=0,this.url="",this.bar_url="",this.block_page=!1,this.isSearchQuery=!1,this.searchEngine="",this.entry="",this.isBlockedSearch=!1,this.isBlockedSearchSuggestion=!1,this.time="",this.customized_page="",this.matchRefererHost=!1}static newUrlTabItem(t,r){const i=new e;return i.url=t,i.bar_url=r,i}}class t{constructor(e){this.url=e,this.time_created=new Date,this.monitor_this_page=!1,this.category="N/A"}}const r={profileserverurl:"https://chromeos.forticlient.com:8443",authserverurl:"http://chromeos.forticlient.com",cloud_emsurl:"https://forticlient-dispatch.forticloud.com/",ratingserverurl:"https://wsfgd1.fortiguard.net:3400",internettesturl:"https://www.fortinet.com",internetTestUrlRegex:/^https?:\/\/www\.fortinet\.com/,fazserverurl:"https://172.18.32.189",monitor_search:!0,no_auth_server:!0,async_mode:!1,main_url_rate_only:!1,safesearch:!0,log_all_URLs:!1,ems_version:null,cloud_mode:!1,invitation_code:"",serial_number:""},i={SEARCH_ENGINE_QUERY_PREFIX:{google:{fieldName:/[?&#]q=/,fieldLength:3},bing:{fieldName:/[?&#]q=/,fieldLength:3},yahoo:{fieldName:/[?&#]p=/,fieldLength:3},yandex:{fieldName:/[?&#]text=/,fieldLength:6},duckduckgo:{fieldName:/[?&#]q=/,fieldLength:3},ask:{fieldName:/[?&#]q=/,fieldLength:3},aol:{fieldName:/[?&#]q=/,fieldLength:3},baidu:{fieldName:/[?&#]wd=/,fieldLength:4},lycos:{fieldName:/[?&#]q=/,fieldLength:3},naver:{fieldName:/[?&#]query=/,fieldLength:7},ecosia:{fieldName:/[?&#]q=/,fieldLength:3},startpage:{fieldName:/[?&#]query=/,fieldLength:7}},SOCIAL_MEDIA_QUERY_PREFIX:{twitter:{fieldName:/[?&#]q=/,fieldLength:3},facebook:{fieldName:/[?&#]q=/,fieldLength:3},instagram:{fieldName:/\/search\//,fieldLength:8},reddit:{fieldName:/[?&#]q=/,fieldLength:3}},XHR_SEARCH_ENGINE:[/^https?:\/\/([^\.]*\.)?baidu\./,/^https?:\/\/([^\.]*\.)?yandex\./],XHR_SOCIAL_MEDIA:[/^https?:\/\/([^\.]*\.)?twitter\./,/^https?:\/\/([^\.]*\.)?facebook\./,/^https?:\/\/([^\.]*\.)?instagram\./,/^https?:\/\/([^\.]*\.)?reddit\./],ACTION:{ALLOW:1,BLOCK:2,WARN:3,MONITOR:4},EXCLUSION_CATEGORY:{BLACKLIST:-2,WHITELIST:-1},YOUTUBE_MODE:{NONE:0,STRICT:1,MODERATE:2},CUSTOM_TYPE:{SEARCH_SUGGEST:"search_suggest",TAB_UPDATE:"tab_update"},GO_BACK_STATE:{COMPLETE:0,LOADING:1},INTERVAL_SECOND:1e3,INTERVAL_MINUTE:6e4,PLATFORM_DETECT_RETRY_INTERVAL:2e3,CHECK_OFFLINE_INTERVAL:1e3,CHECK_ONLINE_INTERVAL:5e3,CACHE_PROFILE_EXPIRE_INTERVAL:864e5,platforminfo:null,platform_os:null,authed:!1,login:!1,window_created:!1,token_error:!1,error_no:0,id_token:"",internet_connected:!1,test:0,testCloudMode:0,ext_version:null,local_IP:null,token_expiry:null,email:null,domain:null,devid:null,tabId:null,lasterr:[],tokenerrortabId:null,initFinished:!1,ignore_pages:["chrome-extension://","chrome://","chrome-devtools://devtools","https://accounts.google","https://accounts.gstatic.com","https://accounts.youtube.com","https://clients1.google.com","https://clients2.google.com","https://clients3.google.com","https://clients4.google.com","https://clients5.google.com","https://clients6.google.com","https://commondatastorage.googleapis.com","https://cros-omahaproxy.appspot.com","https://dl.google.com","https://dl-ssl.google.com","https://gweb-gettingstartedguide.appspot.com","https://m.google.com","https://omahaproxy.appspot.com","https://pack.google.com","https://safebrowsing-cache.google.com","https://safebrowsing.google.com","https://ssl.gstatic.com","https://storage.googleapis.com","https://tools.google.com","https://www.googleapis.com","https://fonts.gstatic.com","https://fonts.googleapis.com","https://security.google.com"],re_ignore_pages:[/^https?:\/\/(?!webcache\.)([^\.]*\.)?googleusercontent\.com/,/^https?:\/\/.*\.1e100\.net/,/^https?:\/\/accounts\.google\./,/^https?:\/\/accounts\.youtube\.com/,/^https?:\/\/clients\d?\.google\.com/,/^https?:\/\/cloudsearch\.googleapis\.com/,/^https?:\/\/commondatastorage\.googleapis\.com/,/^https?:\/\/cros-omahaproxy\.appspot\.com/,/^https?:\/\/dl\.google\.com/,/^https?:\/\/dl-ssl\.google\.com/,/^https?:\/\/[^\.]*\.gvt1\.com/,/^https?:\/\/gweb-gettingstartedguide\.appspot\.com/,/^https?:\/\/m\.google\.com/,/^https?:\/\/omahaproxy\.appspot\.com/,/^https?:\/\/pack\.google\.com/,/^https?:\/\/policies\.google\.com/,/^https?:\/\/safebrowsing-cache\.google\.com/,/^https?:\/\/safebrowsing\.google\.com/,/^https?:\/\/storage\.googleapis\.com/,/^https?:\/\/tools\.google\.com/,/^https?:\/\/www\.googleapis\.com/,/^https?:\/\/.*?\.gstatic\.com/,/^https?:\/\/([^\.]*\.)?google-analytics\.com/,/^https?:\/\/play.google.com\/log\?/],youtube_pages:[/^https?:\/\/www\.youtube\.com/,/^https?:\/\/m\.youtube\.com/,/^https?:\/\/youtubei\.googleapis\.com/,/^https?:\/\/youtube\.googleapis\.com/,/^https?:\/\/www\.youtube-nocookie\.com/],youtube_current_mode:0,get_config:!1,get_cached_config:!1,timer_id:0,refresh_timer:0,session_id:null,block_timer:0,chrome_tabs_status:{},current_tab_id:null,url_browse_time_table:{},mouse_move:!1,last_move_time:null,monitor_all_page:!1,mouse_move_tab_id:null,mouse_move_url:null,idle_detect_timer:0,idle_timeout:18e4,warning_timeout:18e4,ignore_category:{},unresolved_warn_page:{},customized_blacklist_page:"",customized_block_page:"",customized_block_page_FGD_down:"",customized_warning_page:"",customized_warning_page_FGD_down:"",removePunctuationRegex:new RegExp("[`~@#%^&*()_|\\-=?;:'\",.<>\\{\\}\\[\\]\\\\\\/]","gi"),enableSocialMediaSearchFilter:!0,monitorAllSearchEngines:!0,supportedSites:{},supportedDynamicSites:[],goBackTabId:-1,goBackResolve:null,goBackState:0,opener:{},referer:{},UnzipBlob(e,t,r,i,s,o){const a=new zip.fs.FS;a.importBlob(e,()=>{for(const e of a.root.children)switch(e.name){case"blacklisted_page.htm":e.getText(t);break;case"blocked_page.htm":e.getText(r);break;case"blocked_page_FGD_down.htm":e.getText(i);break;case"warning_page.htm":e.getText(s);break;case"warning_page_FGD_down.htm":e.getText(o);break;default:n.LogError(`Unexpected zip blob ${e.name}`)}},e=>n.LogError(e))},SetCustomizedBlockPage(e){this.RemoveCustomizedBlockPage();const t=this.getUint8ArrayFromBase64String(e),r=new Blob([t],{type:"application/zip"});this.UnzipBlob(r,e=>{this.customized_blacklist_page=e},e=>{this.customized_block_page=e},e=>{this.customized_block_page_FGD_down=e},e=>{this.customized_warning_page=e},e=>{this.customized_warning_page_FGD_down=e})},getUint8ArrayFromBase64String(e){const t=[...atob(e)].map(e=>e.charCodeAt(0));return Uint8Array.from(t)},RemoveCustomizedBlockPage(){this.customized_blacklist_page="",this.customized_block_page="",this.customized_block_page_FGD_down="",this.customized_warning_page="",this.customized_warning_page_FGD_down=""},AddIgnoreCategory(e,t){console.log("add to ignore list cat: "+t),this.ignore_category[t]=e},IsCategoryInIgnoreList(e){const t=new Date;return e in this.ignore_category&&t<this.ignore_category[e]},makeSupportedSites(){this.supportedSites=this.SEARCH_ENGINE_QUERY_PREFIX,this.supportedDynamicSites=this.XHR_SEARCH_ENGINE,this.enableSocialMediaSearchFilter&&(this.supportedSites={...this.supportedSites,...this.SOCIAL_MEDIA_QUERY_PREFIX},this.supportedDynamicSites=[...this.XHR_SEARCH_ENGINE,...this.XHR_SOCIAL_MEDIA])},OnCompleted(e){e.url,e.tabId,e.type;/https?:\/\/.+\/logon_success\?sid=/g.test(e.url)&&(this.login||(null!=this.tabId&&(chrome.tabs.remove([this.tabId]),this.tabId=null),null!=this.tokenerrortabId&&(chrome.tabs.remove([this.tokenerrortabId]),this.tokenerrortabId=null),n.LogDebug("** successful logon **"),this.GetUserInfo(e.url)))},onBeforeSendHeaders(e){let t;if(e.initiator&&e.initiator.startsWith("chrome-extension"))return{};let s,o=e.requestHeaders.some(e=>"referer"===e.name.toLowerCase()&&(t=e.value,n.LogDebug(`WebFilterProcess - OnBeforeSendHeaders - Found referer from requetHeaders ${e.value}`),!0));if(o||"initiator"in e&&("/"!==(t=e.initiator).charAt(t.length-1)&&(t+="/"),n.LogDebug(`WebFilterProcess - OnBeforeSendHeaders - Found referer from initiator ${t}`),o=!0),o){let r=l.match_profile_referer(t,e.url);if(r.match){if(r.action===i.ACTION.ALLOW)return e.tabId in this.chrome_tabs_status&&("main_frame"===e.type||"xmlhttprequest"===e.type&&"GET"===e.method||"other"===e.type&&"GET"===e.method)&&(n.LogDebug(`Setting referer bypass for tabID: ${e.tabId}`),this.chrome_tabs_status[e.tabId].matchRefererHost=!0),{};r.action===i.ACTION.BLOCK?s={action:2,remark:"url is in black list",rating:0}:r.action===i.ACTION.MONITOR&&(e.tabId in this.chrome_tabs_status&&(this.chrome_tabs_status[e.tabId].matchRefererHost=!0),s={action:4,remark:"url is in white list",rating:0})}}if("main_frame"!==e.type&&e.tabId in this.chrome_tabs_status&&this.chrome_tabs_status[e.tabId].matchRefererHost)return{};if(this.login&&-1!=e.tabId&&l.init_finish&&l.match_profile_url_in_referer_list(e.url)&&(r.async_mode&&r.main_url_rate_only?"main_frame"===e.type&&this.UrlRating(e.url,e.tabId,e.type,s||null):this.UrlRating(e.url,e.tabId,e.type,s||null)),this.youtube_pages.some(t=>t.test(e.url))){let t=e.requestHeaders.filter(e=>"youtube-restrict"!==e.name.toLowerCase());switch(this.youtube_current_mode){case this.YOUTUBE_MODE.NONE:break;case this.YOUTUBE_MODE.MODERATE:t=[...t,{name:"YouTube-Restrict",value:"Moderate"}];break;case this.YOUTUBE_MODE.STRICT:t=[...t,{name:"YouTube-Restrict",value:"Strict"}];break;default:n.LogError(`Unexpected YOUTUBE_MODE: ${this.youtube_current_mode}.`)}return{requestHeaders:t}}return{}},EnableSafeSearch(e,t){e?(r.safesearch=!0,this.youtube_current_mode="strict"===t?i.YOUTUBE_MODE.STRICT:i.YOUTUBE_MODE.MODERATE):(r.safesearch=!1,this.youtube_current_mode=i.YOUTUBE_MODE.NONE)},SafeSearch(e,t){let r=!1;return-1==e.indexOf("www.bing.com/search?")&&-1==e.indexOf("www.bing.com/images/search?")&&-1==e.indexOf("www.bing.com/videos/search?")||-1!=e.indexOf("adlt=strict")?-1!=e.indexOf("search.yahoo")&&-1!=e.indexOf("/search")&&-1==e.indexOf("vm=r")?(n.LogDebug("it is yahoo search"),t.redirectUrl=e+"&vm=r",r=!0):-1==e.indexOf("google")||-1!=e.indexOf("safe=active")||-1==e.indexOf("&q=")&&-1==e.indexOf("#q=")&&-1==e.indexOf("?q=")||(n.LogDebug("SafeSearch - This is google search"),t.redirectUrl=e+"&safe=active",r=!0):(n.LogDebug("it is bing search"),t.redirectUrl=e+"&adlt=strict",r=!0),r},regexIgnorePage(e){return this.re_ignore_pages.some(t=>t.test(e))},ignorePage(e){return this.ignore_pages.some(t=>e.startsWith(t))},isInternalServer:e=>e.startsWith(r.authserverurl)||e.startsWith(r.profileserverurl)||e.startsWith(r.ratingserverurl)||e.startsWith(r.fazserverurl)||e.startsWith(r.internettesturl)||e.startsWith(r.cloud_emsurl),OnBeforeWebRequest(t){let s,o,a,c=t.tabId,h=t.url,_=t.type;if(!this.internet_connected)return{};if(this.isInternalServer(h))return{};if(this.ignorePage(h))return{};if(""===h)return{};if(!this.authed&&this.window_created&&2!=this.error_no&&this.get_config)return this.Authentication(),{cancel:!0};if(!this.login&&-1!=(o=h.indexOf("//"))&&h.length>o+2&&-1!=(a=h.indexOf("/",o+2))){if(-1!=(s=h.substring(0,a)).indexOf("gstatic"))return{};if(-1!=s.indexOf("google"))return{}}if(this.internet_connected&&(!this.login||!l.init_finish)&&c!==chrome.tabs.TAB_ID_NONE&&"main_frame"===t.type){if(this.regexIgnorePage(h))return{};if(!this.initFinished)return n.LogInfo(`WebFilterProcess - OnBeforeWebRequest - Detected rating during extension initializating. Buffering rating url: ${t.url}`),{};let e,r,i=h;i.length>23&&(i=i.substring(0,23)+"...");let s=`<strong>${i}</strong> has been temporarily blocked due to error:<br>`;return this.get_config||this.get_cached_config?this.login?(s+=" Failed to retrieve user profile from FortiClientEMS.<br>Please contact your network administrator for further assistance.<br>",(e=l.get_error_message())&&(s+="ERROR: ",s+=e)):s+=" Please sign in to G Suite account.<br>Please contact your network administrator for further assistance.":s+=" Failed to retrieve configurations from google domain.<br>Please contact your network administrator for further assistance.",this.lasterr[c]=s,r=chrome.runtime.getURL("../displayerror.html"),chrome.tabs.update(c,{url:r}),{cancel:!0}}if(this.login&&c!==chrome.tabs.TAB_ID_NONE){const s=this.getBaseURL(h);if("main_frame"!==t.type)chrome.tabs.get(t.tabId,r=>{if(chrome.runtime.lastError)n.LogDebug(`No tab with ID ${t.tabId} exists.`);else if(r.url){var s=this.getBaseURL(r.url);if(t.tabId in this.chrome_tabs_status){if("ping"!==t.type&&this.chrome_tabs_status[t.tabId].bar_url!=r.url&&!r.url.startsWith("chrome-extension://")&&this.chrome_tabs_status[t.tabId].action!==i.ACTION.BLOCK&&this.chrome_tabs_status[t.tabId].action!==i.ACTION.WARN&&this.chrome_tabs_status[t.tabId].keywordAction!==i.ACTION.BLOCK&&this.chrome_tabs_status[t.tabId].keywordAction!==i.ACTION.WARN){let i;n.LogDebug(`WebFilterProcess - OnbeforeWebRequest - creating new chrome_tabs_status for ${t.tabId}`),this.referer[t.tabId]=this.chrome_tabs_status[t.tabId].bar_url,i=this.chrome_tabs_status[t.tabId].customized_page,this.chrome_tabs_status[t.tabId]=e.newUrlTabItem(s,r.url),this.chrome_tabs_status[t.tabId].customized_page=i}}else this.chrome_tabs_status[t.tabId]=e.newUrlTabItem(s,r.url)}});else{let r,i;t.tabId in this.chrome_tabs_status&&(this.referer[t.tabId]=this.chrome_tabs_status[t.tabId].bar_url,r=this.chrome_tabs_status[t.tabId].customized_page,i=this.chrome_tabs_status[t.tabId].bar_url),n.LogDebug(`WebFilterProcess - OnbeforeWebRequest - creating new main_frame chrome_tabs_status for ${t.tabId}`),this.chrome_tabs_status[t.tabId]=new e,i===t.url?this.chrome_tabs_status[t.tabId].customized_page=r:delete this.unresolved_warn_page[t.tabId],this.chrome_tabs_status[t.tabId].url=s,this.chrome_tabs_status[t.tabId].bar_url=t.url}if(t.tabId in this.chrome_tabs_status&&this.chrome_tabs_status[t.tabId].matchRefererHost)return{cancel:!1};if(l.match_profile_url_in_referer_list(t.url))return{cancel:!1};if(r.safesearch){let e={redirectUrl:""};if(this.SafeSearch(h,e))return e}return r.monitor_search&&this.MonitorSearch(h,_,c,s)?{cancel:!0}:this.regexIgnorePage(h)?{}:r.async_mode&&r.main_url_rate_only&&"main_frame"!==_?{}:this.UrlRating(h,c,_)}return{}},setOfflineListener(){window.addEventListener("offline",()=>{i.internet_connected=!1})},OnlineDetector(){if(i.internet_connected)return Promise.resolve();{const e=(new Date).getTime(),t=`${r.internettesturl}/?time=${e}`;return fetch(t,{method:"HEAD"}).then(e=>{r.internetTestUrlRegex.test(e.url)&&e.status?(i.internet_connected=!0,n.LogInfo("WebFilterProcess - OnlineDetector - SUCCESS - Internet connection detected. Extension is online.",`color:${n.FORTINET_COLOR.GREEN}`)):(i.internet_connected=!1,n.LogWarn("WebFilterProcess - OnlineDetector - FAILED - No internet connection detected. Extension is offline."))}).catch(e=>{i.internet_connected=!1,n.LogError(`WebFilterProcess - OnlineDetector - FAILED - No internet connection detected. Extension is offline. ${e}`)})}},BlockTab(e){e in this.chrome_tabs_status&&(this.chrome_tabs_status[e].block_page=!0)},replaceSpaceCharacters:e=>decodeURIComponent(e).replace(/\s+/g," ").trim(),updateBlockPage(e,t,r){chrome.tabs.update(e,{url:t},()=>{chrome.runtime.lastError?n.LogError(`WebFilterProcess - updateBlockPage - ERROR - ${chrome.runtime.lastError.message}`):r&&this.BlockTab(e)})},goBackAndUpdateBlockPage(e,t,r){const i=this.chrome_tabs_status[e];chrome.tabs.goBack(e,()=>new Promise(t=>{this.goBackTabId=e,this.goBackResolve=t,this.goBackState=this.GO_BACK_STATE.LOADING}).then(()=>{this.goBackTabId=chrome.tabs.TAB_ID_NONE,this.goBackResolve=null,this.goBackState=this.GO_BACK_STATE.COMPLETE,this.chrome_tabs_status[e]=i,this.updateBlockPage(e,t,r)}))},initSearchTermBlockPage(e,t,r,s){let o=e.categoryId===i.EXCLUSION_CATEGORY.BLACKLIST,a=e.action===i.ACTION.BLOCK,n=e.action===i.ACTION.WARN;if(a||n){let i,l;if((l=o?this.customized_blacklist_page:a?this.customized_block_page:this.customized_warning_page).length>0){let r=h.get_rating_info(e.categoryId);r.length||(r=g.getRatingInfo(e.categoryId));let s=e.entry;s.length>50&&(s=s.substring(0,50)+"...");const a=this.PrepareCustomizedPage(t,l,`"${s}"`,o?"is blacklisted":r);this.SetTabsStatusCustomizedPage(t,a),i=chrome.runtime.getURL("../customize.html")}else i=a?chrome.runtime.getURL("../block.html"):chrome.runtime.getURL("../warning.html");i+=`?tabid=${t}&action=${a?2:3}`,s?n?this.goBackAndUpdateBlockPage(t,i,!1):chrome.tabs.goBack(t,()=>{this.updateBlockPage(t,i,!0)}):r?(chrome.history.search({text:"",maxResults:1},e=>{const t=e[0].url;chrome.history.deleteUrl({url:t})}),this.goBackAndUpdateBlockPage(t,i,a)):this.updateBlockPage(t,i,a)}},testSupportedSite(e){return Object.keys(this.supportedSites).find(t=>e.includes(t))},MonitorSearch(e,t,s,o,a=null){if(!r.monitor_search)return!1;n.LogDebug(`WebFilterProcess - MonitorSearch - On ${e}, type: ${t}, tabId: ${s}`);const l="main_frame"===t,c=t===this.CUSTOM_TYPE.SEARCH_SUGGEST,_=t===this.CUSTOM_TYPE.TAB_UPDATE,u="www.startpage.com"===o;if(l||c||_||u){let t=null;const l=this.chrome_tabs_status[s];let d=this.testSupportedSite(o);if(u&&(l.isSearchQuery=!0,l.searchEngine="startpage"),d){l.searchEngine=d;const r=this.supportedSites[d],i=e.search(r.fieldName);let a;if("twitter"!==d&&"facebook"!==d||(a=/\/hashtag\/([^\/\?#]*)/.exec(e)),"instagram"===d&&(a=/\/tags\/([^\/\?#]*)/.exec(e)),-1!==i||a){let n;n=a?"#"+a[1]:e.slice(i+r.fieldLength).split("&")[0].toLowerCase().replace(/\+/g,"%20");let l=this.replaceSpaceCharacters(n);if(!l.length)return!1;const c=l.replace(this.removePunctuationRegex,""),h={url:o,isSearchQuery:!0,searchEngine:d,entry:l="#"===l[0]?"#"+c:c,isBlockedSearch:!1,isBlockedSearchSuggestion:!1};this.TabsStatusUpdate(s,h),t=g.analyzeSearchTerm(l,e)}}else if(this.monitorAllSearchEngines){let o;if(e in h.url_rate_cache_list&&(o=h.url_rate_cache_list[e].rating),!o){let t=r.ratingserverurl+"/service/wfquery?protover=1.0&";t+="cltkey=",t+=encodeURIComponent(i.id_token),this.emssn&&(t+="&emssn=",t+=this.emssn),t+="&clttype=ie&type=cate&catver=7&qurl="+encodeURIComponent(e);const s=new XMLHttpRequest;let a;const l=setTimeout(()=>{a||s.abort()},2e3);try{s.open("GET",t,!1),s.send()}catch(e){clearTimeout(l),n.LogError("WebFilterProcess - MonitorSearch - query FortiGuard failed: "+e.message)}if(200===s.status){clearTimeout(l);try{0===(a=JSON.parse(s.response)).status&&((o=a.data[0])in h.cat_list||(o=0),0!==o&&(h.url_rate_cache_list[e]={rating:o,date:new Date}))}catch(e){n.LogError("WebFilterProcess - MonitorSearch - parse FortiGuard response failed: "+e)}}}if(41===o){(d=/^https?:\/\/([^\.]*\.)?([^\.]*)\./.exec(e))&&(d=d[2],this.chrome_tabs_status[s].searchEngine=d);let r=e.match(/[\?&][\w]+=[^&]*/g);r&&(r=r.map(e=>/[\?&][\w]+=(.*)/.exec(e)[1])).some(r=>{let i=g.analyzeSearchTerm(this.replaceSpaceCharacters(r.toLowerCase().replace(/\+/g,"%20")),e);return!!i&&(t=i,!0)})}}if(t){t.action,t.categoryId,t.entry;if(t.action===this.ACTION.BLOCK){a&&a({found:!0});const e={url:o,keywordAction:t.action,keywordRating:t.categoryId,isSearchQuery:!0,searchEngine:d,entry:t.entry,isBlockedSearch:!0,isBlockedSearchSuggestion:c};return this.TabsStatusUpdate(s,e),this.initSearchTermBlockPage(t,s,c,_),!0}if(t.action===this.ACTION.MONITOR){const r={url:o,keywordAction:t.action,keywordRating:t.categoryId,isSearchQuery:!0,searchEngine:d,entry:t.entry,isBlockedSearch:!1,isBlockedSearchSuggestion:!1};this.TabsStatusUpdate(s,r),this.SetMonitorThisPage(s,e)}}return a&&a({found:!1}),!1}},getBaseURL:e=>e.startsWith("chrome://")?"":e.replace("http://","").replace("https://","").split(/[/?#]/)[0],UrlRating(e,t,s,o=null){let a,l,c,_,g="main_frame"===s,u=0;if(g&&(this.AddUrlBrowseTimeItem(t,e),u=1,this.ResetMonitorThisPage(t,e)),_=o?h.url_rate(e,t,s,this.id_token,o):h.url_rate(e,t,s,this.id_token),g&&this.UpdateBrowseTimeItme(t,_.remark),_.action===i.ACTION.BLOCK||_.action===i.ACTION.WARN){if(_.action===i.ACTION.BLOCK){if(c="WebFilterProcess - UrlRating - ",c+="Block URL: "+e,n.LogDebug(c,`color:${n.FORTINET_COLOR.TEAL}`),"main_frame"==s){const r={action:_.action,rating:_.rating,url:e};return this.TabsStatusUpdate(t,r),rating_info=h.get_rating_info(_.rating),l=this.customized_block_page.length>0?chrome.runtime.getURL("../customize.html"):chrome.runtime.getURL("../block.html"),l+="?tabid=",l+=t,l+="&action=2",chrome.tabs.update(t,{url:l},()=>{chrome.runtime.lastError?n.LogWarn(`WebFilterProcess - UrlRating - Exception in chrome.tabs.update: ${chrome.runtime.lastError.message}`):this.BlockTab(t)}),{cancel:!0}}return{redirectUrl:h.generate_web_content(e,_.rating)}}if(this.IsCategoryInIgnoreList(_.rating))return{};{c="WebFilterProcess - UrlRating -",c+=" show warning page under sync mode, action:"+_.action,c+=", url:"+e,n.LogDebug(c);const r={action:_.action,rating:_.rating,url:e};return this.TabsStatusUpdate(t,r),this.customized_warning_page.length>0?(a=chrome.runtime.getURL("../customize.html"),customized_page=this.PrepareCustomizedPage(t,this.customized_warning_page,e,h.get_rating_info(_.rating)),this.SetTabsStatusCustomizedPage(t,customized_page)):a=chrome.runtime.getURL("../warning.html"),a+="?tabid=",a+=t,a+="&action=3",chrome.tabs.update(t,{url:a},()=>{chrome.runtime.lastError?n.LogError(`WebFilterProcess - UrlRating - ERROR - ${chrome.runtime.lastError.message}`):this.BlockTab(t)}),{cancel:!0}}}if(_.action!==this.ACTION.ALLOW||!r.log_all_URLs)return{};n.CacheLogInfo(e,"passthrough",n.LOG_ACTION_TYPE.PASSTHROUGH,0,h.cat_list[_.rating].name,u)},ProcessRefreshIDTokenReply(e){let t;n.LogDebug("ProcessRefreshIDTokenReply() ID token response info:"+e),t=JSON.parse(e),0==Number(t.error)?this.id_token=t.id_token:(n.LogError("ProcessRefreshIDTokenReply() error happened when refreshing ID token, try to login again"),this.OnRefreshTokenError(Number(t.error)))},ProcessUserInfo(e){n.LogDebug("ProcessUserInfo() user info:"+e);const t=JSON.parse(e);0==Number(t.error)?(this.id_token=t.id_token,String(this.id_token).length>=10&&(this.devid="FCT810"+String(this.id_token).substring(String(this.id_token).length-10)),this.token_expiry=t.token_expiry,this.email=t.email,this.domain=this.email.substring(this.email.indexOf("@")+1),n.LogDebug("** get user information successfully **"),this.OnLogin()):1==Number(t.error)?(n.LogDebug("** failed to get user information, try to login again **"),this.OnRelogin()):(n.LogDebug("** failed to get a refresh token, please go to https://support.google.com/a/answer/2537800?hl=en and revoke access **"),chrome.tabs.create({url:chrome.runtime.getURL("../logon_error.html"),active:!0},function(e){n.LogDebug("ProcessUserInfo() display logon error web page")}))},GetUserInfo(e){let t,i;t=e.indexOf("sid="),sid=e.substr(t+4),this.session_id=sid;try{i=r.authserverurl+"/userinfo?sid="+sid;let e=new XMLHttpRequest;e.open("GET",i,!0),e.timeout=3e4,e.ontimeout=function(){n.LogDebug("GetUserInfo() request user information timed out.")},e.onload=(()=>{n.LogDebug("GetUserInfo() client.readyState="+e.readyState+",client.status="+e.status),200===e.status&&(n.LogDebug("GetUserInfo() request is done successfully"),this.ProcessUserInfo(e.responseText))}),e.send()}catch(e){n.LogDebug("GetUserInfo() request user information failed: "+e.message)}},TokenRevoke(){if(n.LogDebug("TokenRevoke() Revoke Fefresh Token"),null!=this.session_id)try{requesturl=r.authserverurl+"/revoketoken?sid="+this.session_id;let e=new XMLHttpRequest;e.open("GET",requesturl,!0),e.timeout=1e4,e.ontimeout=function(){n.LogDebug("TokenRevoke() request revoke ID token timed out.")},e.onload=(()=>{200===e.status&&n.LogDebug("TokenRevoke() request revoke refresh token has been done.")}),e.send()}catch(e){n.LogError("TokenRevoke() request revoke refresh token failed: "+e.message)}},TokenRefresh(){n.LogDebug("TokenRefresh() Refresh ID Token");try{requesturl=r.authserverurl+"/refreshtoken?sid="+this.session_id;let e=new XMLHttpRequest;e.open("GET",requesturl,!0),e.timeout=1e4,e.ontimeout=function(){n.LogDebug("TokenRefresh request refresh ID token timed out.")},e.onload=(()=>{200===e.status&&i.ProcessRefreshIDTokenReply(e.responseText)}),e.send()}catch(e){n.LogError("TokenRefresh() request user information failed: "+e.message)}},rateBypassedTabs(){chrome.tabs.query({},t=>{t.forEach(t=>{const r=t.url?t.url:t.pendingUrl;n.LogInfo(`WebFilterProcess - rateBypassedTabs - rating buffered url: ${r}`),this.chrome_tabs_status[t.id]=new e,this.chrome_tabs_status[t.id].url=this.getBaseURL(r),this.chrome_tabs_status[t.id].bar_url=r,this.UrlRating(r,t.id,"main_frame")})})},showErrorOnAllTabs(){chrome.tabs.query({},e=>{e.forEach(e=>{if(e.url.startsWith("chrome://"))return;let t,r,i=e.url?e.url:e.pendingUrl;i.length>23&&(i=i.substring(0,23)+"...");let s=`<strong>${i}</strong> has been temporarily blocked due to error:<br>`;this.get_config||this.get_cached_config?this.login?(s+=" Failed to retrieve user profile from FortiClientEMS.<br>Please contact your network administrator for further assistance.<br>",(t=l.get_error_message())&&(s+="ERROR: ",s+=t)):s+=" Please sign in to G Suite account.<br>Please contact your network administrator for further assistance.":s+=" Failed to retrieve configurations from google domain.<br>Please contact your network administrator for further assistance.",this.lasterr[e.id]=s,r=chrome.runtime.getURL("../displayerror.html"),chrome.tabs.update(e.id,{url:r})})})},GetConfig(e=3e3){this.get_config||(n.LogInfo("WebFilterProcess - GetConfig - Retrieving G Suite configurations..."),this.test?(this.get_config=!0,r.cloud_mode=this.testCloudMode,n.LogDebug("WebFilterProcess - GetConfig - SUCCESS DEBUG MODE - Using predefined profile.",`color:${n.FORTINET_COLOR.GREEN}`),r.no_auth_server&&(chrome.identity.onSignInChanged.addListener((e,t)=>{n.save_cached_faz_logs()}),chrome.identity.getProfileUserInfo(e=>{this.email=e.email,this.domain=this.email.substring(this.email.indexOf("@")+1),this.id_token=e.id,String(this.id_token).length>=10&&(this.devid="FCT810"+String(this.id_token).substring(String(this.id_token).length-10)),n.LogDebug("WebFilterProcess - GetConfig - Email: "+e.email,`color:${n.FORTINET_COLOR.GREEN}`),n.LogDebug("WebFilterProcess - GetConfig - ID: "+e.id,`color:${n.FORTINET_COLOR.GREEN}`),n.LogInfo("WebFilterProcess - GetConfig - SUCCESS",`color:${n.FORTINET_COLOR.GREEN}`),this.getEMSServerList().then(()=>{this.OnLogin()}).catch(e=>{n.LogError(`WebFilterProcess - GetConfig - FAILED - Cloud EMS enabled but cannot retrieve data - ${e.message}`)})}))):chrome.storage.managed.get(["ProfileServerUrl","AuthServerUrl","RatingServerUrl","InvitationCode","SerialNumber"],e=>{n.LogDebug("WebFilterProcess - GetConfig - configuration content:\n"+JSON.stringify(e,null,4)),"ProfileServerUrl"in e||"InvitationCode"in e?(r.cloud_mode=!1,r.profileserverurl=e.ProfileServerUrl,"AuthServerUrl"in e&&(r.authserverurl=e.AuthServerUrl),"RatingServerUrl"in e&&(r.ratingserverurl=e.RatingServerUrl),"InvitationCode"in e&&"SerialNumber"in e&&(r.cloud_mode=!0,r.invitation_code=e.InvitationCode,r.serial_number=e.SerialNumber),this.get_config=!0,n.LogDebug("WebFilterProcess - GetConfig - SUCCESS - Retrieved configuration",`color:${n.FORTINET_COLOR.GREEN}`),r.no_auth_server&&(chrome.identity.onSignInChanged.addListener((e,t)=>{n.save_cached_faz_logs()}),chrome.identity.getProfileUserInfo(e=>{this.email=e.email,this.domain=this.email.substring(this.email.indexOf("@")+1),this.id_token=e.id,String(this.id_token).length>=10&&(this.devid="FCT810"+String(this.id_token).substring(String(this.id_token).length-10)),n.LogDebug("WebFilterProcess - GetConfig - Email: "+e.email,`color:${n.FORTINET_COLOR.GREEN}`),n.LogDebug("WebFilterProcess - GetConfig - ID: "+e.id,`color:${n.FORTINET_COLOR.GREEN}`),n.LogInfo("WebFilterProcess - GetConfig - SUCCESS",`color:${n.FORTINET_COLOR.GREEN}`),this.getEMSServerList().then(()=>{this.OnLogin()}).catch(e=>{n.LogError(`WebFilterProcess - GetConfig - FAILED - Cannot get EMS Address from Cloud EMS: ${e}`)})}))):n.LogError("WebFilterProcess - GetConfig - FAILED - No 'ProfileServerUrl' in configuration")}),this.get_config||setTimeout(()=>{this.GetConfig(Math.min(e+3e3,6e4))},e))},SetTabId(e){void 0!==e&&void 0!==e.id?this.tabId=e.id:this.authed=!1},SetTokenErrorTabId(e){void 0!==e&&void 0!==e.id?this.tokenerrortabId=e.id:this.tokenerrortabId=null},Authentication(){let e,t;e=this,n.LogDebug("Authentication() is called\n"),this.authed=!0,r.no_auth_server||(t=r.authserverurl+"/login",chrome.tabs.create({url:t,active:!0},function(e){i.SetTabId(e)}))},OnGetProfileUserInfo(e){n.LogDebug("OnGetProfileUserInfo() User info:"+e)},OnLogin(){n.LogInfo("WebFilterProcess - OnLogin - Retrieving profile and word signature from EMS...");let e;this.login=!0,this.authed=!0,n.Init(),h.Init(),this.init_started=!0,l.profile_init_json(1/0).then(()=>{n.LogDebug("WebFilterProcess - OnLogin - SUCESS - Retrieved profile from EMS.",`color:${n.FORTINET_COLOR.GREEN}`),l.profile_reset_keepalive_timer(),r.no_auth_server||(this.refresh_timer=setInterval(()=>{this.TokenRefresh()},359e4));let t=r.ems_version.split("."),i=parseInt(t[0]),s=parseInt(t[1]);const o=[6,4];i==o[0]&&s>=o[1]||i>o[0]?(n.LogInfo("WebFilterProcess - OnLogin - Detected EMS version newer than 6.4. Ban word function supported."),(e=g.getSignature(1/0)).then(()=>{n.LogDebug("WebFilterProcess - OnLogin - SUCESS - Retrieved word signature from EMS.",`color:${n.FORTINET_COLOR.GREEN}`),this.makeSupportedSites(),g.setIntervalTimers(),n.LogInfo("WebFilterProcess - OnLogin - Rating buffered webrequest during initialization, if any"),this.rateBypassedTabs(),n.LogInfo("WebFilterProcess - OnLogin - SUCCESS - Retrieved profile and signature.",`color:${n.FORTINET_COLOR.GREEN}`),g.parseDB()}).catch(()=>{n.LogError("WebFilterProcess - OnLogin - FAILED - Unable to retrieve word signature from EMS.",`color:${n.FORTINET_COLOR.CRIMSON}`),this.makeSupportedSites(),this.get_cached_config?this.rateBypassedTabs():this.showErrorOnAllTabs(),n.LogError("WebFilterProcess - OnLogin - FINISHED WITH ERROR")})):e=Promise.resolve().then(()=>{n.LogInfo("WebFilterProcess - OnLogin - Detected EMS version older than 6.4. Ban word function not supported."),n.LogInfo("WebFilterProcess - OnLogin - Rating buffered webrequest during initialization, if any"),this.rateBypassedTabs(),n.LogInfo("WebFilterProcess - OnLogin - SUCCESS - Retrieved profile.",`color:${n.FORTINET_COLOR.GREEN}`)}),this.initFinished=!0}).catch(()=>{n.LogError("WebFilterProcess - OnLogin - FAILED - Unable to retrieve profile from EMS.",`color:${n.FORTINET_COLOR.CRIMSON}`),i.makeSupportedSites(),this.get_cached_config?(n.LogWarn("Using cached profile for userprofile"),n.LogInfo("WebFilterProcess - OnLogin - Rating buffered webrequest during initialization, if any"),this.rateBypassedTabs()):(n.LogInfo("WebFilterProcess - OnLogin - Cannot find cached profile. Showing error on all buffered tabs."),this.showErrorOnAllTabs()),this.initFinished=!0}),this.idle_detect_timer=setInterval(()=>{this.ComputerIdleDetect()},1e4)},checkFortiGuardServerStatus(){let e=r.ratingserverurl+"/service/wfquery?protover=1.0&";e+="cltkey=",e+=encodeURIComponent(i.id_token),this.emssn&&(e+="&emssn=",e+=this.emssn),e+="&clttype=ie&type=cate&catver=7&qurl="+encodeURIComponent("www.fortinet.com"),n.LogInfo(`FortiGuard rating server address: ${r.ratingserverurl}`);const t=(new Date).getTime();fetch(e).then(e=>{const r=(new Date).getTime();e.ok?(n.LogInfo(`FortiGuard rating server responding. Response time: ${r-t}ms`,`color:${n.FORTINET_COLOR.GREEN}`),r-t>3e3&&n.LogWarn("FortiGuard rating server slow response")):n.LogWarn(`FortiGuard rating server responding but with status "${e.status} ${e.statusText}": Response time: ${r-t}ms`)}).catch(e=>{n.LogError(`FortiGuard rating server not responding. ${e}`)})},OnRefreshTokenError(e){let t;t=this,clearInterval(this.refresh_timer),clearInterval(this.idle_detect_timer),this.login=!1,this.authed=!1,this.token_error=!0,this.error_no=e,2===e&&chrome.tabs.create({url:chrome.runtime.getURL("../refresh_token_error.html"),active:!0},function(e){n.LogDebug("OnRefreshTokenError() display refresh token error web page"),t.SetTokenErrorTabId(e)})},OnRelogin(){let e=this;clearInterval(this.refresh_timer),clearInterval(this.idle_detect_timer),l.profile_uninit(),n.Uninit(),h.Uninit(),g.clearIntervalTimers(),this.login=!1,this.authed=!1,this.token_error=!1,setTimeout(function(){e.Authentication()},1e3)},OnLogout(){clearInterval(this.refresh_timer),clearInterval(this.idle_detect_timer),n.Uninit(),this.TokenRevoke(),this.login=!1,this.authed=!1},SetMonitorThisPage(e,t){let r;void 0!=this.url_browse_time_table[e]&&this.url_browse_time_table[e].url==t&&(this.url_browse_time_table[e].monitor_this_page=!0,r="SetMonitorThisPage() monitor_this_page is set",r+=",tabId:"+e,r+=",url:"+t,n.LogDebug(r))},ResetMonitorThisPage(e,t){let r;this.url_browse_time_table[e]&&this.url_browse_time_table[e].url==t&&(this.url_browse_time_table[e].monitor_this_page=!1,r="WebFilterProcess - ResetMonitorThisPage - monitor_this_page is set",r+=",tabId:"+e,r+=",url:"+t,n.LogDebug(r))},SaveCacheLog(e){let t,r,i=new Date;this.chrome_tabs_status[e]&&this.chrome_tabs_status[e].block_page||(r="SaveCacheLog() is called ",r+="tabId:"+e,n.LogDebug(r),void 0!=this.url_browse_time_table[e]&&(this.monitor_all_page||this.url_browse_time_table[e].monitor_this_page)&&(t=(i-this.url_browse_time_table[e].time_created)/1e3,n.CacheLogWarn(this.url_browse_time_table[e].url,"userbrowsed",n.LOG_ACTION_TYPE.USERBROWSED,t,this.url_browse_time_table[e].category,1)))},SetMouseMoveEvent(e){let t,r;if(this.mouse_move){if(this.last_move_time=new Date,this.mouse_move_tab_id!=this.current_tab_id||this.mouse_move_url!=e){t=!1;for(let i in this.url_browse_time_table)if(this.url_browse_time_table[i].url==e){t=!0,r=i;break}t&&r!=this.current_tab_id&&(null!=this.current_tab_id&&this.SaveCacheLog(this.current_tab_id),this.current_tab_id=r,this.url_browse_time_table[r].time_created=new Date,this.mouse_move_tab_id=r,this.mouse_move_url=e)}}else{t=!1;for(let i in this.url_browse_time_table)if(this.url_browse_time_table[i].url==e){t=!0,r=i;break}t&&(this.current_tab_id=r,this.url_browse_time_table[r].time_created=new Date,this.mouse_move_tab_id=r,this.mouse_move_url=e,this.mouse_move=!0,this.last_move_time=new Date)}},BlockTabTimer(){let e=this;chrome.tabs.query({},function(t){for(let r=0;r<t.length;r++)if(null!=t[r]){let i,s=this.getBaseURL(t[r].url),o=t[r].id;if(s.length>0)if(2==(i=h.cache_url_rate(s)).action)n.LogDebug("BlockTabTimer() block web page in timer thread"),chrome.tabs.update(o,{url:i.remark});else if(void 0!==e.chrome_tabs_status[o]){if(2==e.chrome_tabs_status[o].action){let t;e.chrome_tabs_status[o].action=0,n.LogDebug("BlockTabTimer() block web page in timer thread"),t=e.customized_block_page.length>0?chrome.runtime.getURL("../customize.html"):chrome.runtime.getURL("../block.html"),t+="?tabid=",t+=o,t+="&action=2",chrome.tabs.update(o,{url:t}),e.BlockTab(o)}if(3==e.chrome_tabs_status[o].action){let t;e.chrome_tabs_status[o].action=0,t=e.customized_warning_page.length>0?chrome.runtime.getURL("../customize.html"):chrome.runtime.getURL("../warning.html"),t+="?tabid=",t+=o,t+="&action=3",chrome.tabs.update(o,{url:t}),e.BlockTab(o)}}}})},UpdateBrowseTimeItme(e,t){this.url_browse_time_table[e]&&(this.url_browse_time_table[e].category=t)},AddUrlBrowseTimeItem(e,r){let i;void 0==this.url_browse_time_table[e]?(i="WebFilterProcess - AddUrlBrowseTimeItem - url_browse_time_item",i+=" tabId: "+e,i+=" url: "+r,i+=" has been added into table",n.LogDebug(i),this.url_browse_time_table[e]=new t(r)):this.url_browse_time_table[e].url!=r&&(this.SaveCacheLog(e),i="WebFilterProcess - AddUrlBrowseTimeItem AddUrlBrowseTimeItem - url_browse_time_item",i+=" tabId: "+e,i+=" url: "+r,i+=" has been updated",n.LogDebug(i),this.url_browse_time_table[e].url=r,this.url_browse_time_table[e].time_created=new Date)},DeleteUrlBrowseTimeItem(e){let t;void 0!=this.url_browse_time_table[e]&&(t="WebFilterProcess - DeleteUrlBrowseTimeItem - item ",t+=" tabId: "+e,t+=" url: "+this.url_browse_time_table[e].url,t+=" has been removed",n.LogDebug(t),delete this.url_browse_time_table[e])},OnTabRemoved(e){void 0!=this.url_browse_time_table[e]&&(this.SaveCacheLog(e),this.DeleteUrlBrowseTimeItem(e)),e in this.chrome_tabs_status&&(delete this.chrome_tabs_status[e],n.LogDebug("WebFilterProcess - Deleted tab: "+e))},OnTabActivated(e){if(null!=this.current_tab_id){let t=this.current_tab_id;if(this.current_tab_id==e)return;void 0!=this.url_browse_time_table[t]&&this.SaveCacheLog(t)}this.current_tab_id=e,void 0!=this.url_browse_time_table[e]&&(this.url_browse_time_table[e].time_created=new Date)},On_Tab_Replaced(e,t){this.url_browse_time_table[t]!=undefine&&(this.SaveCacheLog(t),this.DeleteUrlBrowseTimeItem(t)),this.current_tab_id=e},OnTabUpdated(e,t,i){if(t.startsWith("chrome://newtab/")||t.startsWith("data:text/html")||t.startsWith("chrome-extension"))e in this.url_browse_time_table&&this.DeleteUrlBrowseTimeItem(e);else if(e in this.chrome_tabs_status&&(this.chrome_tabs_status[e].bar_url=t),void 0==this.url_browse_time_table[e]||this.url_browse_time_table[e].url!=t){let i=this.ignore_pages.some(e=>t.startsWith(e));i||(i=this.re_ignore_pages.some(e=>e.test(t))),i||(i=t.startsWith(r.authserverurl)),i||e in this.url_browse_time_table&&(this.SaveCacheLog(e),this.url_browse_time_table[e].url=t,this.url_browse_time_table[e].time_created=new Date)}},prepareCustomizedBanWordPage(e,t,r,i){let s,o,a,l,c;try{const e=(new DOMParser).parseFromString(t,"text/html");e.title="Search Result Blocked";const r=e.getElementById("msg_text");r.innerText=r.innerText.replace(/URL/,"Search Result");const i=e.getElementsByClassName("reeval")[0];i&&i.parentElement.removeChild(i),t=(new XMLSerializer).serializeToString(e)}catch(e){n.LogError(`Error when on prepareCustomizedBanWordPage: ${e}`)}s=(s=(s=(s=(s=t.replace(/%CODEPAGE%/g,"charset=UTF-8")).replace(/%PRODUCTNAME%/g,"FortiClient")).replace(/%URL%/g,r)).replace(/%REASON_CATEGORY%/g,i)).replace(/%ENCODED_URL%/g,r),o=new RegExp('<a href="http://%HOST%%BYPASS_URL%"><div class="button">(.+?)</div></a>'),void 0!==(a=s.match(o))&&null!=a&&(l='<div class="button" id="button_proceed" style="cursor: pointer;">',l+=a[1],l+="</div>",s=s.replace(o,l));let h,_=new Date,g=(_=new Date(_.getTime()+this.warning_timeout)).getHours();h=g>=12?"PM":"AM",g>12&&(g-=12),c=g>=10?g:"0"+g,c+=":";let u=_.getMinutes();c+=u>=10?u:"0"+u,c+=":";let d=_.getSeconds();return c+=d>=10?d:"0"+d,c+=" "+h,s=s.replace(/%REBLOCK_TIME%/g,c)},PrepareCustomizedPage(e,t,r,i){let s,o,a,n,l;s=(s=(s=(s=(s=(s=t.replace(/%CODEPAGE%/g,"charset=UTF-8")).replace(/%PRODUCTNAME%/g,"FortiClient")).replace(/%URL%/g,r)).replace(/%REASON_CATEGORY%/g,i)).replace(/%SUBMISSIONURL%/g,"http://url.fortinet.net/rate/submit.php?")).replace(/%ENCODED_URL%/g,encodeURI(r)),o=new RegExp('<a href="http://%HOST%%BYPASS_URL%"><div class="button">(.+?)</div></a>'),void 0!==(a=s.match(o))&&null!=a&&(n='<input type="button" value="',n+=a[1],n+='" id="button_proceed">',s=s.replace(o,n));let c,h=new Date,_=(h=new Date(h.getTime()+this.warning_timeout)).getHours();c=_>=12?"PM":"AM",_>12&&(_-=12),l=_>10?_:"0"+_,l+=":";let g=h.getMinutes();l+=g>10?g:"0"+g,l+=":";let u=h.getSeconds();return l+=u>10?u:"0"+u,l+=" "+c,s=s.replace(/%REBLOCK_TIME%/g,l)},SetTabsStatusCustomizedPage(e,t){e in this.chrome_tabs_status&&(this.chrome_tabs_status[e].action===this.ACTION.BLOCK||this.chrome_tabs_status[e].keywordAction===this.ACTION.BLOCK?this.chrome_tabs_status[e].customized_page=t:e in this.unresolved_warn_page||this.chrome_tabs_status[e].action!==this.ACTION.WARN||(this.unresolved_warn_page[e]=!0,this.chrome_tabs_status[e].customized_page=t))},TabsStatusUpdate(e,t){const{action:r,keywordAction:i}=t;if(!(e in this.chrome_tabs_status))return;n.LogDebug(`WebFilterProcess - TabsStatusUpdate - UPDATING ${e}`);let s=t;e in this.unresolved_warn_page&&null!==this.chrome_tabs_status[e].rating&&(delete s.rating,delete s.action);for(const[t,r]of Object.entries(s))if(void 0!==r){const i=this.chrome_tabs_status[e][t];i!==r&&(this.chrome_tabs_status[e][t]=r,n.LogDebug(`WebFilterProcess - TabsStatusUpdate - UPDATED ${t} - old:${i} , new: ${r}`))}if(r===this.ACTION.BLOCK||r===this.ACTION.WARN||i===this.ACTION.BLOCK||i===this.ACTION.WARN){let t=new Date(Date.now()+this.warning_timeout);this.chrome_tabs_status[e].time=t}},TabsStatusUpdate2(e,t="",i=0,s=0,o=null,a=null,n=!1,l="",c="",h=!1,_=!1){if(!(e in this.chrome_tabs_status))return;if(this.IsCategoryInIgnoreList(s)&&i===this.ACTION.WARN)return;let g=!1,u=this.chrome_tabs_status[e].action;if(r.async_mode?r.main_url_rate_only?this.chrome_tabs_status[e].bar_url===t&&(g=!0):u!==this.ACTION.BLOCK&&u!==this.ACTION.WARN&&(g=!0):u!==this.ACTION.WARN&&(g=!0),i||(this.chrome_tabs_status[e].isSearchQuery=n,this.chrome_tabs_status[e].searchEngine=l,this.chrome_tabs_status[e].entry=c,this.chrome_tabs_status[e].isBlockedSearch=h,this.chrome_tabs_status[e].isBlockedSearchSuggestion=_),g&&(i===this.ACTION.BLOCK||i===this.ACTION.WARN||o===this.ACTION.BLOCK||o===this.ACTION.WARN)){let r=new Date(Date.now()+this.warning_timeout);this.chrome_tabs_status[e].action=i,this.chrome_tabs_status[e].url=t,this.chrome_tabs_status[e].time=r,this.chrome_tabs_status[e].rating=s,a&&(this.chrome_tabs_status[e].keywordRating=a),o&&(this.chrome_tabs_status[e].keywordAction=o),l.length&&(this.chrome_tabs_status[e].isSearchQuery=n,this.chrome_tabs_status[e].searchEngine=l,this.chrome_tabs_status[e].isBlockedSearch=h,this.chrome_tabs_status[e].isBlockedSearchSuggestion=_,this.chrome_tabs_status[e].entry=c)}g&&i===this.ACTION.MONITOR&&n&&a&&(this.chrome_tabs_status[e].keywordRating=a)},TabsStatusUpdateUrl(e,t,r=null){e in this.chrome_tabs_status&&(this.chrome_tabs_status[e].bar_url=t,r&&(this.chrome_tabs_status[e].url=r))},ReportUrlAction(e,t,i,s,o,a){(void 0!=this.url_browse_time_table[e]&&this.url_browse_time_table[e].url==t||r.log_all_URLs)&&(2==i?n.CacheLogWarning(t,"blocked",n.LOG_ACTION_TYPE.BLOCKED,0,s,o):3!=i||this.IsCategoryInIgnoreList(a)?1==i&&r.log_all_URLs&&n.CacheLogInfo(t,"passthrough",n.LOG_ACTION_TYPE.PASSTHROUGH,"N/A",s,o):n.CacheLogWarning(t,"blocked",n.LOG_ACTION_TYPE.BLOCKED,0,s,o),void 0==this.url_browse_time_table[e]||this.url_browse_time_table[e].url!=t||this.url_browse_time_table[e].monitor_this_page||this.monitor_all_page||this.DeleteUrlBrowseTimeItem(e))},ComputerIdleDetect(){if(this.mouse_move){let e;(e=new Date-this.last_move_time)>=this.idle_timeout&&(null!=this.current_tab_id&&this.SaveCacheLog(this.current_tab_id),this.mouse_move=!1)}},SetMode(e){let t;t=this,0==e?0!=this.block_timer&&(clearInterval(this.block_timer),this.block_timer=0):0==this.block_timer&&(this.block_timer=setInterval(function(){t.BlockTabTimer()},500))},setLocalIP(){let e=[],t=new(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection)({iceServers:[]});t.createDataChannel(""),t.onicecandidate=(r=>{if(!r.candidate)return t.close(),n.LogDebug("WebFilterProcess - setLocalIP - Candidate gathering completed. IP addresses:",`color:${n.FORTINET_COLOR.GREEN}`),void n.LogDebug(e.join("\n\t\t\t\t\t\t "));let i=/^candidate:.+ (\S+) \d+ typ/.exec(r.candidate.candidate)[1];-1==e.indexOf(i)&&(e.push(i),this.local_IP=i)}),t.createOffer(e=>{t.setLocalDescription(e)},()=>{})},setWebRequestListeners(){chrome.webRequest.onBeforeRequest.addListener(e=>this.OnBeforeWebRequest(e),{urls:["<all_urls>"]},["blocking"]),chrome.webRequest.onCompleted.addListener(e=>this.OnCompleted(e),{urls:["<all_urls>"]},["responseHeaders"]),chrome.webRequest.onBeforeSendHeaders.addListener(e=>this.onBeforeSendHeaders(e),{urls:["<all_urls>"]},["blocking","requestHeaders"])},setTabsListeners(){chrome.tabs.onUpdated.addListener((e,t,r)=>{if("url"in t&&!t.url.startsWith("chrome-extension")&&e in this.unresolved_warn_page&&delete this.unresolved_warn_page[e],e!==this.goBackTabId&&e in this.chrome_tabs_status&&this.chrome_tabs_status[e].searchEngine&&"loading"===t.status&&"url"in t&&this.supportedDynamicSites.some(e=>e.test(r.url))){const t=this.getBaseURL(r.url);this.TabsStatusUpdateUrl(e,r.url,t),this.MonitorSearch(r.url,this.CUSTOM_TYPE.TAB_UPDATE,e,t),chrome.tabs.sendMessage(e,{isSearchQuery:this.chrome_tabs_status[e].isSearchQuery,searchEngine:this.chrome_tabs_status[e].searchEngine,matchSearchSuggestion:g.config.matchSearchSuggestion})}this.goBackState===this.GO_BACK_STATE.LOADING&&this.goBackTabId===e&&("complete"===t.status&&this.goBackResolve?this.goBackResolve():r.url.startsWith("chrome")||chrome.tabs.insertCSS(e,{code:"body { visibility: hidden; }",runAt:"document_start"})),this.OnTabUpdated(e,r.url,t.status),this.window_created=!0}),chrome.tabs.onRemoved.addListener(e=>{e in this.unresolved_warn_page&&delete this.unresolved_warn_page[e],this.OnTabRemoved(e)}),chrome.tabs.onCreated.addListener(e=>{this.window_created=!0}),chrome.tabs.onActivated.addListener(e=>{this.OnTabActivated(e.tabId),this.window_created=!0}),chrome.tabs.onReplaced.addListener((e,t)=>{t in this.chrome_tabs_status&&delete this.chrome_tabs_status[t],this.window_created=!0}),chrome.tabs.onHighlighted.addListener(e=>{this.window_created=!0})},initOnlineDetectors(){this.setOfflineListener();const e=(t,r)=>t().finally(()=>setTimeout(()=>e(t,r),r));e(this.OnlineDetector,this.CHECK_ONLINE_INTERVAL)},isSearchQuery(e,t){if(t){const{isSearchQuery:r,searchEngine:i}=t;e({isSearchQuery:r,searchEngine:i,matchSearchSuggestion:g.config.matchSearchSuggestion})}},setLogLevel(e){let t;switch(e){case"Error":t=4;break;case"Info":t=7;break;case"Debug":t=8;break;default:t=0}n.SetLogLevel(t)},evaluateLinks(e,t,r,i){n.LogDebug("From Content Script - Rate this search: "+t);let s=!1;i.isBlockedSearch||(s=this.MonitorSearch(t,this.CUSTOM_TYPE.SEARCH_SUGGEST,r,i.url,e)),e({found:s})},config(e,t,i){let s=0;"async"===e&&(s=1,r.main_url_rate_only=i),r.safesearch="1"==t,h.set_mode(s),this.SetMode(s)},showConfig(e){const t={mode:"sync"};r.async_mode&&(t.mode="async",t.main_url_rate_only=!1,r.main_url_rate_only&&(t.main_url_rate_only=!0)),t.safe_search="0",r.safesearch&&(t.safe_search="1"),e(t)},showLongConfig(e){let t;const i={mode:"sync"};r.async_mode&&(i.mode="async",i.main_url_rate_only=!1,r.main_url_rate_only&&(i.main_url_rate_only=!0)),i.profileserverurl=r.profileserverurl,i.authserverurl=r.authserverurl,i.ratingserverurl=r.ratingserverurl,t="monitor",1==l.default_action?t="allow":2==l.default_action?t="block":3==l.default_action&&(t="warning"),i.defaultaction=t,i.safesearch="0",r.safesearch&&(i.safesearch="1"),e(i)},mouseEvent(e,t,r){e({}),this.SetMouseMoveEvent(r)},getWarningWebPageInfo(e,t){const r={rating_url:"",home_url:"",category:"",keywordCategory:"",time:"",rating:0,keywordRating:0,isBlockedSearch:!1,entry:""};if(t){let e,i,s;const{url:o,bar_url:a,rating:n,keywordRating:l,isBlockedSearch:c,entry:_,time:u}=t;n&&(r.rating=n),l&&(r.keywordRating=l),r.rating_url=o,r.home_url=a,r.category=h.get_rating_info(n),r.keywordCategory=g.getRatingInfo(l),r.isBlockedSearch=c,r.entry=_,u&&(e=i=(s=u).getHours(),i>12&&(e=i-12),e+=":",e+=s.getMinutes(),e+=":",e+=s.getSeconds(),e+=i>=12?" PM.":" AM.",r.time=e)}e(r)},blockWarningPage(e,t){let{isSearchQuery:r,isBlockedSearchSuggestion:i}=t;e({isSearchQuery:r,isBlockedSearchSuggestion:i})},warningBypass(e,t){let{time:r,action:i,rating:s,keywordAction:o,keywordRating:a}=t;o===this.ACTION.WARN&&(delete this.unresolved_warn_page[e],g.warningBypass(r,a)),i===this.ACTION.WARN&&(delete this.unresolved_warn_page[e],this.AddIgnoreCategory(r,s))},setMessageListener(){chrome.runtime.onMessage.addListener((e,t,i)=>{const s=t.tab.id,o=this.chrome_tabs_status[s];switch(e.action){case"loginagain":i({action:"done"}),this.OnRelogin();break;case"setloglevel":this.setLogLevel(e.level);break;case"clearcache":h.clear_cache();break;case"isSearchQuery":this.isSearchQuery(i,o);break;case"evaluateLinks":this.evaluateLinks(i,e.payload,s,o);break;case"setmode":this.config(e.mode,e.safe_search,e.main_url_rate_only);break;case"config_request":this.showConfig(i);break;case"list_config_request":this.showLongConfig(i);break;case"mouse_move":case"mouse_wheel":this.mouseEvent(i,e.action,e.url);break;case"get_warning_web_page_info":this.getWarningWebPageInfo(i,o);break;case"block_warning_page":this.blockWarningPage(i,o);break;case"get_customized_web_page":i({customized_page:o?o.customized_page:"",action:o?o.action:0});break;case"get_safesearch_config":i({safesearch:r.safesearch?1:0});break;case"set_ignore_category":this.warningBypass(s,o);break;case"refresh_token_revoke":chrome.tabs.create({url:"https://security.google.com/settings/security/permissions",active:!0}),i({action:"refresh_token_revoke is done"});break;case"get_last_error":i({error:this.lasterr[s]});break;default:n.LogError(`Unknown message action: ${e.action}`)}})},removeClientTokenFromCloudStorage:()=>new Promise((e,t)=>{chrome.storage.sync.remove("client_token",()=>{chrome.runtime.lastError?(n.LogError("WebFilterProcess - removeClientTokenFromCloudStorage - Failed to remove client token from cloud."),t()):e()})}),getClientTokenFromCloudStorage:()=>new Promise((e,t)=>{chrome.storage.sync.get("client_token",r=>{chrome.runtime.lastError?(n.LogError("WebFilterProcess - getClientTokenFromCloudStorage - Failed to retrieve client token from cloud."),t()):e(r.client_token)})}),getTokenCode(){const e=`${r.cloud_emsurl}fct/api/public/v1/endpoints/`,t=JSON.stringify({client_id:this.id_token,invitation_code:r.invitation_code});return fetch(e,{method:"POST",body:t}).then(e=>e.ok?e.json():{status:e.status,statusText:e.statusText})},async getEMSServerList(){if(!r.cloud_mode)return;let e=await this.getClientTokenFromCloudStorage();if(!e)try{const t=await this.getTokenCode();if(!("client_token"in t))throw new Error(`Cannot retrieve EMS address from cloud: ${t.status} ${t.statusText}`);e=t.client_token}catch(e){throw new Error(e.message)}this.makeServerUrl(e)},makeServerUrl(e){r.profileserverurl=`https://fct-${this.id_token}-${e}-8443.${r.serial_number}.forticlient-emsproxy.forticloud.com`}},s=()=>{n.LogInfo("Initializing FortiClient Chromebook WebFilter."),l.profile_load(),h.loadLocalStorage(),g.loadLocalStorage(),i.setLocalIP(),i.setWebRequestListeners(),i.setTabsListeners(),i.GetConfig(),i.initOnlineDetectors(),window.addEventListener("beforeunload",()=>{i.TokenRevoke()});const e=chrome.runtime.getManifest();i.ext_version=e.version,i.setMessageListener(),r.async_mode&&(i.block_timer=setInterval(()=>{i.BlockTabTimer()},i.INTERVAL_SECOND/2))},o=e=>{i.platforminfo=e.os+" "+e.arch,i.platforminfo_os=e.os,("cros"===i.platforminfo_os||i.test)&&s()},a=()=>{chrome.runtime.getPlatformInfo(o)};document.addEventListener("DOMContentLoaded",()=>{const e=chrome.runtime.getManifest();i.ext_version=e.version;const t=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 619.8 71.1" enable-background="new 0 0 619.8 71.1">\n <style type="text/css">\n .st3 {\n fill: #768692;\n }\n\n .st4 {\n fill: #DA291C;\n }\n </style>\n <path class="st3" d="M0 70.4V.8h76.8v15.5H17v11.8h51.5v15H17v27.3H0zM257 70.4V46.7c0-2.1-1.8-3-1.8-3-.8-.5-3.2-.6-6.8-.6h.8-35.8v27.4h-17V.8h53c9.2 0 15.5 1.4 19.8 5.6 4.3 4.4 4.8 10.1 4.9 16v5c.1 5-2.6 9.6-5.8 12.3l.6.3c1.3.6 2 1.5 2 1.5 2.4 3.1 2.4 5.7 2.4 9v19.9H257zm-9.2-42.3c4.2 0 6.6 0 7.6-.6 0 0 1.7-1 1.8-3v-4.6c0-2.1-1.8-3-1.8-3-1.3-.7-3.6-.6-8.9-.6h-33.1v11.8h35.1-.7zM299 70.4V16.3h-16V.8h63.8v15.5H316v54.1h-17zm4.4-58.5V9.6v2.3zM567.6 70.4V16.3h-16V.8h63.8v15.5h-30.8v54.1h-17zm4.3-58.5V9.6v2.3zM355.2 70.4V.8h17v69.6h-17zM474.6 70.4V.8h68.5v15.5h-51.5v11.8h35.8v15h-35.8v11.8h51.9v15.5h-68.9zM402 70.4h-17.1V.8h54.9s10.1-.4 16.4 5.9c0 0 6.5 5.5 6.5 18.8v44.9h-17v-46s.2-4.7-1.4-6.3c0 0-1.4-1.8-4.1-1.8H402v54.1zM611.4 70.3c-4.7 0-8.4-3.8-8.4-8.4 0-4.6 3.8-8.4 8.4-8.4 4.6 0 8.4 3.8 8.4 8.4 0 4.7-3.7 8.4-8.4 8.4zm0-15.8c-4.1 0-7.4 3.3-7.4 7.5 0 4.1 3.3 7.4 7.4 7.4 4.1 0 7.4-3.3 7.4-7.4.1-4.2-3.3-7.5-7.4-7.5zm-3.1 2.5h4.1c1.4 0 2.8.3 3 2.4 0 1.2-.3 1.6-1.2 2.3 1 .6 1 .8 1.1 2.4.1 1.2-.1 1.4.4 2.2h-1.4l-.2-1.2c-.2-1.1.3-2.8-1.6-2.8h-3v4h-1.2V57zm1.2 1.1v3.2h3c.8 0 1.6-.2 1.7-1.4.2-1.6-1-1.8-1.7-1.8h-3z"></path>\n <path class="st4" d="M84.3 26.3h28.2v18.5H84.3zM120.3 0H148v18.5h-27.7zM120.3 52.5H148V71h-27.7zM155.7 26.3H184v18.5h-28.3zM95.9 0C90 1.5 85.4 8.1 84.3 16.5v2.1h28.2V0H95.9zM84.3 52.5v2.3c1 8 5.3 14.4 10.9 16.2h17.4V52.5H84.3zM184 18.5v-2.1c-1.1-8.3-5.7-14.9-11.6-16.5h-16.7v18.5H184zM173.1 71.1c5.5-1.9 9.8-8.2 10.9-16.2v-2.3h-28.3v18.5h17.4z"></path>\n</svg>')}`;console.log("%c ",`\n background-image: url(${t});\n padding-bottom: 20px;\n padding-left: 205px;\n background-size: auto;\n background-position: center center;\n background-repeat: no-repeat;\n`);const r="color:#768692; font-weight:bolder;";console.log("%c%s",r,"FortiClient Chromebook WebFilter"),console.log("%c%s",r,"Copyright © 2020 Fortinet, Inc."),console.log("%c%s",r,`Version ${i.ext_version}`),a()});const n={STATE:{IDLE:0,PENDING:1,SUCCESS:2,ERROR:3},ACTION:{INIT:0,CONTINUE:1,RETRY:2},LOG_TYPE:{NONE:-1,EMERGENCY:0,ALERT:1,CRITICAL:2,ERROR:3,WARNING:4,NOTICE:5,INFO:6,DEBUG:7},loglevel:7,cache_log:[],cache_fazlog:[],LOG_ACTION_TYPE:{PASSTHROUGH:0,USERBROWSED:1,BLOCKED:2},timer_id:null,fazlog_timer_id:null,fazlog_retry_timer_id:null,fazlog_continue_timer_id:null,emslog_continue_timer_id:null,save_faz_logs_timer:null,remove_expired_faz_logs_timer:null,remove_expired_ems_logs_timer:null,faz_state:0,ems_state:0,device_id:0,rpc_id:0,data:"",count:0,enable_fazlog:!1,cached_fazlog_dirty:!1,cached_emslog_dirty:!1,compress_content:!1,policyName:null,log_retention:90,fazlog_send_interval:3e5,fazlog_retry_send_interval:3e4,fazlog_continue_send_interval:2e3,fazlog_backup_interval:6e5,fazlog_retry_times:0,fazlog_max_size:32768,emslog_max_size:16384,exponential_ceiling:5,exponential_index:0,session:"",apiver:1,FORTINET_COLOR:{GREEN:"#00BF65",DARK_GREEN:"#004E42",BLUE:"#0071CE",DARK_BLUE:"#002D74",TEAL:"#6AD1E3",DARK_TEAL:"#003E51",CRIMSON:"#BF2426",DARK_RED:"#651D32",PURPLE:"#9164CC",DARK_PURPLE:"#24135F",ORANGE:"#FF8200",YELLOW:"#FFD100",LIGHT_GREY:"#D9E1E2",GREY:"#768692",DARK_GREY:"#253746",BLACK:"#131E29"},Init:function(){var e,t,r;e=this,this.faz_state=this.STATE.IDLE,this.ems_state=this.STATE.IDLE;try{if(localStorage.faz_logs&&(this.cache_fazlog=JSON.parse(localStorage.faz_logs),0!=(r=this.cache_fazlog.length)))for(t=0;t<r;t++)this.cache_fazlog[t].date=new Date(this.cache_fazlog[t].date)}catch(t){e.LogError("failed to get cached faz logs")}try{if(localStorage.ems_logs&&(this.cache_log=JSON.parse(localStorage.ems_logs),0!=(r=this.cache_log.length)))for(t=0;t<r;t++)this.cache_log[t].date=new Date(this.cache_log[t].date)}catch(t){e.LogError("failed to get cached ems logs")}this.timer_id=setInterval(function(){e.SendoutCachedLog(e.ACTION.INIT)},3e5),this.emslog_continue_timer_id=setInterval(function(){e.SendoutCachedLog(e.ACTION.CONTINUE)},2e3),this.remove_expired_ems_logs_timer=setInterval(function(){e.remove_expired_ems_logs()},36e5),this.fazlog_timer_id=setInterval(function(){e.SendoutFAZCachedLog(e.ACTION.INIT)},this.fazlog_send_interval),this.fazlog_continue_timer_id=setInterval(function(){e.SendoutFAZCachedLog(e.ACTION.CONTINUE)},this.fazlog_continue_send_interval),this.save_faz_logs_timer=setInterval(function(){e.save_cached_faz_logs()},this.fazlog_backup_interval),this.remove_expired_faz_logs_timer=setInterval(function(){e.remove_expired_faz_logs()},36e5)},Uninit:function(){null!=this.timer_id&&(clearInterval(this.timer_id),this.timer_id=null),this.emslog_continue_timer_id&&(clearInterval(this.emslog_continue_timer_id),this.emslog_continue_timer_id=null),this.remove_expired_ems_logs_timer&&(clearInterval(this.remove_expired_ems_logs_timer),this.remove_expired_ems_logs_timer=null),this.remove_expired_ems_logs_timer&&(clearInterval(this.remove_expired_ems_logs_timer),this.remove_expired_ems_logs_timer=null),this.fazlog_timer_id&&(clearInterval(this.fazlog_timer_id),this.fazlog_timer_id=null),this.fazlog_continue_timer_id&&(clearInterval(this.fazlog_continue_timer_id),this.fazlog_continue_timer_id=null),this.fazlog_retry_timer_id&&(clearInterval(this.fazlog_retry_timer_id),this.fazlog_retry_timer_id=null),this.save_faz_logs_timer&&(clearInterval(this.save_faz_logs_timer),this.save_faz_logs_timer=null),this.remove_expired_faz_logs_timer&&(clearInterval(this.remove_expired_faz_logs_timer),this.remove_expired_faz_logs_timer=null)},SetFAZSendingInterval:function(e){var t=this;this.fazlog_send_interval=60*e*1e3,this.fazlog_timer_id&&clearInterval(this.fazlog_timer_id),this.fazlog_timer_id=setInterval(function(){t.SendoutFAZCachedLog(t.ACTION.INIT)},this.fazlog_send_interval)},SetFAZBackupInterval:function(e){var t=this;this.fazlog_backup_interval=1e3*e,this.save_faz_logs_timer&&clearInterval(this.save_faz_logs_timer),this.save_faz_logs_timer=setInterval(function(){t.save_cached_faz_logs()},this.fazlog_backup_interval)},LaunchFAZRetryTimer:function(){var e,t,r=this;this.exponential_index<this.exponential_ceiling&&this.exponential_index++,t=Math.pow(2,this.exponential_index),e=this.GetRandomInt(100,1e3*t),this.LogDebug("max interval:"+t+",random interval:"+e),setTimeout(function(){r.SendoutFAZCachedLog(r.ACTION.RETRY)},e)},PayloadAssemble:function(){var e={jsonrpc:"2.0",method:"add",id:this.rpc_id.toString(),session:this.session,params:[{uri:"/faz/logview/logs",apiver:this.apiver,vdom:"root","data-type":"text",devid:this.device_id,count:this.count,data:this.data}]};this.rpc_id++;var t=JSON.stringify(e),r={data:t,compressed:!1};if(this.compress_content){var i=require("lz4"),s=require("buffer").Buffer,o=new s(t),a=new s(i.encodeBound(o.length)),n=i.encodeBlock(o,a);n>0&&(a=(a=a.toArrayBuffer()).slice(0,n),this.LogDebug("output:"+a),r.data=a,r.compressed=!0)}return r},RemoveEMSSentRecords:function(){var e,t,r=0;if(0!=(e=this.cache_log.length)){for(t=0;t<e&&1==this.cache_log[t].state;t++)r++;r>0&&(this.cache_log.splice(0,r),this.cached_emslog_dirty=!0)}},RemoveFAZSentRecords:function(){var e,t,r=0;if(0!=(e=this.cache_fazlog.length)){for(t=0;t<e&&1==this.cache_fazlog[t].state;t++)r++;r>0&&(this.cache_fazlog.splice(0,r),this.cached_fazlog_dirty=!0)}},GetSecureRandom:function(){var e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]},GetRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(this.GetSecureRandom()%(t-e))+e},SendoutFAZCachedLog:function(e){var t,i,s,o;if(this.enable_fazlog){if(e==this.ACTION.INIT){if(this.faz_state!=this.STATE.IDLE)return}else if(e==this.ACTION.CONTINUE){if(this.faz_state!=this.STATE.SUCCESS)return}else if(e==this.ACTION.RETRY&&this.faz_state!=this.STATE.ERROR)return;if(e!=this.ACTION.RETRY){if(0==(t=this.cache_fazlog.length))return;for(this.fazlog_retry_times=0,this.count=0,i=0;i<t;i++){var a;if(0==i?a=this.cache_fazlog[i].log.length:(a=this.data.length,a+=this.cache_fazlog[i].log.length+1),a>=this.fazlog_max_size)break;0==i?this.data=this.cache_fazlog[i].log:this.data+="\n"+this.cache_fazlog[i].log,this.cache_fazlog[i].state=1,this.count++}}s=(o=this.PayloadAssemble()).data;var l,c=new XMLHttpRequest;l=r.fazserverurl;try{c.open("POST",l,!0),c.setRequestHeader("Content-type","application/json"),o.compressed&&c.setRequestHeader("Content-Encoding","lz4"),c.timeout=1e4,c.ontimeout=function(){n.LogDebug("request user information timed out."),delete c,n.LogDebug("sending faz logs timeout")},c.onload=(e=>{200===c.status?(n.LogDebug("logs are sent to FortiAnalyzer successfully"),this.RemoveFAZSentRecords(),this.save_cached_faz_logs(),this.faz_state=this.STATE.IDLE,this.exponential_index=0,0!=this.cache_fazlog.length&&(this.faz_state=this.STATE.SUCCESS)):(n.LogError("Sending faz logs get error status, error:"+c.statusText),delete c,this.faz_state=this.STATE.ERROR,c.abort(),this.LaunchFAZRetryTimer())}),c.send(s),this.faz_state=this.STATE.PENDING}catch(e){this.LogError("Failed to send logs to FortiAnalyzer, error: "+e.message),delete c,this.faz_state=this.STATE.ERROR,this.LaunchFAZRetryTimer()}}},RetrySendoutFAZCachedLog:function(){var e,t,i=this;if(this.enable_fazlog&&this.faz_state==this.STATE.ERROR){e=(t=this.PayloadAssemble()).data;var s,o=new XMLHttpRequest;s=r.fazserverurl;try{o.open("POST",s,!0),o.setRequestHeader("Content-type","application/json"),t.compressed&&o.setRequestHeader("Content-Encoding","lz4"),o.timeout=1e4,o.ontimeout=function(){n.LogDebug("request user information timed out."),delete o,i.faz_state=i.STATE.ERROR,i.fazlog_retry_times++},o.onload=(e=>{200===o.status?(n.LogDebug("logs are sent to FortiAnalyzer successfully"),this.RemoveFAZSentRecords(),this.save_cached_faz_logs(),this.faz_state=this.STATE.IDLE,0!=this.cache_fazlog.length&&(this.faz_state=this.STATE.SUCCESS)):(n.LogError("Error happened when sending log to FAZ"),delete o,this.faz_state=this.STATE.ERROR,this.fazlog_retry_times++)}),o.send(e),this.faz_state=this.STATE.PENDING}catch(e){i.LogError("Failed to resend logs to FortiAnalyzer, error: "+e.message),delete o,i.faz_state=i.STATE.ERROR,i.fazlog_retry_times++}}},SendoutCachedLog:function(e){var t,s,o,a,l,c=[];if(e==this.ACTION.INIT){if(this.ems_state!=this.STATE.IDLE)return}else if(e==this.ACTION.CONTINUE&&this.ems_state!=this.STATE.SUCCESS)return;if(l=this,0!=(a=this.cache_log.length)){for(o=0;o<a;o++)1==this.cache_log[o].state&&(this.cache_log[o].state=0);for(o=0;o<a&&(t=JSON.stringify(c),s=JSON.stringify(this.cache_log[o].log),t.length+s.length<this.emslog_max_size);o++)this.cache_log[o].state=1,c.push(this.cache_log[o].log);t=JSON.stringify(c);var h,_=new XMLHttpRequest;h=r.no_auth_server?r.profileserverurl+"/userid-log":r.profileserverurl+"/token-log",_.open("POST",h,!0),_.setRequestHeader("Content-type","application/json"),r.no_auth_server?_.setRequestHeader("UserID",i.id_token):_.setRequestHeader("Token",i.id_token),this.ems_state=l.STATE.PENDING,_.timeout=1e4,_.ontimeout=function(){n.LogDebug("request user information timed out."),delete _,l.ems_state=l.STATE.IDLE},_.onload=(e=>{200===_.status?(n.LogDebug("monitored logs are sent successfully"),this.RemoveEMSSentRecords(),this.save_cached_ems_logs(),this.ems_state=this.STATE.IDLE,0!=this.cache_log.length&&(this.ems_state=this.STATE.SUCCESS)):(n.LogError("Error happened when sending log to EMS"),this.ems_state=this.STATE.IDLE)}),_.send(t)}},SetLogLevel:function(e){e>=this.LOG_TYPE.NONE&&e<=this.LOG_TYPE.DEBUG&&(this.loglevel=e)},LogDebug:function(e,t=null){if(this.loglevel>=this.LOG_TYPE.DEBUG)if(t)this.PrintLog(this.LOG_TYPE.DEBUG,e,t);else{const t="color:"+this.FORTINET_COLOR.GREY;this.PrintLog(this.LOG_TYPE.DEBUG,e,t)}},LogInfo:function(e,t=null){this.loglevel>=this.LOG_TYPE.INFO&&(t?this.PrintLog(this.LOG_TYPE.INFO,e,t):this.PrintLog(this.LOG_TYPE.INFO,e))},LogWarn:function(e,t=null){if(this.loglevel>=this.LOG_TYPE.NOTICE)if(t)this.PrintLog(this.LOG_TYPE.WARN,e,t);else{const t="color:"+this.FORTINET_COLOR.ORANGE;this.PrintLog(this.LOG_TYPE.WARN,e,t)}},LogError:function(e,t=null){if(this.loglevel>=this.LOG_TYPE.ERROR)if(t)this.PrintLog(this.LOG_TYPE.ERROR,e,t);else{const t="color:"+this.FORTINET_COLOR.CRIMSON;this.PrintLog(this.LOG_TYPE.ERROR,e,t)}},PrintLog:function(e,t,r=""){const i=this.GenerateTimeString();let s,o;switch(e){case this.LOG_TYPE.DEBUG:o="DEBUG",s="color:"+this.FORTINET_COLOR.GREY;break;case this.LOG_TYPE.INFO:o="INFO",s="color:"+this.FORTINET_COLOR.GREEN;break;case this.LOG_TYPE.WARN:o="WARN",s="color:"+this.FORTINET_COLOR.ORANGE;break;case this.LOG_TYPE.ERROR:o="ERROR",s="color:"+this.FORTINET_COLOR.CRIMSON;break;default:o="",s=""}s="font-weight:bold;"+s;const a=`color:${this.FORTINET_COLOR.GREY}`;console.log("%c%s %c%s %c%s",a,i,s,o,r,t)},Group(e,t,r=!0){if(this.loglevel>=e){let i,s;switch(e){case this.LOG_TYPE.DEBUG:i="DEBUG",s="color:"+this.FORTINET_COLOR.GREY;break;case this.LOG_TYPE.INFO:i="INFO",s="color:"+this.FORTINET_COLOR.GREEN;break;case this.LOG_TYPE.WARN:i="WARN",s="color:"+this.FORTINET_COLOR.ORANGE;break;case this.LOG_TYPE.ERROR:i="ERROR",s="color:"+this.FORTINET_COLOR.CRIMSON;break;default:i="",s=""}const o=this.GenerateTimeString(),a=`color:${this.FORTINET_COLOR.GREY}`,n="font-weight:bolder;"+s,l="font-weight:normal;";r?console.groupCollapsed("%c%s %c%s %c%s",a,o,n,i,l,t):console.group("%c%s %c%s %c%s",a,o,n,i,l,t)}},GroupEnd(e){this.loglevel>=e&&console.groupEnd()},CacheLogInfo:function(e,t,r,i,s,o){this.CacheLog(e,t,r,i,"info",s,o)},CacheLogWarning:function(e,t,r,i,s,o){this.CacheLog(e,t,r,i,"warning",s,o)},CacheLogWarn:function(e,t,r,i,s,o){this.CacheLog(e,t,r,i,"notice",s,o)},GenerateTimeString:function(){var e,t,r,i,s;return myDate=new Date,e=myDate.getMonth()+1<10?"0"+String(myDate.getMonth()+1):String(myDate.getMonth()+1),t=myDate.getDate()<10?"0"+String(myDate.getDate()):String(myDate.getDate()),r="",myDate.getHours()<10&&(r="0"),r+=String(myDate.getHours()),i="",myDate.getMinutes()<10&&(i="0"),i+=String(myDate.getMinutes()),s="",myDate.getSeconds()<10&&(s="0"),s+=String(myDate.getSeconds()),myDate.getFullYear()+"-"+e+"-"+t+" "+(r+":"+i+":"+s)},CacheLog:function(e,t,r,s,o,a,n){var l,c,h,_,g,u,d,m,f,b,p,T,S=new Date,L=chrome.runtime.getManifest(),E={},I={},O=/(\w+):\/\/([\w.\-]+)(:\d*)?(\/.*)/i.exec(e),v=!1;if(u=O[1],g=O[2],void 0===O[3]?"http"==u?_=80:"https"==u&&(_=443):_=O[3].substring(1),d=6e4*S.getTimezoneOffset()+S.getTime(),m=(S=new Date(d)).getMonth()+1<10?"0"+String(S.getMonth()+1):String(S.getMonth()+1),f=S.getDate()<10?"0"+String(S.getDate()):String(S.getDate()),b="",S.getHours()<10&&(b="0"),b+=String(S.getHours()),p="",S.getMinutes()<10&&(p="0"),p+=String(S.getMinutes()),T="",S.getSeconds()<10&&(T="0"),T+=String(S.getSeconds()),(l=S.getFullYear()+"-"+m+"-"+f)+" "+(c=b+":"+p+":"+T),r==this.LOG_ACTION_TYPE.BLOCKED&&(v=!0,E.date=l,E.time=c,E.level=o,E.remotename=g,E.dstport=Number(_),E.user=i.email,E.utmaction=t,E.threat=a,E.fctver=L.version,E.os=i.platforminfo,E.service=u,E.url=O[4],E.browsetime=Number(s),E.userinitiated=n,I={date:new Date,log:E,state:0},this.cache_log.push(I)),this.enable_fazlog&&(v=!0,h="",h+="date="+l+" ",h+="time="+c+" ",h+="logver=N/A ",h+="type=traffic ",h+="level="+o+" ",h+="sessionid=N/A ",h+="hostname=N/A ",i.domain?h+="pcdomain="+i.domain+" ":h+="pcdomain=N/A ",h+="uid=N/A ",i.devid?h+="devid="+i.devid+" ":h+="devid=N/A ",h+="fgtserial=N/A ",h+="emsserial="+this.device_id+" ",h+="regip=N/A ",h+="srcname=chrome.exe ",h+="srcproduct=Chrome ",i.local_IP?h+="srcip="+i.local_IP+" ":h+="srcip=N/A ",h+="srcport=N/A ",h+="direction=outbound ",h+="dstip=N/A ",h+="remotename="+g+" ",h+="dstport="+Number(_)+" ",h+="user="+i.email+" ",h+="proto=6 ",h+="rcvdbyte=N/A ",h+="sentbyte=N/A ",h+="utmaction="+t+" ",h+="utmevent=webfilter ",h+="threat="+a+" ",h+="vd=root ",h+="fctver="+i.ext_version+" ",h+="os="+i.platforminfo+" ",this.policyName?h+='usingpolicy="'+this.policyName+'" ':h+="usingpolicy=default ",h+="service="+u+" ",h+="url="+O[4]+" ",h+="userinitiated="+n+" ",h+="browsetime="+Number(s)+" ",E={date:new Date,log:h,state:0},this.cache_fazlog.push(E),this.cached_fazlog_dirty=!0),v){var R=!1;this.loglevel>=this.LOG_TYPE.INFO?R=!0:this.loglevel>=this.LOG_TYPE.NOTICE&&r==this.LOG_ACTION_TYPE.BLOCKED&&(R=!0),R&&(h="LogManager - CacheLog - Log added to table:\n\turl: "+e+"\n",h+="\taction: "+t+"\n",h+="\tbrowse_time: "+s,this.LogDebug(h))}},save_cached_faz_logs:function(){if(this.enable_fazlog&&this.cached_fazlog_dirty)try{localStorage.faz_logs=JSON.stringify(this.cache_fazlog),this.cached_fazlog_dirty=!1}catch(e){n.LogError("failed to save cached FAZ logs, error:"+e.message)}},save_cached_ems_logs:function(){if(this.cached_emslog_dirty)try{localStorage.ems_logs=JSON.stringify(this.cache_log),this.cached_emslog_dirty=!1}catch(e){n.LogError("failed to save cached EMS logs, error:"+e.message)}},remove_expired_ems_logs:function(){var e,t,r,i,s=new Date;if(0!=(r=this.cache_log.length)){for(i=24*this.log_retention*60*60*1e3,t=0,e=0;e<r&&s.getTime()-this.cache_log[e].date.getTime()>=i;e++)t++;0!=t&&(this.cached_emslog_dirty=!0,this.cache_log.splice(0,t),this.save_cached_ems_logs())}},remove_expired_faz_logs:function(){var e,t,r,i,s=new Date;if(this.enable_fazlog&&0!=(r=this.cache_fazlog.length)){for(i=24*this.log_retention*60*60*1e3,t=0,e=0;e<r&&s.getTime()-this.cache_fazlog[e].date.getTime()>=i;e++)t++;0!=t&&(this.cached_log_dirty=!0,this.cache_fazlog.splice(0,t),this.save_cached_faz_logs())}}},l={profile:[1,4,5,6,7,11,12,13,14,16,17,26,57,61,62,83,86],action_table:{0:{action:1},1:{action:2},3:{action:3},4:{action:3},5:{action:2},6:{action:2},7:{action:2},8:{action:4},9:{action:4},11:{action:2},12:{action:2},13:{action:2},14:{action:2},15:{action:4},16:{action:2},17:{action:2},18:{action:4},19:{action:4},20:{action:3},23:{action:4},25:{action:3},26:{action:2},28:{action:4},29:{action:4},31:{action:1},34:{action:4},36:{action:4},37:{action:4},42:{action:3},44:{action:4},46:{action:4},53:{action:3},55:{action:4},57:{action:2},61:{action:2},62:{action:2},64:{action:4},65:{action:4},68:{action:4},69:{action:4},70:{action:4},75:{action:4},78:{action:4},80:{action:4},83:{action:2},86:{action:2},87:{action:2},88:{action:2},89:{action:2}},keywordActions:{6:{action:3},12:{action:3},14:{action:3},96:{action:4},97:{action:3}},default_action:1,init_finish:!1,err_message:null,init_started:!1,profile_changed:!1,signatureChanged:!1,exclusion_list:[],keywordWhiteList:["bomb"],keywordBlackList:["texting"],checksum:0,signatureChecksum:0,PartialMatchHost:0,enable_category:!0,keep_alive_timer_id:0,keep_alive_timeout:1e4,EXCLUSION_LIST_TYPE:{SIMPLE:1,WILDCARD:2,REGEX:3},KeepAlive:function(){const e=()=>{let e=Promise.resolve(),t=Promise.resolve();this.profile_changed&&(e=this.profile_init_json()),this.signatureChanged&&(t=g.getSignature()),Promise.all([e,t]).then(()=>{g.parseDB()})};this.init_finish?this.profile_changed||this.signatureChanged?e():r.profilserverurl?this.checksum_update():i.getEMSServerList().then(()=>{this.checksum_update()}).catch(()=>{n.LogError("ProfileManager - KeepAlive - Failed to get Cloud EMS url")}):e()},checksum_update:function(){let e=r.no_auth_server,t=(new Date).getTime(),s=r.profileserverurl+(e?"/userid-checksum":"/token-checksum"),o=new XMLHttpRequest;o.open("GET",s,!0),o.setRequestHeader(e?"UserID":"Token",i.id_token),o.timeout=this.keep_alive_timeout-2e3,o.ontimeout=(()=>{n.LogError("ProfileManager - checksum_update - Checksum timed out.")}),o.onload=(()=>{if(200===o.status){let e=(new Date).getTime();n.LogDebug(`ProfileManager - checksum_update - Profile checksum result:\n${o.responseText}`,"font-size:x-small;");let r=e-t;n.LogDebug(`profile checksum time cost: ${r}`);try{let e=JSON.parse(o.responseText);e.signature_checksum&&(this.signatureChecksum!==e.signature_checksum?(n.LogDebug("ProfileManager - checksum_update - Signature changed. Retrieving new signature...",`color:${n.FORTINET_COLOR.TEAL}`),this.signatureChanged=!0,g.getSignature()):n.LogDebug("ProfileManager - checksum_update - Signature unchanged.",`color:${n.FORTINET_COLOR.GREEN}`)),e.checksum?(this.keep_alive_timeout!=1e3*e.profileUpdateInterval&&(this.keep_alive_timeout=1e3*e.profileUpdateInterval,this.profile_reset_keepalive_timer()),this.checksum!=e.checksum?(n.LogDebug("ProfileManager - checksum_update - Profile changed. Retrieving new profile...",`color:${n.FORTINET_COLOR.TEAL}`),this.profile_changed=!0,this.profile_init_json().then(()=>{g.parseDB()})):(this.update_profile_retrieve_time(),n.LogDebug("ProfileManager - checksum_update - Profile unchanged.",`color:${n.FORTINET_COLOR.GREEN}`))):(this.err_message=e.content[0],-3===e.id&&i.OnRelogin())}catch(e){n.LogError(`ProfileManager - checksum_update - Error: ${e}`)}}}),o.send()},profile_reset_keepalive_timer:function(){clearInterval(this.keep_alive_timer_id),this.keep_alive_timer_id=setInterval(()=>{this.KeepAlive()},this.keep_alive_timeout)},profile_uninit:function(){clearInterval(this.keep_alive_timer_id)},process_profile:function(e){let t,s;if(e.id){if(s=e.profile?"profile":"content",e.safeSearch?(t="undefined"==e.restrictionLevel?"strict":e.restrictionLevel,i.EnableSafeSearch(!0,t)):i.EnableSafeSearch(!1,"none"),e.logUserInitiatedTraffic?i.monitor_all_page=!0:i.monitor_all_page=!1,e.logAllUrls?r.log_all_URLs=!0:r.log_all_URLs=!1,e.word_scanning_enabled?r.monitor_search=!0:r.monitor_search=!1,void 0!==e.wf_replacement_msg&&e.wf_replacement_msg.length>0?i.SetCustomizedBlockPage(e.wf_replacement_msg):i.RemoveCustomizedBlockPage(),this.keep_alive_timeout!=1e3*e.profileUpdateInterval&&(this.keep_alive_timeout=1e3*e.profileUpdateInterval,this.profile_reset_keepalive_timer()),s in e&&0===e[s].length)this.enable_category=!1;else{this.enable_category=!0;for(const t of e[s]){let[e,r]=t.split(":");r=Number(r),this.action_table[e]={action:r}}}if(e.word_filter_categories){this.keywordActions={};for(const t of e.word_filter_categories){let[e,r]=t.split(":");r=Number(r),this.keywordActions[e]={action:r}}}}else this.err_message=e.error;n.enable_fazlog=!1,e.logSettings.log_server&&(e.emsVer&&e.emsVer>="1.2"?r.fazserverurl=e.logSettings.log_server:r.fazserverurl="https://"+e.logSettings.log_server+"/jsonrpc/fazapi/logs",n.enable_fazlog=!0),e.emssn&&(n.device_id=e.emssn,h.emssn=e.emssn),e.policyName&&(n.policyName=e.policyName),e.logSettings.log_retention&&(n.log_retention=e.logSettings.log_retention),e.logSettings.log_freq&&n.SetFAZSendingInterval(Number(e.logSettings.log_freq)),n.compress_content=!1,e.logSettings.log_compressed&&1==Number(e.logSettings.log_compressed)&&(n.compress_content=!0),e.logSettings.log_level&&n.SetLogLevel(Number(e.logSettings.log_level)),e.emsVer&&(r.ems_version=e.emsVer),e.logSettings.log_backup_interval&&n.SetFAZBackupInterval(Number(e.logSettings.log_backup_interval)),this.exclusion_list=e.exclusionList,g.exclusionList=e.word_filter_custom,e.signature_checksum&&(this.signatureChecksum=e.signature_checksum),e.checksum?(this.checksum=e.checksum,this.profile_changed=!1,this.init_finish=!0):(this.err_message=e[s][0],-3==e.id&&i.OnRelogin())},profile_save:function(e){let t={date:new Date,profile:e};localStorage.user_profile=JSON.stringify(t),localStorage.lastProfileAccess=(new Date).getTime()},update_profile_retrieve_time:function(){localStorage.lastProfileAccess=(new Date).getTime()},profile_load:function(){const{user_profile:e,lastProfileAccess:t}=localStorage;if(e&&t){if(new Date-t>i.CACHE_PROFILE_EXPIRE_INTERVAL)n.LogInfo("ProfileManager - profile_load - Cached profile older than 24h detected. Will not use."),i.get_cached_config=!1;else{const{profile:t}=JSON.parse(e);t&&(this.process_profile(t),i.get_cached_config=!0)}}},profile_init_json:async function(e=0,t=1500,s=0){let o=!1;try{const t=(new Date).getTime(),s=r.no_auth_server,a={};s?a.UserID=i.id_token:a.Token=i.id_token;let l=r.profileserverurl+(s?"/userid-profile":"/token-profile");const c=new AbortController,h=new Promise(e=>setTimeout(t=>{c.abort(),e()},this.keep_alive_timeout-2e3));let _=await Promise.race([fetch(l,{method:"GET",headers:a,signal:c.signal}),h]);if(!_.ok)throw new Error("Failed to retrieve profile");{let e=(new Date).getTime()-t;n.LogDebug("ProfileManager - profile_init_json - profile retrive time:"+e);let r=await _.json();if(n.LogDebug("ProfileManager - profile_init_json - profile result:\n"+JSON.stringify(r,null,2),`color:${n.FORTINET_COLOR.GREY}`),r.error)throw new Error("EMS returned with error");{let e=this.checksum;this.process_profile(r),e&&e===this.checksum?this.update_profile_retrieve_time():this.profile_save(r),o=!0}}}catch(t){n.LogWarn(`ProfileManager - profile_init_json - ${t}. Retries left: ${e}`)}return o?Promise.resolve():0===e?Promise.reject():3===s?(setTimeout(()=>{this.profile_init_json(e-1,Math.min(t+1500,6e5),s+1).then(()=>{l.profile_reset_keepalive_timer(),r.no_auth_server||(this.refresh_timer=setInterval(()=>{this.TokenRefresh()},TOKEN_REFRESH_TIMEOUT))})},t),Promise.reject()):await new Promise((r,i)=>{setTimeout(()=>{this.profile_init_json(e-1,1500,s+1).then(()=>r()).catch(()=>i())},t)})},BlockRate:function(e){return this.profile.includes(Number(e))},get_rating_action:function(e){let t=String(e);return this.enable_category&&t in this.action_table?this.action_table[t].action:this.default_action},getActionFromWordCategoryId:function(e){return e in this.keywordActions?this.keywordActions[e].action:this.default_action},getLocation:function(e,t){let r,i,s=e.match(/(^.*?\:)?\/?\/?(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)?(\?[^#]*|)(#.*|)$/);return r=s[1]?s[1]:t,i=s[5]?s[5]:"",s&&{protocol:r,host:s[2],hostname:s[3],port:s[4],pathname:i,search:s[6],hash:s[7]}},getPatternLocation:function(e,t){let r,i,s;return e||0!=e.length?(s=e,-1!=(r=e.indexOf("://"))?(i=e.substr(0,r+1),s=e.substr(r+3)):-1!=(r=e.indexOf("://"))?(i=e.substr(0,r+1),s=e.substr(r+5)):i=t,{protocol:i,host_pathname:s}):null},WebFilter_IsUrlMatched:function(e,t,r,i){let s,o,a=e;try{switch(i){case this.EXCLUSION_LIST_TYPE.SIMPLE:a=a.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(a);break;case this.EXCLUSION_LIST_TYPE.WILDCARD:a=a.replace(/[.+\-^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".?"),s=new RegExp(a);break;case this.EXCLUSION_LIST_TYPE.REGEX:s=new RegExp(a);break;default:s=new RegExp(a)}o=s.test(t)}catch(e){n.LogError(`Profilmanager - WebFilter_IsUrlMatched - Failed to apply regex ${a}`)}return o},report_stats_in_wblist:function(){let e=!1;return r.ems_version&&(e=r.ems_version>="1.2"),e},in_exclusion_list:function(e){let t={block:!1,allow:!1,action:"1"},r=0;this.exclusion_list&&(r=this.exclusion_list.length);for(var i=0;i<r;i++)if(void 0===this.exclusion_list[i].referer_host&&this.WebFilter_IsUrlMatched(this.exclusion_list[i].url,e,this.PartialMatchHost,Number(this.exclusion_list[i].type))){t.action=this.exclusion_list[i].action,"1"==this.exclusion_list[i].action||"4"==this.exclusion_list[i].action?t.allow=!0:t.block=!0;break}return t},get_error_message:function(){return this.err_message},match_profile_url_in_referer_list:function(e){var t,r=!1,i=0;for(this.exclusion_list&&(i=this.exclusion_list.length),t=0;t<i;t++)if(void 0!==this.exclusion_list[t].referer_host&&this.WebFilter_IsUrlMatched(this.exclusion_list[t].url,e,this.PartialMatchHost,Number(this.exclusion_list[t].type))){r=!0;break}return r},match_profile_referer:function(e,t){let r={match:!1,action:1};return this.exclusion_list.some(i=>{if("referer_host"in i){let s=!1;let o=i.referer_host.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(o,"i");try{s=a.test(e)}catch(e){n.LogError(`ProfileManager - match_profile_referer - Errornous referer url ${i.referer_host}`)}if(s&&this.WebFilter_IsUrlMatched(i.url,t,this.PartialMatchHost,Number(i.type)))return r.match=!0,r.action=i.action,!0}return!1}),r}};class c{constructor(e,t,r,i){this.url=e,this.tabId=t,this.token=i,this.info_type=r}}const h={category_version:"7",cat_list:{0:{name:"Unrated",group:0},1:{name:"Drug Abuse",group:1},2:{name:"Alternative Beliefs",group:2},3:{name:"Hacking",group:1},4:{name:"Illegal or Unethical",group:1},5:{name:"Discrimination",group:1},6:{name:"Explicit Violence",group:1},7:{name:"Abortion",group:2},8:{name:"Other Adult Materials",group:2},9:{name:"Advocacy Organizations",group:2},11:{name:"Gambling",group:2},12:{name:"Extremist Groups",group:1},13:{name:"Nudity and Risque",group:2},14:{name:"Pornography",group:2},15:{name:"Dating",group:2},16:{name:"Weapons (Sales)",group:2},17:{name:"Advertising",group:6},18:{name:"Brokerage and Trading",group:6},19:{name:"Freeware and Software Downloads",group:4},20:{name:"Games",group:6},23:{name:"Web-based Email",group:6},24:{name:"File Sharing and Storage",group:4},25:{name:"Streaming Media and Download",group:4},26:{name:"Malicious Websites",group:5},28:{name:"Entertainment",group:6},29:{name:"Arts and Culture",group:6},30:{name:"Education",group:6},31:{name:"Finance and Banking",group:7},33:{name:"Health and Wellness",group:6},34:{name:"Job Search",group:6},35:{name:"Medicine",group:6},36:{name:"News and Media",group:6},37:{name:"Social Networking",group:6},38:{name:"Political Organizations",group:6},39:{name:"Reference",group:6},40:{name:"Global Religion",group:6},41:{name:"Search Engines and Portals",group:7},42:{name:"Shopping",group:6},43:{name:"General Organizations",group:7},44:{name:"Society and Lifestyles",group:6},46:{name:"Sports",group:6},47:{name:"Travel",group:6},48:{name:"Personal Vehicles",group:6},49:{name:"Business",group:7},50:{name:"Information and Computer Security",group:7},51:{name:"Government and Legal Organizations",group:7},52:{name:"Information Technology",group:7},53:{name:"Armed Forces",group:7},54:{name:"Dynamic Content",group:6},55:{name:"Meaningless Content",group:6},56:{name:"Web Hosting",group:7},57:{name:"Marijuana",group:2},58:{name:"Folklore",group:6},59:{name:"Proxy Avoidance",group:1},61:{name:"Phishing",group:5},62:{name:"Plagiarism",group:1},63:{name:"Sex Education",group:2},64:{name:"Alcohol",group:2},65:{name:"Tobacco",group:2},66:{name:"Lingerie and Swimsuit",group:2},67:{name:"Sports Hunting and War Games",group:2},68:{name:"Web Chat",group:6},69:{name:"Instant Messaging",group:6},70:{name:"Newsgroups and Message Boards",group:6},71:{name:"Digital Postcards",group:6},72:{name:"Peer-to-peer File Sharing",group:4},75:{name:"Internet Radio and TV",group:4},76:{name:"Internet Telephony",group:4},77:{name:"Child Education",group:6},78:{name:"Real Estate",group:6},79:{name:"Restaurant and Dining",group:6},80:{name:"Personal Websites and Blogs",group:6},81:{name:"Secure Websites",group:7},82:{name:"Content Servers",group:6},83:{name:"Child Abuse",group:1},84:{name:"Web-based Applications",group:7},85:{name:"Domain Parking",group:6},86:{name:"Spam URLs",group:5},87:{name:"Personal Privacy",group:6},88:{name:"Dynamic DNS",group:5},89:{name:"Auction",group:6},90:{name:"Newly Observed Domain",group:5},91:{name:"Newly Registered Domain",group:5},92:{name:"Charitable Organizations",group:7},93:{name:"Remote Access",group:7},94:{name:"Web Analytics",group:7},95:{name:"Online Meeting",group:7}},group_list:{0:"Unrated",1:"Potentially Liable",2:"Adult/Mature Content",4:"Bandwidth Consuming",5:"Security Risk",6:"General Interest - Personal",7:"General Interest - Business"},url_rate_cache_list:{},url_rate_item_array:[],url_rate_timer_started:!1,save_url_rate_timer:null,save_web_access_stat_timer:null,send_web_access_stat_timer:null,remove_expired_url_rate_items_timer:null,item_expire_timeout:18e5,web_access_statistics:{},stats_dirty:!1,emssn:null,loadLocalStorage:function(){n.LogInfo("UrlRate - loadLocalStorage - Loading Cache"),this.web_access_statistics={};try{var e=localStorage.getItem("web_access_statistics");if(null!=e){this.web_access_statistics=JSON.parse(e);const t=JSON.stringify(this.web_access_statistics,null,4);n.LogDebug("UrlRate - loadLocalStorage - SUCCESS - Loaded 'web_access_statistics'",`font-size:x-small; color:${n.FORTINET_COLOR.GREEN}`),n.LogDebug(`web_access_statistics = ${t}`,`font-size:x-small; color:${n.FORTINET_COLOR.GREY}`)}else n.LogDebug("UrlRate - loadLocalStorage - No localStorage data for 'web_access_statistics'")}catch(e){n.LogDebug("failed to get cached web access statistics data")}try{var t=localStorage.url_rate_list;null!=t&&(this.url_rate_cache_list=JSON.parse(t))}catch(e){n.LogError("failed to load cached url rating list, error:"+e.message)}},Init:function(){var e=this;this.save_web_access_stat_timer=setInterval(function(){e.save_web_access_statistics_data()},3e4),this.send_web_access_stat_timer=setInterval(function(){e.SendoutStats()},3e5),this.save_url_rate_timer=setInterval(function(){e.save_cached_url_rate_list()},6e4),this.remove_expired_url_rate_items_timer=setInterval(function(){e.remove_expired_url_rate_items()},36e5)},Uninit:function(){if(null!=this.save_web_access_stat_timer&&clearInterval(this.save_web_access_stat_timer),null!=this.send_web_access_stat_timer&&clearInterval(this.send_web_access_stat_timer),null!=this.save_url_rate_timer&&clearInterval(this.save_url_rate_timer),null!=this.remove_expired_url_rate_items_timer&&clearInterval(this.remove_expired_url_rate_items_timer),r.async_mode)for(;this.url_rate_item_array.length;)this.url_rate_item_array.pop()},clear_cache:function(){localStorage.url_rate_list={},this.url_rate_cache_list={}},set_mode:function(e){if(r.async_mode,0==e)for(r.async_mode=!1,this.url_rate_timer_started=!1;this.url_rate_item_array.length;)this.url_rate_item_array.pop();else r.async_mode=!0},remove_expired_url_rate_items:function(){const e=new Date;Object.entries(this.url_rate_cache_list).map(([t,r])=>{e-new Date(r.date)>this.item_expire_timeout&&delete this.url_rate_cache_list[t]})},save_cached_url_rate_list:function(){try{localStorage.url_rate_list=JSON.stringify(this.url_rate_cache_list)}catch(e){n.LogError("failed to save cached url rating list, error:"+e.message)}},save_web_access_statistics_data:function(){try{localStorage.web_access_statistics=JSON.stringify(this.web_access_statistics)}catch(e){n.LogError("failed to save cached web access statistics data, error:"+e.message)}},url_rate:function(e,t,s,o,a=null){var h,_,g=this,u={},d="";let m;if(_=0,"main_frame"===s&&(_=1),a){let r=a.action===i.ACTION.BLOCK?i.EXCLUSION_CATEGORY.BLACKLIST:i.EXCLUSION_CATEGORY.WHITELIST;if(u=a,this.is_google_hostname(e)||"main_frame"!=s||l.report_stats_in_wblist()&&(void 0!=this.web_access_statistics[r]?this.web_access_statistics[r]++:this.web_access_statistics[r]=1,this.stats_dirty=!0),u.action===i.ACTION.MONITOR&&i.SetMonitorThisPage(t,e),u.action!==i.ACTION.ALLOW){const r={action:u.action,rating:u.rating,url:e};i.TabsStatusUpdate(t,r)}return"main_frame"!==s||u.action!=i.ACTION.BLOCK&&u.action!=i.ACTION.WARN||i.customized_blacklist_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_blacklist_page,e,u.remark),i.SetTabsStatusCustomizedPage(t,d)),i.ReportUrlAction(t,e,u.action,u.remark,_,u.rating),u}if((h=l.in_exclusion_list(e)).block||h.allow){let r;u.action=h.action,h.allow?(u.remark="url is in white list",r=-1):(u.remark="url is in black list",r=-2),u.rating=0,this.is_google_hostname(e)||"main_frame"!==s||l.report_stats_in_wblist()&&(void 0!=this.web_access_statistics[r]?this.web_access_statistics[r]++:this.web_access_statistics[r]=1,this.stats_dirty=!0),u.action===i.ACTION.MONITOR&&i.SetMonitorThisPage(t,e);const o={url:e,action:u.action,rating:u.rating};return u.action!==i.ACTION.ALLOW&&i.TabsStatusUpdate(t,o),"main_frame"!==s||u.action!==i.ACTION.BLOCK&&u.action!==i.ACTION.WARN||i.customized_blacklist_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_blacklist_page,e,u.remark),i.SetTabsStatusCustomizedPage(t,d)),i.ReportUrlAction(t,e,u.action,u.remark,_,u.rating),u}if(!l.enable_category)return u.action=i.ACTION.ALLOW,u.rating=0,u.remark="site categories is disabled",u;if(e in this.url_rate_cache_list&&(m=this.url_rate_cache_list[e].rating),m){let r;if(this.is_google_hostname(e)||"main_frame"!==s||(void 0!=this.web_access_statistics[m]?this.web_access_statistics[m]++:this.web_access_statistics[m]=1,this.stats_dirty=!0),r=l.get_rating_action(Number(m)),n.LogInfo(`UrlRate - url_rate - Cached result for ${e}:\n\t\t\t\t\tCategoryId: ${m}, TabId: ${t}, Action: ${r}`,r===i.ACTION.BLOCK?`color:${n.FORTINET_COLOR.TEAL};`:""),u.remark=this.cat_list[String(m)].name,u.action=r,u.rating=m,r!==i.ACTION.ALLOW){const s={url:e,action:r,rating:m};i.TabsStatusUpdate(t,s)}"main_frame"!==s||r!==i.ACTION.BLOCK&&r!==i.ACTION.WARN||(r===i.ACTION.BLOCK?i.customized_block_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_block_page,e,this.get_rating_info(Number(m))),i.SetTabsStatusCustomizedPage(t,d)):i.customized_warning_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_warning_page,e,this.get_rating_info(Number(m))),i.SetTabsStatusCustomizedPage(t,d))),r===i.ACTION.MONITOR&&i.SetMonitorThisPage(t,e),i.ReportUrlAction(t,e,r,g.cat_list[m].name,_,m)}else if(u.action=i.ACTION.ALLOW,r.async_mode){var f=new c(e,t,s,o);this.url_rate_item_array.push(f),this.url_rate_timer_started||(setTimeout(function(){g.url_rating_timer()},10),this.url_rate_timer_started=!0)}else{var b,p,T,S=[],L=r.ratingserverurl+"/service/wfquery?protover=1.0&";L+="cltkey=",L+=encodeURIComponent(i.id_token),this.emssn&&(L+="&emssn=",L+=this.emssn),L+="&clttype=ie&type=cate&catver=7&qurl="+encodeURIComponent(e),S[0]=0,b=l.action_table[0].action;var E=new XMLHttpRequest;T=setTimeout(function(){p||(n.LogError("UrlRate - url_rate - No response from rating server after 1 second. Aborting rate request."),E.abort())},1e3),E.withCredentials=!0;const o=(new Date).getTime();try{E.open("GET",L,!1),E.send()}catch(e){clearTimeout(T),n.LogError("UrlRate - url_rate - Error happened while rating web site:"+e.message)}if(200==E.status){const r=(new Date).getTime();new DOMParser;clearTimeout(T),0==(p=JSON.parse(E.response)).status&&(S=p.data),void 0==this.cat_list[S[0]]&&(S[0]=0),0!=Number(S[0])&&(this.url_rate_cache_list[e]={},this.url_rate_cache_list[e].rating=S[0],this.url_rate_cache_list[e].date=new Date),b=l.get_rating_action(Number(S[0])),n.LogInfo(`UrlRate - url_rate - Result for ${e}:\n\t\t\t\t\tCategoryId: ${S[0]}, TabId: ${t}, Action: ${b}`,2===b?`color:${n.FORTINET_COLOR.TEAL};`:""),n.LogInfo(`UrlRate - url_rate - response time: ${r-o} ms`)}else{const e=(new Date).getTime();n.LogError("UrlRate - url_rate - Error happened while rating web site:"+E.responseText),n.LogInfo(`UrlRate - url_rate - Fortiguard rating server response time: ${e-o}ms`)}if(this.is_google_hostname(e)||"main_frame"!==s||(void 0!=this.web_access_statistics[S[0]]?this.web_access_statistics[S[0]]++:this.web_access_statistics[S[0]]=1,this.stats_dirty=!0),u.action=b,u.remark=this.cat_list[S[0]].name,u.rating=Number(S[0]),b!==i.ACTION.ALLOW){const r={url:e,action:b,rating:S[0]};i.TabsStatusUpdate(t,r)}"main_frame"!=s||b!==i.ACTION.BLOCK&&b!==i.ACTION.WARN||(b===i.ACTION.BLOCK?i.customized_block_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_block_page,e,this.get_rating_info(Number(S[0]))),i.SetTabsStatusCustomizedPage(t,d)):i.customized_warning_page.length>0&&(d=i.PrepareCustomizedPage(t,i.customized_warning_page,e,this.get_rating_info(Number(S[0]))),i.SetTabsStatusCustomizedPage(t,d))),b===i.ACTION.MONITOR&&i.SetMonitorThisPage(t,e),i.ReportUrlAction(t,e,b,g.cat_list[S[0]].name,_,S[0])}return u},url_rate_table_clear:function(e){for(var t=[];this.url_rate_item_array.length;){var r=this.url_rate_item_array.pop();r.tabId!=e&&t.push(r)}this.url_rate_item_array=t},cache_url_rate:function(e){var t,r,i={};if(e in this.url_rate_cache_list&&(t=this.url_rate_cache_list[e].rating),t){var s;if(this.url_rate_cache_list[e].date=new Date,i.remark=this.cat_list[String(t)].name,2===(r=l.get_rating_action(t)))s=this.generate_web_content(e,t),i.remark=s;i.action=r}else i.action=1;return i},generate_web_content:function(e,t){return"data:text/html,<div>According to the policy, web site "+e+" is blocked, rating result:"+this.cat_list[String(t)].name+"</div>"},get_rating_info:function(e){let t,r="";return this.cat_list[String(e)]&&(t=this.cat_list[String(e)].group,r=this.group_list[String(t)],r+=":",r+=this.cat_list[String(e)].name),r},process_rating_category:function(e,t){var r,s="";action=l.get_rating_action(Number(t)),n.LogDebug("block this url:"+e.url),r=0,this.generate_web_content(e.url,t),void 0!=i.chrome_tabs_status[e.tabId]&&1==i.chrome_tabs_status[e.tabId].action&&(2==action||action),1!=action&&i.TabsStatusUpdate(e.tabId,e.url,action,t),"main_frame"!=e.info_type||2!=action&&3!=action||(2==action?i.customized_block_page.length>0&&(s=i.PrepareCustomizedPage(e.tabId,i.customized_block_page,url,this.get_rating_info(t)),i.SetTabsStatusCustomizedPage(e.tabId,s)):i.customized_warning_page.length>0&&(s=i.PrepareCustomizedPage(e.tabId,i.customized_warning_page,url,this.get_rating_info(t)),i.SetTabsStatusCustomizedPage(e.tabId,s))),4==action&&i.SetMonitorThisPage(e.tabId,e.url),"main_frame"==e.info_type&&(r=1),i.ReportUrlAction(e.tabId,e.url,action,this.cat_list[t].name,r,t)},url_rating_timer:function(){var e=this.url_rate_item_array.pop(),t=this;if(void 0!==e){var s=r.ratingserverurl+"/service/wfquery?protover=1.0&";s+="cltkey=",s+=encodeURIComponent(i.id_token),this.emssn&&(s+="&emssn=",s+=this.emssn),s+="&clttype=ie&type=cate&catver=7&qurl="+encodeURIComponent(e.url);var o=new XMLHttpRequest;o.tabId=e.tabId,o.url=e.url,o.token=e.token,o.info_type=e.info_type,o.open("GET",s,!0),o.onreadystatechange=function(){if(o.readyState===XMLHttpRequest.DONE)if(200===o.status){n.LogDebug("******** rating result:"+o.responseText+" tabId:"+o.tabId+" url:"+o.url+" ********");var e=JSON.parse(o.response),r=["0"];t.url_rate_cache_list[o.url]={};try{0==e.status&&(r=e.data),t.url_rate_cache_list[o.url].rating=r[0],t.is_google_hostname(o.url)||"main_frame"!=o.info_type||(void 0!=t.web_access_statistics[r[0]]?t.web_access_statistics[r[0]]++:t.web_access_statistics[r[0]]=1,t.stats_dirty=!0)}catch(e){t.url_rate_cache_list[o.url].rating="0"}t.url_rate_cache_list[o.url].date=new Date,t.process_rating_category(o,r[0]),delete o}else n.LogError("Error happened while rating web site, error:"+o.statusText),t.process_rating_category(o,0),delete o,0==t.url_rate_item_array.length?t.url_rate_timer_started=!1:setTimeout(function(){t.url_rating_timer()},10);0==t.url_rate_item_array.length?t.url_rate_timer_started=!1:setTimeout(function(){t.url_rating_timer()},10)},o.send()}else 0==this.url_rate_item_array.length?this.url_rate_timer_started=!1:setTimeout(function(){t.url_rating_timer()},10)},is_google_hostname:function(e){var t=/(\w+):\/\/([\w.\-]+)(:\d*)?(\/.*)/i.exec(e),r=!0;return!!t&&(-1==t[2].indexOf("google")&&(r=!1),r)},SendoutStats:function(){let e;if(!this.stats_dirty)return;let t=Object.entries(this.web_access_statistics).map(([e,t])=>({category:Number(e),count:t})),s=JSON.stringify(t),o=new XMLHttpRequest;e=r.no_auth_server?r.profileserverurl+"/userid-stat":r.profileserverurl+"/token-stat",o.open("POST",e,!0),o.setRequestHeader("Content-type","application/json"),r.no_auth_server?o.setRequestHeader("UserID",i.id_token):o.setRequestHeader("Token",i.id_token),o.timeout=1e4,o.ontimeout=function(){n.LogDebug("send web access stats timed out."),delete o},o.onload=(e=>{200===o.status?(n.LogDebug("web access stats are sent successfully"),this.web_access_statistics={},localStorage.removeItem("web_access_statistics"),this.stats_dirty=!1):n.LogError("Error happened when sending web access statistics data to EMS")}),o.send(s)}};class _{constructor(e,t,r,i){this.categoryId=e,this.entry=t,this.url=r,this.action=i}}const g={CONSTANTS:{SAVE_BAN_LIST_INTERVAL:30*i.INTERVAL_MINUTE,SAVE_KEYWORD_STATISTICS_INTERVAL:5*i.INTERVAL_SECOND,SEND_KEYWORD_STATISTICS_INTERVAL:5*i.INTERVAL_MINUTE,KEYWORD_STATISTICS_LOCAL_STORAGE_KEY:"keywordStatistics",BAN_LIST_LOCAL_STORAGE_KEY:"banList"},config:{matchSearchSuggestion:!0,enableWordWeight:!1,weightTreshold:.5,fullWordMatchOnly:!1},banList:{},categories:{},categoryIgnoreList:{},exclusionList:[],keywordStatisticsDict:{},saveKeywordStatisticsTimer:0,saveBanListTimer:0,sendKeywordStatisticsTimer:0,keywordStatsDirty:!1,db:{},loadLocalStorage(){n.LogInfo("KeywordAnalyzer - loadLocalStorage - Loading Cache");let e=this.getLocalStorageData(this.CONSTANTS.KEYWORD_STATISTICS_LOCAL_STORAGE_KEY);this.keywordStatisticsDict=e||{},e=this.getLocalStorageData(this.CONSTANTS.BAN_LIST_LOCAL_STORAGE_KEY),this.banList=e||{}},getLocalStorageData(e){let t;try{if(e in localStorage){const r=localStorage.getItem(e);if("{}"===r)return n.LogDebug(`KeywordAnalyzer - getLocalStorageData - No localStorage data for '${e}'`),t;t=JSON.parse(r);let i="";i=e===this.CONSTANTS.KEYWORD_STATISTICS_LOCAL_STORAGE_KEY?JSON.stringify(t,null,4):JSON.stringify(t,null,4).substring(0,300)+"\n......",n.LogDebug(`KeywordAnalyzer - getLocalStorageData - SUCCESS - Loaded '${e}'`,`font-size:x-small; color:${n.FORTINET_COLOR.GREEN};`),n.LogDebug(`${e} = ${i}`,`font-size:x-small; color:${n.FORTINET_COLOR.GREY};`)}else n.LogDebug(`KeywordAnalyzer - getLocalStorageData - No localStorage data for '${e}'`)}catch(t){n.LogError(`KeywordAnalyzer - getLocalStorageData - FAILED - Erro when getting '${e}' - ${t}`)}return t},saveLocalStorageData(e,t){try{const r=JSON.stringify(t);localStorage.setItem(e,r)}catch(t){n.LogError(`failed to save ${e} localStorage data, ${t}`)}},async getSignature(e=0,t=1500,s=0){let o=!1;try{n.LogDebug("KeywordAnalyzer - getSignature - started");let t=`${r.profileserverurl}/word-signature`;const s=await fetch(t,{method:"GET",headers:{UserID:i.id_token}});if(s.ok){const e=await s.json();if(e.error)throw new Error(`EMS returned with ${e.error}`);this.db=e,n.LogDebug(`KeywordAnalyzer - getSignature - signature result:\n${JSON.stringify(e,null,2).substring(0,600)+"\n......"}`,`color:${n.FORTINET_COLOR.GREY}`),o=!0}}catch(t){n.LogWarn(`KeywordAnalyzer - getSignature - FAILED - ${t}. Retries left: ${e}`)}return o?Promise.resolve():0===e?Promise.reject():3===s?(setTimeout(()=>{this.getSignature(e-1,Math.min(t+1500,6e5),s+1).then(()=>{g.parseDB(),i.makeSupportedSites(),g.setIntervalTimers()})},t),Promise.reject()):await new Promise((r,i)=>{setTimeout(()=>{this.getSignature(e-1,1500,s+1).then(()=>r()).catch(()=>i())},t)})},parseCategoryList(){this.db&&this.db.categories?this.db.categories.forEach(e=>{this.categories[e.id]=e.name}):n.LogError("Categories in signature does not exist.")},parseWordList(){if(this.db&&this.db.data){const e=([e,t])=>{const r=this.getCategoryId(e),s=l.getActionFromWordCategoryId(r);s!==i.ACTION.ALLOW&&(n.LogDebug(`KeywordAnalyzer - parseWordList - Category: ${r}, Action: ${s}`),t.map(e=>this.parseWord(e,r,s)))};Object.entries(this.db.data).map(e)}else n.LogError("Word list in signature does not exist.")},processExclusionList(){Object.entries(this.exclusionList).forEach(([e,t])=>{this.processExclusionWord(e.toLocaleLowerCase(),t)})},parseDB(){this.db&&(n.LogInfo("KeywordAnalyzer - parseDB - parsing signature"),this.categories={},this.parseCategoryList(),this.banList={},this.parseWordList(),this.saveLocalStorageData(this.CONSTANTS.BAN_LIST_LOCAL_STORAGE_KEY,this.banList)),this.exclusionList&&(n.LogDebug("KeywordAnalyzer - parsing exclusion list"),this.processExclusionList())},isWordMoreSevere(e,t){return!(e in this.banList&&this.compareActions(this.banList[e].action,t))},makeBanListEntry:(e,t,r)=>({categoryId:e,action:t,weight:r}),parseWord(e,t,r){const s=e.name.toLowerCase().trim();if(this.isWordMoreSevere(s,r)){const o=s.replace(i.removePunctuationRegex,""),a=this.makeBanListEntry(t,r,e.weight);"#"===s[0]&&(this.banList[`#${o}`]=a),o in this.banList||(this.banList[o]=a)}},processExclusionWord(e,t){switch(n.LogDebug(`KeywordAnalyzer - processExclusionWord - Word: ${e}, Action: ${t}`),t){case i.ACTION.ALLOW:delete this.banList[e];break;case i.ACTION.BLOCK:case i.ACTION.WARN:case i.ACTION.MONITOR:this.banList[e]={categoryId:-1*t,action:t,weight:1};break;default:n.LogError(`KeywordAnalyzer - processExclusionWord - Undefined action: ${t}`)}},compareActions(e,t){const r={1:0,2:3,3:2,4:1};return r[e]-r[t]},setIntervalTimers(){n.LogDebug("KeywordAnalyzer - setIntervalTimers called"),this.saveKeywordStatisticsTimer=setInterval(()=>{this.saveLocalStorageData(this.CONSTANTS.KEYWORD_STATISTICS_LOCAL_STORAGE_KEY,this.keywordStatisticsDict)},this.CONSTANTS.SAVE_KEYWORD_STATISTICS_INTERVAL),this.saveBanListTimer=setInterval(()=>{this.saveLocalStorageData(this.CONSTANTS.BAN_LIST_LOCAL_STORAGE_KEY,this.banList)},this.CONSTANTS.SAVE_BAN_LIST_INTERVAL),this.sendKeywordStatisticsTimer=setInterval(()=>{this.sendKeywordStatistics()},this.CONSTANTS.SEND_KEYWORD_STATISTICS_INTERVAL)},clearIntervalTimers(){n.LogDebug("KeywordAnalyzer - clearIntervalTimers called"),this.checkAndClearInterval(this.saveKeywordStatisticsTimer),this.checkAndClearInterval(this.saveBanListTimer),this.checkAndClearInterval(this.sendKeywordStatisticsTimer)},checkAndClearInterval(e){e&&clearInterval(e)},async sendKeywordStatistics(){if(this.keywordStatsDirty)try{const e=r.no_auth_server,t=r.profileserverurl+(e?"/userid-word-stat":"/token-word-stat"),s={};e?s.UserID=i.id_token:s.Token=i.id_token,s["Content-type"]="application/json";const o=Object.values(this.keywordStatisticsDict),a=await fetch(t,{method:"POST",headers:s,body:JSON.stringify(o)});if(!a.ok)throw new Error(a.status);n.LogDebug("keyword statistics are sent successfully"),this.clearKeywordStatistics()}catch(e){n.LogError(`Error happened when sending keyword statistics data: ${e}`)}},getCategoryId(e){const t=Object.keys(this.categories).find(t=>this.categories[t]===e);return Number(t)||0},getRatingInfo(e){return e in this.categories?this.categories[e]:e===-1*i.ACTION.WARN?"Warning List":"Unrated"},getCategoryFromWord(e){const t=[];return Object.entries(this.db.data).forEach(([r,i])=>{i.forEach(i=>{i.name===e&&t.push(r)})}),t},clearKeywordStatistics(){localStorage.removeItem(this.CONSTANTS.KEYWORD_STATISTICS_LOCAL_STORAGE_KEY),this.keywordStatisticsDict={},this.keywordStatsDirty=!1},warningBypass(e,t){this.categoryIgnoreList[t]=e},testWord(e){let t,r=!1;return e in this.banList&&(t=e,r=!0),e.replace(/\s/g,"")in this.banList&&(t=e.replace(/\s/g,""),r=!0),{found:r,word:t}},makePermutation:e=>e.reduce((e,t,r)=>{const i=[...e];i.length=r;const s=i.reduce((e,r)=>[...e,`${t} ${r}`],[]);return[t,...s,...e]},[]),testWordPermutation(e){const t=Object.keys(this.banList).length,r=e.trim().replace(/\s+/g," ").split(" ").reverse();let i=[];if(r.length**2<t){const e=this.makePermutation(r);n.LogInfo(`Testing all possible terms:\n${e}`),i=e.reduce((e,t)=>{let r=t.replace(/\s/g,"");return t in this.banList?[t,...e]:r in this.banList?[r,...e]:e},[])}else{Object.keys(this.banList).forEach(t=>{const r=t,s=t.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),o=s.replace(/\s/g,""),a=new RegExp(`\\b${s}\\b`).test(e),n=new RegExp(`\\b${o}\\b`).test(e);(a||n)&&(i=[...i,r])})}i.sort((e,t)=>this.compareActions(this.banList[t].action,this.banList[e].action));const[s,...o]=i;return{found:i.length,word:s}},testCategoryIgnore(e){if(e in this.categoryIgnoreList){const t=new Date;if(this.categoryIgnoreList[e]>t)return!0;delete this.categoryIgnoreList[e]}return!1},testWordWeight(e){return!this.config.enableWordWeight||this.banList[e].weight>this.config.weightTreshold},addToStatistics(e){e in this.keywordStatisticsDict?this.keywordStatisticsDict[e].count+=1:this.keywordStatisticsDict[e]={word:e,wf_action_id:this.banList[e].action,count:1},this.keywordStatsDirty=!0},analyzeSearchTerm(e,t){let r;const{found:i,word:s}=this.config.fullWordMatchOnly?this.testWord(e):this.testWordPermutation(e);if(i){const{categoryId:e}=this.banList[s];if(this.testCategoryIgnore(e))return r;this.testWordWeight(s)&&(r=new _(e,s,t,this.banList[s].action))}return r?(n.LogInfo(`KeywordAnalyzer - analyzeSearchTerm - MATCH - Keyword: '${s}', Action: ${r.action}.`,`color:${n.FORTINET_COLOR.PURPLE}; font-weight:bolder;`),this.addToStatistics(s)):n.LogInfo(`KeywordAnalyzer - analyzeSearchTerm - NO MATCH. Keyword: '${e}'.`),r}};