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
4 changes: 4 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ jobs:
$parseErrors = $null
[System.Management.Automation.Language.Parser]::ParseFile("$PWD/tools/update-fathi.ps1", [ref]$null, [ref]$parseErrors) | Out-Null
if ($parseErrors) { $parseErrors; exit 1 }
- name: Test Windows API-404 fallback without installing
if: runner.os == 'Windows'
shell: pwsh
run: ./tools/test-update-metadata.ps1
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- 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
worker initialization, header coherence and storage teardown.
- Await proxy setup before target navigation and reject cross-tab identity access.
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ archive. macOS offers Intel and Apple Silicon archives.
Save your browsing work before running an updater. Commands install the latest
**published** release, verify its download checksum and version, and preserve
preferences. Windows installed builds also support in-app installation.
If GitHub's API is unavailable, the updater uses the public release page and
asset digests instead. It never skips checksum verification to work around a
network failure. If both sources fail, no installation is changed.

### Linux

Expand Down
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 && 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 && 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
11 changes: 10 additions & 1 deletion src/main/updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,23 @@ function isNewer(a, b) {
}

async function latestRelease() {
try {
const res = await net.fetch(API_URL, {
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'fathi-updater'
}
});
if (!res.ok) throw new Error(`GitHub responded with ${res.status}`);
return res.json();
return await res.json();
} catch {
const page = await net.fetch(RELEASE_PAGE);
if (!page.ok) throw new Error(`Public release page responded with ${page.status}`);
const url = new URL(page.url);
const match = url.pathname.match(/^\/iMumd\/fathi-browser\/releases\/tag\/(v\d+\.\d+\.\d+)$/);
if (url.protocol !== 'https:' || url.host !== 'github.com' || !match) throw new Error('Could not resolve the latest stable release');
return { tag_name: match[1], html_url: page.url, body: '' };
}
}

/** Check through the GitHub API. Used by manual builds and as a fallback. */
Expand Down
21 changes: 21 additions & 0 deletions tools/test-update-fallback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';
const test = require('node:test'); const assert = require('node:assert/strict');
const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm');
function updater(fetch) {
const filename = path.resolve(__dirname, '../src/main/updater.js');
const context = { module: { exports: {} }, process: { platform: 'linux', env: {}, argv: [] }, URL,
require: () => ({ app: { getVersion: () => '1.0.1', isPackaged: false }, net: { fetch }, shell: {}, clipboard: {} }) };
vm.runInNewContext(fs.readFileSync(filename, 'utf8'), context, { filename });
return context.module.exports;
}
test('manual update checks use the public latest-release redirect when API returns 404', async () => {
const up = updater(async (url) => url.startsWith('https://api.') ? { ok: false, status: 404 } : { ok: true, url: 'https://github.com/iMumd/fathi-browser/releases/tag/v1.0.2' });
const result = await up.check();
assert.equal(result.status, 'available'); assert.equal(result.version, '1.0.2');
});
test('public metadata fallback rejects unexpected origins and missing stable tags', async () => {
for (const page of ['https://evil.test/iMumd/fathi-browser/releases/tag/v1.0.2', 'https://github.com/iMumd/fathi-browser/releases/latest']) {
const up = updater(async (url) => { if (url.startsWith('https://api.')) throw new Error('network error'); return { ok: true, url: page }; });
assert.equal((await up.check()).status, 'error');
}
});
22 changes: 22 additions & 0 deletions tools/test-update-metadata.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
$ErrorActionPreference = 'Stop'
$script:selected = $false
function Invoke-RestMethod { param($Uri, $Headers, $TimeoutSec) throw 'Simulated API 404' }
function Invoke-WebRequest {
param([switch]$UseBasicParsing, $Uri, $TimeoutSec, $OutFile)
if ($OutFile) {
if ($Uri -ne 'https://github.com/iMumd/fathi-browser/releases/download/v1.0.2/Fathi-Setup-1.0.2.exe') { throw "Wrong fallback asset: $Uri" }
$script:selected = $true
throw 'TEST_HALT_BEFORE_DOWNLOAD'
}
if ($Uri -like '*/releases/latest') { return @{ BaseResponse = @{ ResponseUri = [uri]'https://github.com/iMumd/fathi-browser/releases/tag/v1.0.2' } } }
$digest = 'sha256:' + ('a' * 64)
return @{ Content = '<a href="/iMumd/fathi-browser/releases/download/v1.0.2/Fathi-Setup-1.0.2.exe">Setup</a><clipboard-copy aria-label="Copy to clipboard digest for Fathi-Setup-1.0.2.exe" value="' + $digest + '"></clipboard-copy>' }
}
try {
$env:FATHI_PORTABLE_PATH = ''
. "$PSScriptRoot/update-fathi.ps1"
throw 'Expected test download guard'
} catch {
if (-not $script:selected -or $_.Exception.Message -ne 'TEST_HALT_BEFORE_DOWNLOAD') { throw }
}
Write-Output 'Windows API-404 public metadata fallback passed without downloading or executing an installer'
10 changes: 9 additions & 1 deletion tools/test-updater.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ from pathlib import Path
p = Path(os.environ['FIXTURE'])
a = {'name': 'Fathi-1.0.2-linux-x64.tar.gz', 'digest': 'sha256:' + hashlib.sha256((p / 'archive').read_bytes()).hexdigest(), 'browser_download_url': 'https://github.com/iMumd/fathi-browser/releases/download/v1.0.2/Fathi-1.0.2-linux-x64.tar.gz'}
(p / 'release.json').write_text(json.dumps({'tag_name': 'v1.0.2', 'assets': [a]}))
(p / 'assets.html').write_text('<a href="/iMumd/fathi-browser/releases/download/v1.0.2/Fathi-1.0.2-linux-x64.tar.gz">Linux</a><clipboard-copy aria-label="Copy to clipboard digest for Fathi-1.0.2-linux-x64.tar.gz" value="' + a['digest'] + '"></clipboard-copy>')
PY
cat > "$FIXTURE/bin/curl" <<'MOCK'
#!/usr/bin/env bash
Expand All @@ -35,7 +36,9 @@ while [ "$#" -gt 0 ]; do
esac
done
case "$url" in
https://api.github.com/*) cp "$FIXTURE/release.json" "$out" ;;
https://api.github.com/*) if [ -f "$FIXTURE/api-down" ]; then exit 22; else cp "$FIXTURE/release.json" "$out"; fi ;;
https://github.com/iMumd/fathi-browser/releases/latest) echo '<html></html>' > "$out"; printf 'https://github.com/iMumd/fathi-browser/releases/tag/v1.0.2' ;;
https://github.com/iMumd/fathi-browser/releases/expanded_assets/v1.0.2) cp "$FIXTURE/assets.html" "$out" ;;
*) cp "$FIXTURE/archive" "$out" ;;
esac
MOCK
Expand All @@ -48,6 +51,11 @@ test "$(readlink /usr/local/bin/fathi)" = /opt/fathi/fathi
test "$(stat -c %a /opt/fathi/chrome-sandbox)" = 4755
grep -q 'Exec=/opt/fathi/fathi %U' "$HOME/.local/share/applications/old-fathi.desktop"
cmp "$FIXTURE/Fathi-1.0.2-linux-x64/resources/app.asar" /opt/fathi/resources/app.asar
touch "$FIXTURE/api-down"
bash "$ROOT/tools/update-fathi.sh" > "$FIXTURE/fallback.log"
grep -q 'API unavailable' "$FIXTURE/fallback.log"
grep -q 'Installed and verified v1.0.2' "$FIXTURE/fallback.log"
cmp "$FIXTURE/Fathi-1.0.2-linux-x64/resources/app.asar" /opt/fathi/resources/app.asar
echo tampered >> "$FIXTURE/archive"
if bash "$ROOT/tools/update-fathi.sh" > "$FIXTURE/failure.log" 2>&1; then echo 'Checksum mismatch was not rejected'; exit 1; fi
grep -q 'checksum mismatch' "$FIXTURE/failure.log"
Expand Down
21 changes: 20 additions & 1 deletion tools/update-fathi.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,26 @@ $temp = Join-Path ([IO.Path]::GetTempPath()) ('fathi-update-' + [guid]::NewGuid(
New-Item -ItemType Directory -Path $temp | Out-Null
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases/latest" -Headers @{ 'User-Agent' = 'fathi-updater' }
try {
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases/latest" -Headers @{ 'User-Agent' = 'fathi-updater' } -TimeoutSec 45
} catch {
Write-Host '[Fathi Updater] GitHub API unavailable. Checking the public release page...'
$page = Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/$repo/releases/latest" -TimeoutSec 45
$uri = $page.BaseResponse.ResponseUri
if (-not $uri) { $uri = $page.BaseResponse.RequestMessage.RequestUri }
if ($uri.Scheme -ne 'https' -or $uri.Host -ne 'github.com' -or $uri.AbsolutePath -notmatch '^/iMumd/fathi-browser/releases/tag/(v\d+\.\d+\.\d+)$') { throw 'Could not resolve the latest stable public release' }
$tag = $Matches[1]
$assetPage = (Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/$repo/releases/expanded_assets/$tag" -TimeoutSec 45).Content
$assets = @()
foreach ($kind in @('Setup', 'Portable')) {
$filename = "Fathi-$kind-$($tag.Substring(1)).exe"
$pattern = 'aria-label="Copy to clipboard digest for ' + [regex]::Escape($filename) + '"[^>]*\bvalue="(sha256:[a-f0-9]{64})"'
$match = [regex]::Match($assetPage, $pattern)
$path = "/$repo/releases/download/$tag/$filename"
if ($match.Success -and $assetPage.Contains('href="' + $path + '"')) { $assets += @{ name = $filename; digest = $match.Groups[1].Value; browser_download_url = "https://github.com$path" } }
}
$release = @{ tag_name = $tag; assets = $assets }
}
if ($release.tag_name -notmatch '^v\d+\.\d+\.\d+$') { throw 'Invalid stable release version' }
$version = $release.tag_name.Substring(1)
$portable = $env:FATHI_PORTABLE_PATH
Expand Down
37 changes: 36 additions & 1 deletion tools/update-fathi.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,42 @@ case "$(uname -s)/$(uname -m)" in
esac

echo '[Fathi Updater] Checking for updates...'
curl -fsSL "$API" -o "$WORKDIR/release.json"
if ! curl -fsSL --retry 2 --connect-timeout 15 --max-time 45 "$API" -o "$WORKDIR/release.json"; then
echo '[Fathi Updater] GitHub API unavailable. Checking the public release page...'
LATEST_URL=$(curl -fsSL --retry 2 --connect-timeout 15 --max-time 45 -o "$WORKDIR/latest.html" -w '%{url_effective}' "https://github.com/$REPO/releases/latest")
PUBLIC_TAG=$(python3 - "$LATEST_URL" <<'PY'
import re, sys, urllib.parse
u = urllib.parse.urlsplit(sys.argv[1])
m = re.fullmatch(r'/iMumd/fathi-browser/releases/tag/(v\d+\.\d+\.\d+)', u.path)
if u.scheme != 'https' or u.netloc != 'github.com' or not m:
raise SystemExit('Could not resolve a stable public release. No files were changed.')
print(m[1])
PY
)
curl -fsSL --retry 2 --connect-timeout 15 --max-time 45 "https://github.com/$REPO/releases/expanded_assets/$PUBLIC_TAG" -o "$WORKDIR/assets.html"
python3 - "$WORKDIR/assets.html" "$PUBLIC_TAG" > "$WORKDIR/release.json" <<'PY'
import html.parser, json, re, sys, urllib.parse
tag = sys.argv[2]
prefix = '/iMumd/fathi-browser/releases/download/' + tag + '/'
class Assets(html.parser.HTMLParser):
def __init__(self): super().__init__(); self.assets = {}; self.digests = {}
def handle_starttag(self, name, attrs):
a = dict(attrs)
if name == 'a' and a.get('href', '').startswith(prefix):
href = a['href']; filename = urllib.parse.unquote(href[len(prefix):])
if '/' not in filename:
self.assets[filename] = {'name': filename, 'browser_download_url': 'https://github.com' + href}
label = a.get('aria-label', '')
if name == 'clipboard-copy' and label.startswith('Copy to clipboard digest for '):
digest = a.get('value', '')
if re.fullmatch(r'sha256:[a-f0-9]{64}', digest): self.digests[label[len('Copy to clipboard digest for '):]] = digest
p = Assets()
with open(sys.argv[1], encoding='utf-8') as f: p.feed(f.read())
for filename, asset in p.assets.items(): asset['digest'] = p.digests.get(filename)
if not p.assets: raise SystemExit('No verified public release assets were found. No files were changed.')
print(json.dumps({'tag_name': tag, 'assets': list(p.assets.values())}))
PY
fi
python3 - "$WORKDIR/release.json" "$SUFFIX" > "$WORKDIR/asset" <<'PY'
import json, re, sys
r = json.load(open(sys.argv[1]))
Expand Down
Loading