diff --git a/android-app/android/app/build.gradle b/android-app/android/app/build.gradle index f3329ea..13e0fc0 100644 --- a/android-app/android/app/build.gradle +++ b/android-app/android/app/build.gradle @@ -7,6 +7,8 @@ android { applicationId "com.dsmnru.pyq" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion + // versionName/versionCode are bumped by the release flow only — + // tests assert well-formedness, never exact values. versionCode 13 versionName "1.4.2" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" diff --git a/android-app/android/app/src/main/AndroidManifest.xml b/android-app/android/app/src/main/AndroidManifest.xml index 130a1df..ac642bb 100644 --- a/android-app/android/app/src/main/AndroidManifest.xml +++ b/android-app/android/app/src/main/AndroidManifest.xml @@ -104,5 +104,16 @@ nothing except that push stays silent; the decision is never re-asked on later launches. --> + + diff --git a/android-app/android/app/src/main/java/com/dsmnru/pyq/DsmnruAppPlugin.java b/android-app/android/app/src/main/java/com/dsmnru/pyq/DsmnruAppPlugin.java index 369cbef..b7e393c 100644 --- a/android-app/android/app/src/main/java/com/dsmnru/pyq/DsmnruAppPlugin.java +++ b/android-app/android/app/src/main/java/com/dsmnru/pyq/DsmnruAppPlugin.java @@ -4,18 +4,28 @@ import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; import android.net.Uri; import android.app.DownloadManager; import android.os.Environment; +import android.provider.Settings; import android.webkit.MimeTypeMap; import android.webkit.URLUtil; +import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import android.os.Build; import java.io.File; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; +import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import androidx.credentials.CredentialManager; import androidx.credentials.CredentialManagerCallback; @@ -64,6 +74,12 @@ * navigator.share), used for sharing a paper link. * • getLaunchUrl → the /pyq/<slug> URL that started the activity, so the * app can deep-link into its own paper screen. + * • downloadAndInstall → the in-app updater: downloads the official GitHub + * release APK (URL/redirect policy in UpdateUrlPolicy), + * verifies it, and hands it to the system package + * installer; progress streams to JS via + * `updateDownloadProgress` and the plugin call is always + * answered exactly once. */ @CapacitorPlugin(name = "DsmnruApp") public class DsmnruAppPlugin extends Plugin { @@ -376,22 +392,302 @@ public void getAppVersion(PluginCall call) { } catch (Exception e) { call.reject("Unable to read installed app version"); } } + // ── in-app updater: GitHub release APK → verify → package installer ── + + // One download/install at a time: a second tap (or a watchdog retry that + // races a slow first attempt) must never corrupt the in-flight download. + private final AtomicBoolean updaterBusy = new AtomicBoolean(false); + + private static final int CONNECT_TIMEOUT_MS = 15000; + private static final int READ_TIMEOUT_MS = 30000; + /** Progress event cadence during the download phase (~12 ticks for a 5.7 MB APK). */ + private static final long PROGRESS_EVERY_BYTES = 512 * 1024; + private static final String DOWNLOAD_USER_AGENT = "DSMNRU-PYQ-android-updater"; + + /** + * In-app update: download the GitHub release APK into the app cache, + * VERIFY it, then hand it to the Android package installer. + * + * The phases are streamed to JS through `updateDownloadProgress` events + * (phase: download → verify → install) so the updater UI follows REAL + * bytes, and EVERY terminal path resolves or rejects the plugin call + * EXACTLY ONCE — including Throwables that are not Exceptions. The JS + * layer must never be left sitting on "Downloading…" forever. + * + * Security (see UpdateUrlPolicy): HTTPS GitHub release URLs only — the + * initial URL must be github.com or objects.githubusercontent.com, and + * redirects are followed by hand so every hop is re-validated against + * GitHub's own asset CDN (never a scheme downgrade, never another host). + * JS may pass `expectedVersionCode`; the downloaded archive is parsed + * with PackageManager and rejected unless it IS that exact release. + */ @PluginMethod public void downloadAndInstall(PluginCall call) { String source = call.getString("url", ""); - String name = sanitizeName(call.getString("fileName", "dsmnru-update.apk")); - if (!source.startsWith("https://github.com/") && !source.startsWith("https://objects.githubusercontent.com/")) { call.reject("Untrusted update URL"); return; } + String fileName = UpdateUrlPolicy.sanitizeApkFileName(call.getString("fileName", ""), "dsmnru-update.apk"); + int expectedVersionCode = 0; + // `opt` (not `get`): returns null when absent and never throws the + // checked JSONException. JS/native.js passes the Worker-reported + // versionCode so verifyApk can reject any other package. + Object rawExpected = call.getData() == null ? null : call.getData().opt("expectedVersionCode"); + if (rawExpected instanceof Number) expectedVersionCode = ((Number) rawExpected).intValue(); + + if (!UpdateUrlPolicy.isTrustedUpdateUrl(source)) { + call.reject("UPDATE_URL_UNTRUSTED: only official GitHub release downloads can be installed"); + return; + } + if (!updaterBusy.compareAndSet(false, true)) { + call.reject("UPDATE_BUSY: an update is already downloading — try again in a moment"); + return; + } + + final Context appContext = getContext().getApplicationContext(); + final File apkFile = new File(appContext.getCacheDir(), fileName); + final File partFile = new File(appContext.getCacheDir(), fileName + ".part"); + final int expected = expectedVersionCode; + // A plugin call is answered exactly once, even if an unexpected + // Throwable (not an Exception) escapes somewhere below. + final AtomicBoolean answered = new AtomicBoolean(false); + Executors.newSingleThreadExecutor().execute(() -> { - File out = new File(getContext().getCacheDir(), name); try { - HttpURLConnection c = (HttpURLConnection) new URL(source).openConnection(); c.setConnectTimeout(15000); c.setReadTimeout(30000); c.setInstanceFollowRedirects(true); - if (c.getResponseCode() < 200 || c.getResponseCode() >= 300) throw new Exception("Download failed: HTTP " + c.getResponseCode()); - try (InputStream in = c.getInputStream(); FileOutputStream fos = new FileOutputStream(out)) { byte[] b = new byte[8192]; int n; while ((n=in.read(b)) >= 0) fos.write(b,0,n); } - Intent i = new Intent(Intent.ACTION_VIEW); Uri uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName()+".fileprovider", out); i.setDataAndType(uri, "application/vnd.android.package-archive"); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(i); call.resolve(); - } catch (Exception e) { if (out.exists()) out.delete(); call.reject("Could not install update: " + e.getMessage()); } + // ── phase 1: DOWNLOAD (or reuse a fully-verified APK from a + // previous attempt — e.g. the user just granted the + // "Install unknown apps" permission and tapped retry) ────── + long contentLength = -1; + if (apkFile.isFile()) { + try { + verifyApk(appContext, apkFile, -1, expected); + contentLength = apkFile.length(); + emitProgress("download", contentLength, contentLength); + } catch (IOException notReusable) { + apkFile.delete(); // stale/corrupt leftover — download fresh + } + } + if (!apkFile.isFile()) { + partFile.delete(); // never resume into a stale partial file + contentLength = downloadTo(source, partFile); + } + + // ── phase 2: VERIFY, then atomically promote .part → .apk ── + if (partFile.exists()) { + emitProgress("verify", partFile.length(), contentLength); + verifyApk(appContext, partFile, contentLength, expected); + if (!partFile.renameTo(apkFile)) { + partFile.delete(); + throw new IOException("UPDATE_INVALID_APK: could not finalize the downloaded update"); + } + } + + // ── phase 3: INSTALL — launch the system installer on the + // main thread, and wait for its real outcome ─────────────── + emitProgress("install", apkFile.length(), apkFile.length()); + final AtomicReference launchError = new AtomicReference<>(null); + final CountDownLatch launched = new CountDownLatch(1); + ContextCompat.getMainExecutor(appContext).execute(() -> { + try { + launchError.set(startPackageInstaller(appContext, apkFile)); + } catch (Throwable t) { + launchError.set("UPDATE_INSTALL_FAILED: " + safeMessage(t)); + } finally { + launched.countDown(); + } + }); + if (!launched.await(15, TimeUnit.SECONDS)) { + throw new IOException("UPDATE_INSTALL_FAILED: the installer did not respond"); + } + String error = launchError.get(); + if (error != null) throw new IOException(error); + + JSObject done = new JSObject(); + done.put("ok", true); + done.put("installerOpened", true); + resolveOnce(answered, call, done); + } catch (Throwable t) { + // ANY failure — network, verification, or installer — must + // reach JS as a rejection. A partially downloaded or invalid + // file is deleted; a VERIFIED apk is kept so an immediate + // retry (e.g. after granting the install permission) can + // skip straight to the installer. + partFile.delete(); + rejectOnce(answered, call, safeMessage(t)); + } finally { + updaterBusy.set(false); + } }); } + /** + * Stream the release APK to {@code part}, following redirects BY HAND so + * every hop is re-validated (GitHub release downloads redirect from + * github.com to its *.githubusercontent.com asset CDN). Returns the + * server's Content-Length (-1 when absent). + */ + private long downloadTo(String source, File part) throws IOException { + String current = source; + for (int hop = 0; hop <= UpdateUrlPolicy.MAX_REDIRECTS; hop++) { + if (!UpdateUrlPolicy.isTrustedRedirectTarget(current)) { + throw new IOException("UPDATE_DOWNLOAD_FAILED: untrusted download URL"); + } + HttpURLConnection connection = (HttpURLConnection) new URL(current).openConnection(); + try { + connection.setConnectTimeout(CONNECT_TIMEOUT_MS); + connection.setReadTimeout(READ_TIMEOUT_MS); + // Manual redirect handling — the silent default would follow + // ANY Location header without re-validation. + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("User-Agent", DOWNLOAD_USER_AGENT); + int status = connection.getResponseCode(); + if (status >= 300 && status < 400) { + String location = connection.getHeaderField("Location"); + if (location == null || location.isEmpty()) { + throw new IOException("UPDATE_DOWNLOAD_FAILED: HTTP " + status + " redirect without a target"); + } + current = new URL(new URL(current), location).toString(); // resolve relative Location too + continue; + } + if (status < 200 || status >= 300) { + throw new IOException("UPDATE_DOWNLOAD_FAILED: HTTP " + status); + } + long total = connection.getContentLengthLong(); + long written = 0; + long nextTick = 0; + emitProgress("download", 0, total); + try (InputStream in = connection.getInputStream(); + FileOutputStream out = new FileOutputStream(part)) { + byte[] buffer = new byte[16384]; + int read; + while ((read = in.read(buffer)) >= 0) { + out.write(buffer, 0, read); + written += read; + if (written > UpdateUrlPolicy.MAX_APK_BYTES) { + throw new IOException("UPDATE_DOWNLOAD_FAILED: download exceeds any possible release APK"); + } + if (written >= nextTick) { + nextTick = written + PROGRESS_EVERY_BYTES; + emitProgress("download", written, total); + } + } + out.flush(); + } // streams closed HERE — reaching 100% is not "done" until this ran + emitProgress("download", written, total); // the real 100% tick + if (!UpdateUrlPolicy.isPlausibleApkSize(written, total)) { + throw new IOException(total > 0 + ? "UPDATE_DOWNLOAD_FAILED: incomplete download (" + written + " of " + total + " bytes)" + : "UPDATE_DOWNLOAD_FAILED: downloaded file is implausibly small"); + } + return total; + } finally { + connection.disconnect(); + } + } + throw new IOException("UPDATE_DOWNLOAD_FAILED: too many redirects"); + } + + /** + * Prove the file is really the expected, installable APK BEFORE any + * installer intent exists: exists → plausible size → ZIP magic → full + * PackageManager parse (and, when JS supplied one, the exact expected + * versionCode). A single cheap parse for a ~5.7 MB asset; on failure the + * caller deletes the file and JS receives UPDATE_INVALID_APK. + */ + private void verifyApk(Context context, File apk, long contentLength, int expectedVersionCode) throws IOException { + if (!apk.isFile()) throw new IOException("UPDATE_INVALID_APK: downloaded update file is missing"); + long size = apk.length(); + if (!UpdateUrlPolicy.isPlausibleApkSize(size, contentLength)) { + throw new IOException("UPDATE_INVALID_APK: unexpected file size (" + size + " bytes)"); + } + try (RandomAccessFile raf = new RandomAccessFile(apk, "r")) { + byte[] magic = new byte[4]; + if (raf.read(magic) < 4 || !UpdateUrlPolicy.looksLikeZip(magic, 4)) { + throw new IOException("UPDATE_INVALID_APK: file is not an Android package"); + } + } + PackageManager pm = context.getPackageManager(); + PackageInfo info = pm.getPackageArchiveInfo(apk.getAbsolutePath(), 0); + if (info == null || info.packageName == null || info.packageName.isEmpty()) { + throw new IOException("UPDATE_INVALID_APK: Android could not parse the package"); + } + if (expectedVersionCode > 0) { + long code = Build.VERSION.SDK_INT >= 28 ? info.getLongVersionCode() : info.versionCode; + if (code != expectedVersionCode) { + throw new IOException("UPDATE_INVALID_APK: package is version code " + code + ", expected " + expectedVersionCode); + } + } + } + + /** + * Hand a VERIFIED apk to the system package installer. Runs on the MAIN + * thread. Returns null when the installer activity was launched, or a + * machine-readable "CODE: human message" the JS layer can act on. + */ + private String startPackageInstaller(Context context, File apk) { + Uri uri; + try { + uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apk); + } catch (IllegalArgumentException e) { + return "UPDATE_INSTALL_FAILED: downloaded update could not be shared with the installer"; + } + // Android 8+ refuses sideloaded installs until the user allows THIS + // app to "install unknown apps". Detect it and open the EXACT + // settings screen instead of failing opaquely — after granting, the + // retry skips straight to the installer (the verified apk is kept). + if (Build.VERSION.SDK_INT >= 26) { + boolean canInstall = false; + try { + canInstall = context.getPackageManager().canRequestPackageInstalls(); + } catch (Exception e) { + canInstall = false; + } + if (!canInstall) { + try { + Intent settings = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:" + context.getPackageName())); + settings.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(settings); + return "UPDATE_INSTALL_PERMISSION_REQUIRED: allow \"Install unknown apps\" for DSMNRU PYQ, then tap Try again"; + } catch (Throwable settingsUnavailable) { + return "UPDATE_INSTALL_PERMISSION_REQUIRED: enable \"Install unknown apps\" for DSMNRU PYQ in system settings, then tap Try again"; + } + } + } + Intent install = new Intent(Intent.ACTION_VIEW); + install.setDataAndType(uri, "application/vnd.android.package-archive"); + install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); + try { + context.startActivity(install); + return null; + } catch (ActivityNotFoundException noInstaller) { + return "UPDATE_INSTALL_FAILED: no package installer is available on this device"; + } catch (Exception e) { + return "UPDATE_INSTALL_FAILED: " + safeMessage(e); + } + } + + /** Real progress for the JS updater UI (never faked; total may be -1). */ + private void emitProgress(String phase, long bytes, long total) { + JSObject data = new JSObject(); + data.put("phase", phase); + data.put("bytes", bytes); + data.put("total", total); + notifyListeners("updateDownloadProgress", data); + } + + /** A plugin call is answered EXACTLY once — never twice, never never. */ + private static void resolveOnce(AtomicBoolean answered, PluginCall call, JSObject data) { + if (answered.compareAndSet(false, true)) call.resolve(data); + } + + private static void rejectOnce(AtomicBoolean answered, PluginCall call, String message) { + if (answered.compareAndSet(false, true)) call.reject(message); + } + + private static String safeMessage(Throwable t) { + if (t == null) return "unknown error"; + String message = t.getMessage(); + return (message == null || message.isEmpty()) ? t.getClass().getSimpleName() : message; + } + private boolean isHttpUrl(String url) { return url != null && (url.startsWith("https://") || url.startsWith("http://")) diff --git a/android-app/android/app/src/main/java/com/dsmnru/pyq/UpdateUrlPolicy.java b/android-app/android/app/src/main/java/com/dsmnru/pyq/UpdateUrlPolicy.java new file mode 100644 index 0000000..14905c3 --- /dev/null +++ b/android-app/android/app/src/main/java/com/dsmnru/pyq/UpdateUrlPolicy.java @@ -0,0 +1,121 @@ +package com.dsmnru.pyq; + +import java.net.URL; +import java.util.Locale; + +/** + * DSMNRU PYQ — pure-JDK security policy for the in-app updater's + * download/install phase. + * + * Deliberately contains NO android.* imports so the class (and its JUnit + * test) runs on the plain JVM under `gradlew :app:testDebugUnitTest` + * without an emulator. DsmnruAppPlugin.downloadAndInstall consults this + * class for EVERY security-relevant decision: + * + * • which initial URLs may be downloaded (the Worker-supplied GitHub + * release asset URL — same allowlist as update.js); + * • which redirect hops may be followed (GitHub's own HTTPS asset CDN); + * • what a safe APK cache-file name looks like (always ends in .apk); + * • what a sane APK size is before the file is handed to the installer. + */ +final class UpdateUrlPolicy { + + private UpdateUrlPolicy() {} + + /** Hosts a release asset may ORIGINATE from (mirrors update.js regex). */ + static final String INITIAL_HOST_GITHUB = "github.com"; + static final String INITIAL_HOST_OBJECTS = "objects.githubusercontent.com"; + + /** + * Redirects are followed BY HAND (setInstanceFollowRedirects(false)) so + * every hop can be re-validated — HttpURLConnection's silent default + * would go anywhere the Location header says. GitHub release downloads + * redirect from github.com to its asset CDN subdomains (objects. and + * release-assets.) of githubusercontent.com: HTTPS, GitHub-owned, + * never an arbitrary host, never a scheme downgrade. + */ + static final String REDIRECT_HOST_SUFFIX = ".githubusercontent.com"; + + /** Upper bound on hand-followed redirects (GitHub needs exactly one). */ + static final int MAX_REDIRECTS = 5; + + /** + * Plausibility bounds for this app's release APK (the real v1.4.2 asset + * is ~5.7 MB). Catches HTML error pages, truncated downloads and + * runaway writes BEFORE anything is handed to the package installer. + */ + static final long MIN_APK_BYTES = 64 * 1024; + static final long MAX_APK_BYTES = 512L * 1024 * 1024; + + /** + * True when {@code url} is an HTTPS URL on a host the app downloads + * updates FROM (the exact release-asset allowlist; credentials embedded + * in the URL are rejected). + */ + static boolean isTrustedUpdateUrl(String url) { + return isHttpsOnTrustedHost(url, false); + } + + /** + * True when a redirect Location may be followed: HTTPS on github.com or + * any githubusercontent.com subdomain (GitHub-owned asset CDN). + */ + static boolean isTrustedRedirectTarget(String url) { + return isHttpsOnTrustedHost(url, true); + } + + private static boolean isHttpsOnTrustedHost(String url, boolean allowGithubusercontentCdn) { + if (url == null || url.isEmpty()) return false; + try { + URL parsed = new URL(url); + if (!"https".equalsIgnoreCase(parsed.getProtocol())) return false; + if (parsed.getUserInfo() != null) return false; // never user:pass@host + String host = parsed.getHost() == null ? "" : parsed.getHost().toLowerCase(Locale.ROOT); + if (host.isEmpty()) return false; + if (INITIAL_HOST_GITHUB.equals(host) || INITIAL_HOST_OBJECTS.equals(host)) return true; + return allowGithubusercontentCdn + && host.length() > REDIRECT_HOST_SUFFIX.length() + && host.endsWith(REDIRECT_HOST_SUFFIX); + } catch (Exception malformed) { + return false; + } + } + + /** + * Flatten a JS-supplied file name to a safe cache file that ALWAYS ends + * in .apk — the package installer path in the FileProvider URI. Path + * separators and other unsafe characters are replaced, the name is + * length-capped (keeping the tail so an extension survives) and any + * non-.apk extension is replaced with .apk. + */ + static String sanitizeApkFileName(String raw, String fallback) { + String name = raw == null ? "" : raw.trim(); + if (name.isEmpty()) { + name = (fallback == null || fallback.trim().isEmpty()) ? "dsmnru-update.apk" : fallback.trim(); + } + name = name.replaceAll("[^A-Za-z0-9 ._\\-]", "_"); + if (name.length() > 96) name = name.substring(name.length() - 96); + if (!name.toLowerCase(Locale.ROOT).endsWith(".apk")) { + int dot = name.lastIndexOf('.'); + if (dot > 0) name = name.substring(0, dot); // replace wrong extension + name = name + ".apk"; + } + return name; + } + + /** + * True when {@code bytes} is a sane size for this app's release APK: + * within the floor/ceiling, and — when the server sent a length — the + * EXACT length (a truncated download must never reach the installer). + * {@code contentLength <= 0} means "unknown" and skips the exact match. + */ + static boolean isPlausibleApkSize(long bytes, long contentLength) { + if (bytes < MIN_APK_BYTES || bytes > MAX_APK_BYTES) return false; + return contentLength <= 0 || bytes == contentLength; + } + + /** ZIP local-file-header magic — the fastest "is this even an APK" sniff. */ + static boolean looksLikeZip(byte[] header, int length) { + return length >= 4 && header[0] == 'P' && header[1] == 'K' && header[2] == 0x03 && header[3] == 0x04; + } +} diff --git a/android-app/android/app/src/test/java/com/dsmnru/pyq/UpdateUrlPolicyTest.java b/android-app/android/app/src/test/java/com/dsmnru/pyq/UpdateUrlPolicyTest.java new file mode 100644 index 0000000..f35b27c --- /dev/null +++ b/android-app/android/app/src/test/java/com/dsmnru/pyq/UpdateUrlPolicyTest.java @@ -0,0 +1,119 @@ +package com.dsmnru.pyq; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Plain-JVM behaviour tests for the in-app updater's download security + * policy ({@link UpdateUrlPolicy} — pure JDK, no Android APIs, so this runs + * under `gradlew :app:testDebugUnitTest` without an emulator). + * + * Covers the updater-fix requirements: trusted GitHub URLs, rejected + * untrusted/HTTP URLs, redirect-hop validation, .apk file-name sanitizing, + * APK size plausibility (including the real v1.4.2 asset size) and ZIP + * magic detection. + */ +public class UpdateUrlPolicyTest { + + // ── trusted INITIAL download URLs ─────────────────────────────────── + + @Test + public void acceptsTrustedGithubReleaseUrls() { + assertTrue(UpdateUrlPolicy.isTrustedUpdateUrl( + "https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk")); + assertTrue(UpdateUrlPolicy.isTrustedUpdateUrl( + "https://objects.githubusercontent.com/github-production-release-asset-2e65be/977278444/a?X-Amz-Signature=abc")); + } + + @Test + public void rejectsNullEmptyAndMalformedUrls() { + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl(null)); + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("")); + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("not a url")); + } + + @Test + public void rejectsUntrustedSchemesAndHosts() { + // plain HTTP is never allowed + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl( + "http://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk")); + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("http://objects.githubusercontent.com/x.apk")); + // arbitrary domains and look-alike hosts + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://evil.example.com/dsmnru-pyq.apk")); + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://github.com.evil.example.com/dsmnru-pyq.apk")); + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://githubusercontent.com/x.apk")); + // embedded credentials + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("https://user:pass@github.com/x.apk")); + // non-http(s) schemes + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl("file:///data/local/tmp/malicious.apk")); + // CDN subdomains are redirect targets only, never initial sources + assertFalse(UpdateUrlPolicy.isTrustedUpdateUrl( + "https://raw.githubusercontent.com/Lav-developer/PYQ/main/x.apk")); + } + + // ── redirect hops (followed by hand, re-validated per hop) ────────── + + @Test + public void acceptsGithubOwnedRedirectTargets() { + assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget( + "https://objects.githubusercontent.com/github-production-release-asset-2e65be/977278444/a?sig=1")); + assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget( + "https://release-assets.githubusercontent.com/github-production-release-asset/a?sig=1")); + assertTrue(UpdateUrlPolicy.isTrustedRedirectTarget( + "https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk")); + } + + @Test + public void rejectsUntrustedRedirectTargets() { + assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("http://objects.githubusercontent.com/x")); // downgrade + assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("https://objects.githubusercontent.com.evil.com/x")); + assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget("https://evil.com/?u=https://github.com")); + assertFalse(UpdateUrlPolicy.isTrustedRedirectTarget(null)); + } + + // ── APK cache-file names always end in .apk ───────────────────────── + + @Test + public void apkFileNamesAreSanitizedAndAlwaysEndInApk() { + assertEquals("dsmnru-pyq-1.4.2.apk", + UpdateUrlPolicy.sanitizeApkFileName("dsmnru-pyq-1.4.2.apk", "dsmnru-update.apk")); + assertEquals("dsmnru-update.apk", UpdateUrlPolicy.sanitizeApkFileName("", "dsmnru-update.apk")); + assertEquals("dsmnru-update.apk", UpdateUrlPolicy.sanitizeApkFileName(null, null)); + assertEquals("weird name_.apk", UpdateUrlPolicy.sanitizeApkFileName("weird name?.apk", "dsmnru-update.apk")); + assertEquals(".._.._etc_passwd.apk", UpdateUrlPolicy.sanitizeApkFileName("../../etc/passwd.apk", "dsmnru-update.apk")); + // a wrong extension is REPLACED, and a missing one is appended + assertEquals("update.apk", UpdateUrlPolicy.sanitizeApkFileName("update.pdf", "dsmnru-update.apk")); + assertEquals("update.apk", UpdateUrlPolicy.sanitizeApkFileName("update", "dsmnru-update.apk")); + } + + // ── APK size plausibility ─────────────────────────────────────────── + + @Test + public void plausibleApkSizes() { + assertTrue(UpdateUrlPolicy.isPlausibleApkSize(5704283L, 5704283L)); // the REAL v1.4.2 asset + assertTrue(UpdateUrlPolicy.isPlausibleApkSize(5704283L, -1L)); // unknown length → skip exact match + assertFalse(UpdateUrlPolicy.isPlausibleApkSize(0L, -1L)); // empty file + assertFalse(UpdateUrlPolicy.isPlausibleApkSize(1024L, -1L)); // below floor (HTML error page) + assertFalse(UpdateUrlPolicy.isPlausibleApkSize(5704282L, 5704283L)); // truncated by one byte + assertFalse(UpdateUrlPolicy.isPlausibleApkSize(Long.MAX_VALUE, -1L)); // runaway write + } + + // ── ZIP magic (fast "is this even an APK" sniff) ──────────────────── + + @Test + public void zipMagicDetection() { + assertTrue(UpdateUrlPolicy.looksLikeZip(new byte[]{'P', 'K', 3, 4, 0, 0}, 6)); + assertFalse(UpdateUrlPolicy.looksLikeZip(new byte[]{'<', 'h', 't', 'm', 'l'}, 5)); // an error page is not an APK + assertFalse(UpdateUrlPolicy.looksLikeZip(new byte[]{'P', 'K'}, 2)); + } + + // ── redirect budget ───────────────────────────────────────────────── + + @Test + public void redirectBudgetIsBoundedAndSufficient() { + assertTrue(UpdateUrlPolicy.MAX_REDIRECTS > 0); + assertTrue(UpdateUrlPolicy.MAX_REDIRECTS <= 10); // bounded; GitHub needs exactly one + } +} diff --git a/android-app/test/fcm.test.mjs b/android-app/test/fcm.test.mjs index cc87e1d..8d55e51 100644 --- a/android-app/test/fcm.test.mjs +++ b/android-app/test/fcm.test.mjs @@ -62,8 +62,14 @@ test('Gradle wires firebase-messaging and keeps google-services conditional', () assert.match(gradle, /apply plugin: 'com\.google\.gms\.google-services'/, 'google-services plugin applied when google-services.json exists'); assert.match(gradle, /google-services\.json/, 'apply is guarded by the presence of google-services.json'); - assert.match(gradle, /versionCode 12/, 'current production versionCode is 12'); - assert.match(gradle, /versionName \"1\.4\.1\"/, 'current production versionName is 1.4.1'); + // Version metadata is bumped by the release flow on purpose — pinning the + // exact values here made this Firebase-wiring test fail on every + // legitimate bump (it broke when production moved to 1.4.2/13). Assert + // well-formed metadata instead; which exact version ships is owned by the + // release process, and the updater treats versions purely as data + // (see update-install.test.mjs). + assert.match(gradle, /^ versionCode \d+$/m, 'integer versionCode present'); + assert.match(gradle, /^ versionName "\d+\.\d+\.\d+"$/m, 'semver versionName present'); // Consistent package identity + stable debug signature (update-in-place). assert.match(gradle, /applicationId "com\.dsmnru\.pyq"/, 'single applicationId preserved'); assert.match(gradle, /signingConfig signingConfigs\.debug/, 'debug buildType uses the shared debug signing config'); diff --git a/android-app/test/update-install.test.mjs b/android-app/test/update-install.test.mjs new file mode 100644 index 0000000..ed867c5 --- /dev/null +++ b/android-app/test/update-install.test.mjs @@ -0,0 +1,343 @@ +/** + * DSMNRU PYQ Android — in-app updater DOWNLOAD → INSTALL completion tests. + * + * The bug this locks down: the update downloaded to "5.70 MB / 5.70 MB" and + * then NOTHING happened — the installer never opened and the UI stayed on + * "Downloading…" forever. Covers every layer testable without a device: + * + * 1. trusted GitHub APK URL accepted / untrusted rejected (policy source) + * 2. redirect handling is manual + re-validated per hop (policy source) + * 3. download failure & post-download failure always reach JS + * (plugin call answered exactly once — `catch (Throwable)`) + * 4. APK existence/size/ZIP/PackageManager validation + .part→.apk rename + * 5. FileProvider configuration (cache-path, exported=false, grants) + * 6. installer Intent contract (content:// URI, APK MIME, grant flag) + * 7. REQUEST_INSTALL_PACKAGES + unknown-app-sources guidance + * 8. JS never sits on "Downloading…" — jsdom state machine: progress, + * verify/install phases, success, download-failure, install-failure, + * permission-required, watchdog, retry + * 9. Optional updates keep "Later"; mandatory updates keep working + * 10. version comparison unchanged: 1.4.1 (code 12) → v1.4.2 (code 13) + * 11. gradle version metadata stays well-formed (the release flow owns + * which exact version ships — tests never pin it) + * + * jsdom comes from worker/node_modules when installed (skips otherwise) — + * same pattern as app-native-bridge.test.mjs. + */ + +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { dirname, join } from 'node:path'; + +const here = dirname(fileURLToPath(import.meta.url)); +const WWW = join(here, '../www'); +const ANDROID = join(here, '../android/app/src/main'); +const pluginSrc = readFileSync(join(ANDROID, 'java/com/dsmnru/pyq/DsmnruAppPlugin.java'), 'utf8'); +const policySrc = readFileSync(join(ANDROID, 'java/com/dsmnru/pyq/UpdateUrlPolicy.java'), 'utf8'); +const policyTestSrc = readFileSync(join(ANDROID, '../test/java/com/dsmnru/pyq/UpdateUrlPolicyTest.java'), 'utf8'); +const manifestSrc = readFileSync(join(ANDROID, 'AndroidManifest.xml'), 'utf8'); +const pathsSrc = readFileSync(join(ANDROID, 'res/xml/file_paths.xml'), 'utf8'); +const gradleSrc = readFileSync(join(here, '../android/app/build.gradle'), 'utf8'); + +// ── native downloader: URL trust + redirects ───────────────────────────── + +test('policy: only trusted HTTPS GitHub release URLs can be downloaded', () => { + assert.match(policySrc, /INITIAL_HOST_GITHUB = "github\.com"/); + assert.match(policySrc, /INITIAL_HOST_OBJECTS = "objects\.githubusercontent\.com"/); + assert.match(policySrc, /!"https"\.equalsIgnoreCase\(parsed\.getProtocol\(\)\)/); // https only + assert.match(policySrc, /parsed\.getUserInfo\(\) != null/); // no embedded creds + assert.match(pluginSrc, /UpdateUrlPolicy\.isTrustedUpdateUrl\(source\)/); + // behavioural coverage exists in the plain-JVM JUnit suite + assert.match(policyTestSrc, /rejectsUntrustedSchemesAndHosts/); +}); + +test('policy: redirects are followed manually and re-validated per hop', () => { + assert.match(pluginSrc, /setInstanceFollowRedirects\(false\)/); // never the silent default + assert.match(policySrc, /isTrustedRedirectTarget/); // every hop re-validated + assert.match(policySrc, /REDIRECT_HOST_SUFFIX = "\.githubusercontent\.com"/); // GitHub CDN only + assert.match(policySrc, /MAX_REDIRECTS = 5/); // bounded loop + assert.match(pluginSrc, /setConnectTimeout\(\s*CONNECT_TIMEOUT_MS\s*\)/); + assert.match(pluginSrc, /setReadTimeout\(\s*READ_TIMEOUT_MS\s*\)/); + assert.match(pluginSrc, /setRequestProperty\("User-Agent"/); + assert.match(pluginSrc, /connection\.disconnect\(\)/); // streams/connections closed +}); + +// ── post-download phase separation + validation ────────────────────────── + +test('native: download completion is separated from installation (phases)', () => { + assert.match(pluginSrc, /notifyListeners\("updateDownloadProgress"/); // download → JS + assert.match(pluginSrc, /emitProgress\("verify"/); + assert.match(pluginSrc, /emitProgress\("install"/); +}); + +test('native: the APK is verified before any installer intent exists', () => { + assert.match(pluginSrc, /\.part/); // temp download file + assert.match(pluginSrc, /renameTo\(apkFile\)/); // promote only after verification + assert.match(pluginSrc, /partFile\.delete\(\)/); // partial/corrupt cleanup + assert.match(pluginSrc, /verifyApk\(/); + assert.match(pluginSrc, /apk\.isFile\(\)/); // existence + assert.match(pluginSrc, /isPlausibleApkSize\(/); // size + assert.match(pluginSrc, /looksLikeZip\(/); // ZIP magic + assert.match(pluginSrc, /getPackageArchiveInfo\(/); // real package parse + assert.match(pluginSrc, /expectedVersionCode/); // exact expected release +}); + +test('native: the plugin call is ALWAYS answered — no stuck "Downloading…"', () => { + assert.match(pluginSrc, /catch \(Throwable/); // Errors too, not just Exceptions + assert.match(pluginSrc, /resolveOnce/); + assert.match(pluginSrc, /rejectOnce/); + assert.match(pluginSrc, /UPDATE_BUSY/); // single-flight guard + assert.match(policySrc, /private UpdateUrlPolicy\(\)/); // policy is static-only +}); + +test('native: expectedVersionCode is read with the non-throwing JSONObject.opt (compilable)', () => { + // JSONObject.get(String) throws the CHECKED JSONException — a plain .get + // here fails `assembleRelease` with "unreported exception JSONException". + // .opt(String) returns null when absent and never throws. + assert.match(pluginSrc, /getData\(\)\s*==\s*null\s*\?\s*null\s*:\s*call\.getData\(\)\.opt\("expectedVersionCode"\)/); + assert.doesNotMatch(pluginSrc, /getData\(\)\.get\(/); + assert.match(pluginSrc, /rawExpected instanceof Number/); // typed guard preserved +}); + +// ── FileProvider + installer Intent contract ───────────────────────────── + +test('installer: FileProvider content:// URI, correct MIME and granted read permission', () => { + assert.match(pluginSrc, /FileProvider\.getUriForFile\(/); + assert.match(pluginSrc, /getPackageName\(\)\s*\+\s*"\.fileprovider"/); // same authority as the manifest + assert.match(pluginSrc, /application\/vnd\.android\.package-archive/); + assert.match(pluginSrc, /FLAG_GRANT_READ_URI_PERMISSION/); + assert.doesNotMatch(pluginSrc, /file:\/\//); // never a file:// URI + assert.match(manifestSrc, /android:name="androidx\.core\.content\.FileProvider"/); + assert.match(manifestSrc, /android:authorities="\$\{applicationId\}\.fileprovider"/); + assert.match(manifestSrc, /android:exported="false"/); + assert.match(manifestSrc, /android:grantUriPermissions="true"/); + assert.match(pathsSrc, /]*path="\."/); // covers the cache-dir APK +}); + +test('installer: unknown-app-install permission is detected and guided, never silent', () => { + assert.match(manifestSrc, //); + assert.match(pluginSrc, /canRequestPackageInstalls\(\)/); // detect BEFORE launching + assert.match(pluginSrc, /ACTION_MANAGE_UNKNOWN_APP_SOURCES/); // open the exact settings screen + assert.match(pluginSrc, /UPDATE_INSTALL_PERMISSION_REQUIRED/); // JS gets a real error, not silence + assert.match(pluginSrc, /UPDATE_INSTALL_FAILED/); // installer launch failures propagate +}); + +// ── version / release safety ───────────────────────────────────────────── + +test('gradle version metadata stays well-formed (release flow owns the values)', () => { + // PR #20's original task pinned 1.4.1/12 for a temporary local-device + // updater test against the already-published v1.4.2 release; that pin is + // gone now that production is back at its bumped version. What must hold + // FOREVER is only well-formedness: an integer versionCode and a semver + // versionName — accidental damage or garbage here breaks every build + // tool, while legitimate bumps must never break the test suite. The + // updater's version logic is fixture-driven and stays independent of + // build.gradle (see the tests below and update-version.test.mjs). + const code = gradleSrc.match(/^\s*versionCode\s+(\d+)\s*$/m); + const name = gradleSrc.match(/^\s*versionName\s+"(\d+)\.(\d+)\.(\d+)"\s*$/m); + assert.ok(code, 'integer versionCode statement present'); + assert.ok(name, 'semver versionName statement present'); + assert.ok(Number(code[1]) >= 1, 'versionCode is a positive integer'); + assert.doesNotMatch(gradleSrc, /^\s*versionCode\s*$/m); // never left empty +}); + +test('update detection unchanged: local 1.4.1 (code 12) → GitHub v1.4.2 (code 13) = update available', async () => { + const { isNewer, parseUpdate } = await import(pathToFileURL(join(WWW, 'js/update.js')).href); + assert.equal(isNewer(13, 12), true); + const meta = { + version: '1.4.2', versionCode: 13, + downloadUrl: 'https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk', + releaseNotes: ['Fixed in-app update installation'], mandatory: false, + }; + const parsed = parseUpdate(meta, 12); + assert.ok(parsed, 'v1.4.2 (code 13) must be detected from an installed 1.4.1 (code 12)'); + assert.equal(parsed.versionCode, 13); + assert.equal(parsed.mandatory, false); + assert.equal(parseUpdate({ ...meta, versionCode: 12 }, 12), null); // same code → no update + assert.equal(parseUpdate({ ...meta, downloadUrl: 'https://evil.example.com/x.apk' }, 12), null); + assert.equal(parseUpdate({ ...meta, downloadUrl: 'http://github.com/x.apk' }, 12), null); +}); + +const UPDATE_META = { + version: '1.4.2', versionCode: 13, + downloadUrl: 'https://github.com/Lav-developer/PYQ/releases/download/v1.4.2/dsmnru-pyq.apk', + releaseNotes: ['Fixed in-app update installation'], mandatory: false, +}; + +// ── JS updater state machine (jsdom + fake Capacitor bridge) ───────────── + +let JSDOM; +try { + ({ JSDOM } = await import(pathToFileURL(join(here, '../../worker/node_modules/jsdom/lib/api.js')).href)); +} catch { + try { ({ JSDOM } = await import('jsdom')); } catch { /* skipped below */ } +} + +if (JSDOM) { + const tick = (ms = 15) => new Promise((r) => setTimeout(r, ms)); + + /** Fake Capacitor bridge: records calls, lets each test script the outcome. */ + function makeBridge() { + const calls = []; + let installImpl = () => new Promise(() => {}); // default: never settles (worst case) + let progressHandler = null; + const DsmnruApp = { + // isNative() probes for openExternal — present on the real bridge. + async openExternal(opts) { calls.push({ kind: 'openExternal', url: opts && opts.url }); return {}; }, + async getAppVersion() { calls.push({ kind: 'getAppVersion' }); return { versionName: '1.4.1', versionCode: 12 }; }, + downloadAndInstall(opts) { calls.push({ kind: 'downloadAndInstall', opts }); return installImpl(opts); }, + addListener(evt, cb) { + calls.push({ kind: 'addListener', evt }); + if (evt === 'updateDownloadProgress') progressHandler = cb; + return { remove: () => { progressHandler = null; } }; + }, + }; + return { + DsmnruApp, calls, + emit(progress) { if (progressHandler) progressHandler(progress); }, + set impl(fn) { installImpl = fn; }, + }; + } + + async function openUpdateSheet(t, { mandatory = false } = {}) { + const dom = new JSDOM('', { url: 'https://localhost/' }); + const { window } = dom; + t.after(() => { try { window.close(); } catch { /* gone */ } }); + for (const key of ['window', 'document', 'HTMLElement', 'Event']) { + Object.defineProperty(globalThis, key, { value: window[key], configurable: true, writable: true }); + } + const bridge = makeBridge(); + globalThis.Capacitor = { Plugins: { DsmnruApp: bridge.DsmnruApp } }; + globalThis.fetch = async (url) => { + if (String(url).includes('/api/app-update')) { + return { ok: true, status: 200, json: async () => ({ ...UPDATE_META, mandatory }) }; + } + return { ok: false, status: 404, json: async () => ({}) }; + }; + const { checkForUpdate, _setUpdateWatchdogMs } = await import(pathToFileURL(join(WWW, 'js/update.js')).href); + const ui = { + sheetOpts: null, toasts: [], + sheet(o) { this.sheetOpts = o; document.body.innerHTML = `
${o.content}
`; }, + closeSheet() { document.body.innerHTML = ''; return true; }, + toast(m, k) { this.toasts.push({ m, k }); }, + }; + const found = await checkForUpdate({ force: true, ui }); + assert.ok(found && found.versionCode === 13, 'v1.4.2 detected against installed code 12'); + return { dom, window, bridge, ui, _setUpdateWatchdogMs, now: () => document.querySelector('#update-now'), later: () => document.querySelector('#update-later') }; + } + + test('updater: real byte progress renders, then SUCCESS leaves the busy state', async (t) => { + const ctx = await openUpdateSheet(t); + ctx.bridge.impl = () => new Promise((resolve) => { + ctx.resolveInstall = resolve; + }); + const b = ctx.now(); + assert.equal(b.textContent, 'Update Now'); + b.click(); + await tick(); + assert.equal(b.disabled, true, 'busy during download'); + assert.match(b.textContent, /^Downloading…/); + + ctx.bridge.emit({ phase: 'download', bytes: 0, total: 5704283 }); + assert.match(b.textContent, /Downloading… 0\.00 \/ 5\.70 MB/); + ctx.bridge.emit({ phase: 'download', bytes: 5704283, total: 5704283 }); // the real 100% tick + assert.match(b.textContent, /Downloading… 5\.70 \/ 5\.70 MB/); + ctx.bridge.emit({ phase: 'verify', bytes: 5704283, total: 5704283 }); + assert.equal(b.textContent, 'Verifying…'); + ctx.bridge.emit({ phase: 'install', bytes: 5704283, total: 5704283 }); + assert.equal(b.textContent, 'Starting installer…'); + + ctx.resolveInstall({ ok: true, installerOpened: true }); // installer actually launched + await tick(); + assert.equal(ctx.bridge.calls.filter((c) => c.kind === 'downloadAndInstall').length, 1); + assert.equal(b.disabled, false, 'button leaves the busy state on success'); + assert.equal(b.textContent, 'Open installer'); + assert.doesNotMatch(b.textContent, /Downloading…/, 'never stuck on "Downloading…" after completion'); + assert.match(String(ctx.bridge.calls.at(-1).opts.expectedVersionCode), /^13$/, 'expected release code passed to native'); + assert.match(String(ctx.bridge.calls.at(-1).opts.fileName), /^dsmnru-pyq-1\.4\.2\.apk$/, '.apk filename passed to native'); + }); + + test('updater: DOWNLOAD failure → retry state + toast, never "Downloading…"', async (t) => { + const ctx = await openUpdateSheet(t); + ctx.bridge.impl = () => Promise.reject(new Error('UPDATE_DOWNLOAD_FAILED: HTTP 404')); + const b = ctx.now(); + b.click(); + await tick(); + assert.equal(b.disabled, false, 're-enabled for retry'); + assert.equal(b.textContent, 'Try again'); + assert.equal(ctx.ui.toasts.at(-1)?.k, 'err'); + assert.match(ctx.ui.toasts.at(-1)?.m, /HTTP 404/); + // retry issues a fresh native call + ctx.bridge.impl = () => Promise.resolve({ ok: true, installerOpened: true }); + b.click(); + await tick(); + assert.equal(ctx.bridge.calls.filter((c) => c.kind === 'downloadAndInstall').length, 2); + assert.equal(b.textContent, 'Open installer'); + }); + + test('updater: POST-DOWNLOAD installer failure → retry state (JS not left waiting)', async (t) => { + const ctx = await openUpdateSheet(t); + let rejectInstall; + ctx.bridge.impl = () => new Promise((_, reject) => { rejectInstall = reject; }); + const b = ctx.now(); + b.click(); + await tick(); + ctx.bridge.emit({ phase: 'download', bytes: 5704283, total: 5704283 }); // download was fine… + assert.match(b.textContent, /Downloading… 5\.70 \/ 5\.70 MB/); + rejectInstall(new Error('UPDATE_INSTALL_FAILED: no package installer is available on this device')); + await tick(20); + assert.equal(b.textContent, 'Try again', 'installer failure surfaces instead of hanging'); + assert.match(ctx.ui.toasts.at(-1)?.m, /package installer/); + assert.equal(ctx.ui.toasts.at(-1)?.k, 'err'); + }); + + test('updater: missing install permission → settings guidance + "Enable installs & try again"', async (t) => { + const ctx = await openUpdateSheet(t); + ctx.bridge.impl = () => Promise.reject(new Error('UPDATE_INSTALL_PERMISSION_REQUIRED: allow "Install unknown apps" for DSMNRU PYQ, then tap Try again')); + const b = ctx.now(); + b.click(); + await tick(); + assert.equal(b.textContent, 'Enable installs & try again'); + assert.match(ctx.ui.toasts.at(-1)?.m, /Install unknown apps/); + // after granting in Settings, retry installs + ctx.bridge.impl = () => Promise.resolve({ ok: true, installerOpened: true }); + b.click(); + await tick(); + assert.equal(b.textContent, 'Open installer'); + }); + + test('updater: WATCHDOG — a wedged native call cannot park the UI on "Downloading…"', async (t) => { + const ctx = await openUpdateSheet(t); + ctx._setUpdateWatchdogMs(40); // test hook (default 90s) + t.after(() => ctx._setUpdateWatchdogMs(90000)); + ctx.bridge.impl = () => new Promise(() => {}); // never settles + const b = ctx.now(); + b.click(); + await tick(120); + assert.equal(b.disabled, false); + assert.equal(b.textContent, 'Try again'); + assert.match(ctx.ui.toasts.at(-1)?.m, /taking too long/); + // even if native resolves LATE, the UI is not flipped back to busy states + await tick(30); + assert.equal(b.textContent, 'Try again'); + }); + + test('updater: OPTIONAL update keeps "Later"; MANDATORY update has only "Update Now" and still retries', async (t) => { + const optional = await openUpdateSheet(t, { mandatory: false }); + assert.ok(optional.later(), 'Later button present for optional updates'); + assert.equal(optional.now().textContent, 'Update Now'); + optional.later().click(); + assert.equal(optional.now(), null, 'Later closes the sheet'); + + const mandatory = await openUpdateSheet(t, { mandatory: true }); + assert.equal(mandatory.later(), null, 'no Later for mandatory updates'); + mandatory.bridge.impl = () => Promise.reject(new Error('UPDATE_DOWNLOAD_FAILED: HTTP 503')); + mandatory.now().click(); + await tick(); + assert.equal(mandatory.now().textContent, 'Try again', 'mandatory update still offers retry'); + }); +} else { + test('updater UI states (skipped: jsdom not installed)', { skip: true }, () => {}); +} diff --git a/android-app/www/js/native.js b/android-app/www/js/native.js index 41fb07c..b366d6d 100644 --- a/android-app/www/js/native.js +++ b/android-app/www/js/native.js @@ -16,6 +16,11 @@ * free) — only when the user explicitly taps Download. * - share(): the real Android share sheet (ACTION_SEND). navigator.share * does not exist inside the Capacitor WebView, so this is the share action. + * - downloadAndInstall()/onUpdateProgress(): the in-app updater — the + * native layer downloads the official GitHub release APK (real byte + * progress), verifies it and launches the system package installer; + * the plugin call is ALWAYS answered exactly once (resolve or reject), + * so the UI can never sit on "Downloading…" forever. * - Launch/warm deep links from /pyq/ URLs (handled in MainActivity). * * In a plain browser (dev testing, unit harnesses) the fallbacks keep every @@ -37,7 +42,11 @@ function resolveBridge() { let bridge = resolveBridge(); export function isNative() { - if (!bridge) bridge = resolveBridge(); + // Re-resolve on every probe: the injected Capacitor bridge can appear + // AFTER this module is first imported (late bridge injection, test + // harnesses installing a fresh fake per case). Never goes back to null + // once a bridge has been seen. + bridge = resolveBridge() || bridge; return !!(bridge && typeof bridge.openExternal === 'function'); } @@ -128,11 +137,29 @@ export const native = { return { versionName: '', versionCode: 0 }; }, - async downloadAndInstall(url, fileName) { - if (isNative() && typeof bridge.downloadAndInstall === 'function') return bridge.downloadAndInstall({ url, fileName }); + async downloadAndInstall(url, fileName, expectedVersionCode = 0) { + if (isNative() && typeof bridge.downloadAndInstall === 'function') { + return bridge.downloadAndInstall({ url, fileName, expectedVersionCode: Number(expectedVersionCode) || 0 }); + } throw new Error('In-app installation is available only in the Android app'); }, + /** + * Live in-app-updater progress from the native downloader: + * { phase: 'download' | 'verify' | 'install', bytes, total } — REAL bytes + * (total is -1 when the server sends no length). Returns an unsubscribe + * function, like onLink; a no-op outside the Android app. + */ + onUpdateProgress(fn) { + if (isNative() && typeof bridge.addListener === 'function') { + try { + const h = bridge.addListener('updateDownloadProgress', (ev) => fn(ev || {})); + return () => { try { h.remove && h.remove(); } catch { /* ignore */ } }; + } catch { return () => {}; } + } + return () => {}; + }, + /** Save a direct .pdf to the device Downloads via DownloadManager. */ async download(url, fileName) { const safe = httpUrl(url); diff --git a/android-app/www/js/update.js b/android-app/www/js/update.js index 249bd7d..d234fa5 100644 --- a/android-app/www/js/update.js +++ b/android-app/www/js/update.js @@ -12,11 +12,67 @@ export async function checkForUpdate({ force = false, ui = null } = {}) { lastCheck = Date.now(); try { const installed = await native.getAppVersion(); const r = await fetch(`${WORKER_ORIGIN}/api/app-update`, { headers: { Accept: 'application/json' } }); const update = parseUpdate(await r.json(), Number(installed.versionCode)); if (update && ui) showUpdate(update, ui); return update; } catch { return null; } } + +// The native layer now ALWAYS answers downloadAndInstall exactly once +// (resolve or reject, even on internal errors). The watchdog below is the +// belt-and-braces for a wedged bridge: the updater UI must never park on +// "Downloading…" indefinitely. (Test hook lets the suite shrink the window.) +let watchdogMs = 90000; +export function _setUpdateWatchdogMs(ms) { watchdogMs = Number(ms) > 0 ? Number(ms) : 90000; } + +const mb = (b) => (b / 1e6).toFixed(2); +const humanError = (e) => String((e && e.message) || e || 'Update failed').replace(/^[A-Z0-9_]+:\s*/, '') || 'Update failed'; + function showUpdate(update, ui) { const notes = update.releaseNotes.length ? `
    ${update.releaseNotes.map(x => `
  • ${escapeHtml(x)}
  • `).join('')}
` : '

Bug fixes and improvements.

'; const buttons = update.mandatory ? '' : ''; ui.sheet({ title: 'Update Available', content: `

DSMNRU PYQ v${escapeHtml(update.version)}

${notes}
${buttons}
` }); document.querySelector('#update-later')?.addEventListener('click', () => ui.closeSheet()); - document.querySelector('#update-now')?.addEventListener('click', async () => { const b=document.querySelector('#update-now'); b.disabled=true; b.textContent='Downloading…'; try { await native.downloadAndInstall(update.downloadUrl, `dsmnru-pyq-${update.version}.apk`); } catch (e) { b.disabled=false; b.textContent='Try again'; ui.toast(e.message || 'Update failed', 'err'); } }); + document.querySelector('#update-now')?.addEventListener('click', () => runInstall(update, ui)); +} + +/** + * One install attempt, driven by the native layer's REAL phases: + * Downloading… (actual bytes) → Verifying… → Starting installer… → then the + * button leaves the busy state for good. Every failure — download, + * verification, permission, or installer launch — resolves into a re-enabled + * retry button plus a toast, so the UI can never stick on "Downloading…". + */ +async function runInstall(update, ui) { + const b = document.querySelector('#update-now'); + if (!b || b.dataset.busy === '1') return; + b.dataset.busy = '1'; + b.disabled = true; + b.textContent = 'Downloading…'; + let settled = false; + let watchdog = 0; + let stopProgress = () => {}; + const stall = () => fail(new Error('UPDATE_WATCHDOG: update is taking too long — check your connection and try again')); + const arm = () => { clearTimeout(watchdog); watchdog = setTimeout(stall, watchdogMs); }; + const settle = (after) => { if (settled) return; settled = true; clearTimeout(watchdog); stopProgress(); delete b.dataset.busy; if (after) after(); }; + const fail = (e) => settle(() => { + b.disabled = false; + b.textContent = /INSTALL_PERMISSION_REQUIRED/.test(String((e && e.message) || '')) ? 'Enable installs & try again' : 'Try again'; + ui.toast(humanError(e), 'err'); + }); + stopProgress = native.onUpdateProgress((ev) => { + if (settled || !ev) return; + if (ev.phase === 'download') b.textContent = ev.total > 0 ? `Downloading… ${mb(ev.bytes)} / ${mb(ev.total)} MB` : `Downloading… ${mb(ev.bytes)} MB`; + else if (ev.phase === 'verify') b.textContent = 'Verifying…'; + else if (ev.phase === 'install') b.textContent = 'Starting installer…'; + if (ev.phase) arm(); // native is alive — keep deferring the watchdog + }); + arm(); + try { + await native.downloadAndInstall(update.downloadUrl, `dsmnru-pyq-${update.version}.apk`, update.versionCode); + settle(() => { + // The system install screen is up (or the user was taken to the exact + // settings screen to allow installs). Reopening is instant — the + // verified APK stays cached — so a cancelled installer can be + // relaunched from this same button instead of a dead end. + b.disabled = false; + b.textContent = 'Open installer'; + }); + } catch (e) { fail(e); } } function escapeHtml(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }