### Install Dependencies and Build for Firefox Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Installs project dependencies and builds the extension for Firefox. This is typically the first step before development or production builds. ```bash npm install npm run build-ff ``` -------------------------------- ### Full Build Process from Source ZIP for Firefox Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md A comprehensive script to set up the build environment from a source ZIP, install dependencies, and package the Firefox extension. Includes cleanup steps. ```bash apt-get install zip unzip source.zip -d vpn-bex cd vpn-bex npm ci npm run pack-ff mv vpn-proton-firefox.zip ../vpn-proton-firefox.zip cd .. rm -rf vpn-bex ``` -------------------------------- ### Install Dependencies and Build for Chrome Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Installs project dependencies and builds the extension for Chrome. Similar to the Firefox build process but targets Chrome. ```bash npm install npm run build ``` -------------------------------- ### Create Production ZIP Build for Firefox Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Installs exact dependencies and creates a production-ready ZIP archive of the Firefox extension. Ensures consistency with the source ZIP. ```bash npm ci && npm run pack-ff ``` -------------------------------- ### Watch for Changes and Auto-Reload for Firefox Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Starts a development server that automatically rebuilds the extension for Firefox when changes are detected. Useful for rapid development. ```bash npm run watch-ff ``` -------------------------------- ### Create Production ZIP Build for Chrome Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Installs exact dependencies and creates a production-ready ZIP archive of the Chrome extension. Guarantees the build matches the source ZIP. ```bash npm ci && npm run pack ``` -------------------------------- ### Watch for Changes and Auto-Reload for Chrome Source: https://github.com/protonvpn/proton-vpn-browser-extension/blob/main/readme.md Starts a development server that automatically rebuilds the extension for Chrome when changes are detected. Facilitates quick iteration during development. ```bash npm run watch ``` -------------------------------- ### Configure Split Tunneling in TypeScript Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Manage split tunneling settings to include or exclude specific domains from the VPN tunnel. This involves getting the current configuration, updating it with new domain rules, and determining the effective configuration based on user tier. ```typescript import { storedSplitTunneling } from './vpn/storedSplitTunneling'; import { getSplitTunnelingConfig } from './vpn/getSplitTunnelingConfig'; import { SplitTunnelingMode, WebsiteFilter } from './vpn/WebsiteFilter'; // Get stored split tunneling configuration const config = await storedSplitTunneling.getDefined({ value: [] }); // Update split tunneling domains await storedSplitTunneling.set({ enabled: true, mode: SplitTunnelingMode.Exclude, value: [ { domain: 'netflix.com', withSubDomains: true, mode: SplitTunnelingMode.Exclude }, { domain: 'banking.com', withSubDomains: true, mode: SplitTunnelingMode.Exclude } ] }); // Get config for connection (respects user tier) const userTier = 2; // 0 = free, 2 = plus const connectionConfig = getSplitTunnelingConfig(userTier, config); ``` -------------------------------- ### Utilize Typed Storage API Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Demonstrates the use of a typed storage wrapper around Chrome's storage API, supporting local, session, and sync storage. It includes features like transaction support and automatic JSON serialization. ```typescript import { storage, Storage, CacheWrappedValue } from './tools/storage'; // Simple key-value storage await storage.setItem('my-key', { value: 'data' }); const data = await storage.getItem<{ value: string }>('my-key'); // Create typed storage item interface UserPreferences { theme: 'dark' | 'light'; notifications: boolean; } const userPrefs = storage.item('user-preferences', Storage.LOCAL); // Get with default value const prefs = await userPrefs.getDefined({ theme: 'dark', notifications: true }); // Set value with automatic timestamp await userPrefs.setValue({ theme: 'light', notifications: false }); // Transaction for atomic read-modify-write await userPrefs.transaction(currentValue => ({ ...currentValue, notifications: true })); // Using session storage (cleared on browser restart) const tempData = storage.item<{ token: string }>('temp-token', Storage.SESSION); ``` -------------------------------- ### Implement Internationalization and Translations in TypeScript Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Integrate a translation system for internationalization, supporting context-based translations and plural forms. This includes fetching translations, performing simple and variable-based translations, handling pluralization, localizing country names, and translating DOM elements. ```typescript import { c, msgid, fetchTranslations, getCountryName, translateArea } from './tools/translate'; // Initialize translations on startup await fetchTranslations(); // Simple translation const label = c('Label').t`Protected`; const action = c('Action').t`Connect`; // Translation with variables const serverName = 'US-NY#15'; const status = c('Info').t`Connected to ${serverName}`; // Plural forms const count = 5; const message = c('Info').plural( count, msgid`${count} server available`, `${count} servers available` ); // Country name localization const countryName = getCountryName('US'); // "United States" or localized const countryNameInFrench = getCountryName('US', 'fr'); // "États-Unis" // Translate all elements in a DOM area translateArea(document.getElementById('popup-content')!); ``` -------------------------------- ### Enumerate Server Features using Bitmaps in TypeScript Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Identify server features using bitmap flags, allowing for checks and filtering based on supported capabilities. This includes describing server features like Secure Core, Tor, P2P, streaming optimization, and IPv6 support, and filtering servers that support specific features. ```typescript import { Feature } from './vpn/Feature'; import { Logical } from './vpn/Logical'; // Check server features function describeServer(logical: Logical): string[] { const features: string[] = []; if (logical.Features & Feature.SECURE_CORE) { features.push('Secure Core (multi-hop)'); } if (logical.Features & Feature.TOR) { features.push('Tor over VPN'); } if (logical.Features & Feature.P2P) { features.push('P2P/BitTorrent'); } if (logical.Features & Feature.STREAMING) { features.push('Streaming optimized'); } if (logical.Features & Feature.IPV6) { features.push('IPv6 support'); } return features; } // Filter servers by feature const streamingServers = logicals.filter( l => (l.Features & Feature.STREAMING) !== 0 ); ``` -------------------------------- ### Manage User and Subscription Data in TypeScript Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Handle user and subscription management by fetching and caching user information, including VPN subscription details and tier levels. This allows checking subscription tiers and paid access status, and accessing VPN-specific user properties. ```typescript import { getUser, getFreshUser } from './account/user/getUser'; import { getUserMaxTier } from './account/user/getUserMaxTier'; import { canAccessPaidServers } from './account/user/canAccessPaidServers'; import { User } from './account/user/User'; // Get cached user or fetch if needed const user = await getUser(); // Force fresh fetch from API const freshUser = await getFreshUser(); if (user) { // Check subscription tier const tier = getUserMaxTier(user); // 0 = free, 2 = plus // Check paid access const hasPaidAccess = canAccessPaidServers(user); // Access VPN-specific properties console.log(`Plan: ${user.VPN.PlanTitle}`); console.log(`Max connections: ${user.VPN.MaxConnect}`); console.log(`Browser extension enabled: ${user.VPN.BrowserExtension}`); } ``` -------------------------------- ### Implement Background Messaging Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Shows how to use Chrome's messaging API for communication between popup, background script, and content scripts. Messages are typed and routed via a central handler using functions like `sendMessageToBackground` and `getInfoFromBackground`. ```typescript import { sendMessageToBackground } from './tools/sendMessageToBackground'; import { getInfoFromBackground } from './tools/getInfoFromBackground'; import { BackgroundData, StateChange, SettingChange } from './messaging/MessageType'; // Get current connection state from background const connectionState = await getInfoFromBackground(BackgroundData.STATE); // Get user data const user = await getInfoFromBackground(BackgroundData.USER); const pmUser = await getInfoFromBackground(BackgroundData.PM_USER); // Send connection commands await sendMessageToBackground(StateChange.CONNECT, { server: serverData, logical: logicalData, user: userData, splitTunneling: { mode: 'exclude', filteredDomains: [] } }); // Disconnect await sendMessageToBackground(StateChange.DISCONNECT); // Sign out await sendMessageToBackground(StateChange.SIGN_OUT); // Update split tunneling settings await sendMessageToBackground(SettingChange.BYPASS_LIST, { mode: 'exclude', filteredDomains: ['example.com', 'test.org'] }); ``` -------------------------------- ### Manage VPN Connection States (TypeScript) Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Manages VPN connection states using a state machine pattern. It handles logging in, logging out, connecting, and disconnecting from the VPN, including proxy configuration and session management. Dependencies include state management functions like `connect`, `disconnect`, `logIn`, `logOut`, and `isCurrentStateConnected`. ```typescript import { connect, disconnect, logIn, logOut, isCurrentStateConnected } from './state'; // Check if VPN is currently connected const connected = isCurrentStateConnected(); // Connect to VPN with server configuration await connect({ server: { id: 'server-123', name: 'US-NY#15', exitIp: '192.168.1.1', entryCountry: 'US', exitCountry: 'US', exitCity: 'New York', exitEnglishCity: 'New York', secureCore: false, proxyHost: 'node-us-01.protonvpn.net', proxyPort: 4443, splitTunneling: { mode: 'exclude', filteredDomains: ['example.com'] } } }); // Disconnect from VPN disconnect(); // Log out user and clear session logOut(true); // true = delete session on server ``` -------------------------------- ### Manage VPN Server Logicals (TypeScript) Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Fetches, caches, and sorts VPN server logicals (endpoints) for display. It allows filtering servers by features like Secure Core, Tor, or free tier, and checking server status. Dependencies include `getSortedLogicals`, `getLogicalById`, `isLogicalUp`, `loadLoads`, and the `Feature` enum. ```typescript import { getSortedLogicals, getLogicalById, isLogicalUp, loadLoads } from './vpn/getLogicals'; import { Feature } from './vpn/Feature'; // Get all available servers sorted by country and score const logicals = await getSortedLogicals(); // Filter servers by feature flags const secureCoreServers = logicals.filter( logical => (logical.Features & Feature.SECURE_CORE) !== 0 ); const torServers = logicals.filter( logical => (logical.Features & Feature.TOR) !== 0 ); const freeServers = logicals.filter( logical => logical.Tier === 0 ); // Get specific server by ID const server = getLogicalById('abc123'); // Check if server is operational if (server && isLogicalUp(server)) { console.log(`${server.Name} is available in ${server.City}, ${server.ExitCountry}`); } // Refresh server loads (for connection quality) const refreshedLogicals = await loadLoads(); ``` -------------------------------- ### Manage User Sessions (TypeScript) Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Manages user authentication sessions, including storing tokens, user IDs, and connection status. Supports session persistence across browser restarts and session forking for partner authentication. Key functions include `readSession`, `saveSession`, `createSession`, and `startSession`. ```typescript import { readSession } from './account/readSession'; import { saveSession } from './account/saveSession'; import { createSession, startSession } from './account/createSession'; import { Session } from './account/Session'; // Read current session const session = await readSession(); if (session.uid && session.refreshToken) { console.log('User is authenticated'); } // Save session data await saveSession({ uid: 'user-uid-123', accessToken: 'access-token-xyz', refreshToken: 'refresh-token-abc', persistent: true }); // Start new authentication flow const success = await startSession({ partnerId: 'partner-123' // Optional partner integration }); ``` -------------------------------- ### Display Browser Notifications Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Illustrates how to display browser notifications for various events like connection status changes, errors, and other alerts using the `emitNotification` function. It also covers checking and modifying notification settings. ```typescript import { emitNotification } from './notifications/emitNotification'; import { storedNotificationsEnabled } from './notifications/notificationsEnabled'; // Simple notificationemitNotification( 'connected-server', 'Connected to US-NY#15 in New York' ); // Notification with optionsemitNotification( 'connection-error', { message: 'Connection failed: Server unavailable', priority: 2 } ); // Check/toggle notification setting const { value: enabled } = await storedNotificationsEnabled.getDefined({ value: true }); // Disable notifications await storedNotificationsEnabled.set({ value: false }); ``` -------------------------------- ### Manage VPN Proxy Credentials Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Handles fetching, caching, and refreshing VPN proxy credentials, which are separate from user authentication and have shorter lifetimes. It uses functions like `getCredentials` and `getSynchronousCredentials`. ```typescript import { getCredentials, loadCredentials, getSynchronousCredentials, loadCachedCredentials } from './account/credentials/getConnectionCredentials'; // Get credentials, fetching new ones if expired const credentials = await getCredentials(true); // true = try re-authentication if needed if (credentials) { console.log(`Proxy auth: ${credentials.Username}`); console.log(`Expires in: ${credentials.Expire} seconds`); } // Get credentials synchronously from cache (for proxy request handler) const cachedCreds = getSynchronousCredentials(); // Load credentials from storage const loaded = await loadCredentials(); // Check cached credential status const cached = await loadCachedCredentials(); if (cached && cached.time > Date.now()) { console.log('Cached credentials still valid'); } ``` -------------------------------- ### Handle API Requests and Authentication (TypeScript) Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Handles authenticated requests to Proton's API, including automatic token refresh, retry logic for rate limiting (429 responses), and error handling for various HTTP status codes. It utilizes functions like `fetchJson`, `fetchApi`, `jsonRequest`, `isSuccessfulResponse`, `isRetriableError`, and `isUnauthorizedError`. ```typescript import { fetchJson, fetchApi, jsonRequest } from './api'; // Fetch JSON data with automatic authentication const userData = await fetchJson<{ User: User }>( 'core/v4/users', { method: 'GET' } ); // POST request with JSON body const response = await fetchJson( 'vpn/v1/logicals', jsonRequest('POST', { Country: 'US', Tier: 2 }) ); // Raw fetch with session handling const rawResponse = await fetchApi( 'vpn/v1/browser/token?Duration=1200', { method: 'GET' }, 'https://account.proton.me/api/', existingSession ); // Check response types import { isSuccessfulResponse, isRetriableError, isUnauthorizedError } from './api'; if (isSuccessfulResponse(response)) { console.log('Request succeeded'); } else if (isRetriableError(error)) { console.log('Should retry after delay'); } ``` -------------------------------- ### Prevent WebRTC IP Leaks in TypeScript Source: https://context7.com/protonvpn/proton-vpn-browser-extension/llms.txt Implement WebRTC leak prevention to protect user IP addresses when connected to the VPN. This involves applying protection based on stored settings, explicitly enabling or disabling WebRTC, directly controlling its state, and managing the stored preference. ```typescript import { preventLeak } from './webrtc/preventLeak'; import { setWebRTCState } from './webrtc/setWebRTCState'; import { WebRTCState } from './webrtc/state'; import { storedPreventWebrtcLeak } from './webrtc/storedPreventWebrtcLeak'; // Apply WebRTC protection based on stored setting await preventLeak(); // Explicitly enable/disable WebRTC protection await preventLeak(true); // Disable WebRTC await preventLeak(false); // Allow WebRTC // Direct WebRTC state control await setWebRTCState(WebRTCState.DISABLED); // Block WebRTC await setWebRTCState(WebRTCState.CLEAR); // Restore default // Check/update stored preference const { value: isEnabled } = await storedPreventWebrtcLeak.getDefined({ value: true }); await storedPreventWebrtcLeak.set({ value: false }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.