nothyperboiz1
📎 1 file 45,615 chars
📄
pasted-code-1790261753883.txt
txt 2103 lines
▶
You are a principal browser-platform engineering team responsible for designing, implementing, testing, auditing, and packaging a production-grade, best-in-class all-in-one browser extension.

Build a complete product, not a prototype, mockup, proof of concept, or collection of disconnected demos.

The product should combine an extremely fast ad blocker, tracker blocker, privacy/security suite, browser optimizer, reader, dark-mode engine, screenshot/annotation toolkit, session manager, secure password vault, custom site modification engine, and optional proxy/VPN infrastructure into one polished extension.

The product must be engineered around real browser API capabilities. Never fake functionality, silently downgrade security, or claim a capability exists when the target browser does not technically allow it.

PRODUCT OBJECTIVE

Create a premium browser extension that provides:

1. Extremely aggressive but reliable ad blocking.
2. Strong privacy and anti-tracking protection.
3. Minimal CPU, memory, latency, and battery overhead.
4. Excellent website compatibility.
5. A highly understandable user experience.
6. Deep per-site customization.
7. Advanced power-user controls.
8. Secure storage for sensitive information.
9. Cross-browser support from a shared architecture.
10. Optional native components for capabilities that WebExtensions cannot provide directly.
11. Enterprise-grade deployment and administration.
12. Automated updates, recovery, rollback, diagnostics, and testing.

The product must feel closer to a complete browser security/control platform than an ordinary ad-blocking extension.

CORE ENGINEERING PRINCIPLES

Follow these principles throughout the implementation:

* Security before convenience.
* Performance before unnecessary abstraction.
* Browser-native blocking APIs before JavaScript interception.
* Declarative processing before procedural processing.
* Local-first operation.
* Zero telemetry by default.
* No remote executable code.
* No hidden data collection.
* No plaintext secrets in ordinary extension storage.
* Least-privilege permissions.
* Graceful degradation by browser.
* Browser-specific adapters behind a common interface.
* Deterministic builds.
* Automated testing for every critical subsystem.
* No placeholder implementations for advertised features.
* No fake metrics.
* No simulated VPN status.
* No fake "AI" features merely to make the product look advanced.

Before implementing each capability, determine which browser APIs actually support it. Where an API is unavailable, implement the strongest legitimate alternative and explicitly expose its capability status.

PLATFORM TARGET

Support:

* Google Chrome
* Mozilla Firefox
* Microsoft Edge
* Opera
* Apple Safari

Use a unified TypeScript/JavaScript codebase wherever practical.

Use platform adapters such as:

/src/platform/chromium
/src/platform/firefox
/src/platform/safari
/src/platform/shared

Do not fork the entire product per browser.

The architecture should allow:

* shared business logic
* shared filter compilation
* shared settings model
* shared UI components
* shared encryption model
* shared testing infrastructure

while providing browser-specific implementations for APIs that differ.

MANIFEST AND RUNTIME ARCHITECTURE

Target Manifest V3 wherever supported.

Use:

* extension service worker/background runtime
* declarative network request blocking
* content scripts
* dynamic rules
* static rulesets
* optional permissions
* optional host permissions
* extension storage
* IndexedDB where appropriate
* offscreen documents where genuinely required
* side panel where supported
* context menus
* tabs/session APIs
* browser-specific adapters

Never build the entire blocking system around a constantly running JavaScript request interceptor.

The primary request-blocking path must use the browser's declarative request-blocking facilities wherever available.

The service worker must remain extremely lightweight and event-driven.

Design the service worker so that it can be started and stopped repeatedly without losing state or creating correctness bugs.

Do not rely on persistent background execution.

Keep all extension code packaged locally.

Do not dynamically download and execute JavaScript, WebAssembly, HTML, CSS, or executable code from remote servers.

REMOTE FILTER DATA MAY BE DOWNLOADED AS DATA, parsed, validated, compiled, and transformed into supported local rule representations, but never execute remote code.

AD BLOCKING ENGINE

Implement a multi-layer blocking architecture.

LAYER 1 — DECLARATIVE NETWORK BLOCKING

Implement network-level request blocking using browser-supported declarative APIs.

Block or control:

* advertising domains
* tracking domains
* ad servers
* analytics
* telemetry endpoints
* malicious advertising
* malvertising
* redirect chains
* ad auctions
* tracking beacons
* tracking pixels
* third-party scripts
* third-party frames
* suspicious pop-up destinations
* unwanted media
* unwanted prefetch/prerender requests where possible

Support resource types including:

* main frame
* sub frame
* script
* image
* stylesheet
* font
* media
* XMLHttpRequest/fetch
* ping
* websocket where supported
* other browser-supported resource categories

Use filtering conditions based on:

* URL
* domain
* initiator
* resource type
* first-party/third-party status
* allowlist
* blocklist
* rule priority
* browser capabilities

Use a highly optimized rule compilation system.

Do not scan every filter rule sequentially for every request.

Use compact representations such as:

* hashed domains
* suffix trees
* prefix indexing
* trie structures
* tokenized URL indexes
* Bloom filters where useful
* compact bitsets
* resource-type indexes
* priority indexes
* precompiled match structures

Browser-native declarative rules should handle the largest possible percentage of traffic.

LAYER 2 — CUSTOM FILTER ENGINE

Implement an internal filter engine to process filter syntax not directly representable by the browser's declarative APIs.

Support, where technically possible:

* EasyList
* EasyPrivacy
* uBlock Origin-compatible filters
* regional filter lists
* custom user filters
* hosts-format lists
* domain blocklists
* allowlists
* cosmetic filters
* resource-type filters
* important rules
* redirect rules where supported
* CSP/header rules where permitted
* procedural cosmetic filtering where safely implementable

Create a filter parser with:

* syntax validation
* browser capability detection
* normalization
* compilation
* deduplication
* priority resolution
* conflict resolution
* rule compression
* unsupported-syntax reporting

Never silently pretend every uBlock Origin feature is supported by every browser.

Maintain a capability matrix.

Example:

Filter feature -> Chrome -> Firefox -> Edge -> Opera -> Safari -> Fallback

When syntax is unsupported by a browser's native declarative API, use the safest compatible fallback.

LAYER 3 — COSMETIC FILTERING

Implement cosmetic filtering through content scripts and efficiently compiled CSS selectors.

Hide:

* ad placeholders
* empty advertisement containers
* sponsored widgets
* recommended-content blocks
* promotional overlays
* fake download buttons
* sticky advertising elements
* ad-related empty spaces
* newsletter interruptions
* cookie overlays when explicitly enabled by the user
* anti-adblock overlays when safely removable

Implement:

* generic selectors
* domain-specific selectors
* procedural selectors
* dynamically generated DOM handling
* MutationObserver integration
* throttled DOM analysis
* selector deduplication
* incremental updates

Do not repeatedly scan the entire DOM.

Use incremental mutation processing.

Avoid layout thrashing.

Do not cause visible page flicker during cosmetic filtering.

ANTI-ADBLOCK HANDLING

Implement an advanced anti-adblock compatibility system.

Detect patterns such as:

* adblock warning overlays
* page-locking overlays
* "disable your ad blocker" messages
* hidden content revealed only after ad scripts execute
* adblock detection scripts
* artificial delayed-loading barriers

Remove or neutralize these only when technically and legally appropriate.

Provide a per-site control:

"Allow site to detect protection"

and:

"Disable anti-adblock intervention for this site"

Never break legitimate security/login/payment mechanisms merely because they resemble anti-adblock systems.

VIDEO AD BLOCKING

Support video advertising where technically possible.

Handle:

* pre-roll
* mid-roll
* post-roll
* overlay advertising
* ad containers
* video advertising requests
* advertising media streams where detectable and blockable
* player-side ad overlays

Do not claim guaranteed universal video-ad elimination.

For video platforms with architecture that prevents extension-level removal of server-side advertising, implement the strongest compatible combination of:

* network filtering
* cosmetic filtering
* player manipulation where safe
* user controls
* transparent compatibility status

PRIVACY PROTECTION

Implement a dedicated privacy engine capable of blocking or limiting:

* third-party trackers
* analytics
* advertising identifiers
* tracking pixels
* telemetry
* fingerprinting endpoints
* social trackers
* session replay
* cross-site tracking
* suspicious third-party scripts
* tracking query parameters
* known tracking cookies
* third-party cookie access where browser APIs permit
* link decoration/tracking parameters

TRACKER CATEGORIES

Categorize blocked activity into:

* advertising
* analytics
* tracking
* fingerprinting
* social
* malware
* cryptomining
* telemetry
* nuisance
* privacy-invasive content
* custom user rules

PRIVACY LEVELS

Provide:

BASIC

* standard ad blocking
* known tracker blocking
* low compatibility risk

BALANCED

* stronger tracker protection
* cosmetic filtering
* third-party nuisance blocking
* tracking parameter reduction
* moderate fingerprinting protection

STRICT

* aggressive tracker blocking
* stronger third-party isolation
* stricter cookie controls
* aggressive fingerprinting mitigations
* stronger nuisance/overlay protection
* stronger script restrictions where supported

CUSTOM

Allow users to control individual protection categories.

Display clearly what each mode changes.

Do not hide important compatibility consequences.

HTTPS AND TRANSPORT SECURITY

Implement:

* HTTPS upgrade where appropriate
* mixed-content blocking/mitigation where permitted
* insecure resource detection
* HTTP-to-HTTPS upgrading
* certificate/security warning awareness
* unsafe-resource reporting

Do not interfere with browser-native certificate validation.

Do not implement an insecure "accept invalid certificates" mode.

DNS-OVER-HTTPS

Implement DoH where browser/platform APIs allow it.

Allow configurable providers.

Architecture must support:

* provider profiles
* custom DoH endpoint
* fallback provider
* bootstrap resolution where appropriate
* timeout
* failover
* health checks
* privacy-preserving configuration

Important platform constraint:

An extension must never pretend it has system-wide DNS control when it only controls extension-originated traffic.

For browsers where full browser/device DNS control is unavailable to an extension, provide:

* extension-level DoH where possible
* optional browser configuration instructions
* optional native companion support
* capability indicators

PERFORMANCE OPTIMIZATION

Performance is a primary product feature.

TARGET BENCHMARKS

Aim for:

* average blocking decision overhead: <5 ms
* p95 blocking decision overhead: <10 ms
* no repeated linear scans through the full filter database
* service worker idle memory: ideally <20 MB
* normal runtime incremental extension memory: target <50 MB excluding browser-managed native rule storage
* minimal startup work
* near-zero CPU usage while idle
* no visible page-load delay caused by extension initialization
* cosmetic filtering should generally complete in <16 ms per incremental mutation batch
* settings UI should feel instantaneous
* filter update processing should happen off the critical page-load path
* no unnecessary synchronous filesystem/storage operations

Treat the <5 ms figure as an engineering benchmark for the extension's own matching/decision path, not as a promise about total browser networking latency.

Benchmark separately:

* rule lookup
* filter compilation
* cosmetic selector matching
* settings lookup
* whitelist lookup
* service-worker wakeup
* filter-list update
* page instrumentation

Build automated performance benchmarks into CI.

MEMORY OPTIMIZATION

Use:

* compact data structures
* lazy initialization
* lazy rule loading
* deduplication
* typed arrays where appropriate
* IndexedDB for large local data
* browser-native rule storage where possible
* bounded caches
* LRU caches
* disposal of temporary compilation structures
* compressed filter representations

Never load every raw filter list into multiple in-memory representations simultaneously unless profiling proves it necessary.

CPU OPTIMIZATION

Avoid:

* polling loops
* unnecessary MutationObservers
* entire-DOM rescans
* high-frequency timers
* busy-waiting
* synchronous large JSON parsing on critical UI paths
* unnecessary message passing
* repeated serialization/deserialization

PAGE LOAD OPTIMIZATION

Add controls for:

* blocking autoplay
* lazy image loading
* lazy iframe loading where safe
* reducing tracking scripts
* blocking heavy third-party resources
* reducing unnecessary fonts
* blocking resource prefetching where appropriate
* preventing background video playback
* optional JavaScript-heavy resource controls

Do not automatically break legitimate application functionality.

PER-SITE EXCEPTIONS

Every protection layer must support:

* allow this site
* temporarily allow
* permanently allow
* allow only specific features
* strict mode
* custom filtering

Examples:

Allow ads but block trackers.

Block ads but allow analytics.

Allow video.

Allow popups.

Disable cosmetic filtering.

Disable custom JavaScript.

Disable dark mode.

Disable anti-adblock handling.

SITE CONFIGURATION UI

Create a polished per-site control panel.

Display:

* protection status
* blocked requests
* tracker categories
* cosmetic filters applied
* scripts blocked
* privacy level
* current rule lists
* site-specific overrides
* performance impact
* quick enable/disable controls

GLOBAL STATISTICS DASHBOARD

Create a real-time statistics dashboard containing:

* total ads blocked
* trackers blocked
* requests blocked
* scripts blocked
* popups prevented
* suspicious connections blocked
* estimated bandwidth saved
* estimated page-load time saved
* estimated CPU work avoided where measurable
* sites protected
* filter-list activity
* protection events over time

Do not invent precision.

Clearly distinguish:

* exact browser-provided counts
* measured counts
* modeled estimates

Provide daily/weekly/monthly views.

Include:

* charts
* trends
* top blocked domains
* top tracking categories
* top protected sites
* recent events
* privacy score explanation

The dashboard must remain lightweight.

LOGGING AND DIAGNOSTICS

Create an accessible diagnostics system.

Allow users to inspect:

* request URL
* resource type
* initiator
* matching rule/list
* action
* timestamp
* site
* exception/allowlist reason
* cosmetic rule
* filter-list version

Include:

* search
* filtering
* export diagnostics
* copy rule
* create exception
* report false positive
* report broken site

Sensitive URLs or query strings must be sanitized when exported unless the user explicitly chooses full diagnostic export.

PASSWORD MANAGER / SECURE VAULT

Implement a secure local password manager.

Features:

* encrypted vault
* master password
* password generator
* username/password storage
* secure notes
* passkey metadata support where browser APIs permit
* password autofill
* username autofill
* form detection
* save-password prompt
* edit credentials
* search vault
* favorites
* folders
* password health checks
* duplicate password detection
* weak password detection
* optional breach-check integration using privacy-preserving methods

Security requirements:

* never store plaintext passwords in ordinary extension storage
* use modern authenticated encryption
* use a memory-hard key derivation function
* securely wipe sensitive buffers where realistically possible
* minimize password lifetime in memory
* require re-authentication for sensitive operations
* automatic vault locking
* idle timeout
* optional biometric/OS-keychain integration through native components
* clipboard auto-clear for copied secrets
* prevent secrets from appearing in logs
* never transmit plaintext vault data to the server

Cloud synchronization must use end-to-end encryption.

The server should never possess the user's decryption key.

Provide an encrypted export format for offline backup.

Import/export must support schema version migration.

PASSWORD AUTOFILL SECURITY

Never autofill credentials into:

* mismatched domains
* suspicious cross-origin frames
* visually hidden forms
* unrelated pages
* user-disabled domains

Display domain identity clearly before sensitive autofill.

VPN / PROXY ARCHITECTURE

Implement two clearly separated modes.

MODE A — BROWSER PROXY

Where browser APIs permit:

* proxy profiles
* HTTP proxy
* HTTPS proxy
* SOCKS support where available
* routing rules
* bypass lists
* per-domain routing
* quick connect/disconnect
* connection status
* proxy health checks

MODE B — NATIVE VPN

For true device-level VPN capability, implement an optional native companion/application architecture using the operating system's VPN/network APIs.

The extension must not claim that browser proxy mode is a full system VPN.

Support:

* connection state
* endpoint selection
* kill switch where technically available
* DNS leak prevention where technically available
* split tunneling where available
* routing exclusions
* auto-connect
* network-change handling

Do not implement illegal access-control circumvention mechanisms.

Do not bypass DRM.

Do not defeat authentication or paywalls.

DARK MODE ENGINE

Implement a universal website dark-mode system.

Modes:

* off
* browser preference
* automatic
* forced dark
* smart adaptive

Features:

* CSS transformation
* color inversion only when necessary
* image protection
* video protection
* SVG handling
* canvas handling
* per-site overrides
* dynamic SPA support
* readable text contrast
* form/control adaptation
* syntax-highlighting preservation

Avoid crude full-page inversion wherever a semantic CSS transformation is possible.

READER MODE

Create a high-quality reader mode.

Capabilities:

* article extraction
* title detection
* author/date extraction
* main-content extraction
* image preservation
* caption preservation
* heading hierarchy
* lists
* tables where feasible
* code block preservation
* typography controls
* width controls
* font controls
* spacing controls
* reading time
* print mode
* save offline

TEXT-TO-SPEECH

Add reader-mode text-to-speech.

Features:

* play
* pause
* stop
* speed
* voice selection
* sentence highlighting where browser APIs support it
* section navigation
* keyboard shortcuts

Use platform speech APIs before attempting custom audio generation.

SCREENSHOT AND ANNOTATION

Implement:

* visible-page screenshot
* full-page screenshot where technically possible
* selected-area screenshot
* delayed capture
* capture current tab
* copy to clipboard
* save image
* annotation editor

Annotation tools:

* rectangle
* ellipse
* arrow
* line
* freehand drawing
* text
* blur/pixelation
* crop
* highlight
* undo/redo
* copy
* save
* export

SESSION MANAGER

Implement:

* save window
* restore window
* save tabs
* restore tabs
* named sessions
* automatic session backup
* recently closed sessions
* session search
* session export
* session import
* conflict resolution

TAB SUSPENDER

Provide a tab suspension system.

Features:

* configurable inactivity threshold
* excluded sites
* excluded audio tabs
* excluded pinned tabs
* excluded forms
* excluded active downloads
* manual suspend
* manual wake
* memory savings estimate

Never suspend:

* active media playback
* active downloads
* form-entry pages
* pages with user-configured exclusions

CUSTOM CSS AND JAVASCRIPT

Provide an advanced site customization engine.

Users can create:

* CSS rules
* JavaScript snippets

Support:

* per-domain targeting
* enable/disable toggle
* execution timing
* import/export
* syntax highlighting
* validation
* versioning
* backup
* profiles

Security requirements:

* never execute remotely downloaded arbitrary code
* execute only user-authored or locally packaged code
* clearly warn users about the security implications
* isolate execution where possible
* enforce strict extension CSP
* never use eval or new Function unless a browser-specific capability is explicitly proven safe and necessary; default to prohibition

FILTER LIST MANAGEMENT

Support:

* EasyList
* EasyPrivacy
* uBlock-compatible lists where compatible
* regional lists
* malware lists
* nuisance lists
* user-created lists
* hosts files

Provide:

* enable/disable
* priority
* update interval
* last update
* current version
* checksum/hash
* update status
* list size
* parsed rule count
* supported-rule count
* unsupported-rule count
* failed-rule count

UPDATE SYSTEM

Implement resilient filter updates.

Requirements:

* HTTPS-only update transport
* integrity verification
* checksum/signature validation where available
* atomic updates
* version validation
* rollback
* previous-known-good copy
* timeout
* retry
* exponential backoff
* multiple mirrors where appropriate
* fallback lists
* corrupted-data detection
* update cancellation
* offline operation using cached lists

Never replace a healthy ruleset with an invalid or partially downloaded ruleset.

Browser STORE / RELEASE builds must contain a safe default ruleset so protection remains functional when remote updates fail.

FILTER COMPILER

Build a dedicated filter compilation pipeline.

Pipeline:

raw filter list
→ parser
→ syntax classification
→ normalization
→ deduplication
→ compatibility analysis
→ browser-specific compilation
→ optimization
→ validation
→ packaging
→ checksum
→ deployment

Produce browser-specific rule bundles where necessary.

Track unsupported syntax.

Create a test corpus covering thousands of real-world filter patterns.

USER CUSTOM RULES

Support syntax such as:

* domain blocks
* domain allowlists
* resource-specific blocks
* cosmetic CSS selectors
* per-site exceptions

Validate every custom rule before activation.

If a rule is invalid, provide an understandable error explaining why.

PERMISSIONS

Request the minimum permissions necessary.

Use optional permissions where practical.

Do not request broad permissions merely because they are convenient.

Create an in-app permission explanation screen that states:

* why permission is needed
* what data becomes accessible
* which feature requires it
* how the user can revoke it

SECURE STORAGE

Partition storage into:

1. normal settings
2. performance/cache data
3. filter metadata
4. site configuration
5. session data
6. encrypted vault
7. diagnostics

Never mix password-vault secrets with ordinary settings.

Use browser-provided managed storage/policy mechanisms for enterprise configuration where supported.

CLOUD SYNC

Optional account/cloud functionality must support:

* end-to-end encrypted sync
* settings synchronization
* allowlists
* blocklists
* site overrides
* custom filters
* dark-mode preferences
* reader preferences
* sessions
* encrypted vault synchronization only after explicit user opt-in

Never upload:

* browsing history by default
* visited URL telemetry
* password plaintext
* decrypted vault contents
* unrestricted browsing logs
* personal data unrelated to the requested sync feature

Allow users to disable cloud services entirely.

WORK OFFLINE

Core ad blocking, filtering, privacy protection, cosmetic filtering, site preferences, dark mode, reader mode, and basic tools must continue working without a cloud account.

No account should be required for basic protection.

UI/UX

Build a premium, modern, extremely polished interface.

Avoid generic "AI dashboard" aesthetics.

Do not rely on excessive gradients, fake glass effects, or decorative animation that hurts usability.

Prioritize:

* clarity
* fast interaction
* information density where useful
* accessibility
* keyboard navigation
* responsive layout
* obvious protection state
* understandable terminology

PRIMARY POPUP

The popup should display:

Protection ON/OFF

This site:
Protection level
Ads blocked
Trackers blocked
Requests blocked
Data saved

Quick controls:

* protection toggle
* privacy level
* cosmetic filtering
* temporarily allow
* permanent allow
* open dashboard
* open settings

Do not make the popup excessively large.

ADVANCED DASHBOARD

Provide sections:

Overview
Protection
Privacy
Filter Lists
Performance
Sites
Vault
Reader
Tools
Sessions
Proxy/VPN
Settings
Diagnostics
About

Use a consistent design system.

ACCESSIBILITY

Target WCAG 2.1 AA.

Implement:

* keyboard navigation
* focus indicators
* semantic HTML
* ARIA where required
* sufficient contrast
* reduced-motion mode
* screen-reader labels
* logical tab order
* keyboard shortcuts
* scalable typography
* no color-only meaning
* accessible dialogs
* accessible charts

NOTIFICATIONS

Notifications must be:

* useful
* infrequent
* dismissible
* configurable

Never spam users with "blocked ad" notifications on every page.

Use aggregated notifications such as:

"42 requests blocked on this page."

Detailed diagnostics belong in the dashboard.

SECURITY ARCHITECTURE

Implement a formal threat model.

Threats must include:

* malicious webpage
* compromised website
* malicious filter list
* compromised update server
* malicious extension dependency
* supply-chain compromise
* malicious native companion
* privilege escalation
* credential theft
* XSS in extension UI
* CSRF
* confused deputy attacks
* message spoofing
* content-script injection
* prototype pollution
* dependency vulnerabilities
* malicious imported configuration
* malicious custom scripts

SECURITY REQUIREMENTS

* strict extension Content Security Policy
* no unnecessary remote resources
* no inline executable scripts where prohibited
* no arbitrary remote code execution
* strict input validation
* schema validation for imported files
* signed releases
* dependency pinning
* lockfile enforcement
* automated dependency scanning
* static analysis
* secret scanning
* SBOM generation
* reproducible release builds where practical
* secure update validation
* permission minimization
* secure postMessage/message-channel validation
* origin verification
* safe DOM APIs
* DOM sanitization for reader content
* safe URL handling
* secure credential autofill
* encrypted vault
* secure deletion strategy where feasible

Do not collect analytics about browsing behavior unless the user explicitly opts in.

SECURITY AUDITS

Before production release, require:

1. SAST
2. dependency vulnerability scan
3. secret scan
4. license scan
5. SBOM generation
6. extension-manifest review
7. permission audit
8. CSP audit
9. XSS audit
10. content-script isolation review
11. custom-script execution review
12. filter parser fuzz testing
13. import/export fuzz testing
14. malicious-filter testing
15. vault cryptographic review
16. native companion security review if implemented
17. penetration testing
18. third-party security assessment

Critical vulnerabilities must block release.

No "known vulnerability but ship anyway" policy for critical issues.

FILTER PARSER SECURITY

Treat filter lists as hostile/untrusted input.

Test against:

* malformed syntax
* huge rules
* regex bombs
* pathological selectors
* extremely long domains
* deeply nested data
* Unicode edge cases
* null bytes
* unexpected encodings
* resource exhaustion
* parser crashes
* catastrophic regex behavior

Apply hard bounds to:

* rule length
* selector length
* regex complexity
* list size
* memory usage
* compilation time

Do not allow a filter list to freeze the browser or extension.

FALSE POSITIVES

Implement a false-positive reporting workflow.

Users can:

* report broken site
* inspect blocking rule
* temporarily unblock
* whitelist a specific resource
* whitelist a domain
* disable a particular filter list
* report filter conflict

Provide automated conflict diagnostics.

PERFORMANCE OBSERVABILITY

Create an internal benchmark mode that records:

* filter lookup latency
* rule compilation time
* memory usage
* CPU time
* DOM mutation processing time
* service-worker wakeups
* filter-list update time
* settings load time
* dashboard rendering time

Do not expose raw developer metrics to ordinary users unless they explicitly enter diagnostics mode.

BROWSER COMPATIBILITY MATRIX

Maintain a machine-readable compatibility matrix for every major feature.

Example categories:

Network blocking
Cosmetic filtering
Cookie controls
HTTPS upgrades
DoH
Proxy
Native VPN
Screenshot
Full-page screenshot
TTS
Reader mode
Tab suspension
Side panel
Context menus
Cloud sync
OS keychain
Enterprise policy

Every unsupported feature must:

* be disabled gracefully
* have a clear explanation
* never crash the extension
* not affect unrelated functionality

SAFARI ARCHITECTURE

Treat Safari as a first-class platform, but do not assume complete Chromium API parity.

Where Safari requires a containing application or native extension component, create a proper Safari app-extension/native architecture.

Use the shared web-extension logic where possible and provide native bridging where needed.

The Safari implementation should support:

* content blocking
* settings
* native communication where necessary
* secure native storage integrations
* appropriate permissions
* App Store packaging
* macOS support
* iOS/iPadOS support where feasible

Do not compromise Safari security merely to preserve an artificial one-codepath design.

NATIVE COMPANION ARCHITECTURE

For features impossible or impractical in an ordinary browser extension, create an optional native companion design.

Potential responsibilities:

* system-level VPN
* system proxy
* deeper DNS controls
* OS keychain
* native secure storage
* desktop integrations
* system-level performance tools

Implement using a secure local IPC/native messaging protocol.

Requirements:

* authenticated communication
* explicit user installation
* least privilege
* signed binaries
* secure update mechanism
* OS-specific installers
* graceful absence handling
* no permanent privileged daemon unless required
* clear uninstall process

ENTERPRISE MODE

Implement enterprise management.

Support:

* force-install capability where browser policy allows
* managed settings
* administrator-defined filter lists
* administrator-defined allowlists
* locked privacy settings
* locked proxy settings
* disabled user overrides
* update policy
* organization branding where appropriate
* diagnostic mode
* policy import/export
* JSON policy schema
* administrator documentation

Enterprise policies must override user settings only when explicitly configured.

Display policy-controlled options as locked rather than hiding them.

EXPORT / IMPORT

Create versioned configuration exports.

Support:

* settings
* filter configuration
* allowlists
* custom rules
* site profiles
* dark-mode settings
* reader preferences
* sessions
* optional encrypted vault

Use:

* version numbers
* checksums
* schema validation
* migration scripts
* optional encryption
* corruption detection

Never accept unvalidated configuration data directly into privileged extension logic.

AUTOMATIC RECOVERY

The extension must survive:

* corrupt filter database
* failed update
* malformed custom rule
* incompatible migrated settings
* service-worker restart
* browser restart
* browser update
* disabled permissions
* offline state
* cloud-sync conflict

Maintain a known-good local configuration.

If migration fails:

1. preserve the original data
2. roll back
3. notify the user
4. record a diagnostic event

DEVELOPMENT STACK

Default stack:

* TypeScript
* modern ECMAScript
* Vite or equivalent deterministic bundler
* ESLint
* Prettier
* Vitest or equivalent unit testing
* Playwright for browser automation
* WebExtension-compatible API abstraction
* IndexedDB for large local data where appropriate
* browser storage APIs for settings
* Web Crypto API for cryptographic primitives
* Rust/WASM only when profiling demonstrates a meaningful advantage and browser compatibility remains acceptable

Do not introduce React merely for fashion.

Use React/Svelte/Vue only if the UI complexity genuinely justifies it.

Prefer a modular architecture with strong separation between:

UI
domain logic
browser adapters
filter engine
privacy engine
storage
security
performance
native bridge
cloud sync

PROJECT STRUCTURE

Create a scalable architecture similar to:

src/
core/
adblock/
privacy/
filters/
cosmetics/
performance/
security/
stats/
config/

browser/
chromium/
firefox/
safari/
shared/

features/
dashboard/
popup/
settings/
vault/
reader/
darkmode/
screenshot/
sessions/
proxy/
diagnostics/

services/
storage/
sync/
updates/
crypto/
telemetry/
native/

content/
cosmetic/
darkmode/
reader/
customization/

background/
service-worker/

enterprise/
policies/

tests/
unit/
integration/
browser/
performance/
security/
fuzz/

Use strict TypeScript settings.

Avoid "any" unless justified and documented.

Use typed domain models.

Use schema validation for external input.

DEVELOPMENT PHASES

PHASE 0 — ARCHITECTURE

Before writing large amounts of code:

* inspect browser capabilities
* define compatibility matrix
* define architecture
* define data model
* define permission model
* define security threat model
* define testing strategy
* define performance strategy
* define release strategy

Create ARCHITECTURE.md.

PHASE 1 — CORE PLATFORM

Implement:

* manifest
* build system
* browser abstraction
* service worker
* messaging
* storage
* permission manager
* configuration system
* logging

PHASE 2 — BLOCKING ENGINE

Implement:

* declarative rules
* filter parser
* compiler
* EasyList/EasyPrivacy integration
* custom lists
* rule optimizer
* cosmetic engine
* allowlist system

PHASE 3 — PRIVACY ENGINE

Implement:

* tracker blocking
* cookie controls
* fingerprinting protections
* HTTPS handling
* privacy modes
* DNS/DoH integration where available

PHASE 4 — PERFORMANCE

Implement:

* resource controls
* autoplay control
* lazy loading enforcement
* performance dashboard
* suspension
* CPU/memory diagnostics

PHASE 5 — PRODUCTIVITY FEATURES

Implement:

* dark mode
* reader mode
* TTS
* screenshot
* annotation
* sessions
* custom CSS/JS

PHASE 6 — SECURITY VAULT

Implement:

* cryptographic vault
* password generator
* credential storage
* secure autofill
* vault locking
* export/import
* encrypted synchronization

PHASE 7 — PROXY/VPN

Implement:

* browser proxy architecture
* endpoint profiles
* secure connection state
* optional native VPN architecture
* DNS leak controls where possible

PHASE 8 — ENTERPRISE

Implement:

* managed configuration
* policies
* admin controls
* deployment documentation

PHASE 9 — HARDENING

Perform:

* security audits
* performance tests
* fuzzing
* browser compatibility testing
* accessibility testing
* migration testing
* crash testing
* update failure testing

PHASE 10 — RELEASE

Produce:

* Chrome package
* Firefox package
* Edge package
* Opera package
* Safari project/package
* native companion installers if used
* source maps for internal debugging
* release artifacts
* SBOM
* checksums
* changelog
* administrator documentation
* privacy policy draft
* security documentation
* user documentation

TESTING REQUIREMENTS

UNIT TESTS

Cover:

* parser
* compiler
* matcher
* domain matching
* rule priority
* exceptions
* cosmetic filtering
* settings
* permissions
* encryption
* vault state transitions
* synchronization
* migration
* statistics
* proxy state

INTEGRATION TESTS

Test:

* service worker lifecycle
* content scripts
* network rules
* storage
* filter updates
* popup/background communication
* page/background communication
* custom CSS/JS
* vault autofill
* reader extraction

BROWSER TESTS

Automate real browsers.

Minimum coverage:

Chrome
Firefox
Edge
Opera
Safari

Test on:

* Windows
* macOS
* Linux where applicable
* iOS/iPadOS for Safari-compatible components where feasible

WEBSITE COMPATIBILITY TEST SUITE

Create a representative corpus containing:

* news sites
* e-commerce
* social sites
* video sites
* banking
* education
* web apps
* documentation
* forums
* streaming
* blogs
* government websites

For each site measure:

* load success
* visual correctness
* login functionality
* forms
* video
* downloads
* navigation
* scrolling
* dynamic content
* SPA transitions

The extension must not be optimized only for static HTML websites.

PERFORMANCE TESTING

Set CI thresholds.

Examples:

Blocking matcher:
target average <5 ms

Blocking matcher:
p95 <10 ms

Extension runtime memory:
target <50 MB incremental runtime footprint excluding browser-managed storage/rule engines

Idle CPU:
near-zero

Dashboard first interactive:
target <500 ms under normal conditions

Filter compilation:
must have bounded execution and fail safely

Large filter-list test:
must not freeze the browser

Run performance tests on both low-end and high-end machines.

FALSE-POSITIVE TESTING

Maintain a regression corpus of previously broken websites.

Every discovered regression becomes a permanent test.

SECURITY TESTING

Run:

* npm audit/equivalent
* dependency scanner
* SAST
* secret scanner
* CSP validation
* manifest permission audit
* fuzz testing
* malicious filter tests
* malformed import tests
* URL parser tests
* vault tests
* cryptographic misuse tests
* IPC authentication tests
* native companion security tests

ACCESSIBILITY TESTING

Run automated accessibility checks plus keyboard-only manual testing.

Check:

* contrast
* focus
* semantic roles
* screen-reader labels
* keyboard navigation
* reduced motion
* error messages

QUALITY GATES

Do not call the product production-ready unless:

* all critical functionality works
* no critical security findings remain
* core tests pass
* browser compatibility tests pass
* performance targets are measured
* extension permissions are reviewed
* update rollback works
* corrupted filters cannot brick protection
* malformed user settings cannot crash the extension
* vault data is encrypted
* secrets never enter logs
* accessibility baseline passes
* store packaging succeeds

DOCUMENTATION

Create:

README.md
ARCHITECTURE.md
SECURITY.md
PRIVACY.md
CONTRIBUTING.md
DEVELOPMENT.md
BROWSER_COMPATIBILITY.md
FILTER_SUPPORT.md
ENTERPRISE.md
NATIVE_COMPANION.md
RELEASE.md
TROUBLESHOOTING.md
THREAT_MODEL.md

Include diagrams where useful.

ERROR HANDLING

Every subsystem must have explicit error handling.

Never:

* silently swallow critical errors
* leave corrupted state active
* display meaningless stack traces to ordinary users
* crash due to one malformed rule
* destroy working configuration after failed migration

User-facing errors must explain:

What happened
Why it happened
What is affected
What the user can do

DEVELOPER EXPERIENCE

Add scripts such as:

npm run dev
npm run build
npm run build:chrome
npm run build:firefox
npm run build:edge
npm run build:opera
npm run build:safari
npm run test
npm run test:e2e
npm run test:security
npm run test:performance
npm run lint
npm run typecheck
npm run format
npm run audit
npm run package

CI should enforce:

* type safety
* linting
* formatting
* tests
* dependency scanning
* security checks
* build validation
* package generation

RELEASE ENGINEERING

Use semantic versioning.

Every release must have:

* version
* changelog
* checksums
* build metadata
* dependency lockfile
* SBOM
* security review
* regression results

Implement staged rollout capability where infrastructure permits.

Maintain release rollback procedures.

PRIVACY PRINCIPLES

The extension should be privacy-preserving by default.

No browsing-history telemetry.

No selling user data.

No hidden advertising.

No injected advertisements.

No undisclosed affiliate manipulation.

No covert crypto mining.

No credential collection.

No remote command execution.

No arbitrary server-side control over the extension.

The extension's own update infrastructure must not become a tracking system.

USER CONTROL

Provide an advanced control center where users can inspect and modify:

* protection mode
* filter lists
* permissions
* exceptions
* privacy protections
* cookie behavior
* DoH
* proxy
* dark mode
* reader
* scripts
* sessions
* vault
* synchronization
* notifications

Include both:

Simple mode

and

Expert mode.

Simple mode must be understandable to ordinary users.

Expert mode should expose detailed controls for advanced users.

IMPORTANT IMPLEMENTATION RULES

Do not stop after creating the UI.

Do not generate empty buttons.

Do not generate placeholder pages.

Do not label a feature "implemented" if it is only mocked.

Do not hard-code fake statistics.

Do not use fake API responses in production code.

Do not claim universal blocking when browser limitations prevent it.

Do not claim full-device VPN without a genuine native/network implementation.

Do not claim system-wide DoH without actual system/browser-level control.

Do not store credentials insecurely.

Do not bypass browser security controls.

Do not use remote JavaScript.

Do not disable browser certificate validation.

Do not compromise legitimate authentication/payment/security systems.

Do not allow one broken filter to disable the entire engine.

Do not block critical first-party application resources simply to maximize the blocked counter.

Do not optimize for an artificially large number of blocked requests; optimize for actual protection, compatibility, privacy, and performance.

PRODUCT POLISH

The finished extension should feel cohesive.

Use a unified visual system.

Animations should be subtle, fast, and purposeful.

Protection status must be immediately understandable.

All dangerous operations should have confirmation.

Advanced settings should provide explanations and reset controls.

Default configuration should be strong enough for normal users without requiring technical knowledge.

FINAL DELIVERABLE

Produce the actual complete application source code and project structure.

Do not merely provide recommendations or architecture diagrams.

At the end, provide:

1. final project tree
2. browser compatibility matrix
3. implemented feature matrix
4. performance benchmark results
5. security test results
6. accessibility results
7. known browser limitations
8. required native components
9. build instructions
10. packaging instructions
11. deployment instructions
12. enterprise deployment instructions
13. migration/versioning strategy
14. remaining non-critical limitations

When a feature cannot be implemented identically on every browser, preserve the unified product experience while using the strongest technically correct implementation for each platform.

The final result must be maintainable by a professional engineering team, scalable to millions of users, auditable, secure, fast, and suitable for real browser-store submission.
Kodari AI
KodariSep 24 at 2:59 pm 2
SentinelShield
SentinelShield is a comprehensive browser security and privacy platform combining aggressive ad blocking, tracker prevention, and performance optimization with a suite of productivity tools. It features a multi-layer blocking engine using declarative network rules and custom filter compilation, a privacy engine with configurable protection levels, dark mode, reader mode with text-to-speech, screenshot annotation, session management, and a secure encrypted password vault. The extension prioritizes minimal resource overhead, cross-browser compatibility across Chrome, Firefox, Edge, Opera, and Safari, and enterprise-grade deployment with managed policies. All features work locally-first with optional end-to-end encrypted cloud sync, ensuring user privacy and data security by default.

I’ll create a Chrome MV3 privacy extension with local declarative blocking, site exceptions, and optional cosmetic/dark styling. Features that need browser or native support beyond an extension will be clearly identified rather than simulated.

Created Kodari Shield as an unpacked Chrome MV3 extension. It includes local declarative ad/tracker blocking, per-site permanent and temporary exceptions, optional cosmetic filtering and basic dark styling, and settings export/import.

This is a functional first release, not the full platform described in the brief. It does not include a complete filter-list compiler, password vault, VPN, or cross-browser builds. Install it from chrome://extensions → Developer mode → Load unpacked.

Kodari can make mistakes. Review important code before using.
Files
ARCHITECTURE.md
background.js
BROWSER_COMPATIBILITY.md
content.css
content.js
manifest.json
options.css
options.html
options.js
popup.css
popup.html
popup.js
README.md
rules.json
SECURITY.md
Code
15 1,392
background.js
const DEFAULTS = {
  protectionEnabled: true,
  stylingEnabled: false,
  cosmeticFiltering: true,
  darkMode: "off",
  allowlist: []
};

const RULESET_ID = "core_protection";
const EXCEPTION_RULE_BASE = 10000;
const MAX_EXCEPTIONS = 400;
const STYLING_SCRIPT_ID = "kodari-page-styling";
const EXPIRY_ALARM = "expire-site-exceptions";
const RESOURCE_TYPES = [
  "main_frame",
  "sub_frame",
  "stylesheet",
  "script",
  "image",
  "font",
  "object",
  "xmlhttprequest",
  "ping",
  "csp_report",
  "media",
  "websocket",
  "other"
];

function logFailure(context, error) {
  console.error(`[Kodari Shield] ${context}`, error);
}

function normalizeDomain(value) {
  if (typeof value !== "string" || value.length > 253) {
    return null;
  }

  const input = value.trim().toLowerCase().replace(/\.$/, "");
  if (!input || input.includes("/") || input.includes("@")) {
    return null;
  }

  try {
    const hostname = new URL(`https://${input}`).hostname.toLowerCase();
    if (!hostname || hostname.includes(":") || hostname === "localhost") {
      return null;
    }
    return hostname;
  } catch (error) {
    return null;
  }
}

async function ensureDefaults() {
  const stored = await chrome.storage.local.get(Object.keys(DEFAULTS));
  const missing = {};

  for (const [key, value] of Object.entries(DEFAULTS)) {
    if (stored[key] === undefined) {
      missing[key] = value;
    }
  }

  if (Object.keys(missing).length > 0) {
    await chrome.storage.local.set(missing);
  }
}

async function syncProtection() {
  const { protectionEnabled = true } =
    await chrome.storage.local.get("protectionEnabled");

  await chrome.declarativeNetRequest.updateEnabledRulesets({
    enableRulesetIds: protectionEnabled ? [RULESET_ID] : [],
    disableRulesetIds: protectionEnabled ? [] : [RULESET_ID]
  });
}

async function syncExceptions() {
  const { allowlist = [] } = await chrome.storage.local.get("allowlist");
  const domains = [...new Set(
    (Array.isArray(allowlist) ? allowlist : [])
      .filter((entry) => entry && (!entry.expiresAt || entry.expiresAt > Date.now()))
      .map((entry) => normalizeDomain(entry.domain))
      .filter(Boolean)
  )].slice(0, MAX_EXCEPTIONS);

  const existing = await chrome.declarativeNetRequest.getDynamicRules();
  const oldIds = existing
    .filter((rule) => rule.id >= EXCEPTION_RULE_BASE && rule.id < EXCEPTION_RULE_BASE + MAX_EXCEPTIONS)
    .map((rule) => rule.id);

  const addRules = domains.map((domain, index) => ({
    id: EXCEPTION_RULE_BASE + index,
    priority: 100,
    action: { type: "allowAllRequests" },
    condition: {
      initiatorDomains: [domain],
      resourceTypes: ["main_frame"]
    }
  }));

  await chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: oldIds,
    addRules
  });

  const expirations = (Array.isArray(allowlist) ? allowlist : [])
    .map((entry) => entry && entry.expiresAt)
    .filter((time) => Number.isFinite(time) && time > Date.now());

  await chrome.alarms.clear(EXPIRY_ALARM);
  if (expirations.length > 0) {
    chrome.alarms.create(EXPIRY_ALARM, {
      when: Math.min(...expirations)
    });
  }
}

function isExtensionPage(sender) {
  return typeof sender.url === "string" &&
    sender.url.startsWith(chrome.runtime.getURL(""));
}

async function getPageState(domain) {
  const normalized = normalizeDomain(domain);
  const settings = await chrome.storage.local.get(DEFAULTS);
  let exception = null;

  if (normalized && Array.isArray(settings.allowlist)) {
    exception = settings.allowlist.find((entry) => {
      const allowedDomain = normalizeDomain(entry && entry.domain);
      return allowedDomain &&
        (!entry.expiresAt || entry.expiresAt > Date.now()) &&
        (normalized === allowedDomain || normalized.endsWith(`.${allowedDomain}`));
    }) || null;
  }

  return {
    ok: true,
    protectionEnabled: settings.protectionEnabled !== false,
    stylingEnabled: settings.stylingEnabled === true,
    cosmeticFiltering: settings.cosmeticFiltering !== false,
    darkMode: settings.darkMode || "off",
    exception: exception ? {
      domain: normalizeDomain(exception.domain),
      expiresAt: exception.expiresAt || null
    } : null
  };
}

async function setSiteException(message) {
  const domain = normalizeDomain(message.domain);
  if (!domain) {
    throw new Error("That site address is not valid.");
  }

  const { allowlist = [] } = await chrome.storage.local.get("allowlist");
  const records = Array.isArray(allowlist)
    ? allowlist.filter((entry) => entry && normalizeDomain(entry.domain))
    : [];
  const updated = records.filter((entry) => normalizeDomain(entry.domain) !== domain);

  if (message.mode === "allow") {
    if (updated.length >= MAX_EXCEPTIONS) {
      throw new Error("The site exception limit has been reached.");
    }

    const durationMs = message.durationMs === 600000 ? 600000 : 0;
    updated.push({
      domain,
      expiresAt: durationMs ? Date.now() + durationMs : 0
    });
  } else if (message.mode !== "remove") {
    throw new Error("Unknown site exception action.");
  }

  await chrome.storage.local.set({ allowlist: updated });
  await syncExceptions();
  return { ok: true };
}

async function setStyling(enabled) {
  if (enabled) {
    const hasAccess = await chrome.permissions.contains({
      origins: ["<all_urls>"]
    });
    if (!hasAccess) {
      throw new Error("Grant site access from the extension controls first.");
    }

    const registered = await chrome.scripting.getRegisteredContentScripts({
      ids: [STYLING_SCRIPT_ID]
    });
    if (registered.length > 0) {
      await chrome.scripting.unregisterContentScripts({
        ids: [STYLING_SCRIPT_ID]
      });
    }