Documentation

@infralayers/mv3-proxy-kit Developer Guide

Complete module-by-module reference for building cross-browser Manifest V3 (MV3) extensions for Chrome and Firefox.

v0.1.0npmZero DependenciesTypeScript 5.xChrome & Firefox MV3MIT

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.

bash
npm install @infralayers/mv3-proxy-kit
imports.ts·typescript
// 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";
SubpathUse CaseRequires proxy Permission?
@infralayers/mv3-proxy-kit/stateSuspension-safe persisted state for any MV3 extensionNo(only storage)
@infralayers/mv3-proxy-kit/messagingTyped popup ↔ background ↔ content-script messagingNo
@infralayers/mv3-proxy-kit/proxyCross-browser proxy routing (fixed_servers, pac_url, direct) & authYes

02Proxy Configuration (ProxyManager & Standalone Helpers)

Rule of thumb
  • 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 mock BrowserAPI objects 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).

fixed-proxy.ts·typescript
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).

pac-url.ts·typescript
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".

clear-proxy.ts·typescript
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.

proxy-manager.ts·typescript
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();  }}

03Proxy Authentication (registerProxyAuth)

registerProxyAuth listens to webRequest.onAuthRequired and transparently handles the Chrome vs. Firefox MV3 split:

Chrome MV3

Registers with ["asyncBlocking"], invokes asyncCallback({ authCredentials }) (or { cancel: true } on missing credentials), and returns void on non-proxy challenges.

Firefox MV3

Registers with ["blocking"] and returns a Promise directly (or {} synchronously on non-proxy challenges).

background.ts·typescript
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-flight storage.get().
  • Write-wins race protection: calling set() while hydrate() is in flight ensures stale storage reads never overwrite newer writes.
state.ts·typescript
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

background.ts·typescript
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

popup.ts·typescript
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:

proxy.test.ts·typescript
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

Non-proxy extensions
If you only use @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

chrome/manifest.json·json
{  "manifest_version": 3,  "permissions": ["proxy", "webRequest", "webRequestAuthProvider", "storage"],  "host_permissions": ["<all_urls>"],  "background": { "service_worker": "dist/background.js", "type": "module" }}

Firefox MV3manifest.json

firefox/manifest.json·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" }  }}

Need help integrating @infralayers/mv3-proxy-kit?

Open an issue on GitHub for open-source questions, or talk to our engineering team for commercial architecture and integration support.