DataGaurd

Privacy-preserving email marketplace with x402 payments and user control.

DataGaurd

Created At

ETHGlobal New Delhi

Project Description

DataGuard: Privacy-Preserving Email Data Marketplace

DataGuard is a revolutionary browser extension that transforms your email inbox into a privacy-preserving data marketplace where you get paid for controlled access to your email data through the x402 payment protocol. Instead of having your data extracted without permission, DataGuard puts you in complete control of who accesses what data and ensures you're compensated for it.

Core Problem & Solution

The Problem: Currently, AI agents and third-party applications extract email data without user consent or compensation, creating privacy violations and data exploitation.

The Solution: DataGuard intercepts data requests, applies user-defined privacy policies, requires payment through x402 protocol, and returns only filtered, redacted data with cryptographic proofs - all while ensuring users are paid for their data.

How It Works

  1. Request Interception: The browser extension automatically detects when websites or AI agents attempt to access email data
  2. Policy Enforcement: User-defined privacy policies determine what data can be shared and under what conditions
  3. Dynamic Pricing: An AI-powered policy agent negotiates pricing based on data sensitivity, demand, and user preferences
  4. x402 Payment Processing: Data access requires payment through the x402 protocol on Polygon network using USDC
  5. Privacy-Preserving Response: Only filtered, redacted data is returned along with zero-knowledge proofs of predicates
  6. User Compensation: Users receive payments directly to their configured wallet address

Key Features

Privacy Protection

  • Granular Control: Users can selectively allow/disallow different types of email data (subscriptions, deliveries, purchases, financial)
  • Data Redaction: Automatic redaction of email bodies and personal information based on policy settings
  • Time-based Filtering: Control how old emails can be (e.g., only last 90 days)
  • Volume Limits: Set the maximum number of emails per request

Monetization Engine

  • Dynamic Pricing: Base prices with demand multipliers, privacy multipliers, and volume adjustments
  • Predicate-based Pricing: Different rates for different types of data:
    • Subscription emails: $0.05-$0.50 per proof
    • Delivery confirmations: $0.10-$1.00 per proof
    • Purchase receipts: $0.25-$2.00 per proof
    • Financial data: $0.50+ per proof
  • x402 Integration: Seamless payment processing through decentralized payment protocol

Technical Architecture

  • Browser Extension: Chrome extension with background service worker and content scripts
  • Express Server: Built-in HTTP server within the extension for API endpoints
  • Policy Agent: AI-powered negotiation system for automated pricing and policy enforcement
  • Mail Demo Service: Realistic email dataset with 21+ labeled emails for demonstration
  • Zero-Knowledge Proofs: Cryptographic proofs for email predicates without revealing full data

Supported Predicates

  1. Subscription Acknowledgement: "User has received subscription emails from recognized senders"
  2. Package Delivery: "User has received delivery confirmations from carriers/ecommerce"
  3. Purchase Proof: "User has made purchases based on receipt emails"
  4. Financial Activity: "User has financial transaction emails"

User Experience Flow

  1. Setup: User installs extension and configures privacy policy and wallet address
  2. Request Detection: Extension intercepts third-party data requests
  3. Policy Check: System validates request against user's privacy settings
  4. Payment Negotiation: Policy agent calculates dynamic pricing and presents payment request
  5. Payment Processing: Third-party completes payment through x402 facilitator
  6. Data Filtering: Extension applies redaction rules and filters emails by predicate
  7. Proof Generation: System generates cryptographic proof of predicate without revealing full data
  8. Response: Third-party receives filtered data + proof, user receives payment

Technical Implementation

  • Frontend: Chrome Extension (MV3) with TypeScript
  • Backend: Express server within extension background script
  • Payment: x402 protocol on Polygon network with USDC
  • Data: Mock email service with realistic datasets deployed on Vercel
  • Storage: Chrome extension local storage for policies and payment history
  • Networking: CORS-enabled API endpoints for third-party access

Demo & Testing

The project includes a comprehensive demo environment:

  • Mail Demo Service: Deployed at https://data-gaurd.vercel.app with 21 realistic emails
  • Extension UI: Full-featured popup and extension page for policy configuration
  • Payment Simulation: Mock x402 payment processing for demonstration
  • Request Logging: Complete audit trail of all data requests and payments

Innovation Highlights

  1. First-of-its-kind: Browser extension that monetizes user data through x402 protocol
  2. Privacy-by-design: Zero-knowledge proofs ensure data privacy while proving predicates
  3. User sovereignty: Complete control over data access and pricing
  4. Automated negotiation: AI agent handles pricing and policy enforcement
  5. Real-world applicability: Practical implementation for email data marketplace

DataGuard represents a paradigm shift from data extraction to data compensation, empowering users to monetise their personal data while maintaining privacy and control. It's built for the ETHGlobal New Delhi 2025 hackathon and demonstrates a complete end-to-end privacy-preserving data marketplace.

How it's Made

Architecture Overview

DataGuard is built as a multi-component system with a Chrome extension as the core, a separate mail demo service, and sophisticated payment processing - all designed to work together seamlessly.

Technology Stack & Core Technologies

1. Chrome Extension (Main Component)

  • TypeScript: Full TypeScript implementation with strict type checking
  • Chrome Extension Manifest V3: Modern extension architecture
  • Background Service Worker: Handles API requests and payment processing
  • Content Scripts: Intercepts web requests and injects privacy controls
  • Chrome Storage API: Persistent policy and payment history storage

2. Mail Demo Service (External Component)

  • Express.js: RESTful API server for email data
  • TypeScript: Type-safe backend implementation
  • Vercel Deployment: Serverless deployment with automatic scaling
  • CORS-enabled: Cross-origin requests from extension

3. Payment Integration

  • x402 Protocol: Decentralised payment protocol for data access
  • Viem: Ethereum library for blockchain interactions
  • Polygon Network: Layer 2 scaling solution for low-cost transactions
  • USDC: Stablecoin for payment processing

Clever Implementation Details & Hacks

1. Dual-UI Architecture (Hacky but Effective)

// Both popup.ts and extension-page.ts are nearly identical
// This allows the same functionality in both popup and full-page modes
class DataGuardPopup { /* 660 lines */ }
class DataGuardExtensionPage { /* 660 lines */ }

Why this hack? Chrome extension popups have size limitations, so we created a full-page version accessible via chrome.action.onClicked. The code duplication was intentional for rapid development.

2. Request Interception via Content Script Injection

// Injects a global API that websites can call
window.DataGuardAPI = {
    requestEmailData: (predicate, callback) => {
        // Intercepts and processes requests
    }
};

The clever part: Instead of trying to intercept all network requests (which would require broad permissions), we inject a controlled API that websites can use, making the extension more privacy-friendly.

3. Simulated x402 Payment Processing

// All x402 payments are currently simulated for demo purposes
async function simulateFacilitatorPayment(paymentRequest: X402PaymentRequest): Promise<X402PaymentResponse> {
    await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate network delay
    return {
        success: true,
        paymentProof: `proof_${paymentRequest.requestId}_${Date.now()}`,
        transactionHash: `0x${Math.random().toString(16).substr(2, 64)}`
    };
}

Why simulated? Real x402 integration requires complex blockchain setup. The simulation maintains the exact API contract while allowing full demo functionality.

4. Fallback Data System

// Graceful degradation when mail service is unavailable
async function fetchEmailData(predicate: EmailPredicate): Promise<EmailData[]> {
    try {
        const response = await fetch('https://data-gaurd.vercel.app/api/emails');
        return await response.json();
    } catch (error) {
        console.log('Using mock data as fallback');
        return getMockEmailData(predicate); // Always works offline
    }
}

The hack: Built-in fallback ensures the extension always works, even if the external service is down.

5. Dynamic Pricing Algorithm

private calculateDynamicPrice(request: NegotiationRequest, basePrice: number): number {
    let finalPrice = basePrice;
    
    // Demand multiplier based on recent requests
    const requestCount = this.getRecentRequestCount(request.predicateType);
    const demandMultiplier = Math.min(1 + (requestCount * 0.1), 2.0); // Max 2x
    
    // Privacy multiplier
    if (request.requestedData.includeBodies) finalPrice *= 1.5;
    if (request.requestedData.includePersonalInfo) finalPrice *= 1.3;
    
    // Volume multiplier
    const volumeMultiplier = 1 + ((request.requestedData.maxEmails - 10) / 10) * 0.2;
    finalPrice *= Math.min(volumeMultiplier, 2.0);
    
    return Math.round(finalPrice * 1000) / 1000;
}

The innovation: Real-time pricing that adapts to demand, privacy sensitivity, and volume - creating a true marketplace dynamic.

Build System & Deployment

Extension Build Process

{
    "scripts": {
        "build": "tsc && yarn copy-assets",
        "copy-assets": "cp -r src/assets/* dist/ && cp manifest.json dist/ && cp src/ui/popup/popup.html dist/ && cp src/ui/popup/popup.css dist/"
    }
}

The hack: Manual asset copying instead of webpack because Chrome extensions have specific file structure requirements.

Mail Demo Service Deployment

// vercel.json
{
    "rewrites": [
        {
            "source": "/api/emails",
            "destination": "/api/index"
        }
    ]
}

Clever routing: Uses Vercel's rewrite rules to create clean API endpoints without complex routing logic.

Notable Technical Decisions

1. TypeScript Module Strategy

// tsconfig.json
{
    "module": "none",  // No module system - Chrome extensions don't support ES modules
    "target": "ES2020" // Modern JS features
}

Why "module": "none"? Chrome extensions can't use ES modules in content scripts, so we compile to plain JavaScript with proper type checking.

2. Dual Storage Strategy

  • Chrome Storage: User policies and payment history
  • In-Memory: Request queue and negotiation state
  • External Service: Email data (with local fallback)

3. Realistic Demo Data

// 21 carefully crafted emails with realistic senders
const sampleEmails = [
    { from: '[email protected]', subject: 'Your package has been delivered', type: 'delivery' },
    { from: '[email protected]', subject: 'Weekly Tech News', type: 'subscription' },
    { from: '[email protected]', subject: 'Receipt for your purchase', type: 'purchase' }
];

The attention to detail: Each email is realistic and properly categorized, making the demo feel authentic.

Partner Technology Integration

Vercel (Deployment Platform)

  • Benefit: Zero-config deployment for the mail demo service
  • Integration: Automatic HTTPS, global CDN, and serverless scaling
  • Hack: Used Vercel's rewrite rules to create clean API endpoints

x402 Protocol (Payment System)

  • Benefit: Decentralized payment for data access without intermediaries
  • Integration: Full API contract implemented (currently simulated)
  • Innovation: First browser extension to integrate x402 for data monetization

Particularly Hacky Solutions

1. Timeout-Based Status Checking

// Multiple timeout strategies for different scenarios
setTimeout(() => {
    if (this.mailServiceStatus?.textContent === 'Connecting...') {
        this.mailServiceStatus.textContent = 'Timeout';
    }
}, 15000);

// And also:
const timeoutId = setTimeout(() => controller.abort(), 8000);

Why multiple timeouts? Different operations need different timeout strategies - UI feedback vs network requests.

2. Promise-Based Chrome API Wrapper

private sendMessageToBackground(message: any): Promise<any> {
    return new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(message, (response) => {
            if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
            } else {
                resolve(response);
            }
        });
    });
}

The hack: Chrome's callback-based APIs are wrapped in Promises for cleaner async/await code.

3. Visual Indicator Injection

// Injects a subtle indicator when DataGuard is active
const indicator = document.createElement('div');
indicator.innerHTML = '🛡️';
indicator.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;font-size:16px;opacity:0.7;';
document.body.appendChild(indicator);

User experience hack: Provides visual feedback that the extension is protecting the user's data.

Development Workflow

Justfile for Project Management

# Simple commands for multi-component development
extension-build:
    cd extension && yarn build

demo-start:
    cd mail-demo && yarn start

Why Just instead of npm scripts? Cross-directory commands are cleaner with Just, and it handles the multi-component nature better.

Security & Privacy Considerations

  1. Minimal Permissions: Only requests necessary Chrome permissions
  2. Local-First: All sensitive data processing happens locally
  3. Redaction by Default: Email bodies and personal info are redacted unless explicitly allowed
  4. User Control: Every aspect of data sharing is user-configurable

Performance Optimizations

  1. Lazy Loading: UI components load as needed
  2. Request Batching: Multiple requests are queued and processed efficiently
  3. Fallback Caching: Mock data is always available for offline operation
  4. Minimal Network Calls: Only essential API calls to external services

This architecture demonstrates how to build a complex privacy-preserving system using modern web technologies while maintaining simplicity and reliability. The "hacky" solutions were often intentional trade-offs that prioritised functionality and user experience over perfect architectural purity.

background image mobile

Join the mailing list

Get the latest news and updates