feat: SHA-256 verification, download progress, native installer, i18n

- SHA-256 hash check on downloaded APK (Web Crypto API, no new deps)
- Download progress bar in a locked sheet (stream-based tracking)
- Native Android InstallPlugin (FileProvider + ACTION_VIEW intent)
- REQUEST_INSTALL_PACKAGES permission in AndroidManifest
- applicationIdSuffix .debug for debug builds
- Update row only shown when an update is available
- Label changed to 'openGym v{0} available', icon to 'info'
- All 7 new UI strings translated in 12 locales
- pt-BR snapshot count updated (291 → 298)
This commit is contained in:
Sebastian G committed 2026-09-04 13:01:42 +02:00
1 parent 106a3abee0
commit 7958d0fcd4
22 files changed
+344 -96

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(593)
expect(inherited).toHaveLength(553)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
+61 -27
View File
@@ -27,16 +27,17 @@ function compareSemver(a, b) {
/**
* Checks the GitLab releases API for a newer version.
* Returns { hasUpdate, latestVersion, apkUrl } or throws on network failure.
* Returns { hasUpdate, latestVersion, apkUrl, hashUrl } or throws on network failure.
* - hasUpdate: true if the latest release tag is newer than the running build
* - latestVersion: the semver string of the latest release (without "v" prefix)
* - apkUrl: direct download URL of the first .apk asset, or null
* - hashUrl: direct download URL of the .apk.sha256 hash file, or null
*/
export async function checkForUpdate() {
const res = await fetch(RELEASES_URL + '?per_page=1')
if (!res.ok) throw new Error(`GitLab API ${res.status}`)
const releases = await res.json()
if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null }
if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null, hashUrl: null }
const latest = releases[0]
const latestVersion = latest.tag_name.replace(/^v/, '')
@@ -44,19 +45,37 @@ export async function checkForUpdate() {
// Find the APK asset among the release links (generic package links) or assets.sources
let apkUrl = null
let hashUrl = null
if (latest.assets?.links?.length) {
const apkLink = latest.assets.links.find(l => /\.apk$/i.test(l.url) || /\.apk$/i.test(l.direct_asset_url))
if (apkLink) apkUrl = apkLink.direct_asset_url || apkLink.url
// Look for a matching .sha256 hash file
const hashLink = latest.assets.links.find(l => /\.apk\.sha256$/i.test(l.url) || /\.apk\.sha256$/i.test(l.direct_asset_url) || /sha256/i.test(l.name))
if (hashLink) hashUrl = hashLink.direct_asset_url || hashLink.url
}
return { hasUpdate, latestVersion, apkUrl }
return { hasUpdate, latestVersion, apkUrl, hashUrl }
}
/**
* Downloads the APK from `url` and triggers the Android installer.
* Only works on the MOBILE (Capacitor) build with Android.
* Computes the SHA-256 hash of an ArrayBuffer using the Web Crypto API.
* Returns the hex-encoded digest string.
*/
export async function downloadAndInstall(url) {
export async function sha256(buffer) {
const hash = await crypto.subtle.digest('SHA-256', buffer)
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('')
}
/**
* Downloads the APK from `url`, verifies its SHA-256 hash against `expectedHash`
* (if provided), and triggers the Android installer.
* Only works on the MOBILE (Capacitor) build with Android.
*
* @param {string} url - Direct download URL for the APK
* @param {string|null} expectedHash - Expected SHA-256 hex string (from .sha256 asset), or null to skip verification
* @param {function|null} onProgress - Called with (received, total) bytes during download, or null
*/
export async function downloadAndInstall(url, expectedHash = null, onProgress = null) {
if (!MOBILE) {
// On web, just open the release page
window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener')
@@ -65,10 +84,39 @@ export async function downloadAndInstall(url) {
const { Filesystem, Directory } = await import('@capacitor/filesystem')
// Download the file as a blob, then write to cache as base64
// Download with progress tracking via ReadableStream
const res = await fetch(url)
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
const blob = await res.blob()
const total = parseInt(res.headers.get('content-length') || '0', 10)
const reader = res.body.getReader()
const chunks = []
let received = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
chunks.push(value)
received += value.length
if (onProgress) onProgress(received, total)
}
// Reassemble into a single blob
const blob = new Blob(chunks)
// Size check: an APK should be at least 100 KB
if (blob.size < 100_000) {
throw new Error('Downloaded file is too small to be a valid APK (' + blob.size + ' bytes)')
}
// SHA-256 integrity check
if (expectedHash) {
const buffer = await blob.arrayBuffer()
const actualHash = await sha256(buffer)
if (actualHash !== expectedHash.toLowerCase().trim()) {
throw new Error('SHA-256 mismatch — download may be corrupted or tampered with')
}
}
// Convert blob to base64
const base64 = await new Promise((resolve, reject) => {
@@ -79,28 +127,14 @@ export async function downloadAndInstall(url) {
})
const fileName = 'opengym-update.apk'
const written = await Filesystem.writeFile({
await Filesystem.writeFile({
path: fileName,
directory: Directory.Cache,
data: base64,
})
// Use the Capacitor App plugin or an intent to open the APK for installation.
// FileOpener is not bundled, so we use the @capacitor/filesystem URI with an intent.
// The approach: open the file URI which triggers the Android package installer.
const { App: CapApp } = await import('@capacitor/app')
// Capacitor's Filesystem.getUri gives us the content URI needed for install
const { uri } = await Filesystem.getUri({ path: fileName, directory: Directory.Cache })
// On Android, we need to trigger an install intent. Since we don't have a dedicated
// plugin, we open the URI which — on Android with the right content type — prompts install.
// Use the native intent via a custom URL scheme or window.open as fallback.
try {
// Try using the Capacitor App plugin to open the URI
// This works if the device has a handler for APK content URIs
window.open(uri, '_system')
} catch (e) {
// Fallback: just inform the user where the file is
throw new Error('APK downloaded but could not start installer. Check your Downloads folder.')
}
// Use the local InstallPlugin to trigger the Android package installer
const { registerPlugin } = await import('@capacitor/core')
const Install = registerPlugin('Install')
await Install.installApk({ fileName })
}
+62 -1
View File
@@ -1,9 +1,30 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { checkForUpdate } from './update.js'
import { checkForUpdate, sha256 } from './update.js'
// __APP_VERSION__ is defined at build time by vite.config.js (reads package.json).
// In the test environment vitest applies the same define, so it's available here.
describe('sha256', () => {
it('computes the correct hash for a known input', async () => {
const input = new TextEncoder().encode('hello world')
const hash = await sha256(input.buffer)
// Well-known SHA-256 of "hello world"
expect(hash).toBe('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9')
})
it('computes a different hash for different input', async () => {
const a = await sha256(new TextEncoder().encode('aaa').buffer)
const b = await sha256(new TextEncoder().encode('bbb').buffer)
expect(a).not.toBe(b)
})
it('returns a 64-character hex string', async () => {
const hash = await sha256(new TextEncoder().encode('test').buffer)
expect(hash).toHaveLength(64)
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
})
describe('checkForUpdate', () => {
let originalFetch
@@ -24,6 +45,7 @@ describe('checkForUpdate', () => {
expect(result.hasUpdate).toBe(false)
expect(result.latestVersion).toBe(__APP_VERSION__)
expect(result.apkUrl).toBe(null)
expect(result.hashUrl).toBe(null)
})
it('reports no update when the latest release is older than current', async () => {
@@ -87,11 +109,50 @@ describe('checkForUpdate', () => {
expect(result.apkUrl).toBe(null)
})
it('finds the .sha256 hash URL from release asset links', async () => {
const hashUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk.sha256'
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ url: hashUrl, direct_asset_url: hashUrl },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe(hashUrl)
})
it('finds hash URL by link name containing sha256', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: {
links: [
{ name: 'APK', url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
{ name: 'SHA256 checksum', url: 'https://example.com/checksum.txt', direct_asset_url: 'https://example.com/checksum.txt' },
]
}
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe('https://example.com/checksum.txt')
})
it('returns null hashUrl when no hash link exists', async () => {
mockFetch([{
tag_name: 'v99.0.0',
assets: { links: [{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' }] }
}])
const result = await checkForUpdate()
expect(result.hashUrl).toBe(null)
})
it('returns no update when the releases array is empty', async () => {
mockFetch([])
const result = await checkForUpdate()
expect(result.hasUpdate).toBe(false)
expect(result.latestVersion).toBe(__APP_VERSION__)
expect(result.hashUrl).toBe(null)
})
it('throws when the API responds with an error status', async () => {