diff --git a/CHANGELOG.md b/CHANGELOG.md
index af97214..c54b505 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,11 @@
## Unreleased
+- Audit profile entropy, canvas/audio consistency, timezone semantics, native
+ worker initialization, header coherence and storage teardown.
+- Await proxy setup before target navigation and reject cross-tab identity access.
+- Replace certificate-name trust with verified public-CA pinning; automatically
+ retrieve Burp's public CA through the explicitly selected local HTTP proxy.
- Move interception actions above the request editor and keep them visible
while scrolling; place Forward all beside the interceptor toggle.
- Add a session-only research workspace with include/exclude target scope and
diff --git a/README.md b/README.md
index 65b0ca7..87ffd72 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@ Built with Electron and Chromium for Windows, Linux, and macOS.
[Download](https://github.com/iMumd/fathi-browser/releases/latest) ·
[Research guide](docs/research-workspace.md) ·
+[Identity audit](docs/identity-audit.md) ·
[Contribute](CONTRIBUTING.md) ·
[Changelog](CHANGELOG.md)
@@ -38,6 +39,11 @@ Research tools do not automatically crawl, scan, or attack targets. Passive
notes do not issue extra requests and are not confirmed vulnerability reports.
JWT inspection decodes claims; it does not verify their signature.
+Use Burp also retrieves and validates the public CA from the local Burp listener
+and pins it inside Fathi. No system-wide certificate installation is performed.
+If retrieval fails, open Burp and retry Retrieve local Burp CA, or import its
+public certificate manually. Remote proxy CAs are never fetched automatically.
+
## Privacy, with clear boundaries
- Browsing sessions, captured traffic, scope, toolbox input, and comparison
diff --git a/docs/identity-audit.md b/docs/identity-audit.md
new file mode 100644
index 0000000..b63f73d
--- /dev/null
+++ b/docs/identity-audit.md
@@ -0,0 +1,116 @@
+# Identity and isolation audit
+
+Status: unreleased changes following 1.0.2. No release is published by this audit.
+
+## Contract
+
+A new tab and New identity allocate a fresh random profile and a fresh
+non-persistent Electron session. Reloading the same tab keeps its identity and
+storage stable. Different identities do not require every individual field to
+change: two realistic Chrome profiles can share a UA, screen size, or core
+count. Identity and noise material must be independently generated instead of
+inventing impossible values merely to make every field different.
+
+The generator uses independent cryptographic material for a 128-bit identity
+seed and canvas/audio noise. Partition IDs use independent UUIDs. Renderer
+supplied profiles are not reused. Profile lists and device GPU data are copied
+so mutating one profile cannot change another.
+
+## Findings addressed
+
+- Canvas readout used a parity-only noise pattern and inconsistent seeds across
+ read and export APIs. Stable coordinate-based noise now agrees across
+ getImageData, PNG export, and OffscreenCanvas, including dedicated workers.
+- Audio variation missed OfflineAudioContext results. AudioBuffer reads and
+ copyFromChannel now receive stable per-profile perturbations without repeated
+ drift. Tiny noise can affect audio applications; the preference can disable it.
+- Date timezone-offset sign was reversed and explicit Intl timezones were
+ overwritten. Offsets, daylight saving, explicit UTC, and native page timezone
+ configuration are now checked.
+- Native worker values could race profile installation. Guests initialize on
+ about:blank and target navigation waits for native identity and worker hooks.
+- Chromium client hints leaked into Safari-shaped profiles, native header
+ spellings could coexist with spoofed ones, and Android model hints were empty.
+- Chrome versions were randomly invented despite a fixed underlying engine.
+ Reported Chromium versions now match the installed engine. Device-memory
+ values respect Chromium's 8 GiB reporting cap; Intel Mac GPU profiles use x86.
+- Plain arrays replaced PluginArray/MimeTypeArray, and device group IDs
+ contained a literal application marker. Native plugin arrays are preserved;
+ that marker is removed. OS speech-voice enumeration is minimized.
+- Spoofing preferences were not propagated to new profiles. Changes now apply
+ to new tabs and New identity, without silently changing an existing profile.
+- Proxy setup was not awaited before navigation. Initialization now waits, and
+ configured-proxy failures do not silently continue as successful preparation.
+- Session teardown retained fingerprint/proxy mappings. Teardown now removes
+ those mappings, closes connections and clears auth, storage, cache and DNS
+ state before New identity continues.
+- Guests cannot create/destroy arbitrary tab sessions or retrieve another
+ tab's fingerprint. Only known, non-persistent partitions can attach.
+- The extension-install bridge is no longer exposed to arbitrary websites.
+
+## Burp certificate trust
+
+Previously, certificate issuer/subject names containing Burp or PortSwigger
+could bypass verification. Names are not proof of trust. That path is removed.
+
+Use Burp now configures the explicit loopback HTTP proxy and retrieves its
+public CA from `http://burp/cert` through that proxy. The response must parse as
+a currently valid CA certificate. Downloads are bounded to 64 KiB and five
+seconds, do not follow redirects, and cannot use a remote or SOCKS proxy for
+automatic retrieval. A manual public-certificate import remains available.
+
+Trust is limited to the imported public CA, with signature-chain, validity,
+hostname and server-auth usage checks. It only applies while proxy trust and
+the proxy itself are enabled. Certificate names alone never suffice. The
+public CA persists in proxy preferences; no CA private key is imported or
+stored. Nothing is installed into the operating system trust store.
+
+This workflow is tested with a generated local test CA and a loopback proxy
+fixture. A live Burp installation is not part of the automated test environment.
+Review the locally selected proxy: another process controlling that listener
+can supply its own CA when you explicitly retrieve it. Retrieval does not
+silently replace an existing pin on startup.
+
+## Validation
+
+`npm test` covers 2,000 independently generated profiles, mutation isolation,
+timezone behavior, navigator/prototype agreement, header consistency, scoped
+research tools and network history. Certificate tests generate temporary keys
+with OpenSSL, test real signatures/hostnames, reject malformed certificates and
+exercise the bounded local download. No test private keys are committed.
+
+Run the application audit with:
+
+```bash
+npx electron . --fathi-e2e --fathi-identity-audit
+```
+
+The local HTTP fixture checks early page scripts, cross-origin frames, workers,
+on-wire identity, canvas/audio stability and differences, storage isolation
+(cookies, localStorage, IndexedDB and CacheStorage), reload stability, and New
+identity teardown. E2E uses temporary preferences. The broader E2E suite also
+visits example.com. Runtime checks here are executed locally on Windows; CI
+unit checks run on Windows, Linux and macOS. This is not a claim of independent
+third-party certification or identical runtime coverage on every platform.
+
+## Important limits
+
+- Fathi remains Chromium. An iOS/Safari profile does not turn it into WebKit;
+ CSS behavior, TLS/HTTP transport, fonts, codecs and API implementations can
+ reveal the real engine or host. System fonts are not virtualized.
+- This is profile emulation and session isolation, not a guarantee that every
+ fingerprint surface is covered or that automation cannot be detected.
+- Main-world wrappers are observable. Sophisticated pages may detect them.
+ Service-worker startup, nested worker chains, worklets and all browser
+ extensions are not comprehensively audited by these tests.
+- Worker initialization shares the recorder's debugger connection. Opening
+ DevTools can detach it; worker protections are not guaranteed while another
+ debugger owns the target. Avoid that during privacy-sensitive browsing.
+- A new fingerprint does not change a direct public IP, account identity,
+ server-side identifiers, downloaded files, exported data or clipboard history.
+ Proxy rotation changes only what the configured proxy actually provides.
+- WebRTC non-proxied UDP is disabled per guest, but this is not a blanket
+ guarantee against every possible network-side correlation channel.
+
+Treat these limits as part of the product contract, not as reasons to label a
+profile fully anonymous or undetectable.
diff --git a/package.json b/package.json
index 5fe0759..512d717 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,7 @@
"license": "MIT",
"main": "src/main/main.js",
"scripts": {
- "test": "node tools/check-syntax.js && node --test tools/test-research.js tools/test-network.js && node tools/test-rules.js",
+ "test": "node tools/check-syntax.js && node --test tools/test-research.js tools/test-network.js tools/test-identity.js tools/test-certificate.js && node tools/test-rules.js",
"start": "electron .",
"icons": "node tools/make-icons.js && node tools/make-installer-art.js",
"dist:win": "electron-builder --win nsis portable --x64 --publish never",
diff --git a/src/main/burp-ca.js b/src/main/burp-ca.js
new file mode 100644
index 0000000..0b1ebde
--- /dev/null
+++ b/src/main/burp-ca.js
@@ -0,0 +1,25 @@
+'use strict';
+const http = require('node:http');
+const { parseCa } = require('./certificate-trust');
+/** Fetch only through the explicitly selected loopback HTTP proxy. */
+function fetchCa(entry) {
+ if (!entry || entry.scheme !== 'http' || !['127.0.0.1', 'localhost', '[::1]', '::1'].includes(entry.host.toLowerCase())) return Promise.reject(new Error('Automatic CA import requires a loopback HTTP Burp proxy'));
+ return new Promise((resolve, reject) => {
+ const headers = { Host: 'burp', Connection: 'close' };
+ if (entry.username) headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(`${entry.username}:${entry.password || ''}`).toString('base64');
+ const request = http.request({ hostname: entry.host.replace(/^\[|\]$/g, ''), port: entry.port, method: 'GET', path: 'http://burp/cert', headers, agent: false }, (response) => {
+ if (response.statusCode !== 200) { response.resume(); reject(new Error('Burp did not return a CA certificate')); return; }
+ const chunks = []; let size = 0;
+ response.on('data', (chunk) => {
+ size += chunk.length;
+ if (size > 65536) { request.destroy(new Error('CA certificate exceeds 64 KiB')); return; }
+ chunks.push(chunk);
+ });
+ response.on('error', reject);
+ response.on('end', () => { try { resolve(parseCa(Buffer.concat(chunks))); } catch (error) { reject(error); } });
+ });
+ request.setTimeout(5000, () => request.destroy(new Error('Burp CA download timed out. Confirm Burp is listening locally.')));
+ request.on('error', reject); request.end();
+ });
+}
+module.exports = { fetchCa };
diff --git a/src/main/certificate-trust.js b/src/main/certificate-trust.js
new file mode 100644
index 0000000..805c704
--- /dev/null
+++ b/src/main/certificate-trust.js
@@ -0,0 +1,34 @@
+'use strict';
+const { X509Certificate } = require('node:crypto');
+const { isIP } = require('node:net');
+function valid(cert) { const now = Date.now(); return now >= Date.parse(cert.validFrom) && now <= Date.parse(cert.validTo); }
+function parseCa(data) {
+ const ca = new X509Certificate(data);
+ if (!ca.ca || !valid(ca)) throw new Error('Select a currently valid CA certificate');
+ return ca;
+}
+function verifies(request, pem) {
+ try {
+ const root = parseCa(pem);
+ const leaf = new X509Certificate(request.certificate.data);
+ if (!valid(leaf) || !(isIP(request.hostname) ? leaf.checkIP(request.hostname) : leaf.checkHost(request.hostname))) return false;
+ const usages = leaf.keyUsage;
+ if (usages?.length && !usages.includes('1.3.6.1.5.5.7.3.1') && !usages.includes('2.5.29.37.0')) return false;
+ let node = request.certificate;
+ const seen = new Set();
+ for (let depth = 0; node && depth < 10; depth++) {
+ const cert = new X509Certificate(node.data);
+ if (!valid(cert) || seen.has(cert.fingerprint256)) return false;
+ seen.add(cert.fingerprint256);
+ if (cert.fingerprint256 === root.fingerprint256) return true;
+ if (cert.checkIssued(root) && cert.verify(root.publicKey)) return true;
+ const issuer = node.issuerCert;
+ if (!issuer) return false;
+ const next = new X509Certificate(issuer.data);
+ if (!next.ca || !cert.checkIssued(next) || !cert.verify(next.publicKey)) return false;
+ node = issuer;
+ }
+ } catch {}
+ return false;
+}
+module.exports = { parseCa, verifies };
diff --git a/src/main/e2e.js b/src/main/e2e.js
index 5f22859..5f51dd8 100644
--- a/src/main/e2e.js
+++ b/src/main/e2e.js
@@ -153,6 +153,11 @@ async function run(win) {
JSON.stringify(about));
/* ---- 3. second tab gets a different partition */
+ if (process.argv.includes('--fathi-identity-audit')) {
+ trace('identity isolation audit');
+ const checks = await require('./identity-checks').run(ui);
+ for (const check of checks) add(check.name, check.pass, check.detail);
+ }
const updateUi = await ui.executeJavaScript(`(async () => {
openSettings('proxy');
const port = document.getElementById('tor-port');
diff --git a/src/main/fingerprint.js b/src/main/fingerprint.js
index cc6a39d..c7988b2 100644
--- a/src/main/fingerprint.js
+++ b/src/main/fingerprint.js
@@ -182,14 +182,16 @@ function randHex(bytes) { return crypto.randomBytes(bytes).toString('hex'); }
function generate(opts) {
const options = typeof opts === 'string' ? { seed: opts } : (opts || {});
const device = devices.get(options.deviceId);
- const seed = options.seed ? hash32(String(options.seed)) : crypto.randomBytes(4).readUInt32LE(0);
- const rng = mulberry32(seed);
+ const material = options.seed ? crypto.createHash('sha256').update(String(options.seed)).digest() : crypto.randomBytes(32);
+ const seed = material.subarray(0, 16).toString('hex');
+ const rng = mulberry32(material.readUInt32LE(0));
const osKey = pickWeighted(rng, Object.keys(OS_PROFILES));
const os = OS_PROFILES[osKey];
const lang = pick(rng, LANG_POOL);
- const ver = REAL_CHROME - Math.floor(rng() * 7); // last ~7 majors
- const fullVer = `${ver}.0.${6482 + Math.floor(rng() * 60)}.${40 + Math.floor(rng() * 90)}`;
+ // The JavaScript engine cannot become an older Chrome build by changing UA.
+ const ver = REAL_CHROME;
+ const fullVer = process.versions.chrome || `${ver}.0.0.0`;
const ua = `Mozilla/5.0 (${os.uaOs}) AppleWebKit/537.36 (KHTML, like Gecko) ` +
`Chrome/${ver}.0.0.0 Safari/537.36`;
@@ -199,8 +201,8 @@ function generate(opts) {
const gpu = pick(rng, os.gpus);
const cores = pick(rng, os.cores);
- const memory = pick(rng, os.memory);
- const plugins = pick(rng, PLUGIN_SETS);
+ const memory = Math.min(8, pick(rng, os.memory));
+ const plugins = PLUGIN_SETS[0].slice();
const platformVersion = pick(rng, os.platformVersions);
const brands = shuffle(rng, [
@@ -233,7 +235,7 @@ function generate(opts) {
productSub: '20030107',
oscpu: undefined,
language: lang.language,
- languages: lang.languages,
+ languages: lang.languages.slice(),
doNotTrack: null,
hardwareConcurrency: cores,
deviceMemory: memory,
@@ -247,7 +249,7 @@ function generate(opts) {
uaMobile: false,
uaDataPlatform: os.uaDataPlatform,
platformVersion,
- architecture: os.architecture,
+ architecture: osKey === 'mac' && /Intel/.test(gpu.r) ? 'x86' : os.architecture,
bitness: os.bitness,
wow64: os.wow64,
@@ -264,13 +266,13 @@ function generate(opts) {
// graphics / media
webgl: { vendor: gpu.v, renderer: gpu.r },
- canvasSeed: Math.floor(rng() * 0xFFFFFFFF),
- audioSeed: Math.floor(rng() * 0xFFFFFFFF),
+ canvasSeed: material.readUInt32LE(16),
+ audioSeed: material.readUInt32LE(20),
fonts,
plugins,
// misc
- timezone: lang.timezone,
+ timezone: new Intl.DateTimeFormat('en-US', { timeZone: lang.timezone }).resolvedOptions().timeZone,
timezoneOffsetBase: 0,
colorScheme: rng() > 0.28 ? 'light' : 'dark',
pdfViewerEnabled: true,
@@ -338,11 +340,11 @@ function applyMobileProfile(fp, device, rng, chromeMajor) {
};
// ---- graphics
- fp.webgl = device.gpu;
+ fp.webgl = { ...device.gpu };
// ---- hardware
fp.hardwareConcurrency = isIOS ? pick(rng, [6]) : pick(rng, [8, 8, 8]);
- fp.deviceMemory = isIOS ? 8 : pick(rng, [4, 6, 8]);
+ fp.deviceMemory = isIOS ? undefined : pick(rng, [4, 8]);
fp.pdfViewerEnabled = true;
fp.cookieEnabled = true;
fp.connection = {
diff --git a/src/main/identity-checks.js b/src/main/identity-checks.js
new file mode 100644
index 0000000..e3bfb46
--- /dev/null
+++ b/src/main/identity-checks.js
@@ -0,0 +1,135 @@
+'use strict';
+const http = require('node:http');
+const crypto = require('node:crypto');
+const { webContents } = require('electron');
+const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+async function pageProbe(frameUrl) {
+ const hash = async (bytes) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (v) => v.toString(16).padStart(2, '0')).join('');
+ const identity = () => ({ ua: navigator.userAgent, platform: navigator.platform, language: navigator.language, cores: navigator.hardwareConcurrency, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone });
+ const workerResult = await new Promise((resolve) => {
+ const worker = new Worker('/worker.js');
+ const timer = setTimeout(() => { worker.terminate(); resolve({ error: 'worker timeout' }); }, 4000);
+ worker.onmessage = (event) => { clearTimeout(timer); worker.terminate(); resolve(event.data); };
+ worker.onerror = () => { clearTimeout(timer); worker.terminate(); resolve({ error: 'worker error' }); };
+ });
+ const frameResult = await new Promise((resolve) => {
+ const frame = document.createElement('iframe');
+ const timer = setTimeout(() => { frame.remove(); resolve({ error: 'frame timeout' }); }, 4000);
+ const handler = (event) => {
+ if (event.source !== frame.contentWindow || event.data?.type !== 'identity-probe') return;
+ clearTimeout(timer); window.removeEventListener('message', handler); frame.remove(); resolve(event.data.identity);
+ };
+ window.addEventListener('message', handler); frame.src = frameUrl; document.body.appendChild(frame);
+ });
+ const c = document.createElement('canvas'); c.width = 128; c.height = 64;
+ const context = c.getContext('2d'); context.fillStyle = '#777'; context.fillRect(0, 0, c.width, c.height);
+ const dataUrl = c.toDataURL();
+ const pixels = await hash(context.getImageData(0, 0, c.width, c.height).data);
+ const audio = new OfflineAudioContext(1, 4096, 44100);
+ const oscillator = audio.createOscillator(); oscillator.type = 'triangle'; oscillator.frequency.value = 1000; oscillator.connect(audio.destination); oscillator.start();
+ const rendered = await audio.startRendering();
+ const first = new Float32Array(rendered.getChannelData(0));
+ const second = new Float32Array(rendered.getChannelData(0));
+ const copied = new Float32Array(first.length); rendered.copyFromChannel(copied, 0);
+ const audioHash = await hash(first);
+ return { early: window.__earlyIdentity, main: identity(), worker: workerResult, frame: frameResult,
+ headers: await (await fetch('/echo')).json(),
+ canvas: await hash(new TextEncoder().encode(dataUrl)), canvasStable: dataUrl === c.toDataURL(), dataUrl, pixels,
+ audio: audioHash, audioStable: audioHash === await hash(second) && audioHash === await hash(copied),
+ offsetWinter: new Date('2026-01-15T12:00:00Z').getTimezoneOffset(), explicitUTC: Intl.DateTimeFormat('en-US', { timeZone: 'UTC' }).resolvedOptions().timeZone };
+}
+const worker = `(async () => {
+ const canvas = new OffscreenCanvas(128, 64); const context = canvas.getContext('2d'); context.fillStyle = '#777'; context.fillRect(0, 0, 128, 64);
+ const digest = await crypto.subtle.digest('SHA-256', context.getImageData(0, 0, 128, 64).data);
+ const pixels = Array.from(new Uint8Array(digest), v => v.toString(16).padStart(2, '0')).join('');
+ const png = Array.from(new Uint8Array(await (await canvas.convertToBlob()).arrayBuffer()));
+ postMessage({ ua: navigator.userAgent, platform: navigator.platform, language: navigator.language, cores: navigator.hardwareConcurrency, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, pixels, png });
+})()`;
+const frame = ``;
+async function storage(write) {
+ if (write) { document.cookie = 'identityMarker=A; path=/'; localStorage.setItem('identityMarker', 'A'); }
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open('identity-audit', 1);
+ request.onupgradeneeded = () => request.result.createObjectStore('markers');
+ request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);
+ });
+ const idb = await new Promise((resolve, reject) => {
+ const tx = db.transaction('markers', write ? 'readwrite' : 'readonly');
+ const request = write ? tx.objectStore('markers').put('A', 'identity') : tx.objectStore('markers').get('identity');
+ tx.oncomplete = () => resolve(write ? 'A' : request.result || null); tx.onerror = () => reject(tx.error);
+ }); db.close();
+ const cache = await caches.open('identity-audit');
+ if (write) await cache.put('/cache-marker', new Response('A'));
+ const cached = await cache.match('/cache-marker');
+ return { cookie: document.cookie, local: localStorage.getItem('identityMarker'), idb, cache: cached ? await cached.text() : null };
+}
+async function run(ui) {
+ const trace = (message) => require('node:fs').appendFileSync(require('node:path').join(__dirname, '../../e2e-trace.txt'), `identity: ${message}\n`);
+ const checks = []; const tabs = [];
+ const add = (name, pass, detail = '') => checks.push({ name, pass: !!pass, detail: typeof detail === 'string' ? detail : JSON.stringify(detail) });
+ let framePort;
+ const handler = (request, response) => {
+ if (request.url === '/worker.js') { response.setHeader('Content-Type', 'text/javascript'); response.end(worker); }
+ else if (request.url === '/frame') { response.setHeader('Content-Type', 'text/html'); response.end(frame); }
+ else if (request.url === '/echo') { response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(request.headers)); }
+ else { response.setHeader('Content-Type', 'text/html'); response.end(`
`); }
+ };
+ const server = http.createServer(handler); const frameServer = http.createServer(handler);
+ await new Promise((resolve) => frameServer.listen(0, '127.0.0.1', resolve)); framePort = frameServer.address().port;
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const url = `http://127.0.0.1:${server.address().port}/`;
+ async function create() {
+ trace('create tab');
+ const info = await ui.executeJavaScript(`(async () => { const tab = await createTab({ url: ${JSON.stringify(url)}, deviceId: 'desktop' }); return { id: tab.id, fp: tab.fp, partition: tab.partition }; })()`);
+ tabs.push(info.id);
+ return resolveTab(info);
+ }
+ async function resolveTab(info) {
+ for (let i = 0; i < 80; i++) {
+ const wcId = await ui.executeJavaScript(`(() => { try { return state.tabs.find(t => t.id === ${JSON.stringify(info.id)}).wv.getWebContentsId(); } catch { return null; } })()`);
+ const wc = wcId && webContents.fromId(wcId);
+ if (wc && wc.getURL() === url && await wc.executeJavaScript('!!window.__identityReady').catch(() => false)) {
+ const snapshot = await wc.executeJavaScript(`window.__identityReady.catch(error => { throw new Error('Probe: ' + (error.stack || error.message || JSON.stringify(error))); })`);
+ trace('probe complete');
+ return { ...info, wc, snapshot };
+ }
+ await delay(100);
+ }
+ throw new Error('Identity probe did not load');
+ }
+ try {
+ const a = await create(); trace('storage A'); const aStorage = await a.wc.executeJavaScript(`(${storage.toString()})(true)`);
+ const b = await create(); trace('storage B'); const bStorage = await b.wc.executeJavaScript(`(${storage.toString()})(false)`);
+ add('identity audit: tab IDs, partitions and noise seeds differ', a.fp.id !== b.fp.id && a.partition !== b.partition && a.fp.canvasSeed !== b.fp.canvasSeed && a.fp.audioSeed !== b.fp.audioSeed);
+ add('identity audit: cookies, localStorage, IndexedDB and CacheStorage are isolated', !!aStorage.cookie && !bStorage.cookie && bStorage.local === null && bStorage.idb === null && bStorage.cache === null, bStorage);
+ for (const item of [a, b]) {
+ const s = item.snapshot;
+ const matches = (value) => value.ua === item.fp.ua && value.platform === item.fp.platform && value.language === item.fp.language && value.cores === item.fp.hardwareConcurrency && value.timezone === item.fp.timezone;
+ add('identity audit: early page and cross-origin frame match the tab profile', s.early.ua === item.fp.ua && s.early.platform === item.fp.platform && matches(s.main) && matches(s.frame), { main: s.main, frame: s.frame });
+ add('identity audit: dedicated worker matches the tab profile', matches(s.worker), { ...s.worker, png: undefined });
+ const workerPixels = s.worker.png ? await require('sharp')(Buffer.from(s.worker.png)).ensureAlpha().raw().toBuffer() : null;
+ add('identity audit: worker OffscreenCanvas matches page noise and PNG export', s.worker.pixels === s.pixels && workerPixels && crypto.createHash('sha256').update(workerPixels).digest('hex') === s.pixels);
+ add('identity audit: network UA, platform hints and language match the page', s.headers['user-agent'] === item.fp.ua && s.headers['sec-ch-ua-platform'] === '"' + item.fp.uaDataPlatform + '"' && s.headers['accept-language'].startsWith(item.fp.language));
+ add('identity audit: canvas and audio reads are stable; UTC is respected', s.canvasStable && s.audioStable && s.explicitUTC === 'UTC');
+ const png = Buffer.from(s.dataUrl.split(',')[1], 'base64');
+ const pixels = await require('sharp')(png).ensureAlpha().raw().toBuffer();
+ add('identity audit: canvas PNG and getImageData expose consistent pixels', crypto.createHash('sha256').update(pixels).digest('hex') === s.pixels);
+ }
+ add('identity audit: rendered canvas and offline audio vary between tabs', a.snapshot.canvas !== b.snapshot.canvas && a.snapshot.audio !== b.snapshot.audio);
+ trace('reload A'); a.wc.reload(); await delay(100);
+ const reloaded = (await resolveTab(a)).snapshot;
+ add('identity audit: reload preserves identity and its storage', reloaded.canvas === a.snapshot.canvas && (await a.wc.executeJavaScript(`(${storage.toString()})(false)`)).local === 'A');
+ trace('rotate A'); await ui.executeJavaScript(`(async () => { activate(${JSON.stringify(a.id)}); await rotateTab(${JSON.stringify(a.id)}); })()`);
+ const replacement = await ui.executeJavaScript('({ id: activeTab().id, fp: activeTab().fp, partition: activeTab().partition })'); tabs.push(replacement.id);
+ const reset = await resolveTab(replacement);
+ const resetStorage = await reset.wc.executeJavaScript(`(${storage.toString()})(false)`);
+ const old = await ui.executeJavaScript(`window.api.fp.current(${JSON.stringify(a.fp.id)})`);
+ add('identity audit: New identity replaces profile and clears old session data', replacement.fp.id !== a.fp.id && replacement.partition !== a.partition && !old.ok && !resetStorage.cookie && resetStorage.local === null && resetStorage.idb === null && resetStorage.cache === null, resetStorage);
+ } finally {
+ for (const id of tabs) await ui.executeJavaScript(`closeTab(${JSON.stringify(id)}, { silent: true })`).catch(() => {});
+ server.closeAllConnections(); frameServer.closeAllConnections();
+ await new Promise((resolve) => server.close(resolve)); await new Promise((resolve) => frameServer.close(resolve));
+ }
+ return checks;
+}
+module.exports = { run };
diff --git a/src/main/identity-runtime.js b/src/main/identity-runtime.js
new file mode 100644
index 0000000..f526c8e
--- /dev/null
+++ b/src/main/identity-runtime.js
@@ -0,0 +1,60 @@
+'use strict';
+const { fathiSpoof } = require('../shared/spoof');
+const { acceptLanguage } = require('./session');
+const installed = new WeakSet();
+const configuring = new WeakMap();
+const configurators = new WeakMap();
+function attach(wc, fp) {
+ if (!fp || fp.enabled === false) return;
+ const dbg = wc.debugger;
+ const apply = () => {
+ if (installed.has(wc)) return Promise.resolve();
+ if (configuring.has(wc)) return configuring.get(wc);
+ if (wc.isDestroyed() || !dbg.isAttached()) return Promise.reject(new Error('Identity debugger is not ready'));
+ const job = (async () => {
+ await dbg.sendCommand('Target.setAutoAttach', {
+ autoAttach: true, waitForDebuggerOnStart: true, flatten: true,
+ filter: [{ type: 'worker', exclude: false }, { type: 'shared_worker', exclude: false }, { exclude: true }]
+ });
+ await dbg.sendCommand('Emulation.setTimezoneOverride', { timezoneId: fp.timezone });
+ const identity = { userAgent: fp.ua, acceptLanguage: acceptLanguage(fp), platform: fp.platform };
+ if (fp.clientHints !== false) identity.userAgentMetadata = {
+ brands: fp.uaBrands, fullVersionList: fp.uaFullVersionList,
+ fullVersion: fp.uaFullVersion, platform: fp.uaDataPlatform,
+ platformVersion: fp.platformVersion, architecture: fp.architecture,
+ model: fp.model || '', mobile: !!fp.uaMobile, bitness: fp.bitness, wow64: !!fp.wow64
+ };
+ await dbg.sendCommand('Emulation.setUserAgentOverride', identity);
+ installed.add(wc);
+ })();
+ configuring.set(wc, job);
+ job.finally(() => configuring.delete(wc)).catch(() => {});
+ return job;
+ };
+ configurators.set(wc, apply);
+ dbg.on('message', async (_event, method, params) => {
+ if (method !== 'Target.attachedToTarget' || !['worker', 'shared_worker'].includes(params.targetInfo?.type)) return;
+ const id = params.sessionId;
+ // Always release the worker, including on unsupported protocol commands.
+ const rescue = setTimeout(() => { dbg.sendCommand('Runtime.runIfWaitingForDebugger', {}, id).catch(() => {}); }, 2000);
+ try {
+ await dbg.sendCommand('Runtime.enable', {}, id);
+ await dbg.sendCommand('Runtime.evaluate', { expression: `(${fathiSpoof.toString()})(${JSON.stringify(fp)})` }, id);
+ } catch {} finally {
+ clearTimeout(rescue);
+ await dbg.sendCommand('Runtime.runIfWaitingForDebugger', {}, id).catch(() => {});
+ }
+ });
+ dbg.on('detach', () => installed.delete(wc));
+ const kick = () => apply().catch(() => {});
+ wc.once('dom-ready', kick);
+ wc.on('devtools-closed', kick);
+ kick();
+}
+async function ready(wc, fp) {
+ if (fp.enabled === false) return;
+ const apply = configurators.get(wc);
+ if (!apply) throw new Error('Identity runtime is not attached');
+ await apply();
+}
+module.exports = { attach, ready };
diff --git a/src/main/main.js b/src/main/main.js
index 9b4e862..5487246 100644
--- a/src/main/main.js
+++ b/src/main/main.js
@@ -63,6 +63,7 @@ const network = require('./network');
const tor = require('./tor');
const updater = require('./updater');
const researchScope = require('./research-scope');
+const identityRuntime = require('./identity-runtime');
/* ----------------------------------------------------------------- state */
@@ -79,7 +80,7 @@ protocolPages.registerPrivileged();
/* -------------------------------------------------------------- sessions */
-function ensureSession(partition, fp) {
+async function ensureSession(partition, fp) {
if (partitions.has(partition)) {
const rec = partitions.get(partition);
rec.fp = fp;
@@ -91,8 +92,10 @@ function ensureSession(partition, fp) {
proxyMgr.assign(partition);
protocolPages.bind(ses);
- configureSession(ses, fp, partition, { downloadDir: DOWNLOAD_DIR });
+ configureSession(ses, fp, partition, { downloadDir: DOWNLOAD_DIR, proxy: false });
partitions.set(partition, { ses, fp });
+ // A guest must not navigate before its proxy is configured.
+ await proxyMgr.applyTo(ses, partition);
return ses;
}
@@ -101,7 +104,11 @@ async function destroySession(partition) {
const rec = partitions.get(partition);
partitions.delete(partition);
partitionFp.delete(partition);
+ proxyMgr.assignments.delete(partition);
if (!rec) return;
+ fps.delete(rec.fp.id);
+ try { await rec.ses.closeAllConnections(); } catch {}
+ try { await rec.ses.clearAuthCache(); } catch {}
try { await rec.ses.clearStorageData(); } catch {}
try { await rec.ses.clearCache(); } catch {}
try { await rec.ses.clearHostResolverCache(); } catch {}
@@ -145,6 +152,7 @@ function createWindow() {
mainWindow.webContents.on('will-attach-webview', (event, webPreferences, params) => {
const partition = params.partition || '';
const fpId = partitionFp.get(partition) || '';
+ if (!fpId || !partitions.has(partition) || partition.startsWith('persist:')) { event.preventDefault(); return; }
// Never trust a renderer supplied preload / node integration
delete webPreferences.preloadURL;
@@ -226,7 +234,7 @@ async function applyDeviceEmulation(wc, fp, viewport) {
scale
});
await wc.debugger.sendCommand('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
- if (fp.ua) wc.setUserAgent(fp.ua, (fp.languages || ['en-US']).join(','));
+ if (fp.ua && fp.enabled !== false) wc.setUserAgent(fp.ua, (fp.languages || ['en-US']).join(','));
} catch (e) {
emulationLayouts.delete(wc);
// Target already gone or emulation unsupported; the page still renders.
@@ -235,11 +243,13 @@ async function applyDeviceEmulation(wc, fp, viewport) {
app.on('web-contents-created', (_event, wc) => {
if (wc.getType() !== 'webview') return;
+ try { wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp'); } catch {}
intercept.attach(wc);
network.attach(wc);
const rec = recordForWebContents(wc);
+ if (rec) identityRuntime.attach(wc, rec.fp);
if (rec && rec.fp && rec.fp.device && rec.fp.device.mobile) {
const apply = () => applyDeviceEmulation(wc, rec.fp, lastViewport);
// A newly created guest has no render view yet. Configuring it synchronously
@@ -380,22 +390,34 @@ ipcMain.handle('fathi:fp:new', () => {
});
ipcMain.on('fathi:fp:sync', (event, fpId) => {
- const fp = fps.get(fpId);
+ const own = recordForWebContents(event.sender);
+ const fp = own?.fp.id === fpId ? own.fp : null;
event.returnValue = fp ? JSON.stringify(fp) : 'null';
});
ipcMain.handle('fathi:fp:current', (event, fpId) => {
- const fp = fps.get(fpId);
+ const own = recordForWebContents(event.sender);
+ const fp = event.sender === mainWindow?.webContents ? fps.get(fpId) : own?.fp.id === fpId ? own.fp : null;
return fp ? ok({ fp }) : fail('no fingerprint');
});
/* --- tabs */
+ipcMain.handle('fathi:tab:ready', async (event, wcId) => {
+ if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may initialize tab sessions');
+ try {
+ const wc = webContents.fromId(Number(wcId));
+ const rec = wc && recordForWebContents(wc);
+ if (!rec) return fail('Unknown tab session');
+ await identityRuntime.ready(wc, rec.fp);
+ return ok({});
+ } catch (error) { return fail(error); }
+});
ipcMain.handle('fathi:tab:prepare', async (event, opts = {}) => {
+ if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may create tab sessions');
+ let partition;
try {
- let fp = opts.fp && opts.fp.id ? opts.fp : null;
- if (!fp) {
- fp = fpgen.generate({ deviceId: opts.deviceId });
- if (opts.landscape && fp.device && fp.device.mobile) {
+ const fp = fpgen.generate({ deviceId: opts.deviceId });
+ if (opts.landscape && fp.device && fp.device.mobile) {
const w = fp.device.width;
fp.device.width = fp.device.height;
fp.device.height = w;
@@ -404,15 +426,13 @@ ipcMain.handle('fathi:tab:prepare', async (event, opts = {}) => {
fp.screen.height = fp.device.height;
fp.screen.availWidth = fp.device.width;
fp.screen.availHeight = Math.round(fp.device.height * 0.94);
- }
- fps.set(fp.id, fp);
- } else {
- fps.set(fp.id, fp);
}
+ for (const key of ['enabled', 'spoofCanvas', 'spoofWebgl', 'spoofAudio']) fp[key] = settings.get().fingerprint?.[key] !== false;
+ fps.set(fp.id, fp);
- const partition = `fathi-tab-${fp.id}-${Date.now().toString(36)}`;
+ partition = `fathi-tab-${require('node:crypto').randomUUID()}`;
partitionFp.set(partition, fp.id);
- ensureSession(partition, fp);
+ await ensureSession(partition, fp);
return ok({
fp,
@@ -421,11 +441,13 @@ ipcMain.handle('fathi:tab:prepare', async (event, opts = {}) => {
proxy: proxyMgr.status(partition)
});
} catch (e) {
+ if (partition) await destroySession(partition);
return fail(e);
}
});
ipcMain.handle('fathi:tab:destroy', async (event, { partition } = {}) => {
+ if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may destroy tab sessions');
if (partition) await destroySession(partition);
return ok({});
});
@@ -435,6 +457,31 @@ ipcMain.handle('fathi:tab:proxy-status', (event, { partition } = {}) => {
});
/* --- proxy */
+ipcMain.handle('fathi:proxy:fetch-ca', async (event) => {
+ if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may import a CA');
+ try {
+ const cfg = settings.get().proxy;
+ if (!cfg.enabled) return fail('Enable the local Burp proxy first');
+ const entry = proxyMgr.parseEntry(cfg.pool?.[0]);
+ const ca = await require('./burp-ca').fetchCa(entry);
+ settings.save({ proxy: { burpCaPem: ca.toString(), trustBurpCert: true } });
+ for (const rec of partitions.values()) applyCertTrust(rec.ses);
+ return ok({ fingerprint: ca.fingerprint256 });
+ } catch (error) { return fail(error); }
+});
+ipcMain.handle('fathi:proxy:import-ca', async (event) => {
+ if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may import a CA');
+ try {
+ const result = await dialog.showOpenDialog(mainWindow, { title: 'Import Burp public CA certificate', properties: ['openFile'], filters: [{ name: 'Certificates', extensions: ['pem', 'der', 'crt', 'cer'] }] });
+ if (result.canceled) return ok({ canceled: true });
+ const data = await fs.promises.readFile(result.filePaths[0]);
+ if (data.length > 65536) return fail('Certificate file is too large');
+ const ca = require('./certificate-trust').parseCa(data);
+ settings.save({ proxy: { burpCaPem: ca.toString(), trustBurpCert: true } });
+ for (const rec of partitions.values()) applyCertTrust(rec.ses);
+ return ok({ fingerprint: ca.fingerprint256 });
+ } catch (error) { return fail(error); }
+});
ipcMain.handle('fathi:proxy:get', () => ok({ config: settings.get().proxy }));
ipcMain.handle('fathi:proxy:set', async (event, patch = {}) => {
diff --git a/src/main/proxy.js b/src/main/proxy.js
index 027bdb1..4d55bb5 100644
--- a/src/main/proxy.js
+++ b/src/main/proxy.js
@@ -82,6 +82,7 @@ async function applyTo(ses, partition, forceEntry) {
return entry;
} catch (e) {
console.error('[proxy] apply failed', e);
+ if (entry && cfg.enabled) throw e;
return null;
}
}
diff --git a/src/main/session.js b/src/main/session.js
index 15c999d..271183b 100644
--- a/src/main/session.js
+++ b/src/main/session.js
@@ -16,6 +16,7 @@ const rewrite = require('./rewrite');
/* ------------------------------------------------------------ header spoof */
function buildClientHints(fp) {
+ if (fp.clientHints === false) return {};
const brands = (fp.uaBrands || []).map((b) => `"${b.brand}";v="${b.version}"`).join(', ');
return {
'sec-ch-ua': brands,
@@ -24,7 +25,7 @@ function buildClientHints(fp) {
'sec-ch-ua-platform-version': `"${fp.platformVersion}"`,
'sec-ch-ua-arch': `"${fp.architecture}"`,
'sec-ch-ua-bitness': `"${fp.bitness}"`,
- 'sec-ch-ua-model': '""',
+ 'sec-ch-ua-model': `"${fp.model || ''}"`,
'sec-ch-ua-full-version': `"${fp.uaFullVersion}"`,
'sec-ch-ua-full-version-list': (fp.uaFullVersionList || [])
.map((b) => `"${b.brand}";v="${b.version}"`).join(', ')
@@ -47,24 +48,12 @@ function acceptLanguage(fp) {
function applyCertTrust(ses) {
try {
const cfg = settings.get().proxy || {};
- if (!cfg.trustBurpCert) {
+ if (!cfg.trustBurpCert || !cfg.enabled || !cfg.burpCaPem) {
ses.setCertificateVerifyProc(null);
return;
}
ses.setCertificateVerifyProc((request, callback) => {
- const c = request.certificate || {};
- const names = [
- c.issuerName,
- c.issuer && c.issuer.commonName,
- c.issuer && c.issuer.organizationName,
- c.issuer && c.issuer.organization,
- c.subjectName,
- c.subject && c.subject.commonName,
- c.subject && c.subject.organizationName
- ].filter(Boolean).join(' ');
- // PortSwigger ships its CA as "PortSwigger CA" but organizations have
- // been renamed over the years, so match every known spelling.
- if (/portswigger|burp\s*suite|burp\s*ca/i.test(names)) return callback(0);
+ if (require('./certificate-trust').verifies(request, cfg.burpCaPem)) return callback(0);
callback(-3); // fall back to the default verification
});
} catch (e) {
@@ -87,14 +76,16 @@ function configureSession(ses, fp, partition, opts = {}) {
try {
ses.webRequest.onBeforeSendHeaders({ urls: ['*://*/*'] }, (details, callback) => {
const h = details.requestHeaders || {};
- const hints = buildClientHints(fp);
-
- h['User-Agent'] = fp.ua;
- h['Accept-Language'] = acceptLanguage(fp);
- for (const k of Object.keys(hints)) h[k] = hints[k];
-
- delete h['DNT'];
- delete h['X-Client-Data'];
+ if (fp.enabled !== false) {
+ const hints = buildClientHints(fp);
+ // Header names are case-insensitive; remove old spellings first.
+ for (const key of Object.keys(h)) {
+ if (/^(user-agent|accept-language|dnt|x-client-data)$/i.test(key) || /^sec-ch-ua(?:-|$)/i.test(key)) delete h[key];
+ }
+ h['User-Agent'] = fp.ua;
+ h['Accept-Language'] = acceptLanguage(fp);
+ for (const k of Object.keys(hints)) h[k] = hints[k];
+ }
// Match and Replace on request headers, before anything leaves the tab.
const rules = (settings.get().matchReplace || []);
@@ -121,7 +112,7 @@ function configureSession(ses, fp, partition, opts = {}) {
});
} catch {}
- try { ses.setUserAgent(fp.ua, fp.language); } catch {}
+ if (fp.enabled !== false) { try { ses.setUserAgent(fp.ua, acceptLanguage(fp)); } catch {} }
/* ---- permissions: deny everything that could de-anonymise the tab */
try {
diff --git a/src/main/settings.js b/src/main/settings.js
index 9d542b4..26c8443 100644
--- a/src/main/settings.js
+++ b/src/main/settings.js
@@ -33,7 +33,8 @@ const DEFAULTS = {
bypass: '',
testUrl: 'https://api.ipify.org?format=json',
dnsOverProxy: true,
- trustBurpCert: true // accept MITM certs issued by the PortSwigger CA by default
+ trustBurpCert: false, // requires an explicitly imported public CA
+ burpCaPem: ''
},
intercept: {
diff --git a/src/preload/fp.js b/src/preload/fp.js
index 0dd8bd0..f324729 100644
--- a/src/preload/fp.js
+++ b/src/preload/fp.js
@@ -1,551 +1,34 @@
'use strict';
-/**
- * Fathi page preload.
- *
- * Runs in every tab (and sub-frame). Two jobs:
- * 1. inject the per-tab fingerprint into the page's main world, before any
- * page script executes;
- * 2. expose a small bridge (fathi:// internal pages only) for the new tab.
- */
const { ipcRenderer, contextBridge, webFrame } = require('electron');
-
-/* ---------------------------------------------------------- fingerprint */
-
-function fathiSpoof(cfg) {
- 'use strict';
- const w = window;
-
- const def = (obj, prop, value) => {
- try {
- Object.defineProperty(obj, prop, { get: () => value, configurable: true, enumerable: true });
- } catch (e) {}
- };
- const defGet = (obj, prop, fn) => {
- try { Object.defineProperty(obj, prop, { get: fn, configurable: true, enumerable: true }); } catch (e) {}
- };
-
- const nav = w.navigator;
- if (!nav) return;
-
- /* ---------- navigator identity ---------- */
- def(nav, 'userAgent', cfg.ua);
- def(nav, 'appVersion', cfg.appVersion);
- def(nav, 'appName', cfg.appName || 'Netscape');
- def(nav, 'appCodeName', cfg.appCodeName || 'Mozilla');
- def(nav, 'platform', cfg.platform);
- def(nav, 'vendor', cfg.vendor || 'Google Inc.');
- def(nav, 'vendorSub', cfg.vendorSub || '');
- def(nav, 'productSub', cfg.productSub || '20030107');
- def(nav, 'language', cfg.language);
- def(nav, 'languages', Object.freeze((cfg.languages || [cfg.language]).slice()));
- def(nav, 'hardwareConcurrency', cfg.hardwareConcurrency);
- def(nav, 'deviceMemory', cfg.deviceMemory);
- def(nav, 'maxTouchPoints', cfg.maxTouchPoints || 0);
- def(nav, 'webdriver', false);
- def(nav, 'doNotTrack', null);
- def(nav, 'cookieEnabled', true);
- def(nav, 'onLine', true);
- def(nav, 'pdfViewerEnabled', true);
- if (cfg.oscpu) def(nav, 'oscpu', cfg.oscpu);
-
- /* ---------- plugins / mimeTypes ---------- */
- try {
- const names = cfg.plugins || ['PDF Viewer', 'Chrome PDF Viewer', 'Chromium PDF Viewer'];
- const plugins = names.map((n) => {
- const p = { name: n, filename: 'internal-pdf-viewer', description: 'Portable Document Format', length: 0 };
- p.item = () => null; p.namedItem = () => null;
- return p;
- });
- plugins.item = (i) => plugins[i] || null;
- plugins.namedItem = (n) => plugins.find((p) => p.name === n) || null;
- plugins.refresh = () => {};
- def(nav, 'plugins', plugins);
-
- const mimes = [{ type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format' }];
- mimes.item = (i) => mimes[i] || null;
- mimes.namedItem = (t) => mimes.find((m) => m.type === t) || null;
- def(nav, 'mimeTypes', mimes);
- } catch (e) {}
-
- /* ---------- client hints ---------- */
- try {
- if (cfg.clientHints === false) {
- // Safari (iOS) never exposes User-Agent Client Hints.
- try {
- Object.defineProperty(nav, 'userAgentData', {
- get: () => undefined, configurable: true, enumerable: false
- });
- } catch (e) {}
- } else {
- const brands = cfg.uaBrands || [];
- const fullList = cfg.uaFullVersionList || [];
- const isMobile = !!(cfg.device && cfg.device.mobile);
- const highEntropy = (hints) => {
- const out = {
- architecture: cfg.architecture,
- bitness: cfg.bitness,
- brands,
- fullVersionList: fullList,
- mobile: isMobile,
- model: cfg.model || '',
- platform: cfg.uaDataPlatform,
- platformVersion: cfg.platformVersion,
- uaFullVersion: cfg.uaFullVersion,
- wow64: cfg.wow64
- };
- if (!hints || !hints.length) return out;
- const filtered = {};
- for (const h of hints) if (Object.prototype.hasOwnProperty.call(out, h)) filtered[h] = out[h];
- return filtered;
- };
- const uaData = {
- brands,
- mobile: isMobile,
- platform: cfg.uaDataPlatform,
- getHighEntropyValues: (hints) => Promise.resolve(highEntropy(hints)),
- toJSON: () => ({ brands, mobile: isMobile, platform: cfg.uaDataPlatform })
- };
- def(nav, 'userAgentData', uaData);
- }
- } catch (e) {}
-
- /* ---------- connection ---------- */
- try {
- const c = cfg.connection || {};
- def(nav, 'connection', {
- effectiveType: c.effectiveType || '4g',
- rtt: c.rtt || 50,
- downlink: c.downlink || 10,
- saveData: false,
- onchange: null,
- addEventListener: () => {},
- removeEventListener: () => {}
- });
- } catch (e) {}
-
- /* ---------- screen ---------- */
- try {
- const s = cfg.screen || {};
- const scr = w.screen;
- if (scr) {
- const keys = ['width', 'height', 'availWidth', 'availHeight', 'colorDepth', 'pixelDepth'];
- for (const k of keys) if (s[k] != null) def(scr, k, s[k]);
- defGet(scr, 'availLeft', () => 0);
- defGet(scr, 'availTop', () => 0);
- }
- if (s.dpr) def(w, 'devicePixelRatio', s.dpr);
- if (s.width) {
- def(w, 'outerWidth', s.width);
- def(w, 'outerHeight', s.height || 900);
- def(w, 'screenX', 0);
- def(w, 'screenY', 0);
- }
- // NOTE: innerWidth/innerHeight are intentionally left untouched, because the
- // webview is CSS-sized to the device viewport, so the real values already
- // match the spoofed screen. Overriding them here caused self-recursion.
- } catch (e) {}
-
- /* ---------- timezone ---------- */
- try {
- const tz = cfg.timezone;
- if (tz) {
- const dtf = new Intl.DateTimeFormat('en-US', {
- timeZone: tz, hour12: false,
- year: 'numeric', month: '2-digit', day: '2-digit',
- hour: '2-digit', minute: '2-digit', second: '2-digit'
- });
-
- const offsetFor = (date) => {
- const parts = dtf.formatToParts(date);
- const m = {};
- for (const p of parts) m[p.type] = p.value;
- const asUTC = Date.UTC(+m.year, +m.month - 1, +m.day, +m.hour % 24, +m.minute, +m.second);
- return Math.round((date.getTime() - asUTC) / 60000);
- };
-
- const origOffset = Date.prototype.getTimezoneOffset;
- Date.prototype.getTimezoneOffset = function () {
- try { return -offsetFor(new Date(this.getTime())); }
- catch (e) { return origOffset.call(this); }
- };
-
- const OrigDTF = Intl.DateTimeFormat;
- const Wrapped = function (locale, opts) {
- const o = opts ? Object.assign({}, opts) : {};
- if (!o.timeZone) o.timeZone = tz;
- return new OrigDTF(locale || cfg.language, o);
- };
- Wrapped.prototype = OrigDTF.prototype;
- Wrapped.supportedLocalesOf = OrigDTF.supportedLocalesOf.bind(OrigDTF);
- try { Intl.DateTimeFormat = Wrapped; } catch (e) {}
-
- try {
- const origResolved = OrigDTF.prototype.resolvedOptions;
- OrigDTF.prototype.resolvedOptions = function () {
- const r = origResolved.call(this);
- try { r.timeZone = tz; } catch (e) {}
- return r;
- };
- } catch (e) {}
- }
- } catch (e) {}
-
- /* ---------- WebGL ---------- */
- if (cfg.webgl) {
- const patchGL = (proto) => {
- if (!proto) return;
- try {
- const orig = proto.getParameter;
- proto.getParameter = function (p) {
- try {
- if (p === 37445 || p === 7936) return cfg.webgl.vendor;
- if (p === 37446 || p === 7937) return cfg.webgl.renderer;
- } catch (e) {}
- return orig.call(this, p);
- };
- } catch (e) {}
- try {
- const origExt = proto.getSupportedExtensions;
- proto.getSupportedExtensions = function () {
- const list = origExt.call(this) || [];
- for (const e of ['WEBGL_debug_renderer_info', 'EXT_texture_filter_anisotropic']) {
- if (list.indexOf(e) === -1) list.push(e);
- }
- return list;
- };
- } catch (e) {}
- };
- patchGL(w.WebGLRenderingContext && w.WebGLRenderingContext.prototype);
- patchGL(w.WebGL2RenderingContext && w.WebGL2RenderingContext.prototype);
- }
-
- /* ---------- canvas noise (stable per canvas size + seed) ---------- */
- try {
- const Ctx = w.CanvasRenderingContext2D;
- const origGetImageData = Ctx.prototype.getImageData;
-
- const perturb = (data, seedBase) => {
- let s = seedBase >>> 0;
- const step = 4 * 251;
- for (let i = 0; i < data.length; i += step) {
- s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
- const delta = (s & 1) ? 1 : -1;
- const v = data[i] + delta;
- data[i] = v < 0 ? 0 : (v > 255 ? 255 : v);
- }
- };
-
- Ctx.prototype.getImageData = function (x, y, w2, h2) {
- const out = origGetImageData.call(this, x, y, w2, h2);
- try {
- if (w2 > 4 && h2 > 4) {
- perturb(out.data, (cfg.canvasSeed ^ Math.imul(w2, 73856093) ^ Math.imul(h2, 19349663)) >>> 0);
- }
- } catch (e) {}
- return out;
- };
-
- const noisify = (canvas) => {
- try {
- const c2 = document.createElement('canvas');
- c2.width = canvas.width;
- c2.height = canvas.height;
- const ctx = c2.getContext('2d');
- if (!ctx) return canvas;
- ctx.drawImage(canvas, 0, 0);
- const img = origGetImageData.call(ctx, 0, 0, c2.width, c2.height);
- perturb(img.data, (cfg.canvasSeed ^ Math.imul(c2.width, 83492791)) >>> 0);
- ctx.putImageData(img, 0, 0);
- return c2;
- } catch (e) { return canvas; }
- };
-
- const origToDataURL = w.HTMLCanvasElement.prototype.toDataURL;
- w.HTMLCanvasElement.prototype.toDataURL = function () {
- try {
- if (this.width > 4 && this.height > 4) {
- return origToDataURL.apply(noisify(this), arguments);
- }
- } catch (e) {}
- return origToDataURL.apply(this, arguments);
- };
-
- const origToBlob = w.HTMLCanvasElement.prototype.toBlob;
- w.HTMLCanvasElement.prototype.toBlob = function () {
- try {
- if (this.width > 4 && this.height > 4) {
- return origToBlob.apply(noisify(this), arguments);
- }
- } catch (e) {}
- return origToBlob.apply(this, arguments);
- };
- } catch (e) {}
-
- /* ---------- audio noise ---------- */
- try {
- const A = w.AnalyserNode;
- if (A) {
- const gffd = A.prototype.getFloatFrequencyData;
- A.prototype.getFloatFrequencyData = function (arr) {
- gffd.call(this, arr);
- try {
- let s = cfg.audioSeed >>> 0;
- for (let i = 0; i < arr.length; i += 97) {
- s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
- arr[i] = arr[i] + ((s / 4294967296) - 0.5) * 0.0002;
- }
- } catch (e) {}
- };
- const gbfd = A.prototype.getByteFrequencyData;
- A.prototype.getByteFrequencyData = function (arr) {
- gbfd.call(this, arr);
- try {
- for (let i = 0; i < arr.length; i += 211) {
- if (arr[i] > 0) arr[i] = Math.max(0, Math.min(255, arr[i] + ((i % 3) - 1)));
- }
- } catch (e) {}
- };
- }
- } catch (e) {}
-
- /* ---------- chrome object ---------- */
- try {
- if (cfg.hasChromeObject === false) {
- try { Object.defineProperty(w, 'chrome', { get: () => undefined, configurable: true }); } catch (e) {
- try { delete w.chrome; } catch (e2) {}
- }
- } else {
- if (!w.chrome) w.chrome = {};
- const ch = w.chrome;
- if (!ch.runtime) ch.runtime = {};
- if (!ch.runtime.id) ch.runtime.id = undefined;
- ch.loadTimes = () => ({
- requestTime: Date.now() / 1000 - 0.05,
- startLoadTime: Date.now() / 1000 - 0.04,
- commitLoadTime: Date.now() / 1000 - 0.02,
- finishDocumentLoadTime: Date.now() / 1000 - 0.01,
- finishLoadTime: Date.now() / 1000,
- firstPaintTime: Date.now() / 1000 - 0.015,
- firstPaintAfterLoadTime: 0,
- navigationType: 'Other',
- wasFetchedViaSpdy: true,
- wasNpnNegotiated: true,
- npnNegotiatedProtocol: 'h2',
- wasAlternateProtocolAvailable: false,
- connectionInfo: 'h2'
- });
- ch.csi = () => ({
- onloadT: Date.now(), startE: Date.now() - 120, pageT: 120,
- tran: 15, navigationStart: Date.now() - 120
- });
- if (!ch.app) ch.app = { isInstalled: false, InstallState: { DISABLED: 'disabled' }, RunningState: { RUNNING: 'running' }, getDetails: () => null, getIsInstalled: () => false };
-
- /* ---------- chrome.webstore shim (real install via Fathi) ---------- */
- try {
- if (!ch.webstore) {
- ch.webstore = {
- install: function (url, onSuccess, onFailure) {
- try {
- const bridge = w.__fathiBridge;
- const p = bridge && bridge.installExtension
- ? bridge.installExtension(String(url))
- : Promise.reject(new Error('unsupported'));
- p.then(() => onSuccess && onSuccess(), (e) => onFailure && onFailure(String(e && e.message || e)));
- } catch (e) { onFailure && onFailure(String(e)); }
- }
- };
- }
- } catch (e) {}
- }
- } catch (e) {}
-
- /* ---------- touch + mobile media (consistent with the device preset) ---------- */
- try {
- const mobile = !!(cfg.device && cfg.device.mobile);
- if (mobile) {
- def(nav, 'maxTouchPoints', cfg.device.touch || 5);
- try { if (!('ontouchstart' in w)) def(w, 'ontouchstart', null); } catch (e) {}
- try {
- const origMM = w.matchMedia.bind(w);
- w.matchMedia = function (q) {
- const query = String(q || '');
- let res = origMM(query);
- try {
- if (/pointer:\s*coarse/.test(query) || /any-pointer:\s*coarse/.test(query)) {
- return { matches: true, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
- }
- if (/hover:\s*none/.test(query) || /any-hover:\s*none/.test(query)) {
- return { matches: true, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
- }
- if (/pointer:\s*fine/.test(query) || /hover:\s*hover/.test(query)) {
- return { matches: false, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
- }
- } catch (e) {}
- return res;
- };
- } catch (e) {}
- }
-
- if (nav.mediaDevices && nav.mediaDevices.enumerateDevices) {
- const fake = mobile
- ? [
- { deviceId: 'default', kind: 'audioinput', label: '' },
- { deviceId: 'default', kind: 'audiooutput', label: '' },
- { deviceId: 'cam0', kind: 'videoinput', label: '' }
- ]
- : [
- { deviceId: 'default', kind: 'audioinput', label: '' },
- { deviceId: 'default', kind: 'audiooutput', label: '' },
- { deviceId: 'cam0', kind: 'videoinput', label: '' }
- ];
- nav.mediaDevices.enumerateDevices = () => Promise.resolve(fake.map((d) => ({ ...d, groupId: 'fathi' })));
- if (!nav.mediaDevices.getDisplayMedia) {
- nav.mediaDevices.getDisplayMedia = () => Promise.reject(new Error('Not allowed'));
- }
- }
-
- if (w.screen && w.screen.orientation) {
- const portrait = !cfg.device || cfg.device.height >= cfg.device.width;
- def(w.screen.orientation, 'type', portrait ? 'portrait-primary' : 'landscape-primary');
- def(w.screen.orientation, 'angle', 0);
- }
- } catch (e) {}
-
- /* ---------- storage quota (device-class consistent) ---------- */
- try {
- if (nav.storage && nav.storage.estimate) {
- const mem = cfg.deviceMemory || 8;
- const quota = (mem >= 16 ? 240 : mem >= 8 ? 120 : 60) * 1024 * 1024 * 1024;
- nav.storage.estimate = () => Promise.resolve({
- quota: Math.round(quota * (0.82 + ((cfg.canvasSeed % 100) / 100) * 0.12)),
- usage: 1024 * 1024 * (4 + (cfg.canvasSeed % 90))
- });
- }
- } catch (e) {}
-
- /* ---------- battery ---------- */
- try {
- if (nav.getBattery) {
- const level = 0.35 + ((cfg.audioSeed % 60) / 100);
- nav.getBattery = () => Promise.resolve({
- charging: level > 0.8,
- chargingTime: level > 0.8 ? 0 : Infinity,
- dischargingTime: level > 0.8 ? Infinity : Math.round(level * 8 * 3600),
- level: Math.min(0.99, level),
- addEventListener() {}, removeEventListener() {}
- });
- }
- } catch (e) {}
-
- /* ---------- speech synthesis voices ---------- */
- try {
- if (w.speechSynthesis && w.speechSynthesis.getVoices) {
- const lang = (cfg.language || 'en-US').split('-')[0];
- w.speechSynthesis.getVoices = () => ([
- { name: 'Microsoft David - English (United States)', lang: 'en-US', localService: true, default: lang === 'en', voiceURI: 'Microsoft David' },
- { name: 'Microsoft Zira - English (United States)', lang: 'en-US', localService: true, default: false, voiceURI: 'Microsoft Zira' },
- { name: 'Google US English', lang: 'en-US', localService: false, default: false, voiceURI: 'Google US English' }
- ]);
- }
- } catch (e) {}
-
- /* ---------- WebRTC: never leak a local/public IP outside the proxy ---------- */
- try {
- const PC = w.RTCPeerConnection || w.webkitRTCPeerConnection;
- if (PC) {
- const isPrivate = (s) =>
- /(^|\s)(10\.|127\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|fe80:|::1)/i.test(String(s));
- const cleanSdp = (sdp) => String(sdp || '').split('\r\n')
- .filter((line) => !(/^a=candidate:/.test(line) && isPrivate(line)))
- .join('\r\n');
- const origSLD = PC.prototype.setLocalDescription;
- PC.prototype.setLocalDescription = function (desc) {
- if (desc && typeof desc.sdp === 'string') {
- try { desc = { type: desc.type, sdp: cleanSdp(desc.sdp) }; } catch (e) {}
- }
- return origSLD.call(this, desc);
- };
- const origAdd = PC.prototype.addIceCandidate;
- PC.prototype.addIceCandidate = function (cand) {
- try {
- if (cand && typeof cand.candidate === 'string' && isPrivate(cand.candidate)) return Promise.resolve();
- } catch (e) {}
- return origAdd.call(this, cand);
- };
- }
- } catch (e) {}
-
-
- /* ---------- notifications / permissions ---------- */
- try {
- const N = w.Notification;
- if (N) def(N, 'permission', 'default');
- if (nav.permissions && nav.permissions.query) {
- const origQuery = nav.permissions.query.bind(nav.permissions);
- nav.permissions.query = function (desc) {
- try {
- if (desc && (desc.name === 'notifications' || desc.name === 'geolocation' ||
- desc.name === 'camera' || desc.name === 'microphone')) {
- return Promise.resolve({ state: 'prompt', onchange: null });
- }
- } catch (e) {}
- return origQuery(desc);
- };
- }
- } catch (e) {}
-}
-
-/* ----------------------------------------------------------- bootstrap */
-
-const fpArg = process.argv.find((a) => a.startsWith('--fathi-fp='));
+const { fathiSpoof } = require('../shared/spoof');
+const fpArg = process.argv.find((arg) => arg.startsWith('--fathi-fp='));
const fpId = fpArg ? fpArg.slice('--fathi-fp='.length) : '';
-
let cfg = null;
-try {
- cfg = JSON.parse(ipcRenderer.sendSync('fathi:fp:sync', fpId) || 'null');
-} catch (e) { cfg = null; }
-
-const isTopFrame = (() => {
- try { return window.top === window; } catch (e) { return false; }
-})();
-
+try { cfg = JSON.parse(ipcRenderer.sendSync('fathi:fp:sync', fpId) || 'null'); } catch {}
if (cfg && cfg.enabled !== false) {
try {
- const src = `(${fathiSpoof.toString()})(${JSON.stringify(cfg)})`;
- webFrame.executeJavaScript(src);
- } catch (e) {
- console.error('[fathi] spoof inject failed', e);
- }
+ if (contextBridge.executeInMainWorld) contextBridge.executeInMainWorld({ func: fathiSpoof, args: [cfg] });
+ else webFrame.executeJavaScript(`(${fathiSpoof.toString()})(${JSON.stringify(cfg)})`).catch(() => {});
+ } catch (error) { console.error('[fathi] identity injection failed', error); }
}
-
-/* ------------------------------------------------------- bridge (top frame) */
-
-if (isTopFrame) {
- // Available on every page: lets the chrome.webstore shim reach the main process.
- try {
- contextBridge.exposeInMainWorld('__fathiBridge', {
- installExtension: (url) => ipcRenderer.invoke('fathi:ext:install', { input: url })
- });
- } catch (e) {}
-
- // Internal pages only.
- if (location.protocol === 'fathi:') {
- try {
- contextBridge.exposeInMainWorld('fathi', {
- fpId,
- fingerprint: () => ipcRenderer.invoke('fathi:fp:current', fpId),
- wallpaper: () => ipcRenderer.invoke('fathi:wallpaper:fetch'),
- navigate: (url) => ipcRenderer.invoke('fathi:newtab:navigate', url),
- newTab: () => ipcRenderer.invoke('fathi:newtab:new'),
- rotate: () => ipcRenderer.invoke('fathi:newtab:rotate'),
- focusOmnibox: () => ipcRenderer.invoke('fathi:newtab:focus'),
- proxyStatus: () => ipcRenderer.invoke('fathi:page:status'),
- settings: () => ipcRenderer.invoke('fathi:settings:get'),
- openExternal: (url) => ipcRenderer.invoke('fathi:open-external', url),
- installExtension: (url) => ipcRenderer.invoke('fathi:ext:install', { input: url }),
- openGuide: () => ipcRenderer.invoke('fathi:newtab:guide'),
- openShortcuts: () => ipcRenderer.invoke('fathi:newtab:shortcuts')
- });
- } catch (e) {}
- }
+const storePage = location.protocol === 'https:' && (location.hostname === 'chromewebstore.google.com' || (location.hostname === 'chrome.google.com' && location.pathname.startsWith('/webstore')));
+if (process.isMainFrame && storePage) {
+ contextBridge.exposeInMainWorld('__fathiBridge', { installExtension: (url) => ipcRenderer.invoke('fathi:ext:install', { input: url }) });
+}
+if (process.isMainFrame && location.protocol === 'fathi:') {
+ contextBridge.exposeInMainWorld('fathi', {
+ fpId,
+ fingerprint: () => ipcRenderer.invoke('fathi:fp:current', fpId),
+ wallpaper: () => ipcRenderer.invoke('fathi:wallpaper:fetch'),
+ navigate: (url) => ipcRenderer.invoke('fathi:newtab:navigate', url),
+ newTab: () => ipcRenderer.invoke('fathi:newtab:new'),
+ rotate: () => ipcRenderer.invoke('fathi:newtab:rotate'),
+ focusOmnibox: () => ipcRenderer.invoke('fathi:newtab:focus'),
+ proxyStatus: () => ipcRenderer.invoke('fathi:page:status'),
+ settings: () => ipcRenderer.invoke('fathi:settings:get'),
+ openExternal: (url) => ipcRenderer.invoke('fathi:open-external', url),
+ installExtension: (url) => ipcRenderer.invoke('fathi:ext:install', { input: url }),
+ openGuide: () => ipcRenderer.invoke('fathi:newtab:guide'),
+ openShortcuts: () => ipcRenderer.invoke('fathi:newtab:shortcuts')
+ });
}
diff --git a/src/preload/ui.js b/src/preload/ui.js
index 8dacdb8..9d3f8e9 100644
--- a/src/preload/ui.js
+++ b/src/preload/ui.js
@@ -46,6 +46,7 @@ contextBridge.exposeInMainWorld('api', {
},
tab: {
+ ready: (wcId) => ipcRenderer.invoke('fathi:tab:ready', wcId),
prepare: (opts) => ipcRenderer.invoke('fathi:tab:prepare', opts || {}),
destroy: (partition) => ipcRenderer.invoke('fathi:tab:destroy', { partition }),
proxyStatus: (partition) => ipcRenderer.invoke('fathi:tab:proxy-status', { partition })
@@ -56,6 +57,8 @@ contextBridge.exposeInMainWorld('api', {
},
proxy: {
+ fetchBurpCa: () => ipcRenderer.invoke('fathi:proxy:fetch-ca'),
+ importCa: () => ipcRenderer.invoke('fathi:proxy:import-ca'),
get: () => ipcRenderer.invoke('fathi:proxy:get'),
set: (patch) => ipcRenderer.invoke('fathi:proxy:set', patch),
test: (entry, url) => ipcRenderer.invoke('fathi:proxy:test', { entry, url })
diff --git a/src/renderer/app.js b/src/renderer/app.js
index e42ed49..4971274 100644
--- a/src/renderer/app.js
+++ b/src/renderer/app.js
@@ -263,7 +263,6 @@ function makeTabElement(tab) {
async function createTab(opts = {}) {
const prep = await window.api.tab.prepare({
- ...(opts.fp ? { fp: opts.fp } : {}),
deviceId: opts.deviceId || (state.settings && state.settings.defaultDevice) || 'desktop',
landscape: !!opts.landscape
});
@@ -283,8 +282,9 @@ async function createTab(opts = {}) {
// The src attribute must be set *after* the element is attached, otherwise
// Chromium creates the guest but never starts a navigation.
- wv.setAttribute('src', startUrl);
- try { wv.loadURL(startUrl); } catch { /* queued until dom-ready */ }
+ // Initialize the guest on a local blank document. No target request or page
+ // script runs until native identity and worker hooks are ready.
+ wv.setAttribute('src', 'about:blank');
const tab = {
id,
@@ -293,6 +293,8 @@ async function createTab(opts = {}) {
fpId: prep.fpId,
proxy: prep.proxy,
wv,
+ startUrl,
+ identityReady: false,
url: opts.url || startUrl,
title: t('tab.new'),
favicon: null,
@@ -314,7 +316,7 @@ async function createTab(opts = {}) {
// first-attach race), kick it once more.
setTimeout(() => {
try {
- if (!wv.getURL()) wv.loadURL(startUrl);
+ if (!wv.getURL()) wv.loadURL('about:blank');
} catch {}
}, 1200);
@@ -415,10 +417,17 @@ function wireWebview(tab) {
toast(t('toast.crashed'), 'err');
});
- wv.addEventListener('dom-ready', () => {
- wv.classList.add('ready');
+ wv.addEventListener('dom-ready', async () => {
try { wv.setZoomFactor(1); } catch {}
try { tab.wcId = wv.getWebContentsId(); } catch {}
+ if (!tab.identityReady) {
+ const initialized = await window.api.tab.ready(tab.wcId);
+ if (!initialized.ok) { toast(initialized.error, 'err'); return; }
+ tab.identityReady = true;
+ try { await wv.loadURL(tab.startUrl); } catch {}
+ return;
+ }
+ wv.classList.add('ready');
if (state.activeId === tab.id) applyTabLayout(tab);
updateNavButtons();
});
@@ -501,7 +510,7 @@ async function closeTab(id, opts = {}) {
clearResearchForTab(tab.wcId);
if (flow.detail?.wcId === tab.wcId) flowBack();
try { tab.el.remove(); } catch {}
- window.api.tab.destroy(tab.partition);
+ await window.api.tab.destroy(tab.partition);
state.tabs.splice(idx, 1);
@@ -548,6 +557,7 @@ function navigate(url) {
const target = normalizeInput(url);
if (!target) return;
tab.url = target;
+ if (!tab.identityReady) { tab.startUrl = target; omnibox.blur(); return; }
try { tab.wv.loadURL(target); } catch { tab.wv.setAttribute('src', target); }
omnibox.blur();
}
@@ -2415,6 +2425,7 @@ function renderSection(section) {
${esc(t('fp.title'))}
${esc(t('fp.hint'))}
+
${esc(t('fp.nextIdentity'))}
${esc(t('fp.enabledSub'))}
@@ -2509,6 +2520,7 @@ function renderSection(section) {
${esc(t('proxy.trustHint'))}
+
${esc(t(p.burpCaPem ? 'proxy.caImported' : 'proxy.caRequired'))}
${esc(t('proxy.interceptHint'))}
@@ -2589,17 +2601,33 @@ function renderSection(section) {
if (res.ok) { state.settings.proxy = res.config; toast(t('toast.saved'), 'ok'); }
else toast(res.error, 'err');
});
+ $('#px-import-ca').addEventListener('click', async () => {
+ const result = await window.api.proxy.importCa();
+ if (!result.ok) { toast(result.error, 'err'); return; }
+ if (!result.canceled) { state.settings = (await window.api.settings.get()).settings; renderSection('proxy'); }
+ });
+ $('#px-fetch-ca').addEventListener('click', async (event) => {
+ event.currentTarget.disabled = true;
+ const result = await window.api.proxy.fetchBurpCa();
+ state.settings = (await window.api.settings.get()).settings;
+ renderSection('proxy');
+ toast(result.ok ? t('proxy.caReady') : result.error, result.ok ? 'ok' : 'err');
+ });
- $('#px-burp').addEventListener('click', async () => {
+ $('#px-burp').addEventListener('click', async (event) => {
+ event.currentTarget.disabled = true;
const res = await window.api.proxy.set({
enabled: true,
mode: 'single',
pool: ['http://127.0.0.1:8080'],
bypass: '
',
- trustBurpCert: true
+ trustBurpCert: false
});
- if (!res.ok) return toast(res.error, 'err');
- state.settings.proxy = res.config;
+ if (!res.ok) { event.currentTarget.disabled = false; return toast(res.error, 'err'); }
+ const certificate = await window.api.proxy.fetchBurpCa();
+ if (!certificate.ok) toast(certificate.error, 'err');
+ else toast(t('proxy.caReady'), 'ok');
+ state.settings = (await window.api.settings.get()).settings;
updateChips();
renderSection('proxy');
toast(t('toast.applied', { n: res.applied }), 'ok');
diff --git a/src/renderer/i18n.js b/src/renderer/i18n.js
index 161b68b..7fcde60 100644
--- a/src/renderer/i18n.js
+++ b/src/renderer/i18n.js
@@ -6,6 +6,12 @@
(function () {
const DICT = {
en: {
+ 'proxy.importCa': 'Import Burp public CA',
+ 'proxy.fetchCa': 'Retrieve local Burp CA',
+ 'proxy.caReady': 'Burp public CA verified and trusted inside Fathi.',
+ 'proxy.caImported': 'Public CA imported. Only chains signed by this CA can use the proxy trust exception.',
+ 'proxy.caRequired': 'Export Burp’s public CA and import it here. Certificate names alone are never trusted.',
+ 'fp.nextIdentity': 'Changes apply to new tabs and New identity. Existing profiles stay stable until reset.',
'intercept.actions': 'Request actions',
'about.principle.inspect': 'Inspect with intent',
'about.principle.inspectHint': 'Understand requests, responses and the decisions between them.',
@@ -267,8 +273,8 @@
'proxy.burp': 'Burp Suite',
'proxy.burpHint': 'Routes every tab through Burp at 127.0.0.1:8080 and trusts its PortSwigger CA. Keep Burp’s own interception off while using Fathi’s interceptor.',
'proxy.burpApply': 'Use Burp',
- 'proxy.trust': 'Trust PortSwigger certificate',
- 'proxy.trustHint': 'Accepts HTTPS interception certificates issued by Burp’s CA only.',
+ 'proxy.trust': 'Trust the imported Burp CA',
+ 'proxy.trustHint': 'Requires an imported public CA and an enabled proxy. Names alone do not establish trust.',
'proxy.intercept': 'Request interception',
'proxy.interceptHint': 'Pause, edit, forward or drop requests inside the browser.',
'proxy.openIntercept': 'Open interceptor',
@@ -550,6 +556,12 @@
},
ar: {
+ 'proxy.importCa': 'استيراد شهادة CA العامة لبارب',
+ 'proxy.fetchCa': 'جلب شهادة Burp المحلي',
+ 'proxy.caReady': 'تم التحقق من شهادة Burp العامة وتوثيقها داخل فتحي.',
+ 'proxy.caImported': 'تم استيراد الشهادة العامة. استثناء الثقة مقيّد بالسلاسل الموقعة منها فقط.',
+ 'proxy.caRequired': 'صدّر شهادة CA العامة من Burp واستوردها هنا. لا تُوثق الشهادات بالاسم وحده.',
+ 'fp.nextIdentity': 'تُطبق التغييرات على التبويبات الجديدة وإعادة الهوية. تبقى الهوية الحالية ثابتة حتى إعادة التهيئة.',
'intercept.actions': 'إجراءات الطلب',
'about.principle.inspect': 'تحليل هادف',
'about.principle.inspectHint': 'افهم الطلبات والاستجابات والتفاصيل التي تربط بينها.',
@@ -811,8 +823,8 @@
'proxy.burp': 'Burp Suite',
'proxy.burpHint': 'يوجّه كل التبويبات عبر Burp على 127.0.0.1:8080 ويثق بشهادة PortSwigger. أطفئ الاعتراض داخل Burp إذا استخدمت اعتراض فتحي.',
'proxy.burpApply': 'استخدام Burp',
- 'proxy.trust': 'الثقة بشهادة PortSwigger',
- 'proxy.trustHint': 'يقبل شهادات HTTPS الصادرة من شهادة Burp فقط.',
+ 'proxy.trust': 'الثقة بشهادة CA المستوردة لبارب',
+ 'proxy.trustHint': 'يتطلب شهادة عامة مستوردة وبروكسي مفعلاً. الاسم وحده لا يكفي للثقة.',
'proxy.intercept': 'اعتراض الطلبات',
'proxy.interceptHint': 'أوقف وعدّل ومرّر أو أسقط الطلبات داخل المتصفح.',
'proxy.openIntercept': 'فتح الاعتراض',
diff --git a/src/shared/spoof.js b/src/shared/spoof.js
new file mode 100644
index 0000000..ed3a906
--- /dev/null
+++ b/src/shared/spoof.js
@@ -0,0 +1,524 @@
+'use strict';
+/**
+ * Fathi page preload.
+ *
+ * Runs in every tab (and sub-frame). Two jobs:
+ * 1. inject the per-tab fingerprint into the page's main world, before any
+ * page script executes;
+ * 2. expose a small bridge (fathi:// internal pages only) for the new tab.
+ */
+
+/* ---------------------------------------------------------- fingerprint */
+
+function fathiSpoof(cfg) {
+ 'use strict';
+ const w = typeof window === 'object' ? window : globalThis;
+ const nav = w.navigator;
+ if (!nav) return;
+
+ const def = (obj, prop, value) => {
+ if (obj === nav) obj = Object.getPrototypeOf(nav);
+ try {
+ Object.defineProperty(obj, prop, { get: () => value, configurable: true, enumerable: true });
+ } catch (e) {}
+ };
+ const defGet = (obj, prop, fn) => {
+ try { Object.defineProperty(obj, prop, { get: fn, configurable: true, enumerable: true }); } catch (e) {}
+ };
+
+
+ /* ---------- navigator identity ---------- */
+ def(nav, 'userAgent', cfg.ua);
+ def(nav, 'appVersion', cfg.appVersion);
+ def(nav, 'appName', cfg.appName || 'Netscape');
+ def(nav, 'appCodeName', cfg.appCodeName || 'Mozilla');
+ def(nav, 'platform', cfg.platform);
+ def(nav, 'vendor', cfg.vendor ?? 'Google Inc.');
+ def(nav, 'vendorSub', cfg.vendorSub || '');
+ def(nav, 'productSub', cfg.productSub || '20030107');
+ def(nav, 'language', cfg.language);
+ def(nav, 'languages', Object.freeze((cfg.languages || [cfg.language]).slice()));
+ def(nav, 'hardwareConcurrency', cfg.hardwareConcurrency);
+ def(nav, 'deviceMemory', cfg.deviceMemory);
+ def(nav, 'maxTouchPoints', cfg.maxTouchPoints || 0);
+ def(nav, 'webdriver', false);
+ def(nav, 'doNotTrack', null);
+ def(nav, 'cookieEnabled', true);
+ def(nav, 'onLine', true);
+ def(nav, 'pdfViewerEnabled', true);
+ if (cfg.oscpu) def(nav, 'oscpu', cfg.oscpu);
+
+ /* ---------- plugins / mimeTypes ---------- */
+ // Preserve native PluginArray and MimeTypeArray behavior rather than exposing
+ // recognizable plain-array shims.
+
+ /* ---------- client hints ---------- */
+ try {
+ if (cfg.clientHints === false) {
+ // Safari (iOS) never exposes User-Agent Client Hints.
+ try {
+ Object.defineProperty(Object.getPrototypeOf(nav), 'userAgentData', {
+ get: () => undefined, configurable: true, enumerable: false
+ });
+ } catch (e) {}
+ } else {
+ const brands = cfg.uaBrands || [];
+ const fullList = cfg.uaFullVersionList || [];
+ const isMobile = !!(cfg.device && cfg.device.mobile);
+ const highEntropy = (hints) => {
+ const out = {
+ architecture: cfg.architecture,
+ bitness: cfg.bitness,
+ brands,
+ fullVersionList: fullList,
+ mobile: isMobile,
+ model: cfg.model || '',
+ platform: cfg.uaDataPlatform,
+ platformVersion: cfg.platformVersion,
+ uaFullVersion: cfg.uaFullVersion,
+ wow64: cfg.wow64
+ };
+ if (!hints || !hints.length) return out;
+ const filtered = { brands, mobile: isMobile, platform: cfg.uaDataPlatform };
+ for (const h of hints) if (Object.prototype.hasOwnProperty.call(out, h)) filtered[h] = out[h];
+ return filtered;
+ };
+ const uaData = {
+ brands,
+ mobile: isMobile,
+ platform: cfg.uaDataPlatform,
+ getHighEntropyValues: (hints) => Promise.resolve(highEntropy(hints)),
+ toJSON: () => ({ brands, mobile: isMobile, platform: cfg.uaDataPlatform })
+ };
+ def(nav, 'userAgentData', uaData);
+ }
+ } catch (e) {}
+
+ /* ---------- connection ---------- */
+ try {
+ const c = cfg.connection || {};
+ def(nav, 'connection', {
+ effectiveType: c.effectiveType || '4g',
+ rtt: c.rtt || 50,
+ downlink: c.downlink || 10,
+ saveData: false,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {}
+ });
+ } catch (e) {}
+
+ /* ---------- screen ---------- */
+ if (typeof window === 'object') try {
+ const s = cfg.screen || {};
+ const scr = w.screen;
+ if (scr) {
+ const keys = ['width', 'height', 'availWidth', 'availHeight', 'colorDepth', 'pixelDepth'];
+ for (const k of keys) if (s[k] != null) def(scr, k, s[k]);
+ defGet(scr, 'availLeft', () => 0);
+ defGet(scr, 'availTop', () => 0);
+ }
+ if (s.dpr) def(w, 'devicePixelRatio', s.dpr);
+ if (s.width) {
+ def(w, 'outerWidth', s.width);
+ def(w, 'outerHeight', s.height || 900);
+ def(w, 'screenX', 0);
+ def(w, 'screenY', 0);
+ }
+ // NOTE: innerWidth/innerHeight are intentionally left untouched, because the
+ // webview is CSS-sized to the device viewport, so the real values already
+ // match the spoofed screen. Overriding them here caused self-recursion.
+ } catch (e) {}
+
+ /* ---------- timezone ---------- */
+ try {
+ const tz = cfg.timezone;
+ if (tz) {
+ const dtf = new Intl.DateTimeFormat('en-US', {
+ timeZone: tz, hour12: false,
+ year: 'numeric', month: '2-digit', day: '2-digit',
+ hour: '2-digit', minute: '2-digit', second: '2-digit'
+ });
+
+ const offsetFor = (date) => {
+ const parts = dtf.formatToParts(date);
+ const m = {};
+ for (const p of parts) m[p.type] = p.value;
+ const asUTC = Date.UTC(+m.year, +m.month - 1, +m.day, +m.hour % 24, +m.minute, +m.second);
+ return Math.round((date.getTime() - asUTC) / 60000);
+ };
+
+ const origOffset = Date.prototype.getTimezoneOffset;
+ Date.prototype.getTimezoneOffset = function () {
+ try { return offsetFor(new Date(this.getTime())); }
+ catch (e) { return origOffset.call(this); }
+ };
+
+ const OrigDTF = Intl.DateTimeFormat;
+ const Wrapped = function (locale, opts) {
+ const o = opts ? Object.assign({}, opts) : {};
+ if (!o.timeZone) o.timeZone = tz;
+ return new OrigDTF(locale || cfg.language, o);
+ };
+ Wrapped.prototype = OrigDTF.prototype;
+ Wrapped.supportedLocalesOf = OrigDTF.supportedLocalesOf.bind(OrigDTF);
+ try { Intl.DateTimeFormat = Wrapped; } catch (e) {}
+
+ // Do not rewrite explicit UTC or another caller-selected time zone.
+ }
+ } catch (e) {}
+
+ /* ---------- WebGL ---------- */
+ if (cfg.webgl && cfg.spoofWebgl !== false) {
+ const patchGL = (proto) => {
+ if (!proto) return;
+ try {
+ const orig = proto.getParameter;
+ proto.getParameter = function (p) {
+ try {
+ if (p === 37445) return cfg.webgl.vendor;
+ if (p === 37446) return cfg.webgl.renderer;
+ } catch (e) {}
+ return orig.call(this, p);
+ };
+ } catch (e) {}
+ try {
+ const origExt = proto.getSupportedExtensions;
+ proto.getSupportedExtensions = function () {
+ const list = origExt.call(this) || [];
+ return list;
+ };
+ } catch (e) {}
+ };
+ patchGL(w.WebGLRenderingContext && w.WebGLRenderingContext.prototype);
+ patchGL(w.WebGL2RenderingContext && w.WebGL2RenderingContext.prototype);
+ }
+
+ /* ---------- canvas noise (stable per canvas size + seed) ---------- */
+ const perturb = (data, width, startX = 0, startY = 0) => {
+ const mix = (n) => {
+ let s = n >>> 0;
+ s = Math.imul(s ^ (s >>> 16), 0x45d9f3b) >>> 0;
+ s = Math.imul(s ^ (s >>> 16), 0x45d9f3b) >>> 0;
+ return (s ^ (s >>> 16)) >>> 0;
+ };
+ for (let row = 0; row < data.length / 4 / width; row++) {
+ const y = startY + row;
+ const rowSeed = mix(cfg.canvasSeed ^ Math.imul(y, 19349663));
+ const offset = ((rowSeed % 251 - startX) % 251 + 251) % 251;
+ for (let x = offset; x < width; x += 251) {
+ const i = (row * width + x) * 4;
+ if (data[i + 3] === 0) continue;
+ const delta = (mix(rowSeed ^ Math.imul(startX + x, 73856093)) & 256) ? 1 : -1;
+ const v = data[i] + delta;
+ data[i] = v < 0 ? 0 : (v > 255 ? 255 : v);
+ }
+ }
+ };
+
+ if (cfg.spoofCanvas !== false) try {
+ const Ctx = w.CanvasRenderingContext2D;
+ const origGetImageData = Ctx.prototype.getImageData;
+
+ Ctx.prototype.getImageData = function (x, y, w2, h2) {
+ const out = origGetImageData.call(this, x, y, w2, h2);
+ try {
+ if (w2 > 4 && h2 > 4) {
+ perturb(out.data, out.width, Math.trunc(x), Math.trunc(y));
+ }
+ } catch (e) {}
+ return out;
+ };
+
+ const noisify = (canvas) => {
+ try {
+ const c2 = document.createElement('canvas');
+ c2.width = canvas.width;
+ c2.height = canvas.height;
+ const ctx = c2.getContext('2d');
+ if (!ctx) return canvas;
+ ctx.drawImage(canvas, 0, 0);
+ const img = origGetImageData.call(ctx, 0, 0, c2.width, c2.height);
+ perturb(img.data, c2.width);
+ ctx.putImageData(img, 0, 0);
+ return c2;
+ } catch (e) { return canvas; }
+ };
+
+ const origToDataURL = w.HTMLCanvasElement.prototype.toDataURL;
+ w.HTMLCanvasElement.prototype.toDataURL = function () {
+ try {
+ if (this.width > 4 && this.height > 4) {
+ return origToDataURL.apply(noisify(this), arguments);
+ }
+ } catch (e) {}
+ return origToDataURL.apply(this, arguments);
+ };
+
+ const origToBlob = w.HTMLCanvasElement.prototype.toBlob;
+ w.HTMLCanvasElement.prototype.toBlob = function () {
+ try {
+ if (this.width > 4 && this.height > 4) {
+ return origToBlob.apply(noisify(this), arguments);
+ }
+ } catch (e) {}
+ return origToBlob.apply(this, arguments);
+ };
+ } catch (e) {}
+
+ if (cfg.spoofCanvas !== false && w.OffscreenCanvasRenderingContext2D && w.OffscreenCanvas) try {
+ const proto = w.OffscreenCanvasRenderingContext2D.prototype;
+ const get = proto.getImageData;
+ proto.getImageData = function (x, y, width, height) {
+ const image = get.call(this, x, y, width, height);
+ if (image.width > 4 && image.height > 4) perturb(image.data, image.width, Math.trunc(x), Math.trunc(y));
+ return image;
+ };
+ const convert = w.OffscreenCanvas.prototype.convertToBlob;
+ w.OffscreenCanvas.prototype.convertToBlob = function (options) {
+ if (this.width <= 4 || this.height <= 4) return convert.call(this, options);
+ try {
+ const copy = new w.OffscreenCanvas(this.width, this.height);
+ const context = copy.getContext('2d');
+ context.drawImage(this, 0, 0);
+ const image = get.call(context, 0, 0, copy.width, copy.height);
+ perturb(image.data, image.width); context.putImageData(image, 0, 0);
+ return convert.call(copy, options);
+ } catch { return convert.call(this, options); }
+ };
+ } catch {}
+
+ /* ---------- audio noise ---------- */
+ if (cfg.spoofAudio !== false) try {
+ const A = w.AnalyserNode;
+ if (A) {
+ const gffd = A.prototype.getFloatFrequencyData;
+ A.prototype.getFloatFrequencyData = function (arr) {
+ gffd.call(this, arr);
+ try {
+ let s = cfg.audioSeed >>> 0;
+ for (let i = 0; i < arr.length; i += 97) {
+ s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
+ arr[i] = arr[i] + ((s / 4294967296) - 0.5) * 0.0002;
+ }
+ } catch (e) {}
+ };
+ const gbfd = A.prototype.getByteFrequencyData;
+ A.prototype.getByteFrequencyData = function (arr) {
+ gbfd.call(this, arr);
+ try {
+ for (let i = 0; i < arr.length; i += 211) {
+ if (arr[i] > 0) arr[i] = Math.max(0, Math.min(255, arr[i] + (((cfg.audioSeed ^ Math.imul(i, 31)) >>> 0) % 3 - 1)));
+ }
+ } catch (e) {}
+ };
+ }
+ } catch (e) {}
+
+ if (cfg.spoofAudio !== false && w.AudioBuffer) {
+ const proto = w.AudioBuffer.prototype;
+ const original = proto.getChannelData;
+ const copied = proto.copyFromChannel;
+ const buffers = new WeakMap();
+ const channel = (buffer, index) => {
+ const data = original.call(buffer, index);
+ let channels = buffers.get(buffer);
+ if (!channels) { channels = new Map(); buffers.set(buffer, channels); }
+ let last = channels.get(index);
+ if (!last) { last = new Map(); channels.set(index, last); }
+ for (let i = cfg.audioSeed % 97; i < data.length; i += 101) {
+ if (!Number.isFinite(data[i]) || data[i] === 0 || last.get(i) === data[i]) continue;
+ const mixed = Math.imul(cfg.audioSeed ^ i ^ index, 2654435761) >>> 0;
+ data[i] = Math.fround(data[i] + ((mixed / 4294967296) - 0.5) * 0.0000002);
+ last.set(i, data[i]);
+ }
+ return data;
+ };
+ proto.getChannelData = function (index) { return channel(this, index); };
+ if (copied) proto.copyFromChannel = function (destination, index, start) { channel(this, index); return copied.call(this, destination, index, start); };
+ }
+
+ /* ---------- chrome object ---------- */
+ if (typeof window === 'object') try {
+ if (cfg.hasChromeObject === false) {
+ try { Object.defineProperty(w, 'chrome', { get: () => undefined, configurable: true }); } catch (e) {
+ try { delete w.chrome; } catch (e2) {}
+ }
+ } else {
+ if (!w.chrome) w.chrome = {};
+ const ch = w.chrome;
+ if (!ch.runtime) ch.runtime = {};
+ if (!ch.runtime.id) ch.runtime.id = undefined;
+ ch.loadTimes = () => ({
+ requestTime: Date.now() / 1000 - 0.05,
+ startLoadTime: Date.now() / 1000 - 0.04,
+ commitLoadTime: Date.now() / 1000 - 0.02,
+ finishDocumentLoadTime: Date.now() / 1000 - 0.01,
+ finishLoadTime: Date.now() / 1000,
+ firstPaintTime: Date.now() / 1000 - 0.015,
+ firstPaintAfterLoadTime: 0,
+ navigationType: 'Other',
+ wasFetchedViaSpdy: true,
+ wasNpnNegotiated: true,
+ npnNegotiatedProtocol: 'h2',
+ wasAlternateProtocolAvailable: false,
+ connectionInfo: 'h2'
+ });
+ ch.csi = () => ({
+ onloadT: Date.now(), startE: Date.now() - 120, pageT: 120,
+ tran: 15, navigationStart: Date.now() - 120
+ });
+ if (!ch.app) ch.app = { isInstalled: false, InstallState: { DISABLED: 'disabled' }, RunningState: { RUNNING: 'running' }, getDetails: () => null, getIsInstalled: () => false };
+
+ /* ---------- chrome.webstore shim (real install via Fathi) ---------- */
+ try {
+ if (!ch.webstore) {
+ ch.webstore = {
+ install: function (url, onSuccess, onFailure) {
+ try {
+ const bridge = w.__fathiBridge;
+ const p = bridge && bridge.installExtension
+ ? bridge.installExtension(String(url))
+ : Promise.reject(new Error('unsupported'));
+ p.then(() => onSuccess && onSuccess(), (e) => onFailure && onFailure(String(e && e.message || e)));
+ } catch (e) { onFailure && onFailure(String(e)); }
+ }
+ };
+ }
+ } catch (e) {}
+ }
+ } catch (e) {}
+
+ /* ---------- touch + mobile media (consistent with the device preset) ---------- */
+ try {
+ const mobile = !!(cfg.device && cfg.device.mobile);
+ if (mobile) {
+ def(nav, 'maxTouchPoints', cfg.device.touch || 5);
+ try { if (!('ontouchstart' in w)) def(w, 'ontouchstart', null); } catch (e) {}
+ try {
+ const origMM = w.matchMedia.bind(w);
+ w.matchMedia = function (q) {
+ const query = String(q || '');
+ let res = origMM(query);
+ try {
+ if (/pointer:\s*coarse/.test(query) || /any-pointer:\s*coarse/.test(query)) {
+ return { matches: true, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
+ }
+ if (/hover:\s*none/.test(query) || /any-hover:\s*none/.test(query)) {
+ return { matches: true, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
+ }
+ if (/pointer:\s*fine/.test(query) || /hover:\s*hover/.test(query)) {
+ return { matches: false, media: query, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent() { return false; } };
+ }
+ } catch (e) {}
+ return res;
+ };
+ } catch (e) {}
+ }
+
+ if (nav.mediaDevices && nav.mediaDevices.enumerateDevices) {
+ const fake = mobile
+ ? [
+ { deviceId: 'default', kind: 'audioinput', label: '' },
+ { deviceId: 'default', kind: 'audiooutput', label: '' },
+ { deviceId: 'cam0', kind: 'videoinput', label: '' }
+ ]
+ : [
+ { deviceId: 'default', kind: 'audioinput', label: '' },
+ { deviceId: 'default', kind: 'audiooutput', label: '' },
+ { deviceId: 'cam0', kind: 'videoinput', label: '' }
+ ];
+ nav.mediaDevices.enumerateDevices = () => Promise.resolve(fake.map((d) => ({ ...d, groupId: '' })));
+ if (!nav.mediaDevices.getDisplayMedia) {
+ nav.mediaDevices.getDisplayMedia = () => Promise.reject(new Error('Not allowed'));
+ }
+ }
+
+ if (w.screen && w.screen.orientation) {
+ const portrait = cfg.device?.mobile ? cfg.device.height >= cfg.device.width : cfg.screen.height >= cfg.screen.width;
+ def(w.screen.orientation, 'type', portrait ? 'portrait-primary' : 'landscape-primary');
+ def(w.screen.orientation, 'angle', portrait ? 0 : 90);
+ }
+ } catch (e) {}
+
+ /* ---------- storage quota (device-class consistent) ---------- */
+ try {
+ if (nav.storage && nav.storage.estimate) {
+ const mem = cfg.deviceMemory || 8;
+ const quota = (mem >= 16 ? 240 : mem >= 8 ? 120 : 60) * 1024 * 1024 * 1024;
+ nav.storage.estimate = () => Promise.resolve({
+ quota: Math.round(quota * (0.82 + ((cfg.canvasSeed % 100) / 100) * 0.12)),
+ usage: 1024 * 1024 * (4 + (cfg.canvasSeed % 90))
+ });
+ }
+ } catch (e) {}
+
+ /* ---------- battery ---------- */
+ try {
+ if (nav.getBattery) {
+ const level = 0.35 + ((cfg.audioSeed % 60) / 100);
+ nav.getBattery = () => Promise.resolve({
+ charging: level > 0.8,
+ chargingTime: level > 0.8 ? 0 : Infinity,
+ dischargingTime: level > 0.8 ? Infinity : Math.round(level * 8 * 3600),
+ level: Math.min(0.99, level),
+ addEventListener() {}, removeEventListener() {}
+ });
+ }
+ } catch (e) {}
+
+ /* ---------- speech synthesis voices ---------- */
+ try {
+ if (w.speechSynthesis && w.speechSynthesis.getVoices) {
+ const lang = (cfg.language || 'en-US').split('-')[0];
+ w.speechSynthesis.getVoices = () => [];
+ }
+ } catch (e) {}
+
+ /* ---------- WebRTC: never leak a local/public IP outside the proxy ---------- */
+ try {
+ const PC = w.RTCPeerConnection || w.webkitRTCPeerConnection;
+ if (PC) {
+ const isPrivate = (s) =>
+ /(^|\s)(10\.|127\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.|fe80:|::1)/i.test(String(s));
+ const cleanSdp = (sdp) => String(sdp || '').split('\r\n')
+ .filter((line) => !(/^a=candidate:/.test(line) && isPrivate(line)))
+ .join('\r\n');
+ const origSLD = PC.prototype.setLocalDescription;
+ PC.prototype.setLocalDescription = function (desc) {
+ if (desc && typeof desc.sdp === 'string') {
+ try { desc = { type: desc.type, sdp: cleanSdp(desc.sdp) }; } catch (e) {}
+ }
+ return origSLD.call(this, desc);
+ };
+ const origAdd = PC.prototype.addIceCandidate;
+ PC.prototype.addIceCandidate = function (cand) {
+ try {
+ if (cand && typeof cand.candidate === 'string' && isPrivate(cand.candidate)) return Promise.resolve();
+ } catch (e) {}
+ return origAdd.call(this, cand);
+ };
+ }
+ } catch (e) {}
+
+
+ /* ---------- notifications / permissions ---------- */
+ try {
+ const N = w.Notification;
+ if (N) def(N, 'permission', 'default');
+ if (nav.permissions && nav.permissions.query) {
+ const origQuery = nav.permissions.query.bind(nav.permissions);
+ nav.permissions.query = function (desc) {
+ try {
+ if (desc && (desc.name === 'notifications' || desc.name === 'geolocation' ||
+ desc.name === 'camera' || desc.name === 'microphone')) {
+ return Promise.resolve({ state: 'prompt', onchange: null });
+ }
+ } catch (e) {}
+ return origQuery(desc);
+ };
+ }
+ } catch (e) {}
+}
+
+module.exports = { fathiSpoof };
diff --git a/tools/test-certificate.js b/tools/test-certificate.js
new file mode 100644
index 0000000..391046a
--- /dev/null
+++ b/tools/test-certificate.js
@@ -0,0 +1,54 @@
+'use strict';
+const { test, after } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path');
+const http = require('node:http'); const { spawnSync } = require('node:child_process');
+const { parseCa, verifies } = require('../src/main/certificate-trust');
+const { fetchCa } = require('../src/main/burp-ca');
+const candidates = ['openssl', 'C:/Program Files/Git/usr/bin/openssl.exe'];
+const openssl = candidates.find((file) => spawnSync(file, ['version'], { stdio: 'ignore' }).status === 0);
+let fixture;
+function certificates() {
+ if (fixture) return fixture;
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fathi-ca-test-'));
+ const run = (...args) => { const result = spawnSync(openssl, args, { cwd: dir, stdio: 'pipe', env: { ...process.env, MSYS_NO_PATHCONV: '1' } }); if (result.status !== 0) throw new Error(result.stderr.toString()); };
+ run('req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', 'ca.key', '-out', 'ca.pem', '-days', '2', '-subj', '/CN=Fathi Test CA', '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign');
+ run('req', '-newkey', 'rsa:2048', '-nodes', '-keyout', 'leaf.key', '-out', 'leaf.csr', '-subj', '/CN=target.test');
+ fs.writeFileSync(path.join(dir, 'extensions'), 'subjectAltName=DNS:target.test\nbasicConstraints=critical,CA:FALSE\nextendedKeyUsage=serverAuth\n');
+ run('x509', '-req', '-in', 'leaf.csr', '-CA', 'ca.pem', '-CAkey', 'ca.key', '-CAcreateserial', '-out', 'leaf.pem', '-days', '1', '-extfile', 'extensions');
+ fixture = { dir, ca: fs.readFileSync(path.join(dir, 'ca.pem')), leaf: fs.readFileSync(path.join(dir, 'leaf.pem')) };
+ return fixture;
+}
+after(() => { if (fixture) fs.rmSync(fixture.dir, { recursive: true, force: true }); });
+test('certificate names alone never establish trust', () => {
+ assert.equal(verifies({ hostname: 'target.test', certificate: { issuerName: 'PortSwigger CA', subjectName: 'Burp Suite', data: 'not a certificate' } }, ''), false);
+ assert.throws(() => parseCa('not a certificate'));
+});
+test('pinned CA verifies a signed leaf and rejects hostname mismatch and non-CA imports', { skip: !openssl }, () => {
+ const { ca, leaf } = certificates();
+ assert(parseCa(ca).ca);
+ assert.throws(() => parseCa(leaf));
+ assert.equal(verifies({ hostname: 'target.test', certificate: { data: leaf } }, ca), true);
+ assert.equal(verifies({ hostname: 'other.test', certificate: { data: leaf } }, ca), false);
+ assert.equal(verifies({ hostname: 'target.test', certificate: { data: 'corrupt' } }, ca), false);
+});
+test('automatic CA retrieval is loopback-only, bounded and validates returned certificates', { skip: !openssl }, async () => {
+ const { ca } = certificates(); let mode = 'valid'; let target;
+ const server = http.createServer((request, response) => {
+ target = request.url;
+ if (mode === 'redirect') { response.writeHead(302, { Location: 'https://example.test/cert' }); response.end(); }
+ else if (mode === 'large') response.end(Buffer.alloc(70000));
+ else response.end(parseCa(ca).raw);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const entry = { scheme: 'http', host: '127.0.0.1', port: server.address().port };
+ try {
+ const result = await fetchCa(entry);
+ assert.equal(result.fingerprint256, parseCa(ca).fingerprint256);
+ assert.equal(target, 'http://burp/cert');
+ await assert.rejects(fetchCa({ ...entry, host: 'remote.test' }), /loopback/);
+ await assert.rejects(fetchCa({ ...entry, scheme: 'socks5' }), /loopback/);
+ mode = 'redirect'; await assert.rejects(fetchCa(entry), /did not return/);
+ mode = 'large'; await assert.rejects(fetchCa(entry), /exceeds/);
+ } finally { server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }
+});
diff --git a/tools/test-identity.js b/tools/test-identity.js
new file mode 100644
index 0000000..77bf5e4
--- /dev/null
+++ b/tools/test-identity.js
@@ -0,0 +1,72 @@
+'use strict';
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const vm = require('node:vm');
+const fs = require('node:fs');
+const path = require('node:path');
+const { generate, REAL_CHROME } = require('../src/main/fingerprint');
+const { fathiSpoof } = require('../src/shared/spoof');
+test('new profiles have independent cryptographic identity and noise material', () => {
+ const profiles = Array.from({ length: 2000 }, () => generate());
+ assert.equal(new Set(profiles.map((p) => p.id)).size, profiles.length);
+ assert.equal(new Set(profiles.map((p) => p.seed)).size, profiles.length);
+ assert.equal(new Set(profiles.map((p) => `${p.canvasSeed}:${p.audioSeed}`)).size, profiles.length);
+ for (const p of profiles) {
+ assert.match(p.seed, /^[0-9a-f]{32}$/);
+ assert.equal(p.chromeMajor, REAL_CHROME);
+ assert(p.deviceMemory <= 8);
+ assert(p.screen.availHeight <= p.screen.height);
+ assert.equal(p.language, p.languages[0]);
+ if (p.osKey === 'mac' && p.webgl.renderer.includes('Intel')) assert.equal(p.architecture, 'x86');
+ }
+});
+test('profile mutation cannot alter later tabs or device presets', () => {
+ const a = generate({ seed: 'fixed', deviceId: 'iphone-15-pro' });
+ const b = generate({ seed: 'fixed', deviceId: 'iphone-15-pro' });
+ a.languages.push('bad'); a.webgl.vendor = 'bad';
+ assert(!b.languages.includes('bad')); assert.notEqual(b.webgl.vendor, 'bad');
+ assert.equal(generate({ deviceId: 'iphone-15-pro' }).clientHints, false);
+});
+function realm(fp) {
+ const context = vm.createContext({ cfg: fp });
+ vm.runInContext('globalThis.navigator = Object.create({});', context);
+ vm.runInContext(`(${fathiSpoof.toString()})(cfg)`, context);
+ return (script) => vm.runInContext(script, context);
+}
+test('timezone offsets have correct sign and daylight saving; explicit UTC stays UTC', () => {
+ const run = realm({ ...generate(), timezone: 'America/New_York', spoofCanvas: false, spoofAudio: false });
+ assert.equal(run('new Date("2026-01-15T12:00:00Z").getTimezoneOffset()'), 300);
+ assert.equal(run('new Date("2026-07-15T12:00:00Z").getTimezoneOffset()'), 240);
+ assert.equal(run('Intl.DateTimeFormat().resolvedOptions().timeZone'), 'America/New_York');
+ assert.equal(run('Intl.DateTimeFormat("en-US", { timeZone: "UTC" }).resolvedOptions().timeZone'), 'UTC');
+});
+test('navigator prototype and instance agree, with default UA hint fields preserved', async () => {
+ const fp = generate();
+ const run = realm(fp);
+ assert.equal(run('navigator.userAgent'), fp.ua);
+ assert.equal(run('Object.getOwnPropertyDescriptor(Object.getPrototypeOf(navigator), "userAgent").get.call(navigator)'), fp.ua);
+ const hints = await run('navigator.userAgentData.getHighEntropyValues(["architecture"])');
+ assert.equal(hints.platform, fp.uaDataPlatform); assert.equal(hints.architecture, fp.architecture); assert(hints.brands.length);
+});
+test('network identity strips native hint spellings, omits Safari hints and carries Android model', () => {
+ const filename = path.resolve(__dirname, '../src/main/session.js');
+ let hook;
+ const context = { module: { exports: {} }, console, require: (name) => {
+ if (name === 'node:path') return path;
+ if (name === './settings') return { get: () => ({ proxy: {}, matchReplace: [] }) };
+ if (name === './rewrite') return require('../src/main/rewrite');
+ return {};
+ } };
+ vm.runInNewContext(fs.readFileSync(filename, 'utf8'), context, { filename });
+ const api = context.module.exports;
+ const ios = generate({ deviceId: 'iphone-15-pro' });
+ const ses = { webRequest: { onBeforeSendHeaders: (_filter, callback) => { hook = callback; }, onHeadersReceived() {} }, setUserAgent() {}, setPermissionRequestHandler() {}, setPermissionCheckHandler() {}, setCertificateVerifyProc() {} };
+ api.configureSession(ses, ios, 'test', { proxy: false, extensions: false });
+ let output;
+ hook({ requestHeaders: { 'uSeR-aGeNt': 'original', 'Sec-CH-UA': 'original', 'sec-ch-ua-platform': 'original', 'X-Client-Data': 'secret' } }, (result) => { output = result.requestHeaders; });
+ assert.equal(output['User-Agent'], ios.ua);
+ assert(!Object.keys(output).some((key) => /^sec-ch-ua/i.test(key)));
+ assert(!('uSeR-aGeNt' in output));
+ const android = generate({ deviceId: 'galaxy-s24-ultra' });
+ assert.equal(api.buildClientHints(android)['sec-ch-ua-model'], '"SM-S928B"');
+});