|
| 1 | +import { CosmeticRuleType } from '@adguard/agtree'; |
1 | 2 | import { type CosmeticResult, type CosmeticRule } from '@adguard/tsurlfilter';
|
2 | 3 |
|
| 4 | +import { LF, SEMICOLON } from './constants'; |
| 5 | +import { defaultFilteringLog, FilteringEventType } from './filtering-log'; |
3 | 6 | import { type ContentType } from './request-type';
|
| 7 | +import { getDomain } from './utils/url'; |
| 8 | +import { nanoid } from './utils/nanoid'; |
4 | 9 |
|
5 | 10 | /**
|
6 | 11 | * Information for logging js rules.
|
@@ -76,13 +81,18 @@ export class CosmeticApiCommon {
|
76 | 81 | /**
|
77 | 82 | * Separator for hit stats.
|
78 | 83 | */
|
79 |
| - protected static readonly HIT_SEP = encodeURIComponent(';'); |
| 84 | + protected static readonly HIT_SEP = encodeURIComponent(SEMICOLON); |
80 | 85 |
|
81 | 86 | /**
|
82 | 87 | * Element hiding CSS style ending.
|
83 | 88 | */
|
84 | 89 | protected static readonly HIT_END = "' !important; }";
|
85 | 90 |
|
| 91 | + /** |
| 92 | + * Regular expression to find content attribute in css rule. |
| 93 | + */ |
| 94 | + protected static CONTENT_ATTR_RE = /[{;"(]\s*content\s*:/gi; |
| 95 | + |
86 | 96 | /**
|
87 | 97 | * Builds stylesheets from rules.
|
88 | 98 | * If `groupElemhideSelectors` is set,
|
@@ -163,4 +173,238 @@ export class CosmeticApiCommon {
|
163 | 173 | }
|
164 | 174 | return elemhideStyles;
|
165 | 175 | }
|
| 176 | + |
| 177 | + /** |
| 178 | + * Patches rule selector adding adguard mark rule info in the content attribute. |
| 179 | + * |
| 180 | + * @example |
| 181 | + * `.selector` -> `.selector { content: 'adguard{filterId};{ruleText} !important;}` |
| 182 | + * |
| 183 | + * @param rule Elemhide cosmetic rule. |
| 184 | + * |
| 185 | + * @returns Rule with modified stylesheet, containing content marker. |
| 186 | + */ |
| 187 | + private static addMarkerToElemhideRule(rule: CosmeticRule): string { |
| 188 | + const result: string[] = []; |
| 189 | + result.push(rule.getContent()); |
| 190 | + result.push(CosmeticApiCommon.ELEMHIDE_HIT_START); |
| 191 | + result.push(String(rule.getFilterListId())); |
| 192 | + result.push(CosmeticApiCommon.HIT_SEP); |
| 193 | + result.push(String(rule.getIndex())); |
| 194 | + result.push(CosmeticApiCommon.HIT_END); |
| 195 | + return result.join(''); |
| 196 | + } |
| 197 | + |
| 198 | + /** |
| 199 | + * Patches rule selector adding adguard mark and rule info in the content style attribute. |
| 200 | + * Example: |
| 201 | + * .selector { color: red } -> .selector { color: red, content: 'adguard{filterId};{ruleText} !important;}. |
| 202 | + * |
| 203 | + * @param rule Inject cosmetic rule. |
| 204 | + * |
| 205 | + * @returns Modified rule with injected content marker into stylesheet. |
| 206 | + */ |
| 207 | + private static addMarkerToInjectRule(rule: CosmeticRule): string { |
| 208 | + const result: string[] = []; |
| 209 | + const ruleContent = rule.getContent(); |
| 210 | + // if rule text has content attribute we don't add rule marker |
| 211 | + if (CosmeticApiCommon.CONTENT_ATTR_RE.test(ruleContent)) { |
| 212 | + return ruleContent; |
| 213 | + } |
| 214 | + |
| 215 | + // remove closing brace |
| 216 | + const ruleTextWithoutCloseBrace = ruleContent.slice(0, -1).trim(); |
| 217 | + // check semicolon |
| 218 | + const ruleTextWithSemicolon = ruleTextWithoutCloseBrace.endsWith(SEMICOLON) |
| 219 | + ? ruleTextWithoutCloseBrace |
| 220 | + : `${ruleTextWithoutCloseBrace}${SEMICOLON}`; |
| 221 | + result.push(ruleTextWithSemicolon); |
| 222 | + result.push(CosmeticApiCommon.INJECT_HIT_START); |
| 223 | + result.push(String(rule.getFilterListId())); |
| 224 | + result.push(CosmeticApiCommon.HIT_SEP); |
| 225 | + result.push(String(rule.getIndex())); |
| 226 | + result.push(CosmeticApiCommon.HIT_END); |
| 227 | + |
| 228 | + return result.join(''); |
| 229 | + } |
| 230 | + |
| 231 | + /** |
| 232 | + * Builds stylesheets with css-hits marker. |
| 233 | + * |
| 234 | + * @param elemhideRules Elemhide css rules. |
| 235 | + * @param injectRules Inject css rules. |
| 236 | + * |
| 237 | + * @returns List of stylesheet expressions. |
| 238 | + */ |
| 239 | + private static buildStyleSheetsWithHits( |
| 240 | + elemhideRules: CosmeticRule[], |
| 241 | + injectRules: CosmeticRule[], |
| 242 | + ): string[] { |
| 243 | + const elemhideStyles = elemhideRules.map((x) => CosmeticApiCommon.addMarkerToElemhideRule(x)); |
| 244 | + const injectStyles = injectRules.map((x) => CosmeticApiCommon.addMarkerToInjectRule(x)); |
| 245 | + |
| 246 | + return [...elemhideStyles, ...injectStyles]; |
| 247 | + } |
| 248 | + |
| 249 | + /** |
| 250 | + * Builds extended css rules from cosmetic result. |
| 251 | + * |
| 252 | + * @param cosmeticResult Cosmetic result. |
| 253 | + * @param collectingCosmeticRulesHits Flag to collect cosmetic rules hits. |
| 254 | + * @returns Array of extended css rules or null. |
| 255 | + */ |
| 256 | + public static getExtCssRules( |
| 257 | + cosmeticResult: CosmeticResult, |
| 258 | + collectingCosmeticRulesHits = false, |
| 259 | + ): string[] | null { |
| 260 | + const { elementHiding, CSS } = cosmeticResult; |
| 261 | + |
| 262 | + const elemhideExtCss = elementHiding.genericExtCss.concat(elementHiding.specificExtCss); |
| 263 | + const injectExtCss = CSS.genericExtCss.concat(CSS.specificExtCss); |
| 264 | + |
| 265 | + let extCssRules: string[]; |
| 266 | + |
| 267 | + if (collectingCosmeticRulesHits) { |
| 268 | + extCssRules = CosmeticApiCommon.buildStyleSheetsWithHits(elemhideExtCss, injectExtCss); |
| 269 | + } else { |
| 270 | + extCssRules = CosmeticApiCommon.buildStyleSheets(elemhideExtCss, injectExtCss, false); |
| 271 | + } |
| 272 | + |
| 273 | + return extCssRules.length > 0 |
| 274 | + ? extCssRules |
| 275 | + : null; |
| 276 | + } |
| 277 | + |
| 278 | + /** |
| 279 | + * Retrieves CSS styles from the cosmetic result. |
| 280 | + * |
| 281 | + * @param cosmeticResult Cosmetic result. |
| 282 | + * @param collectingCosmeticRulesHits Flag to collect cosmetic rules hits. |
| 283 | + * |
| 284 | + * @returns Css styles as string, or `undefined` if no styles found. |
| 285 | + */ |
| 286 | + public static getCssText( |
| 287 | + cosmeticResult: CosmeticResult, |
| 288 | + collectingCosmeticRulesHits = false, |
| 289 | + ): string | undefined { |
| 290 | + const { elementHiding, CSS } = cosmeticResult; |
| 291 | + |
| 292 | + const elemhideCss = elementHiding.generic.concat(elementHiding.specific); |
| 293 | + const injectCss = CSS.generic.concat(CSS.specific); |
| 294 | + |
| 295 | + let styles: string[]; |
| 296 | + |
| 297 | + if (collectingCosmeticRulesHits) { |
| 298 | + styles = CosmeticApiCommon.buildStyleSheetsWithHits(elemhideCss, injectCss); |
| 299 | + } else { |
| 300 | + styles = CosmeticApiCommon.buildStyleSheets(elemhideCss, injectCss, true); |
| 301 | + } |
| 302 | + |
| 303 | + if (styles.length > 0) { |
| 304 | + return styles.join(CosmeticApiCommon.LINE_BREAK); |
| 305 | + } |
| 306 | + |
| 307 | + return undefined; |
| 308 | + } |
| 309 | + |
| 310 | + /** |
| 311 | + * Wraps the given JavaScript code in a self-invoking function for safe execution |
| 312 | + * and appends a source URL comment for debugging purposes. |
| 313 | + * |
| 314 | + * @param scriptText The JavaScript code to wrap. |
| 315 | + * @returns The wrapped script code, or an empty string if the input is falsy. |
| 316 | + */ |
| 317 | + protected static wrapScriptText(scriptText: string): string { |
| 318 | + if (!scriptText) { |
| 319 | + return ''; |
| 320 | + } |
| 321 | + |
| 322 | + // The "//# sourceURL=ag-scripts.js" line is necessary to ensure the script always has the same URL, |
| 323 | + // making it possible to debug consistently. |
| 324 | + return ` |
| 325 | + (function () { |
| 326 | + try { |
| 327 | + ${scriptText} |
| 328 | + } catch (ex) { |
| 329 | + console.error('Error executing AG js: ' + ex); |
| 330 | + } |
| 331 | + })(); |
| 332 | + //# sourceURL=ag-scripts.js |
| 333 | + `; |
| 334 | + } |
| 335 | + |
| 336 | + /** |
| 337 | + * Combines unique script strings into a single script text. |
| 338 | + * |
| 339 | + * Script string is being trimmed and a semicolon is added if it is missing. |
| 340 | + * |
| 341 | + * @param uniqueScriptStrings Set of unique script strings to combine. |
| 342 | + * |
| 343 | + * @returns Combined script string. |
| 344 | + */ |
| 345 | + protected static combineScripts(uniqueScriptStrings: Set<string>): string { |
| 346 | + let scriptText = ''; |
| 347 | + |
| 348 | + uniqueScriptStrings.forEach((rawScriptStr) => { |
| 349 | + const script = rawScriptStr.trim(); |
| 350 | + |
| 351 | + scriptText += script.endsWith(SEMICOLON) |
| 352 | + ? `${script}${LF}` |
| 353 | + : `${script}${SEMICOLON}${LF}`; |
| 354 | + }); |
| 355 | + |
| 356 | + return scriptText; |
| 357 | + } |
| 358 | + |
| 359 | + /** |
| 360 | + * Logs js rules applied to a specific frame. |
| 361 | + * |
| 362 | + * @param params Data for js rule logging. |
| 363 | + * @param predicate Function to filter script rules before logging, e.g. check if the script rule is local. |
| 364 | + */ |
| 365 | + protected static logScriptRules( |
| 366 | + params: LogJsRulesParams, |
| 367 | + predicate: (cosmeticResult: CosmeticRule) => boolean, |
| 368 | + ): void { |
| 369 | + const { |
| 370 | + tabId, |
| 371 | + cosmeticResult, |
| 372 | + url, |
| 373 | + contentType, |
| 374 | + timestamp, |
| 375 | + } = params; |
| 376 | + |
| 377 | + const scriptRules = cosmeticResult.getScriptRules().filter(predicate); |
| 378 | + |
| 379 | + for (const scriptRule of scriptRules) { |
| 380 | + if (scriptRule.isGeneric()) { |
| 381 | + continue; |
| 382 | + } |
| 383 | + |
| 384 | + const ruleType = scriptRule.getType(); |
| 385 | + defaultFilteringLog.publishEvent({ |
| 386 | + type: FilteringEventType.JsInject, |
| 387 | + data: { |
| 388 | + script: true, |
| 389 | + tabId, |
| 390 | + // for proper filtering log request info rule displaying |
| 391 | + // event id should be unique for each event, not copied from request |
| 392 | + // https://github.com/AdguardTeam/AdguardBrowserExtension/issues/2341 |
| 393 | + eventId: nanoid(), |
| 394 | + requestUrl: url, |
| 395 | + frameUrl: url, |
| 396 | + frameDomain: getDomain(url) as string, |
| 397 | + requestType: contentType, |
| 398 | + timestamp, |
| 399 | + filterId: scriptRule.getFilterListId(), |
| 400 | + ruleIndex: scriptRule.getIndex(), |
| 401 | + cssRule: ruleType === CosmeticRuleType.ElementHidingRule |
| 402 | + || ruleType === CosmeticRuleType.CssInjectionRule, |
| 403 | + scriptRule: ruleType === CosmeticRuleType.ScriptletInjectionRule |
| 404 | + || ruleType === CosmeticRuleType.JsInjectionRule, |
| 405 | + contentRule: ruleType === CosmeticRuleType.HtmlFilteringRule, |
| 406 | + }, |
| 407 | + }); |
| 408 | + } |
| 409 | + } |
166 | 410 | }
|
0 commit comments