01Installation & Subpath Imports
Install the package from npm. You can import everything from the root package or pull in individual modular subpaths so bundlers tree-shake unused code cleanly.
npm install @infralayers/mv3-proxy-kit// Root import (all modules)import { ProxyManager, setProxyConfig, clearProxyConfig, getProxyConfig, registerProxyAuth, createPersistedState, createChannel, getBrowserAPI,} from "@infralayers/mv3-proxy-kit";
// Modular subpath imports (tree-shakeable for any MV3 extension)import { createPersistedState } from "@infralayers/mv3-proxy-kit/state";import { createChannel } from "@infralayers/mv3-proxy-kit/messaging";import { ProxyManager, setProxyConfig, registerProxyAuth } from "@infralayers/mv3-proxy-kit/proxy";| Subpath | Use Case | Requires proxy Permission? |
|---|---|---|
| @infralayers/mv3-proxy-kit/state | Suspension-safe persisted state for any MV3 extension | No(only storage) |
| @infralayers/mv3-proxy-kit/messaging | Typed popup ↔ background ↔ content-script messaging | No |
| @infralayers/mv3-proxy-kit/proxy | Cross-browser proxy routing (fixed_servers, pac_url, direct) & auth | Yes |
02Proxy Configuration (ProxyManager & Standalone Helpers)
- Use the standalone helpers (
setProxyConfig,getProxyConfig,clearProxyConfig) for standard extensions managing a single global proxy state. - Instantiate
new ProxyManager(api?, enableLogging?)when you want structured console logging (enableLogging: true), isolated instances, or dependency-injected mockBrowserAPIobjects in unit tests.
Declarative Fixed Serverfixed_servers · HTTP / SOCKS
Translates to Chrome mode: "fixed_servers" and Firefox proxyType: "manual" (automatically mapping socks / socks5 / socks4to Firefox's socks + socksVersion fields, and bypassList to passthrough).
import { setProxyConfig } from "@infralayers/mv3-proxy-kit/proxy";
async function applyFixedProxy(host: string, port: number) { await setProxyConfig({ mode: "fixed_servers", rules: { singleProxy: { host, port, scheme: "http", // "http" | "https" | "socks4" | "socks5" | "socks" }, bypassList: ["localhost", "127.0.0.1"], }, });}
// Legacy bare ProxyTarget objects are also accepted and normalized automatically:// await setProxyConfig({ host, port });Hosted PAC Script URLpac_url
Translates to Chrome mode: "pac_script" (pacScript.url) and Firefox proxyType: "autoConfig" (autoConfigUrl).
import { setProxyConfig } from "@infralayers/mv3-proxy-kit/proxy";
async function applyPacUrl(pacUrl: string) { await setProxyConfig({ mode: "pac_url", url: pacUrl, });}Direct Mode / Clear Proxydirect
Reverts browser traffic to a direct connection. Translates to Chrome mode: "direct" and Firefox proxyType: "none".
import { clearProxyConfig } from "@infralayers/mv3-proxy-kit/proxy";
async function disableProxy() { await clearProxyConfig();}Using ProxyManager DirectlyClass API
Pass undefined as the first argument to use the default browser API and true to enable structured [ProxyManager] logs.
import { ProxyManager } from "@infralayers/mv3-proxy-kit/proxy";
const proxyManager = new ProxyManager(undefined, true);
async function toggleProxy(host: string, port: number) { await proxyManager.setConfig({ mode: "fixed_servers", rules: { singleProxy: { host, port, scheme: "socks5" } }, });
const active = proxyManager.getConfig(); // In-memory config for this worker lifecycle if (active?.mode === "fixed_servers") { await proxyManager.clearConfig(); }}getProxyConfig() / proxyManager.getConfig()getConfig() reads in-memory state and resets to null whenever Chrome or Firefox suspends and restarts the background service worker. If you need your active proxy configuration to survive restarts (for example, to repopulate a popup form), store it with createPersistedState.03Proxy Authentication (registerProxyAuth)
registerProxyAuth listens to webRequest.onAuthRequired and transparently handles the Chrome vs. Firefox MV3 split:
Registers with ["asyncBlocking"], invokes asyncCallback({ authCredentials }) (or { cancel: true } on missing credentials), and returns void on non-proxy challenges.
Registers with ["blocking"] and returns a Promise directly (or {} synchronously on non-proxy challenges).
import { registerProxyAuth } from "@infralayers/mv3-proxy-kit/proxy";import { createPersistedState } from "@infralayers/mv3-proxy-kit/state";
// Register synchronously at the top level of your service worker (never inside async callbacks)const credentials = createPersistedState<{ username: string; password: string }>("proxyCreds");
registerProxyAuth(async () => credentials.get());If your getCredentials provider returns undefined or throws an error, registerProxyAuth cancels the proxy auth challenge ({ cancel: true }). Non-proxy auth challenges (details.isProxy === false) are ignored cleanly so regular website HTTP auth is unaffected.
04Suspension-Safe State (createPersistedState)
Chrome terminates idle MV3 service workers after roughly 30 seconds, wiping module-level variables. createPersistedState wraps chrome.storage.session (automatically falling back to storage.local if session is unavailable) with three built-in guarantees:
- Lazy auto-hydration:
await state.get()hydrates automatically on the first read after a cold restart. - Concurrent read deduplication: multiple simultaneous
get()calls share a single in-flightstorage.get(). - Write-wins race protection: calling
set()whilehydrate()is in flight ensures stale storage reads never overwrite newer writes.
import { createPersistedState } from "@infralayers/mv3-proxy-kit/state";
interface ProxySettings { host: string; port: number; pacUrl?: string;}
const proxyState = createPersistedState<ProxySettings>("proxySettings");
async function saveAndRead(settings: ProxySettings) { await proxyState.set(settings); const current = await proxyState.get(); // Survives service worker suspension return current;}05Typed Messaging (createChannel)
createChannel provides a lightweight, strongly typed request/response layer over runtime.onMessage and runtime.sendMessage for background, popup, and content-script communication.
In Your Background Service Workerbackground.ts
import { createChannel } from "@infralayers/mv3-proxy-kit/messaging";import { setProxyConfig } from "@infralayers/mv3-proxy-kit/proxy";
interface EnablePayload { host: string; port: number;}
const channel = createChannel();
channel.on<EnablePayload, { ok: true }>("ENABLE_PROXY", async (payload) => { await setProxyConfig({ host: payload.host, port: payload.port }); return { ok: true };});In Your Popup or Content Scriptpopup.ts
import { createChannel } from "@infralayers/mv3-proxy-kit/messaging";
const channel = createChannel();
async function onEnableClick(host: string, port: number) { const res = await channel.send<{ host: string; port: number }, { ok: true }>({ type: "ENABLE_PROXY", payload: { host, port }, }); return res.ok;}06Cross-Browser API Resolver (getBrowserAPI)
getBrowserAPI() resolves the active WebExtension namespace (globalThis.browser on Firefox, globalThis.chrome on Chrome, with safe fallback) and throws a clear error if executed outside an extension context.
Every core function (setProxyConfig, clearProxyConfig, registerProxyAuth, createPersistedState, createChannel, and new ProxyManager(api)) accepts an optional api: BrowserAPI parameter so you can inject a lightweight mock in Node.js unit tests without needing a real browser:
import { setProxyConfig, type BrowserAPI } from "@infralayers/mv3-proxy-kit";
const fakeApi = { proxy: { settings: { set: async () => {} } },} as unknown as BrowserAPI;
async function testClearProxy() { await setProxyConfig({ mode: "direct" }, fakeApi);}07Manifest Permissions & Browser Quirks
@infralayers/mv3-proxy-kit/state, you only need the "storage" permission. @infralayers/mv3-proxy-kit/messaging requires no extra manifest permissions. The manifests below apply when using the /proxy module.Chrome MV3manifest.json
{ "manifest_version": 3, "permissions": ["proxy", "webRequest", "webRequestAuthProvider", "storage"], "host_permissions": ["<all_urls>"], "background": { "service_worker": "dist/background.js", "type": "module" }}- No top-level
await: Chrome MV3 service workers reject top-levelawait. Always registerregisterProxyAuth(...)andchannel.on(...)synchronously at module load time. chrome://newtabquirk: Chrome intentionally blocks extensions from interceptingwebRequest.onAuthRequiredfor requests initiated bychrome://pages (including the New Tab page). Navigating to any standardhttps://page triggersregisterProxyAuthand populates Chrome's HTTP Auth Cache.
Firefox MV3manifest.json
{ "manifest_version": 3, "permissions": ["proxy", "webRequest", "webRequestBlocking", "storage"], "host_permissions": ["<all_urls>"], "background": { "scripts": ["dist/background.js"], "type": "module" }, "browser_specific_settings": { "gecko": { "id": "your-extension@example.com" } }}- Private Browsing permission: Firefox requires the user to set "Run in Private Windows: Allow" (in
about:addons) beforebrowser.proxy.settings.set()is permitted. - Host permissions in MV3: In Firefox MV3,
<all_urls>underhost_permissionsmay start disabled until the user enables "Access your data for all websites" in the extension's Permissions tab inabout:addons.