adblock-rust

repository·master·Indexed 25 days ago

https://github.com/brave/adblock-rust

A high-performance adblocking engine used by the Brave browser. It provides native Rust parsing and matching for Adblock Plus syntax (e.g., EasyList, EasyPrivacy) and supports network blocking, cosmetic filtering, resource replacements, and extensions for uBlock Origin and Apple's content-blocking format. Available as a Rust crate, a Node.js npm package (adblock-rs), and community-maintained Python bindings.

Tokens
9.4K
Snippets
10
Records
67
Agent score
83%

What's inside adblock-rust

  1. Install adblock-rust via Rust or Node.js

    master

    adblock-rust is available as a library for multiple environments. You can use the Rust implementation via crates.io or the JavaScript implementation via npm.

    • Rust: Use the adblock crate.
    • JavaScript/Node.js: Use the adblock-rs npm package.
    • Python: Community-maintained bindings are available on PyPI as adblock.
  2. Configure adblock-rust optional features

    master

    You can customize the adblock-rust engine using Cargo features to suit your specific use case.

    FeatureDescription
    css-validationEnables built-in CSS validation during cosmetic filter rule parsing. Invalid CSS syntax will cause rules to be rejected.
    content-blockingEnables support for converting standard ABP-style rules into Apple's content-blocking format for iOS and macOS.
    embedded-domain-resolver(Default) Uses a built-in domain resolution implementation. Disable this to provide your own external domain resolution implementation (useful for reducing binary size in browsers).
    resource-assemblerAllows parsing uBlock Origin-compatible resources (for scriptlet injection and redirects) directly from their repository file formats.
    single-threadEnables optimizations for speed and memory. Note: Disabling this makes the engine Send + Sync, but it is recommended to use the engine on a single thread for optimal performance.
  3. Initialize the adblock Engine

    master

    The Engine is the primary interface for adblocking. It is designed to be immutable after creation; to change rules, you must create a new engine.

    To initialize an engine, combine your filter lists into a FilterSet and use Engine::new_with_filter_set. You can also provide Resources (used for $redirect filters and ##+js(...) scriptlets) using Engine::use_resources.

  4. Perform cosmetic filtering

    master

    Cosmetic filtering is a two-step process:

    1. Identify required resources: Call Engine::url_cosmetic_resources(url) to get UrlSpecificResources. This tells you what actions are needed to prepare the page.
    2. Handle dynamic elements: As the page loads, pass any new CSS classes or IDs to Engine::hidden_class_id_selectors to find additional elements that should be hidden.

    hidden_class_id_selectors requires a HashSet<String> of exceptions passed directly from the UrlSpecificResources obtained in step 1.

  5. Configure parsing with ParseOptions

    master

    When adding filters to a FilterSet, use ParseOptions to control how the rules are interpreted. It is recommended to use the struct update syntax with ParseOptions::default() to ensure compatibility with future fields.

    Key options include:

    • format: The FilterFormat to use (e.g., Standard or Hosts). Defaults to FilterFormat::Standard.
    • rule_types: A RuleTypes enum to filter which rules are kept (e.g., All, NetworkOnly, or CosmeticOnly). This can reduce memory usage.
    • permissions: A PermissionMask specifying permissions for the parsed list.
    use adblock::lists::{FilterFormat, ParseOptions, RuleTypes};
    
    let parse_options = ParseOptions {
        format: FilterFormat::Hosts,
        rule_types: RuleTypes::NetworkOnly,
        ..ParseOptions::default()
    };
  6. Configure RegexManager discard policy

    master

    The RegexManager manages the storage of compiled regular expressions used by filters. To reduce the memory footprint, it can discard infrequently used regexes. You can customize this behavior using the RegexManagerDiscardPolicy struct.

    Set the following fields:

    • cleanup_interval: The duration at which the RegexManager checks for and cleans up unused filters.
    • discard_unused_time: The duration after which a regex is considered unused and eligible for discarding.

    Use set_discard_policy to apply a new policy to an existing RegexManager instance.

  7. Unsupported cosmetic filter pseudo-classes

    master

    When writing cosmetic filters, be aware that the following pseudo-classes are currently unsupported and will cause parsing errors:

    • -abp-contains / -abp-has (Note: these are aliases for has-text and are supported, but other specific -abp- prefixes might not be)
    • -abp-properties
    • if
    • if-not
    • matches-property
    • nth-ancestor
    • properties
    • subject
    • remove
    • remove-attr
    • remove-class
  8. Configure CbAction types and selectors

    master

    The CbAction struct defines what happens when a rule's trigger matches. It contains a typ (of type CbType) and an optional selector.

    Available CbType values:

    • Block: Stops loading of the resource.
    • BlockCookies: Strips cookies from the header.
    • CssDisplayNone: Hides elements using a CSS selector. Note: The selector field is required when using this type and should contain a comma-separated list of CSS identifiers.
    • IgnorePreviousRules: Ignores previously triggered actions.
    • MakeHttps: Changes a URL from http to https.

    Important: If typ is CssDisplayNone, the selector field must be populated, otherwise Safari will ignore the rule.

  9. Manage and assemble filter lists with FilterSet

    master

    Use FilterSet to assemble a compound list of rules from multiple sources before compiling them into an Engine. This is necessary to handle special options like $badfilter and to allow for optimizations during engine creation.

    To create a new set, use FilterSet::new(debug). Setting debug to true allows the engine to retain information about the original raw filter rules.

  10. Configure Resource storage backend

    master
    By default, Engine::use_resources stores resources in-memory. If you have custom requirements for managing or sharing resources (e.g., a custom cache or disk-backed storage), you can provide a custom implementation of the ResourceStorageBackend trait using Engine::use_resource_storage.