← Back to home

DataGaurd

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

Problem Statement

DataGuard: Privacy-Preserving Email Data MarketplaceDataGuard is a revolutionary browser extension that transforms your email inbox into aprivacy-preserving data marketplacewhere you get paid for controlled access to your email data through thex402 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 & SolutionThe 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 WorksRequest Interception: The browser extension automatically detects when websites or AI agents attempt to access email dataPolicy Enforcement: User-defined privacy policies determine what data can be shared and under what conditionsDynamic Pricing: An AI-powered policy agent negotiates pricing based on data sensitivity, demand, and user preferencesx402 Payment Processing: Data access requires payment through the x402 protocol on Polygon network using USDCPrivacy-Preserving Response: Only filtered, redacted data is returned along with zero-knowledge proofs of predicatesUser Compensation: Users receive payments directly to their configured wallet addressKey FeaturesPrivacy ProtectionGranular 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 settingsTime-based Filtering: Control how old emails can be (e.g., only last 90 days)Volume Limits: Set the maximum number of emails per requestMonetization EngineDynamic Pricing: Base prices with demand multipliers, privacy multipliers, and volume adjustmentsPredicate-based Pricing: Different rates for different types of data:Subscription emails: $0.05-$0.50 per proofDelivery confirmations: $0.10-$1.00 per proofPurchase receipts: $0.25-$2.00 per proofFinancial data: $0.50+ per proofx402 Integration: Seamless payment processing through decentralized payment protocolTechnical ArchitectureBrowser Extension: Chrome extension with background service worker and content scriptsExpress Server: Built-in HTTP server within the extension for API endpointsPolicy Agent: AI-powered negotiation system for automated pricing and policy enforcementMail Demo Service: Realistic email dataset with 21+ labeled emails for demonstrationZero-Knowledge Proofs: Cryptographic proofs for email predicates without revealing full dataSupported PredicatesSubscription Acknowledgement: "User has received subscription emails from recognized senders"Package Delivery: "User has received delivery confirmations from carriers/ecommerce"Purchase Proof: "User has made purchases based on receipt emails"Financial Activity: "User has financial transaction emails"User Experience FlowSetup: User installs extension and configures privacy policy and wallet addressRequest Detection: Extension intercepts third-party data requestsPolicy Check: System validates request against user's privacy settingsPayment Negotiation: Policy agent calculates dynamic pricing and presents payment requestPayment Processing: Third-party completes payment through x402 facilitatorData Filtering: Extension applies redaction rules and filters emails by predicateProof Generation: System generates cryptographic proof of predicate without revealing full dataResponse: Third-party receives filtered data + proof, user receives paymentTechnical ImplementationFrontend: Chrome Extension (MV3) with TypeScriptBackend: Express server within extension background scriptPayment: x402 protocol on Polygon network with USDCData: Mock email service with realistic datasets deployed on VercelStorage: Chrome extension local storage for policies and payment historyNetworking: CORS-enabled API endpoints for third-party accessDemo & TestingThe project includes a comprehensive demo environment:Mail Demo Service: Deployed athttps://data-gaurd.vercel.appwith 21 realistic emailsExtension UI: Full-featured popup and extension page for policy configurationPayment Simulation: Mock x402 payment processing for demonstrationRequest Logging: Complete audit trail of all data requests and paymentsInnovation HighlightsFirst-of-its-kind: Browser extension that monetizes user data through x402 protocolPrivacy-by-design: Zero-knowledge proofs ensure data privacy while proving predicatesUser sovereignty: Complete control over data access and pricingAutomated negotiation: AI agent handles pricing and policy enforcementReal-world applicability: Practical implementation for email data marketplaceDataGuard represents a paradigm shift from data extraction todata 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.

Solution

Architecture OverviewDataGuard is built as amulti-component systemwith a Chrome extension as the core, a separate mail demo service, and sophisticated payment processing - all designed to work together seamlessly.Technology Stack & Core Technologies1. Chrome Extension (Main Component)TypeScript: Full TypeScript implementation with strict type checkingChrome Extension Manifest V3: Modern extension architectureBackground Service Worker: Handles API requests and payment processingContent Scripts: Intercepts web requests and injects privacy controlsChrome Storage API: Persistent policy and payment history storage2. Mail Demo Service (External Component)Express.js: RESTful API server for email dataTypeScript: Type-safe backend implementationVercel Deployment: Serverless deployment with automatic scalingCORS-enabled: Cross-origin requests from extension3. Payment Integrationx402 Protocol: Decentralised payment protocol for data accessViem: Ethereum library for blockchain interactionsPolygon Network: Layer 2 scaling solution for low-cost transactionsUSDC: Stablecoin for payment processingClever Implementation Details & Hacks1. 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 viachrome.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 Algorithmprivate 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 & DeploymentExtension 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 Decisions1. 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 StrategyChrome Storage: User policies and payment historyIn-Memory: Request queue and negotiation stateExternal Service: Email data (with local fallback)3. Realistic Demo Data// 21 carefully crafted emails with realistic senders const sampleEmails = [ { from: 'tracking@amazon.com', subject: 'Your package has been delivered', type: 'delivery' }, { from: 'newsletter@techcrunch.com', subject: 'Weekly Tech News', type: 'subscription' }, { from: 'receipts@stripe.com', 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 IntegrationVercel (Deployment Platform)Benefit: Zero-config deployment for the mail demo serviceIntegration: Automatic HTTPS, global CDN, and serverless scalingHack: Used Vercel's rewrite rules to create clean API endpointsx402 Protocol (Payment System)Benefit: Decentralized payment for data access without intermediariesIntegration: Full API contract implemented (currently simulated)Innovation: First browser extension to integrate x402 for data monetizationParticularly Hacky Solutions1. 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 Wrapperprivate 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 WorkflowJustfile for Project Management# Simple commands for multi-component development extension-build: cd extension && yarn build demo-start: cd mail-demo && yarn startWhy Just instead of npm scripts?Cross-directory commands are cleaner with Just, and it handles the multi-component nature better.Security & Privacy ConsiderationsMinimal Permissions: Only requests necessary Chrome permissionsLocal-First: All sensitive data processing happens locallyRedaction by Default: Email bodies and personal info are redacted unless explicitly allowedUser Control: Every aspect of data sharing is user-configurablePerformance OptimizationsLazy Loading: UI components load as neededRequest Batching: Multiple requests are queued and processed efficientlyFallback Caching: Mock data is always available for offline operationMinimal Network Calls: Only essential API calls to external servicesThis 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.

Hackathon

ETHGlobal New Delhi

2025

Contributors