Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,26 @@ jobs:
if: runner.os == 'Windows'
shell: pwsh
run: ./tools/test-update-metadata.ps1
- name: Run browser identity and live interception audits
if: runner.os == 'Windows'
shell: pwsh
run: |
if (-not (Test-Path ./node_modules/electron/dist/electron.exe)) {
$env:ELECTRON_SKIP_BINARY_DOWNLOAD = ''
node ./node_modules/electron/install.js
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
$executable = (Resolve-Path ./node_modules/electron/dist/electron.exe).Path
$app = Start-Process -FilePath $executable -ArgumentList '.', '--fathi-e2e', '--fathi-identity-audit', '--fathi-intercept-audit' -PassThru -Wait
Get-Content e2e-result.txt
if ($app.ExitCode -ne 0) { exit $app.ExitCode }
- name: Preserve browser audit reports
if: always() && runner.os == 'Windows'
uses: actions/upload-artifact@v4
with:
name: browser-audit-windows
path: |
e2e-report.json
e2e-result.txt
e2e-*.png
if-no-files-found: ignore
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Unreleased

- Keep the interception queue visible while editing, preserve per-request
drafts and advance selection after Forward or Drop.
- Apply all four rule targets to live traffic, including body rules with
Intercept off; preserve repeated headers and enforce worker timeouts.
- Send Repeat through the source tab session and report redirects without
automatically following them.
- Fall back to public GitHub release metadata when the API is unavailable;
command-line updates still require GitHub's SHA-256 digest before replacing files.
- Audit profile entropy, canvas/audio consistency, timezone semantics, native
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,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) ·
[Interception and rules](docs/interception-and-rules.md) ·
[Contribute](CONTRIBUTING.md) ·
[Changelog](CHANGELOG.md)

Expand All @@ -35,6 +36,12 @@ still **1.0.2**. Updating a released installation does not install unreleased co
5. Pin one response as a baseline, open another, and select **Compare**.
6. Export only the filtered records. Use **Redacted JSON** when sharing context.

Intercept keeps the pending queue visible while you edit a request. Switch
between requests without losing drafts; Forward and Drop stay at the top.
Live rules cover header values and supported text bodies, including when
manual interception is off. See the [rule limits](docs/interception-and-rules.md)
before relying on a transformation.

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.
Expand Down
89 changes: 89 additions & 0 deletions docs/interception-and-rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Interception and live rules

Status: unreleased source changes after 1.0.2.

## Queue and editor

With Intercept enabled, the first matching request opens automatically. The
pending queue stays visible above the editor and scrolls independently. Select
another request without forwarding the current one; URL, method, header rows,
body and selected editor view are retained as an in-memory draft.

Forward, Drop and Repeat stay above the editor and remain visible while it
scrolls. Forward sends the selected edits. Drop aborts the selected request
without sending it to the target. Resolving a request selects the next queued
request. Forward all submits the current queue snapshot with saved drafts.
Failed sends retain the pause rather than removing it from the UI.

The interceptor filter affects future pause decisions. It does not hide
already-paused requests. Pauses from different tabs have distinct IDs, even if
Chromium reuses a Fetch request ID. Closed/detached targets and expired pauses
are removed from the UI. Drafts are never written to disk.

Safety limits: at most 80 pending requests and a two-minute pause deadline.
Timeout or turning Intercept off forwards the backend's initially rewritten
request, not an unsent frontend draft. Use Forward or Forward all to explicitly
send edits. This avoids leaving a tab frozen indefinitely.

## Rules in real traffic

Request headers, request bodies, response headers and response bodies are
tested against a local HTTP server, not just through the preview UI. Header
rules are applied once through the session request hooks. Body rules use the
existing shared Fetch debugger connection and remain enabled when manual
interception is off. Response pauses are recognized from the actual
`Fetch.requestPaused` event with response metadata.

- Header rules match **header values**, not entire raw header lines or names.
Use the structured interception editor to rename, add or remove headers.
- Rules run in their saved order. Disabled rules do not run.
- Plain-text replacement treats `$1` and other dollar sequences literally.
Regex replacement supports JavaScript capture-group syntax.
- Repeated response headers, especially Set-Cookie, remain separate values.
- Body changes update length/encoding metadata and remove stale entity hashes.
Modified response text is delivered as UTF-8. CSP and application-level
integrity protections are not silently removed.
- The manual request editor starts with request-body rule output. Forward
sends that output or your edits once, rather than applying it again.

## Bounds and unsupported cases

Live processing uses at most two worker threads, a queue of 32 waiting jobs,
and a 1.5-second execution timeout per job. Up to 100 rules can be saved; match
patterns are limited to 4,096 characters and replacements to 65,536. Invalid
regexes are rejected on save.

Body-rule input is limited to 64 KiB of UTF-8 text. Large, binary or unavailable
upload bodies, HEAD responses, redirects, empty responses and partial-content
responses are not rewritten. Only supported textual response MIME types are
processed. CDP may obtain an unknown-length response before the decoded size
can be checked; this is not a streaming or general binary rewrite engine.

If a worker times out, the queue is full, or input cannot be processed safely,
traffic continues unchanged and the UI reports a rate-limited warning. Do not
use Match and Replace as an enforced data-loss prevention or network-security
boundary. DevTools can detach the shared debugger and disrupt body rewriting;
closing it reconfigures the Fetch hooks.

## Repeat

Repeat sends the editor's current request through its source tab's session,
including that session's proxy, cookies, identity headers and pinned CA trust.
There is no unconfigured direct-network fallback. It has a 15-second timeout
and a 512 KiB response preview cap. Redirects are reported but not followed
automatically. Request-body edits already shown in the editor are sent as-is.

## Reproduce the checks

```bash
npm test
npx electron . --fathi-e2e --fathi-identity-audit --fathi-intercept-audit
```

The local live-rule fixture checks all four targets with non-idempotent plain
replacements and regex capture groups, both automatic processing and manual
forwarding, separate cookies, source-session replay, redirects, and a
three-request queue with saved drafts and dropped requests. Unit tests also
exercise worker timeouts, equal IDs across tabs, failed continuation and UTF-8
response-length correction. Passing these cases is not a promise that every
protocol, site, payload size, or external network condition is supported.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 tools/test-identity.js tools/test-certificate.js tools/test-update-fallback.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 tools/test-update-fallback.js tools/test-intercept.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",
Expand Down
7 changes: 6 additions & 1 deletion src/main/e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ async function run(win) {
JSON.stringify(about));

/* ---- 3. second tab gets a different partition */
if (process.argv.includes('--fathi-intercept-audit')) {
trace('live interception and rule audit');
const checks = await require('./intercept-checks').run(ui);
for (const check of checks) add(check.name, check.pass, check.detail);
}
if (process.argv.includes('--fathi-identity-audit')) {
trace('identity isolation audit');
const checks = await require('./identity-checks').run(ui);
Expand Down Expand Up @@ -313,7 +318,7 @@ async function run(win) {
const topActions = await ui.executeJavaScript(`(async () => {
devOpen('intercept'); await ixOpenItem(ix.items[0].id);
ixRenderHeaderRows(Object.fromEntries(Array.from({ length: 30 }, (_, i) => ['X-Test-' + i, 'test value'])));
const scroller = document.querySelector('#pane-intercept .ix-body');
const scroller = document.getElementById('ix-detail');
const bar = document.querySelector('.ix-action-bar');
const aboveEditor = bar.getBoundingClientRect().bottom <= document.getElementById('ix-url').getBoundingClientRect().top;
scroller.scrollTop = 300;
Expand Down
101 changes: 101 additions & 0 deletions src/main/intercept-checks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
'use strict';
const http = require('node:http');
const { webContents } = require('electron');
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function run(ui) {
const checks = []; let tab; const received = [];
const add = (name, pass, detail = '') => checks.push({ name, pass: !!pass, detail: typeof detail === 'string' ? detail : JSON.stringify(detail) });
const server = http.createServer((req, res) => {
if (req.url === '/redirect') { res.writeHead(302, { Location: '/off-target' }); res.end(); return; }
if (req.url === '/') { res.setHeader('Content-Type', 'text/html'); res.end('<body>Local rule fixture<script>window.__rulesFixture = true</script>'); return; }
let body = ''; req.on('data', (chunk) => { body += chunk; });
req.on('end', () => {
received.push({ url: req.url, body, header: req.headers['x-rule-probe'], cookie: req.headers.cookie || '' });
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('X-Response-Probe', 'response-token');
res.setHeader('Set-Cookie', ['first=one; Path=/', 'second=two; Path=/']);
res.end(JSON.stringify({ body, header: req.headers['x-rule-probe'] || '', marker: 'response-body' }));
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = `http://127.0.0.1:${server.address().port}/`;
const old = await ui.executeJavaScript('(async () => (await window.api.rules.list()).rules)()');
let wc;
try {
await ui.executeJavaScript('window.api.intercept.set(false)');
tab = await ui.executeJavaScript(`(async () => { const t = await createTab({ url: ${JSON.stringify(url)} }); return { id: t.id }; })()`);
for (let i = 0; i < 80; i++) {
const id = await ui.executeJavaScript(`(() => { try { return state.tabs.find(t => t.id === ${JSON.stringify(tab.id)}).wv.getWebContentsId(); } catch { return null; } })()`);
wc = id && webContents.fromId(id);
if (wc && await wc.executeJavaScript('!!window.__rulesFixture').catch(() => false)) break;
await delay(100);
}
const cases = [
{ regex: false, matchRequestBody: 'request-body', matchResponseBody: 'response-body', matchRequestHeader: 'request-token', matchResponseHeader: 'response-token', replacement: (value) => value + '-once', body: 'request-body-once', requestHeader: 'request-token-once', responseHeader: 'response-token-once', responseBody: 'response-body-once' },
{ regex: true, matchRequestBody: '(request)-(body)', matchResponseBody: '(response)-(body)', matchRequestHeader: '(request)-(token)', matchResponseHeader: '(response)-(token)', replacement: () => '$2/$1', body: 'body/request', requestHeader: 'token/request', responseHeader: 'token/response', responseBody: 'body/response' }
];
for (const scenario of cases) {
const targets = ['requestBody', 'responseBody', 'requestHeader', 'responseHeader'];
const list = targets.map((target, i) => {
const match = scenario['match' + target[0].toUpperCase() + target.slice(1)];
return { id: 'live-' + i, enabled: true, target, match, replace: scenario.replacement(match), regex: scenario.regex };
});
const saved = await ui.executeJavaScript(`window.api.rules.save(${JSON.stringify(list)})`);
if (!saved.ok) throw new Error(saved.error);
const result = await wc.executeJavaScript(`(async () => { const r = await fetch('/echo', { method: 'POST', headers: { 'X-Rule-Probe': 'request-token', 'Content-Type': 'text/plain' }, body: 'request-body' }); return { status: r.status, header: r.headers.get('x-response-probe'), data: await r.json(), cookies: document.cookie }; })()`);
add(`live rules: all four ${scenario.regex ? 'regex/capture' : 'plain-text'} targets apply once while Intercept is off`, result.data.body === scenario.body && result.data.header === scenario.requestHeader && result.header === scenario.responseHeader && result.data.marker === scenario.responseBody, result);
add('live rules: response header rewriting preserves separate Set-Cookie fields', result.cookies.includes('first=one') && result.cookies.includes('second=two'), result.cookies);
}
const manualRules = ['requestBody', 'responseBody', 'requestHeader', 'responseHeader'].map((target, i) => {
const match = cases[0]['match' + target[0].toUpperCase() + target.slice(1)];
return { id: 'manual-' + i, enabled: true, target, match, replace: match + '-once' };
});
await ui.executeJavaScript(`window.api.rules.save(${JSON.stringify(manualRules)})`);
await ui.executeJavaScript('window.api.intercept.filter("/manual-rule")');
await ui.executeJavaScript('window.api.intercept.set(true)');
await wc.executeJavaScript(`window.__manualRule = fetch('/manual-rule', { method: 'POST', headers: { 'X-Rule-Probe': 'request-token' }, body: 'request-body' }).then(async r => ({ header: r.headers.get('x-response-probe'), data: await r.json() })); true`);
for (let i = 0; i < 80; i++) { if (await ui.executeJavaScript(`ix.items.some(r => r.wcId === ${wc.id})`)) break; await delay(100); }
const editorRewritten = await ui.executeJavaScript(`(async () => { const row = ix.items.find(r => r.wcId === ${wc.id}); await ixOpenItem(row.id); const rewritten = document.getElementById('ix-body-text').value === 'request-body-once'; await ixResolve('continue'); return rewritten; })()`);
const manual = await wc.executeJavaScript('window.__manualRule');
add('live rules: edited interception forwards all four targets exactly once', editorRewritten && manual.data.body === 'request-body-once' && manual.data.header === 'request-token-once' && manual.header === 'response-token-once' && manual.data.marker === 'response-body-once', manual);
await ui.executeJavaScript('window.api.intercept.set(false)');
await ui.executeJavaScript('window.api.rules.save([])');
const replay = await ui.executeJavaScript(`window.api.intercept.repeat({ wcId: ${wc.id}, url: ${JSON.stringify(url + 'echo')}, method: 'POST', postData: 'manual-repeat' })`);
add('Repeat uses the source tab session and cookies', replay.ok && received.some((record) => record.body === 'manual-repeat' && record.cookie.includes('first=one') && record.cookie.includes('second=two')));
const redirect = await ui.executeJavaScript(`window.api.intercept.repeat({ wcId: ${wc.id}, url: ${JSON.stringify(url + 'redirect')}, method: 'GET' })`);
add('Repeat reports redirects without following a new destination', redirect.ok && redirect.response.status === 302 && !received.some((record) => record.url === '/off-target'), redirect);
await ui.executeJavaScript('window.api.intercept.filter("/queue")');
await ui.executeJavaScript('window.api.intercept.set(true)');
await wc.executeJavaScript(`window.__queuedRequests = Promise.all([1,2,3].map(i => fetch('/queue?i=' + i, { method: 'POST', body: 'original-' + i }).then(r => r.json()).catch(() => ({ dropped: true })))); true`);
let queued;
for (let i = 0; i < 80; i++) {
queued = await ui.executeJavaScript(`ix.items.filter(r => r.wcId === ${wc.id}).length`);
if (queued >= 3) break; await delay(100);
}
const queue = await ui.executeJavaScript(`(async () => {
devOpen('intercept'); const rows = ix.items.filter(r => r.wcId === ${wc.id});
const automatic = !!ix.current && !document.getElementById('ix-detail').classList.contains('hidden');
const visible = !document.getElementById('ix-list').classList.contains('hidden') && document.querySelectorAll('#ix-list .ix-item').length >= 3;
await ixOpenItem(rows[0].id); document.getElementById('ix-body-text').value = 'edited-first';
await ixOpenItem(rows[2].id); await ixOpenItem(rows[0].id);
const preserved = document.getElementById('ix-body-text').value === 'edited-first';
await ixOpenItem(rows[2].id); await ixResolve('drop');
await ixOpenItem(rows[0].id); await ixResolve('continue');
const advanced = ix.current === rows[1].id;
await ixResolve('drop');
return { automatic, visible, preserved, advanced };
})()`);
const results = await wc.executeJavaScript('window.__queuedRequests');
add('interception queue remains visible and selects the first request automatically', queued >= 3 && queue.automatic && queue.visible, queue);
add('interception queue preserves drafts while switching and advances after forwarding', queue.preserved && queue.advanced, queue);
add('Forward sends edited data and Drop never reaches the target', results.filter((r) => r.dropped).length === 2 && received.filter((r) => r.url.startsWith('/queue')).length === 1 && received.some((r) => r.url.startsWith('/queue') && r.body === 'edited-first'), results);
} finally {
await ui.executeJavaScript('window.api.intercept.set(false)').catch(() => {});
await ui.executeJavaScript('window.api.intercept.filter("")').catch(() => {});
await ui.executeJavaScript(`window.api.rules.save(${JSON.stringify(old || [])})`).catch(() => {});
if (tab) await ui.executeJavaScript(`closeTab(${JSON.stringify(tab.id)}, { silent: true })`).catch(() => {});
server.closeAllConnections(); await new Promise((resolve) => server.close(resolve));
}
return checks;
}
module.exports = { run };
Loading
Loading