diff --git a/.gitea/workflows/android-apk.yml b/.gitea/workflows/android-apk.yml new file mode 100644 index 0000000000..ed35fa79c9 --- /dev/null +++ b/.gitea/workflows/android-apk.yml @@ -0,0 +1,34 @@ +name: Fork Android APK + +on: + push: + tags: + - apk-* + +concurrency: + group: android-apk-release + cancel-in-progress: false + +jobs: + release: + runs-on: android-apk + env: + T3CODE_APK_RELEASE_TAG: ${{ gitea.ref_name }} + T3CODE_APK_REPOSITORY_URL: ${{ gitea.server_url }}/${{ gitea.repository }} + T3CODE_APK_RELEASES_URL: ${{ vars.APK_RELEASES_URL }} + steps: + - uses: https://github.com/actions/checkout@v4 + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Build and sign APK + env: + APK_KEYSTORE_BASE64: ${{ secrets.APK_KEYSTORE_BASE64 }} + APK_KEYSTORE_PASSWORD: ${{ secrets.APK_KEYSTORE_PASSWORD }} + APK_KEY_ALIAS: ${{ secrets.APK_KEY_ALIAS }} + APK_KEY_PASSWORD: ${{ secrets.APK_KEY_PASSWORD }} + run: bash scripts/build-fork-apk.sh + - name: Publish repository release + env: + APK_RELEASE_TOKEN: ${{ secrets.APK_RELEASE_TOKEN }} + APK_RELEASE_COMMIT: ${{ gitea.sha }} + run: node scripts/publish-fork-apk.ts diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 5daaa64a79..16d384219b 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -1,6 +1,10 @@ import type { ExpoConfig } from "expo/config"; import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts"; +import { + parseAndroidApkReleaseTag, + resolveAndroidApkRepository, +} from "../../scripts/lib/android-apk-release.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; type AppVariant = "development" | "preview" | "production"; @@ -9,6 +13,11 @@ const repoEnv = loadRepoEnv(); Object.assign(process.env, repoEnv); const APP_VARIANT = resolveAppVariant(repoEnv.APP_VARIANT); +const apkReleaseTag = repoEnv.T3CODE_APK_RELEASE_TAG; +const apkVersionCode = apkReleaseTag ? parseAndroidApkReleaseTag(apkReleaseTag) : undefined; +const apkRepository = repoEnv.T3CODE_APK_REPOSITORY_URL + ? resolveAndroidApkRepository(repoEnv.T3CODE_APK_REPOSITORY_URL) + : undefined; const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1"; const runtimeVersionPolicy = process.env.MOBILE_VERSION_POLICY ?? @@ -225,7 +234,10 @@ const config: ExpoConfig = { icon: variant.assets.appIcon, userInterfaceStyle: "automatic", updates: { - enabled: repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0", + enabled: + apkRepository === undefined && + apkVersionCode === undefined && + repoEnv.T3CODE_MOBILE_UPDATES_ENABLED !== "0", url: "https://u.expo.dev/d763fcb8-d37c-41ea-a773-b54a0ab4a454", checkAutomatically: "ON_LOAD", fallbackToCacheTimeout: 0, @@ -274,8 +286,10 @@ const config: ExpoConfig = { }, }, android: { + ...(apkVersionCode === undefined ? {} : { versionCode: apkVersionCode }), icon: variant.assets.appIcon, package: variant.androidPackage, + ...(apkRepository ? { permissions: ["android.permission.REQUEST_INSTALL_PACKAGES"] } : {}), ...(repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE ? { googleServicesFile: repoEnv.T3CODE_ANDROID_GOOGLE_SERVICES_FILE } : {}), @@ -429,6 +443,7 @@ const config: ExpoConfig = { ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { + apkReleaseApiUrl: apkRepository?.apiUrl || null, appVariant: APP_VARIANT, iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { diff --git a/apps/mobile/modules/t3-native-controls/android/build.gradle b/apps/mobile/modules/t3-native-controls/android/build.gradle index ba0622b7f0..a785befab2 100644 --- a/apps/mobile/modules/t3-native-controls/android/build.gradle +++ b/apps/mobile/modules/t3-native-controls/android/build.gradle @@ -16,4 +16,5 @@ android { dependencies { implementation project(':expo-modules-core') + testImplementation 'junit:junit:4.13.2' } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt index baea4a9590..c6b18fce60 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt @@ -1,15 +1,78 @@ package expo.modules.t3nativecontrols +import android.content.ComponentName import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import android.os.Build import androidx.core.content.FileProvider import expo.modules.kotlin.Promise import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition import java.io.File import java.net.URI +import java.security.MessageDigest + +private const val FILE_PREVIEW_REQUEST_CODE = 7343 +private const val APK_INSTALL_REQUEST_CODE = 7344 +private const val MAX_ANDROID_VERSION_CODE = 2_100_000_000L +private const val APK_MIME_TYPE = "application/vnd.android.package-archive" + +internal data class ApkIdentity( + val packageName: String, + val versionCode: Long, + val signerDigests: Set +) + +internal data class InstallerCandidate( + val packageName: String, + val className: String, + val applicationFlags: Int +) { + val componentKey = "$packageName/$className" +} + +internal fun validateApkIdentity( + installed: ApkIdentity, + archive: ApkIdentity, + expectedVersionCode: Long +) { + require(expectedVersionCode in 1..MAX_ANDROID_VERSION_CODE) { + "The expected APK version is invalid." + } + require(archive.packageName == installed.packageName) { + "The downloaded APK belongs to a different app." + } + require(archive.versionCode == expectedVersionCode) { + "The downloaded APK version does not match the selected update." + } + require(archive.versionCode > installed.versionCode) { + "The downloaded APK is not newer than the installed app." + } + require(archive.signerDigests.isNotEmpty() && archive.signerDigests == installed.signerDigests) { + "The downloaded APK signing certificate does not match the installed app." + } +} + +internal fun selectTrustedInstaller( + candidates: List, + resolvedComponentKey: String? +): InstallerCandidate? { + val trusted = candidates + .filter { candidate -> + candidate.packageName.isNotBlank() && + candidate.className.isNotBlank() && + candidate.applicationFlags and + (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0 + } + .sortedBy(InstallerCandidate::componentKey) + return trusted.firstOrNull { it.componentKey == resolvedComponentKey } ?: trusted.firstOrNull() +} class T3NativeControlsModule : Module() { private var filePreviewPromise: Promise? = null + private var apkInstallPromise: Promise? = null @Suppress("TooGenericExceptionCaught") // Clear the pending promise before rethrowing. override fun definition() = ModuleDefinition { @@ -31,17 +94,37 @@ class T3NativeControlsModule : Module() { } filePreviewPromise = promise try { - activity.startActivityForResult(intent, 7343) + activity.startActivityForResult(intent, FILE_PREVIEW_REQUEST_CODE) } catch (error: Exception) { filePreviewPromise = null throw error } } + AsyncFunction("installApk") { uri: String, expectedVersionCode: Long, promise: Promise -> + launchVerifiedApkInstaller(uri, expectedVersionCode, promise) + } + + Function("getInstalledVersionCode") { + val context = appContext.reactContext ?: error("The app is not active.") + val installedInfo = getInstalledPackageInfo( + context.packageManager, + context.packageName, + 0 + ) + packageVersionCode(installedInfo) + } + OnActivityResult { _, (requestCode) -> - if (requestCode == 7343) { - filePreviewPromise?.resolve(null) - filePreviewPromise = null + when (requestCode) { + FILE_PREVIEW_REQUEST_CODE -> { + filePreviewPromise?.resolve(null) + filePreviewPromise = null + } + APK_INSTALL_REQUEST_CODE -> { + apkInstallPromise?.resolve(null) + apkInstallPromise = null + } } } @@ -77,4 +160,95 @@ class T3NativeControlsModule : Module() { ?.writeText(scene) } } + + @Suppress("DEPRECATION", "TooGenericExceptionCaught") + private fun launchVerifiedApkInstaller(uri: String, expectedVersionCode: Long, promise: Promise) { + check(apkInstallPromise == null) { "An APK installation is already open." } + val activity = appContext.currentActivity ?: error("The app is not active.") + val file = File(URI(uri)).canonicalFile + require(file.isFile) { "The downloaded APK is no longer available." } + val packageManager = activity.packageManager + val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + PackageManager.GET_SIGNING_CERTIFICATES + } else { + PackageManager.GET_SIGNATURES + } + val installedInfo = getInstalledPackageInfo(packageManager, activity.packageName, flags) + val archiveInfo = packageManager.getPackageArchiveInfo(file.path, flags) + ?: error("Android could not parse the downloaded APK.") + validateApkIdentity( + packageIdentity(installedInfo), + packageIdentity(archiveInfo), + expectedVersionCode + ) + + val contentUri = FileProvider.getUriForFile( + activity, + "${activity.packageName}.FileSystemFileProvider", + file + ) + val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE).apply { + setDataAndType(contentUri, APK_MIME_TYPE) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + putExtra(Intent.EXTRA_RETURN_RESULT, true) + } + val resolvedComponentKey = packageManager + .resolveActivity(installIntent, PackageManager.MATCH_DEFAULT_ONLY) + ?.activityInfo + ?.let { "${it.packageName}/${it.name}" } + val candidates = packageManager + .queryIntentActivities(installIntent, PackageManager.MATCH_DEFAULT_ONLY) + .mapNotNull { resolved -> + val info = resolved.activityInfo ?: return@mapNotNull null + InstallerCandidate(info.packageName, info.name, info.applicationInfo.flags) + } + val installer = selectTrustedInstaller(candidates, resolvedComponentKey) + ?: error("No trusted Android package installer is available.") + installIntent.component = ComponentName(installer.packageName, installer.className) + activity.grantUriPermission( + installer.packageName, + contentUri, + Intent.FLAG_GRANT_READ_URI_PERMISSION + ) + + apkInstallPromise = promise + try { + activity.startActivityForResult(installIntent, APK_INSTALL_REQUEST_CODE) + } catch (error: Exception) { + apkInstallPromise = null + throw error + } + } + + @Suppress("DEPRECATION") + private fun getInstalledPackageInfo( + packageManager: PackageManager, + packageName: String, + flags: Int + ): PackageInfo = packageManager.getPackageInfo(packageName, flags) + + @Suppress("DEPRECATION") + private fun packageIdentity(info: PackageInfo): ApkIdentity { + val signatures = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + info.signingInfo?.apkContentsSigners?.toList().orEmpty() + } else { + info.signatures?.toList().orEmpty() + } + val digests = signatures.mapTo(mutableSetOf()) { signature -> + MessageDigest + .getInstance("SHA-256") + .digest(signature.toByteArray()) + .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) } + } + require(digests.isNotEmpty()) { "Android could not read the APK signing certificate." } + return ApkIdentity(info.packageName, packageVersionCode(info), digests) + } + + @Suppress("DEPRECATION") + private fun packageVersionCode(info: PackageInfo): Long = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + info.longVersionCode + } else { + info.versionCode.toLong() + } } diff --git a/apps/mobile/modules/t3-native-controls/android/src/test/java/expo/modules/t3nativecontrols/ApkInstallerSecurityTest.kt b/apps/mobile/modules/t3-native-controls/android/src/test/java/expo/modules/t3nativecontrols/ApkInstallerSecurityTest.kt new file mode 100644 index 0000000000..9668f79418 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/test/java/expo/modules/t3nativecontrols/ApkInstallerSecurityTest.kt @@ -0,0 +1,66 @@ +package expo.modules.t3nativecontrols + +import android.content.pm.ApplicationInfo +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test + +class ApkInstallerSecurityTest { + private val installed = ApkIdentity("com.t3tools.t3code", 50, setOf("signer-a")) + + @Test + fun acceptsOnlyTheExpectedNewerVersionOfTheSameSignedPackage() { + validateApkIdentity( + installed, + ApkIdentity("com.t3tools.t3code", 51, setOf("signer-a")), + 51 + ) + } + + @Test + fun rejectsPackageVersionAndSignerMismatches() { + assertThrows(IllegalArgumentException::class.java) { + validateApkIdentity(installed, ApkIdentity("example.other", 51, setOf("signer-a")), 51) + } + assertThrows(IllegalArgumentException::class.java) { + validateApkIdentity( + installed, + ApkIdentity("com.t3tools.t3code", 52, setOf("signer-a")), + 51 + ) + } + assertThrows(IllegalArgumentException::class.java) { + validateApkIdentity( + installed, + ApkIdentity("com.t3tools.t3code", 51, setOf("signer-b")), + 51 + ) + } + assertThrows(IllegalArgumentException::class.java) { + validateApkIdentity(installed, installed, 50) + } + } + + @Test + fun selectsOnlyAConfiguredSystemInstallerActivity() { + val untrusted = InstallerCandidate("example.viewer", "ViewerActivity", 0) + val updatedSystem = InstallerCandidate( + "android.installer.updated", + "InstallActivity", + ApplicationInfo.FLAG_UPDATED_SYSTEM_APP + ) + val system = InstallerCandidate( + "android.installer", + "InstallActivity", + ApplicationInfo.FLAG_SYSTEM + ) + + assertEquals( + updatedSystem, + selectTrustedInstaller(listOf(untrusted, system, updatedSystem), updatedSystem.componentKey) + ) + assertEquals(system, selectTrustedInstaller(listOf(untrusted, system), null)) + assertNull(selectTrustedInstaller(listOf(untrusted), untrusted.componentKey)) + } +} diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 7768909150..caef4e2707 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -55,6 +55,7 @@ import { SettingsRow } from "./components/SettingsRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic"; +import { SoftwareUpdateSection } from "./SoftwareUpdateSection"; import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync"; type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported"; @@ -145,6 +146,7 @@ function LocalSettingsRouteScreen() { + @@ -566,6 +568,7 @@ function ConfiguredSettingsRouteScreen() { + diff --git a/apps/mobile/src/features/settings/SoftwareUpdateSection.tsx b/apps/mobile/src/features/settings/SoftwareUpdateSection.tsx new file mode 100644 index 0000000000..221205f1e0 --- /dev/null +++ b/apps/mobile/src/features/settings/SoftwareUpdateSection.tsx @@ -0,0 +1,193 @@ +import Constants from "expo-constants"; +import { useState } from "react"; +import { Alert, Platform, View } from "react-native"; + +import { AppText as Text } from "../../components/AppText"; +import { + AndroidApkUpdateError, + type AndroidApkUpdatePhase, + downloadTrustedAndroidApk, + runAndroidApkUpdate, +} from "./androidApkUpdater"; +import { SettingsRow } from "./components/SettingsRow"; +import { SettingsSection } from "./components/SettingsSection"; + +type UpdateStatus = + | "idle" + | AndroidApkUpdatePhase + | "already-in-progress" + | "up-to-date" + | "unavailable" + | "installer-launched" + | "failed"; + +const STATUS_LABEL: Record = { + idle: undefined, + checking: "Checking…", + downloading: "Downloading…", + installing: "Opening installer…", + "already-in-progress": "Update in progress", + "up-to-date": "Up to date", + unavailable: "No release available", + "installer-launched": "Installer launched", + failed: "Try again", +}; + +async function fetchReleasePage( + apiUrl: string, + init: { credentials: "omit"; redirect: "error"; signal: AbortSignal }, +) { + const { fetch: expoFetch } = await import("expo/fetch"); + return expoFetch(apiUrl, { ...init, headers: { Accept: "application/json" } }); +} + +async function downloadApk( + downloadUrl: string, + versionCode: number, + expectedSize: number, +): Promise { + const { randomUUID } = await import("expo-crypto"); + const { fetch: expoFetch } = await import("expo/fetch"); + const { Directory, File, Paths } = await import("expo-file-system"); + const cache = new Directory(Paths.cache, "t3-apk-updates"); + cache.create({ idempotent: true, intermediates: true }); + return downloadTrustedAndroidApk(downloadUrl, versionCode, expectedSize, { + fetchApk: (url, init) => expoFetch(url, init), + createTemporaryFile: (candidateVersionCode) => { + const temporary = new File(cache, `t3code-apk-${candidateVersionCode}-${randomUUID()}.part`); + temporary.create(); + return temporary; + }, + openTemporaryFileStream: (file) => { + const writable = file as { writableStream(): WritableStream }; + return writable.writableStream(); + }, + finalizeTemporaryFile: async (file, candidateVersionCode) => { + const temporary = file as InstanceType; + const destination = new File(cache, `t3code-apk-${candidateVersionCode}.apk`); + await temporary.move(destination, { overwrite: true }); + return destination.uri; + }, + deleteTemporaryFile: (file) => { + const temporary = file as InstanceType; + if (temporary.exists) temporary.delete(); + }, + pruneObsoleteFiles: (candidateVersionCode) => { + try { + const currentName = `t3code-apk-${candidateVersionCode}.apk`; + for (const entry of cache.list()) { + if ( + entry instanceof File && + entry.name !== currentName && + (/^t3code-apk-\d+\.apk$/.test(entry.name) || + /^t3code-apk-\d+-[0-9a-f-]+\.part$/.test(entry.name)) + ) { + entry.delete(); + } + } + } catch { + // Cache pruning must not block an otherwise verified download from being installed. + } + }, + }); +} + +async function getInstalledVersionCode(): Promise { + const { requireNativeModule } = await import("expo"); + return requireNativeModule<{ + getInstalledVersionCode(): number; + }>("T3NativeControls").getInstalledVersionCode(); +} + +async function launchPackageInstaller( + localUri: string, + expectedVersionCode: number, +): Promise { + const { requireNativeModule } = await import("expo"); + await requireNativeModule<{ + installApk(uri: string, expectedVersionCode: number): Promise; + }>("T3NativeControls").installApk(localUri, expectedVersionCode); +} + +export function SoftwareUpdateSection() { + const [status, setStatus] = useState("idle"); + const apiUrl = Constants.expoConfig?.extra?.apkReleaseApiUrl; + const manifestVersionCode = + Constants.platform?.android?.versionCode ?? Constants.expoConfig?.android?.versionCode; + + if (Platform.OS !== "android" || typeof apiUrl !== "string" || !apiUrl) return null; + + const update = async () => { + try { + const result = await runAndroidApkUpdate({ + apiUrl, + getInstalledVersionCode, + fetchReleasePage, + downloadApk, + installApk: launchPackageInstaller, + onPhase: setStatus, + }); + if (result.kind === "already-in-progress") { + setStatus("already-in-progress"); + Alert.alert( + "Update already in progress", + "Another update check, download, or installer launch is already in progress.", + ); + } else if (result.kind === "no-compatible-release") { + setStatus("unavailable"); + Alert.alert( + "No APK release available", + "The repository does not currently have a compatible published Android APK release.", + ); + } else if (result.kind === "up-to-date") { + setStatus("up-to-date"); + Alert.alert( + "T3 Code is up to date", + `Installed build ${result.installedVersionCode} is the newest available APK.`, + ); + } else { + setStatus("installer-launched"); + } + } catch (error) { + setStatus("failed"); + Alert.alert( + error instanceof AndroidApkUpdateError && error.stage === "install" + ? "Could not open installer" + : error instanceof AndroidApkUpdateError && error.stage === "download" + ? "Could not download update" + : "Could not check for updates", + error instanceof AndroidApkUpdateError + ? error.userMessage + : "The update could not be completed. Please try again.", + ); + } + }; + + const busy = status === "checking" || status === "downloading" || status === "installing"; + + return ( + + + + Installed version + + {Constants.expoConfig?.version ?? "Unknown"} + {manifestVersionCode ? ` (${manifestVersionCode})` : ""} + + + void update()} + /> + + + Checks the repository, downloads a newer APK inside T3 Code, then opens Android’s installer + for your confirmation. Android may require permission to install unknown apps from T3 Code. + Updates must use the same signing key as your installed app. + + + ); +} diff --git a/apps/mobile/src/features/settings/androidApkUpdater.test.ts b/apps/mobile/src/features/settings/androidApkUpdater.test.ts new file mode 100644 index 0000000000..82ef00fc42 --- /dev/null +++ b/apps/mobile/src/features/settings/androidApkUpdater.test.ts @@ -0,0 +1,636 @@ +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + AndroidApkUpdateError, + downloadTrustedAndroidApk, + isNewerAndroidVersion, + runAndroidApkUpdate, + selectLatestAndroidApkRelease, +} from "./androidApkUpdater"; + +const API_URL = "https://git.example.com/api/v1/repos/alex/t3code/releases"; +const SUBPATH_API_URL = "https://git.example.com/git/api/v1/repos/alex/t3code/releases"; + +function attachmentUuid(versionCode: number): string { + return `00000000-0000-4000-8000-${String(versionCode).padStart(12, "0")}`; +} + +function release( + versionCode: number, + overrides: Record = {}, +): Record { + return { + id: versionCode, + tag_name: `apk-${versionCode}`, + name: `Android APK · build ${versionCode}`, + draft: false, + prerelease: false, + assets: [ + { + id: versionCode, + name: `t3code-apk-${versionCode}.apk`, + size: 4, + browser_download_url: `https://git.example.com/attachments/${attachmentUuid(versionCode)}`, + }, + ], + ...overrides, + }; +} + +function releasePageResponse( + url: string, + items: ReadonlyArray, + totalCount: number | string, + overrides: Partial<{ + ok: boolean; + status: number; + url: string; + redirected: boolean; + }> = {}, +) { + return { + ok: true, + status: 200, + url, + redirected: false, + headers: { + get: (name: string) => (name.toLowerCase() === "x-total-count" ? String(totalCount) : null), + }, + json: vi.fn().mockResolvedValue(items), + ...overrides, + }; +} + +function successfulReleaseFetch(items: ReadonlyArray) { + return vi.fn(async (url: string) => releasePageResponse(url, items, items.length)); +} + +function downloadResponse( + url: string, + chunks: ReadonlyArray, + contentLength: string | null = null, +) { + return { + ok: true, + status: 200, + url, + redirected: false, + headers: { + get: (name: string) => (name.toLowerCase() === "content-length" ? contentLength : null), + }, + body: new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), + }; +} + +function downloadDependencies(response: ReturnType) { + const temporaryFile = { uri: "file:///cache/t3code-apk-51-unique.part" }; + const written: Uint8Array[] = []; + return { + temporaryFile, + written, + dependencies: { + fetchApk: vi.fn().mockResolvedValue(response), + createTemporaryFile: vi.fn().mockReturnValue(temporaryFile), + openTemporaryFileStream: vi.fn().mockReturnValue( + new WritableStream({ + write(chunk) { + written.push(chunk); + }, + }), + ), + finalizeTemporaryFile: vi.fn().mockResolvedValue("file:///cache/t3code-apk-51.apk"), + deleteTemporaryFile: vi.fn(), + pruneObsoleteFiles: vi.fn(), + }, + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("Android APK release selection", () => { + it("selects the highest valid published release and retains its trusted size", () => { + const selected = selectLatestAndroidApkRelease( + [ + release(42), + release(105, { prerelease: true }), + release(91), + release(120, { draft: true }), + release(75), + ], + API_URL, + ); + + expect(selected).toEqual({ + versionCode: 91, + downloadUrl: `https://git.example.com/attachments/${attachmentUuid(91)}`, + expectedSize: 4, + }); + }); + + it("requires matching release and asset identity metadata", () => { + expect( + selectLatestAndroidApkRelease( + [ + release(20, { id: 0 }), + release(21, { tag_name: "v21" }), + release(22, { name: "Unexpected release" }), + release(23, { assets: [] }), + release(24, { + assets: [ + { + id: 24, + name: "t3code-apk-23.apk", + size: 4, + browser_download_url: `https://git.example.com/attachments/${attachmentUuid(24)}`, + }, + ], + }), + release(25, { assets: [{ id: 0, name: "t3code-apk-25.apk", size: 4 }] }), + ], + API_URL, + ), + ).toBeNull(); + }); + + it("rejects same-origin assets outside the exact Gitea attachment path", () => { + for (const browser_download_url of [ + `https://git.example.com/alex/t3code/releases/download/apk-5/t3code-apk-5.apk`, + `https://git.example.com/api/v1/repos/alex/t3code/releases/assets/5`, + `https://git.example.com/other/attachments/${attachmentUuid(5)}`, + `https://git.example.com/attachments/not-a-uuid`, + ]) { + expect( + selectLatestAndroidApkRelease( + [ + release(5, { + assets: [ + { + id: 5, + name: "t3code-apk-5.apk", + size: 4, + browser_download_url, + }, + ], + }), + ], + API_URL, + ), + ).toBeNull(); + } + }); + + it("uses the exact configured Gitea subpath for attachments", () => { + const valid = release(5, { + assets: [ + { + id: 5, + name: "t3code-apk-5.apk", + size: 4, + browser_download_url: `https://git.example.com/git/attachments/${attachmentUuid(5)}`, + }, + ], + }); + expect(selectLatestAndroidApkRelease([valid], SUBPATH_API_URL)?.versionCode).toBe(5); + expect(selectLatestAndroidApkRelease([valid], API_URL)).toBeNull(); + }); + + it("rejects assets with invalid or excessive declared sizes", () => { + for (const size of [0, -1, 1.5, 500 * 1024 * 1024 + 1]) { + expect( + selectLatestAndroidApkRelease( + [ + release(5, { + assets: [ + { + id: 5, + name: "t3code-apk-5.apk", + size, + browser_download_url: `https://git.example.com/attachments/${attachmentUuid(5)}`, + }, + ], + }), + ], + API_URL, + ), + ).toBeNull(); + } + }); + + it("rejects non-HTTPS, cross-origin, credential-bearing, and queried asset URLs", () => { + const unsafeUrls = [ + `http://git.example.com/attachments/${attachmentUuid(5)}`, + `https://evil.example/attachments/${attachmentUuid(5)}`, + `https://user:secret@git.example.com/attachments/${attachmentUuid(5)}`, + `https://git.example.com/attachments/${attachmentUuid(5)}?token=secret`, + ]; + + for (const browser_download_url of unsafeUrls) { + expect( + selectLatestAndroidApkRelease( + [ + release(5, { + assets: [{ id: 5, name: "t3code-apk-5.apk", size: 4, browser_download_url }], + }), + ], + API_URL, + ), + ).toBeNull(); + } + }); + + it("requires a trusted unqueried HTTPS API URL", () => { + expect(() => selectLatestAndroidApkRelease([], "http://git.example.com/releases")).toThrow( + /HTTPS/, + ); + expect(() => + selectLatestAndroidApkRelease([], "https://user:secret@git.example.com/releases"), + ).toThrow(/credentials/); + expect(() => selectLatestAndroidApkRelease([], `${API_URL}?token=secret`)).toThrow(/query/); + }); + + it("compares integer Android version codes", () => { + expect(isNewerAndroidVersion(11, 10)).toBe(true); + expect(isNewerAndroidVersion(10, 10)).toBe(false); + expect(isNewerAndroidVersion(9, 10)).toBe(false); + expect(() => isNewerAndroidVersion(11, 0)).toThrow(/installed version code/); + }); +}); + +describe("Android APK update orchestration", () => { + it("rejects a cross-origin redirected API response before reading JSON", async () => { + const requested = `${API_URL}?limit=50&page=1`; + const response = releasePageResponse(requested, [release(51)], 1, { + redirected: true, + url: "https://evil.example/releases", + }); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: vi.fn().mockResolvedValue(response), + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).rejects.toMatchObject({ name: "AndroidApkUpdateError", stage: "check" }); + expect(response.json).not.toHaveBeenCalled(); + }); + + it("rejects a non-redirected API final URL mismatch before reading JSON", async () => { + const response = releasePageResponse(`${API_URL}?limit=50&page=1`, [release(51)], 1, { + url: "https://evil.example/api/v1/repos/alex/t3code/releases?limit=50&page=1", + }); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: vi.fn().mockResolvedValue(response), + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).rejects.toMatchObject({ stage: "check" }); + expect(response.json).not.toHaveBeenCalled(); + }); + + it("passes redirect rejection, omitted credentials, and an abort signal to release fetches", async () => { + const fetchReleasePage = vi.fn(async (url: string) => releasePageResponse(url, [], 0)); + await runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage, + downloadApk: vi.fn(), + installApk: vi.fn(), + }); + + expect(fetchReleasePage).toHaveBeenCalledWith(`${API_URL}?limit=50&page=1`, { + credentials: "omit", + redirect: "error", + signal: expect.any(AbortSignal), + }); + }); + + it("uses X-Total-Count to fetch exactly 20 full pages for 1,000 releases", async () => { + const requestedUrls: string[] = []; + const fetchReleasePage = vi.fn(async (url: string) => { + requestedUrls.push(url); + const page = Number(new URL(url).searchParams.get("page")); + const start = (page - 1) * 50 + 1; + return releasePageResponse( + url, + Array.from({ length: 50 }, (_, index) => release(start + index)), + 1_000, + ); + }); + const downloadApk = vi.fn().mockResolvedValue("file:///cache/update.apk"); + const installApk = vi.fn().mockResolvedValue(undefined); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage, + downloadApk, + installApk, + }), + ).resolves.toEqual({ kind: "installer-launched", versionCode: 1_000 }); + expect(requestedUrls).toHaveLength(20); + expect(new URL(requestedUrls.at(-1)!).searchParams.get("page")).toBe("20"); + expect(downloadApk).toHaveBeenCalledWith( + `https://git.example.com/attachments/${attachmentUuid(1_000)}`, + 1_000, + 4, + ); + expect(installApk).toHaveBeenCalledWith("file:///cache/update.apk", 1_000); + }); + + it("validates every page length and the final aggregate count", async () => { + const fetchReleasePage = vi.fn(async (url: string) => + releasePageResponse( + url, + Array.from({ length: 49 }, (_, index) => release(index + 1)), + 50, + ), + ); + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(1), + fetchReleasePage, + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).rejects.toMatchObject({ stage: "check" }); + }); + + it("rejects a changed X-Total-Count on a later page", async () => { + const fetchReleasePage = vi.fn(async (url: string) => { + const page = Number(new URL(url).searchParams.get("page")); + const items = + page === 1 ? Array.from({ length: 50 }, (_, index) => release(index + 1)) : [release(51)]; + return releasePageResponse(url, items, page === 1 ? 51 : 52); + }); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(1), + fetchReleasePage, + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).rejects.toMatchObject({ stage: "check" }); + }); + + it("rejects a duplicate positive release ID across pages", async () => { + const fetchReleasePage = vi.fn(async (url: string) => { + const page = Number(new URL(url).searchParams.get("page")); + const items = + page === 1 + ? Array.from({ length: 50 }, (_, index) => release(index + 1)) + : [release(50, { tag_name: "apk-51", name: "Android APK · build 51" })]; + return releasePageResponse(url, items, 51); + }); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(1), + fetchReleasePage, + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).rejects.toMatchObject({ stage: "check" }); + }); + + it("uses the native installed version value for update selection", async () => { + const getInstalledVersionCode = vi.fn().mockResolvedValue(51); + const downloadApk = vi.fn(); + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode, + fetchReleasePage: successfulReleaseFetch([release(51)]), + downloadApk, + installApk: vi.fn(), + }), + ).resolves.toEqual({ + kind: "up-to-date", + installedVersionCode: 51, + latestVersionCode: 51, + }); + expect(getInstalledVersionCode).toHaveBeenCalledOnce(); + expect(downloadApk).not.toHaveBeenCalled(); + }); + + it("reports the installed build when it is newer than the latest release", async () => { + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(60), + fetchReleasePage: successfulReleaseFetch([release(50)]), + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).resolves.toEqual({ + kind: "up-to-date", + installedVersionCode: 60, + latestVersionCode: 50, + }); + }); + + it("passes the trusted release size to download and expected version to the installer", async () => { + const downloadApk = vi.fn().mockResolvedValue("content://trusted/update.apk"); + const installApk = vi.fn().mockResolvedValue(undefined); + await runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: successfulReleaseFetch([release(51)]), + downloadApk, + installApk, + }); + expect(downloadApk).toHaveBeenCalledWith( + `https://git.example.com/attachments/${attachmentUuid(51)}`, + 51, + 4, + ); + expect(installApk).toHaveBeenCalledWith("content://trusted/update.apk", 51); + }); + + it("aborts a stalled API request and releases the module lock", async () => { + vi.useFakeTimers(); + const fetchReleasePage = vi.fn( + (_url: string, init: { signal: AbortSignal }) => + new Promise((_, reject) => { + init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true }); + }), + ); + const stalled = runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage, + downloadApk: vi.fn(), + installApk: vi.fn(), + }); + const stalledRejection = expect(stalled).rejects.toMatchObject({ stage: "check" }); + await vi.advanceTimersByTimeAsync(60_000); + await stalledRejection; + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: successfulReleaseFetch([]), + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).resolves.toEqual({ kind: "no-compatible-release" }); + }); + + it("cleans up an aborted download and releases the module lock", async () => { + vi.useFakeTimers(); + const downloadUrl = `https://git.example.com/attachments/${attachmentUuid(51)}`; + const fixture = downloadDependencies({ + ...downloadResponse(downloadUrl, []), + body: new ReadableStream({ start() {} }), + }); + const stalled = runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: successfulReleaseFetch([release(51)]), + downloadApk: (url, versionCode, expectedSize) => + downloadTrustedAndroidApk(url, versionCode, expectedSize, fixture.dependencies), + installApk: vi.fn(), + }); + const stalledRejection = expect(stalled).rejects.toMatchObject({ stage: "download" }); + await vi.advanceTimersByTimeAsync(10 * 60_000); + await stalledRejection; + expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile); + + await expect( + runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: successfulReleaseFetch([]), + downloadApk: vi.fn(), + installApk: vi.fn(), + }), + ).resolves.toEqual({ kind: "no-compatible-release" }); + }); + + it.each([ + ["check", { fetchReleasePage: vi.fn().mockRejectedValue(new Error("offline")) }], + [ + "download", + { + fetchReleasePage: successfulReleaseFetch([release(51)]), + downloadApk: vi.fn().mockRejectedValue(new Error("disk full")), + }, + ], + [ + "install", + { + fetchReleasePage: successfulReleaseFetch([release(51)]), + downloadApk: vi.fn().mockResolvedValue("content://trusted/update.apk"), + installApk: vi.fn().mockRejectedValue(new Error("permission denied")), + }, + ], + ] as const)("labels %s failures with a safe user message", async (stage, overrides) => { + const promise = runAndroidApkUpdate({ + apiUrl: API_URL, + getInstalledVersionCode: vi.fn().mockResolvedValue(50), + fetchReleasePage: overrides.fetchReleasePage, + downloadApk: "downloadApk" in overrides ? overrides.downloadApk : vi.fn(), + installApk: "installApk" in overrides ? overrides.installApk : vi.fn(), + }); + + await expect(promise).rejects.toMatchObject({ + name: "AndroidApkUpdateError", + stage, + userMessage: expect.any(String), + }); + await promise.catch((error: unknown) => { + expect(error).toBeInstanceOf(AndroidApkUpdateError); + expect((error as AndroidApkUpdateError).userMessage).not.toMatch( + /offline|disk full|permission denied/, + ); + }); + }); +}); + +describe("Android APK streaming download", () => { + const downloadUrl = `https://git.example.com/attachments/${attachmentUuid(51)}`; + + it("rejects an oversized Content-Length before creating a temporary file", async () => { + const fixture = downloadDependencies( + downloadResponse(downloadUrl, [], String(500 * 1024 * 1024 + 1)), + ); + await expect( + downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies), + ).rejects.toThrow(/size|large|length/i); + expect(fixture.dependencies.createTemporaryFile).not.toHaveBeenCalled(); + }); + + it("rejects redirected and mismatched final download URLs before reading the body", async () => { + for (const overrides of [ + { redirected: true, url: "https://evil.example/update.apk" }, + { redirected: false, url: `https://git.example.com/attachments/${attachmentUuid(52)}` }, + ]) { + const fixture = downloadDependencies({ + ...downloadResponse(downloadUrl, [new Uint8Array([1, 2, 3, 4])], "4"), + ...overrides, + }); + await expect( + downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies), + ).rejects.toThrow(/redirect|URL/i); + expect(fixture.dependencies.createTemporaryFile).not.toHaveBeenCalled(); + } + }); + + it("streams without buffering and accepts the exact trusted byte count", async () => { + const fixture = downloadDependencies( + downloadResponse(downloadUrl, [new Uint8Array([1, 2]), new Uint8Array([3, 4])], "4"), + ); + await expect(downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies)).resolves.toBe( + "file:///cache/t3code-apk-51.apk", + ); + expect(fixture.written).toHaveLength(2); + expect(fixture.dependencies.fetchApk).toHaveBeenCalledWith(downloadUrl, { + credentials: "omit", + redirect: "error", + signal: expect.any(AbortSignal), + }); + }); + + it.each([ + ["overrun", [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5])]], + ["underrun", [new Uint8Array([1, 2, 3])]], + ])("rejects a streaming %s and deletes the partial file", async (_kind, chunks) => { + const fixture = downloadDependencies(downloadResponse(downloadUrl, chunks)); + await expect( + downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies), + ).rejects.toThrow(/size|bytes/i); + expect(fixture.dependencies.finalizeTemporaryFile).not.toHaveBeenCalled(); + expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile); + }); + + it("aborts a stalled body stream and deletes the partial file", async () => { + vi.useFakeTimers(); + const fixture = downloadDependencies({ + ...downloadResponse(downloadUrl, []), + body: new ReadableStream({ start() {} }), + }); + const download = downloadTrustedAndroidApk(downloadUrl, 51, 4, fixture.dependencies); + const downloadRejection = expect(download).rejects.toThrow(/abort|timed out/i); + await vi.advanceTimersByTimeAsync(10 * 60_000); + await downloadRejection; + expect(fixture.dependencies.deleteTemporaryFile).toHaveBeenCalledWith(fixture.temporaryFile); + }); +}); diff --git a/apps/mobile/src/features/settings/androidApkUpdater.ts b/apps/mobile/src/features/settings/androidApkUpdater.ts new file mode 100644 index 0000000000..f16bdd51f6 --- /dev/null +++ b/apps/mobile/src/features/settings/androidApkUpdater.ts @@ -0,0 +1,511 @@ +const MAX_ANDROID_VERSION_CODE = 2_100_000_000; +const GITEA_RELEASE_PAGE_SIZE = 50; +const MAX_GITEA_RELEASE_COUNT = 10_000; +const API_TIMEOUT_MS = 30_000; +const DOWNLOAD_TIMEOUT_MS = 5 * 60_000; +const GITEA_ATTACHMENT_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export const MAX_ANDROID_APK_BYTES = 500 * 1024 * 1024; + +export interface AndroidApkRelease { + readonly versionCode: number; + readonly downloadUrl: string; + readonly expectedSize: number; +} + +export type AndroidApkUpdatePhase = "checking" | "downloading" | "installing"; +export type AndroidApkUpdateErrorStage = "check" | "download" | "install"; + +export type AndroidApkUpdateResult = + | { readonly kind: "already-in-progress" } + | { readonly kind: "no-compatible-release" } + | { + readonly kind: "up-to-date"; + readonly installedVersionCode: number; + readonly latestVersionCode: number; + } + | { readonly kind: "installer-launched"; readonly versionCode: number }; + +export class AndroidApkUpdateError extends Error { + readonly stage: AndroidApkUpdateErrorStage; + readonly userMessage: string; + + constructor(stage: AndroidApkUpdateErrorStage, userMessage: string, cause: unknown) { + super(userMessage, { cause }); + this.name = "AndroidApkUpdateError"; + this.stage = stage; + this.userMessage = userMessage; + } +} + +interface TrustedFetchInit { + readonly credentials: "omit"; + readonly redirect: "error"; + readonly signal: AbortSignal; +} + +interface HeadersLike { + get(name: string): string | null; +} + +interface GiteaReleasePageResponse { + readonly ok: boolean; + readonly status: number; + readonly url: string; + readonly redirected: boolean; + readonly headers: HeadersLike; + json(): Promise; +} + +interface AndroidApkUpdateDependencies { + readonly apiUrl: string; + readonly getInstalledVersionCode: () => Promise; + readonly fetchReleasePage: ( + apiUrl: string, + init: TrustedFetchInit, + ) => Promise; + readonly downloadApk: ( + downloadUrl: string, + versionCode: number, + expectedSize: number, + ) => Promise; + readonly installApk: (localUri: string, expectedVersionCode: number) => Promise; + readonly onPhase?: (phase: AndroidApkUpdatePhase) => void; +} + +interface AndroidApkDownloadResponse { + readonly ok: boolean; + readonly status: number; + readonly url: string; + readonly redirected: boolean; + readonly headers: HeadersLike; + readonly body: ReadableStream | null; +} + +interface AndroidApkDownloadDependencies { + readonly fetchApk: (url: string, init: TrustedFetchInit) => Promise; + readonly createTemporaryFile: (versionCode: number) => unknown; + readonly openTemporaryFileStream: (file: unknown) => WritableStream; + readonly finalizeTemporaryFile: (file: unknown, versionCode: number) => Promise; + readonly deleteTemporaryFile: (file: unknown) => void; + readonly pruneObsoleteFiles: (versionCode: number) => void; +} + +let androidApkUpdateInProgress = false; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isPositiveSafeInteger(value: unknown): value is number { + return typeof value === "number" && Number.isSafeInteger(value) && value > 0; +} + +function validVersionCode(value: number): boolean { + return Number.isSafeInteger(value) && value >= 1 && value <= MAX_ANDROID_VERSION_CODE; +} + +function validApkSize(value: unknown): value is number { + return isPositiveSafeInteger(value) && value <= MAX_ANDROID_APK_BYTES; +} + +function parseVersionCode(tag: unknown): number | null { + if (typeof tag !== "string") return null; + const match = /^apk-([1-9]\d*)$/.exec(tag); + if (!match) return null; + const versionCode = Number(match[1]); + return validVersionCode(versionCode) ? versionCode : null; +} + +function trustedHttpsUrl(rawUrl: string, kind: "API" | "asset"): URL { + let url: URL; + try { + url = new URL(rawUrl); + } catch { + throw new Error(`The update ${kind} URL is invalid.`); + } + if (url.protocol !== "https:") { + throw new Error(`The update ${kind} URL must use HTTPS.`); + } + if (url.username || url.password) { + throw new Error(`The update ${kind} URL must not contain credentials.`); + } + if (url.search || url.hash) { + throw new Error(`The update ${kind} URL must not contain query parameters or fragments.`); + } + return url; +} + +function giteaServerBase(apiUrl: string): { readonly origin: string; readonly path: string } { + const url = trustedHttpsUrl(apiUrl, "API"); + const match = /^(.*)\/api\/v1\/repos\/[^/]+\/[^/]+\/releases\/?$/.exec(url.pathname); + if (!match) throw new Error("The update API URL is not a Gitea repository releases URL."); + return { origin: url.origin, path: match[1] ?? "" }; +} + +function trustedAttachmentUrl(rawUrl: unknown, apiUrl: string): string | null { + if (typeof rawUrl !== "string") return null; + try { + const url = trustedHttpsUrl(rawUrl, "asset"); + const server = giteaServerBase(apiUrl); + if (url.origin !== server.origin) return null; + const prefix = `${server.path}/attachments/`; + if (!url.pathname.startsWith(prefix)) return null; + const uuid = url.pathname.slice(prefix.length); + return GITEA_ATTACHMENT_UUID.test(uuid) ? url.href : null; + } catch { + return null; + } +} + +function urlsAreEquivalent(actualUrl: string, requestedUrl: string): boolean { + try { + return new URL(actualUrl).href === new URL(requestedUrl).href; + } catch { + return false; + } +} + +function validateExactResponseUrl( + response: Pick, + requestedUrl: string, + kind: "release API" | "APK download", +): void { + if (response.redirected) throw new Error(`The ${kind} redirected and was rejected.`); + if (!urlsAreEquivalent(response.url, requestedUrl)) { + throw new Error(`The ${kind} final URL is not the requested trusted URL.`); + } +} + +function giteaReleasePageUrl(apiUrl: string, page: number): string { + giteaServerBase(apiUrl); + const url = new URL(apiUrl); + url.searchParams.set("limit", String(GITEA_RELEASE_PAGE_SIZE)); + url.searchParams.set("page", String(page)); + return url.href; +} + +function parseTotalCount(value: string | null): number { + if (value === null || !/^(0|[1-9]\d*)$/.test(value)) { + throw new TypeError("The repository did not return a valid X-Total-Count header."); + } + const total = Number(value); + if (!Number.isSafeInteger(total) || total > MAX_GITEA_RELEASE_COUNT) { + throw new TypeError("The repository release count exceeds the supported safe limit."); + } + return total; +} + +function validatePageItems( + items: unknown, + expectedLength: number, +): asserts items is ReadonlyArray { + if (!Array.isArray(items) || items.length !== expectedLength) { + throw new TypeError("The repository did not return a valid releases page."); + } +} + +function addUniqueReleaseIds(items: ReadonlyArray, releaseIds: Set): void { + for (const item of items) { + if (!isRecord(item) || !isPositiveSafeInteger(item.id)) continue; + if (releaseIds.has(item.id)) { + throw new TypeError("The repository returned a duplicate release ID during pagination."); + } + releaseIds.add(item.id); + } +} + +async function readExactReleasePage( + pageUrl: string, + expectedLength: number, + expectedTotalCount: number, + fetchReleasePage: AndroidApkUpdateDependencies["fetchReleasePage"], + signal: AbortSignal, +): Promise> { + const response = await fetchReleasePage(pageUrl, { + credentials: "omit", + redirect: "error", + signal, + }); + validateExactResponseUrl(response, pageUrl, "release API"); + if (!response.ok) throw new Error(`Release API returned HTTP ${response.status}.`); + const totalCount = parseTotalCount(response.headers.get("X-Total-Count")); + if (totalCount !== expectedTotalCount) { + throw new TypeError("The repository release total changed during pagination."); + } + const items = await response.json(); + validatePageItems(items, expectedLength); + return items; +} + +async function fetchAllGiteaReleases( + apiUrl: string, + fetchReleasePage: AndroidApkUpdateDependencies["fetchReleasePage"], + signal: AbortSignal, +): Promise> { + const firstUrl = giteaReleasePageUrl(apiUrl, 1); + const firstResponse = await fetchReleasePage(firstUrl, { + credentials: "omit", + redirect: "error", + signal, + }); + validateExactResponseUrl(firstResponse, firstUrl, "release API"); + if (!firstResponse.ok) throw new Error(`Release API returned HTTP ${firstResponse.status}.`); + const totalCount = parseTotalCount(firstResponse.headers.get("X-Total-Count")); + const firstItems = await firstResponse.json(); + validatePageItems(firstItems, Math.min(GITEA_RELEASE_PAGE_SIZE, totalCount)); + + const releaseIds = new Set(); + addUniqueReleaseIds(firstItems, releaseIds); + const releases = [...firstItems]; + const pageCount = Math.ceil(totalCount / GITEA_RELEASE_PAGE_SIZE); + for (let page = 2; page <= pageCount; page += 1) { + const offset = (page - 1) * GITEA_RELEASE_PAGE_SIZE; + const expectedLength = Math.min(GITEA_RELEASE_PAGE_SIZE, totalCount - offset); + const items = await readExactReleasePage( + giteaReleasePageUrl(apiUrl, page), + expectedLength, + totalCount, + fetchReleasePage, + signal, + ); + addUniqueReleaseIds(items, releaseIds); + releases.push(...items); + } + if (releases.length !== totalCount) { + throw new TypeError("The repository release total changed during pagination."); + } + return releases; +} + +async function withAbortDeadline( + milliseconds: number, + label: string, + operation: (signal: AbortSignal) => Promise, +): Promise { + const controller = new AbortController(); + const timeout = setTimeout( + () => controller.abort(new Error(`${label} timed out.`)), + milliseconds, + ); + try { + return await operation(controller.signal); + } finally { + clearTimeout(timeout); + } +} + +function parseContentLength(value: string | null, expectedSize: number): void { + if (value === null) return; + if (!/^(0|[1-9]\d*)$/.test(value)) { + throw new Error("The APK download returned an invalid Content-Length."); + } + const contentLength = Number(value); + if (!Number.isSafeInteger(contentLength) || contentLength > MAX_ANDROID_APK_BYTES) { + throw new Error("The APK download is larger than the allowed maximum size."); + } + if (contentLength !== expectedSize) { + throw new Error("The APK download Content-Length does not match its trusted asset size."); + } +} + +async function streamExactApkBytes( + body: ReadableStream, + destination: WritableStream, + expectedSize: number, + signal: AbortSignal, +): Promise { + let streamedBytes = 0; + const byteCounter = new TransformStream({ + transform(chunk, controller) { + if (!(chunk instanceof Uint8Array)) { + throw new TypeError("The APK download returned a non-byte stream."); + } + streamedBytes += chunk.byteLength; + if (streamedBytes > expectedSize || streamedBytes > MAX_ANDROID_APK_BYTES) { + throw new Error("The APK download exceeded its trusted asset size."); + } + controller.enqueue(chunk); + }, + }); + await body.pipeThrough(byteCounter, { signal }).pipeTo(destination, { signal }); + if (streamedBytes !== expectedSize) { + throw new Error("The APK download byte count does not match its trusted asset size."); + } +} + +export async function downloadTrustedAndroidApk( + downloadUrl: string, + versionCode: number, + expectedSize: number, + dependencies: AndroidApkDownloadDependencies, +): Promise { + if (!validVersionCode(versionCode)) throw new Error("The candidate version code is invalid."); + if (!validApkSize(expectedSize)) throw new Error("The trusted APK asset size is invalid."); + trustedHttpsUrl(downloadUrl, "asset"); + + return withAbortDeadline(DOWNLOAD_TIMEOUT_MS, "APK download", async (signal) => { + const response = await dependencies.fetchApk(downloadUrl, { + credentials: "omit", + redirect: "error", + signal, + }); + validateExactResponseUrl(response, downloadUrl, "APK download"); + if (!response.ok) throw new Error(`The APK download returned HTTP ${response.status}.`); + parseContentLength(response.headers.get("Content-Length"), expectedSize); + if (response.body === null) + throw new Error("The APK download returned an empty response body."); + + const temporaryFile = dependencies.createTemporaryFile(versionCode); + try { + await streamExactApkBytes( + response.body, + dependencies.openTemporaryFileStream(temporaryFile), + expectedSize, + signal, + ); + const localUri = await dependencies.finalizeTemporaryFile(temporaryFile, versionCode); + dependencies.pruneObsoleteFiles(versionCode); + return localUri; + } catch (cause) { + try { + dependencies.deleteTemporaryFile(temporaryFile); + } catch { + // The original download failure is more useful than best-effort cache cleanup failure. + } + throw cause; + } + }); +} + +export function selectLatestAndroidApkRelease( + releases: unknown, + apiUrl: string, +): AndroidApkRelease | null { + giteaServerBase(apiUrl); + if (!Array.isArray(releases)) return null; + + let latest: AndroidApkRelease | null = null; + for (const release of releases) { + if ( + !isRecord(release) || + !isPositiveSafeInteger(release.id) || + release.draft !== false || + release.prerelease !== false + ) + continue; + const versionCode = parseVersionCode(release.tag_name); + if ( + versionCode === null || + release.name !== `Android APK · build ${versionCode}` || + !Array.isArray(release.assets) + ) + continue; + const expectedAssetName = `t3code-apk-${versionCode}.apk`; + let candidate: AndroidApkRelease | null = null; + for (const asset of release.assets) { + if ( + !isRecord(asset) || + !isPositiveSafeInteger(asset.id) || + !validApkSize(asset.size) || + asset.name !== expectedAssetName + ) + continue; + const downloadUrl = trustedAttachmentUrl(asset.browser_download_url, apiUrl); + if (!downloadUrl) continue; + candidate = { versionCode, downloadUrl, expectedSize: asset.size }; + break; + } + if (!candidate || (latest && latest.versionCode >= versionCode)) continue; + latest = candidate; + } + return latest; +} + +export function isNewerAndroidVersion(candidate: number, installed: number): boolean { + if (!validVersionCode(installed)) { + throw new Error("The installed version code is unavailable or invalid."); + } + if (!validVersionCode(candidate)) { + throw new Error("The candidate version code is invalid."); + } + return candidate > installed; +} + +export async function runAndroidApkUpdate( + dependencies: AndroidApkUpdateDependencies, +): Promise { + if (androidApkUpdateInProgress) return { kind: "already-in-progress" }; + androidApkUpdateInProgress = true; + try { + return await runCoordinatedAndroidApkUpdate(dependencies); + } finally { + androidApkUpdateInProgress = false; + } +} + +async function runCoordinatedAndroidApkUpdate({ + apiUrl, + getInstalledVersionCode, + fetchReleasePage, + downloadApk, + installApk, + onPhase, +}: AndroidApkUpdateDependencies): Promise< + Exclude +> { + let latest: AndroidApkRelease | null; + let installedVersionCode: number; + try { + onPhase?.("checking"); + giteaServerBase(apiUrl); + installedVersionCode = await getInstalledVersionCode(); + if (!validVersionCode(installedVersionCode)) { + throw new Error("The installed version code is unavailable or invalid."); + } + const releases = await withAbortDeadline(API_TIMEOUT_MS, "Release check", (signal) => + fetchAllGiteaReleases(apiUrl, fetchReleasePage, signal), + ); + latest = selectLatestAndroidApkRelease(releases, apiUrl); + if (latest && !isNewerAndroidVersion(latest.versionCode, installedVersionCode)) { + return { + kind: "up-to-date", + installedVersionCode, + latestVersionCode: latest.versionCode, + }; + } + } catch (cause) { + const userMessage = + cause instanceof TypeError && /valid releases (page|list)/.test(cause.message) + ? "The repository did not return a valid releases list. Try again later." + : "Could not check for updates. Check your connection and try again."; + throw new AndroidApkUpdateError("check", userMessage, cause); + } + + if (!latest) return { kind: "no-compatible-release" }; + + let localUri: string; + try { + onPhase?.("downloading"); + localUri = await downloadApk(latest.downloadUrl, latest.versionCode, latest.expectedSize); + } catch (cause) { + throw new AndroidApkUpdateError( + "download", + "Could not download the update. Check your connection and available storage, then try again.", + cause, + ); + } + + try { + onPhase?.("installing"); + await installApk(localUri, latest.versionCode); + } catch (cause) { + throw new AndroidApkUpdateError( + "install", + "Could not open Android’s package installer. Allow T3 Code to install unknown apps if Android asks, then try again.", + cause, + ); + } + + return { kind: "installer-launched", versionCode: latest.versionCode }; +} diff --git a/docs/operations/fork-apk.md b/docs/operations/fork-apk.md new file mode 100644 index 0000000000..56613b6514 --- /dev/null +++ b/docs/operations/fork-apk.md @@ -0,0 +1,73 @@ +# Fork Android APK releases + +The fork publishes signed APKs to the repository running the workflow using +`.gitea/workflows/android-apk.yml`. This is separate from upstream's EAS/store +release workflows. Fork APK builds disable Expo OTA updates so upstream JavaScript +cannot replace the fork's bundled code. + +## One-time setup + +Enable repository Actions and register a dedicated Linux runner with the +`android-apk` label. Use an isolated CI checkout, not a running T3 environment: +the build regenerates `apps/mobile/android`. Install Node 24.13.1 or later in +the supported Node 24 line, the repository's pinned pnpm version, Java 17, +Git, curl, tar, xz, and the Android SDK with accepted licenses. Set `ANDROID_HOME` +and `ANDROID_NDK_HOME` in the runner environment. Install the SDK/NDK versions +required by the current Expo/React Native dependencies and CMake 3.22.1. +Signing uses SDK build-tools 36.0.0 by default; override +`ANDROID_BUILD_TOOLS_VERSION` if needed. The terminal build script downloads +its pinned Zig compiler and Ghostty sources. + +Configure these repository Actions secrets: + +| Secret | Value | +| ----------------------- | ------------------------------------------------------ | +| `APK_KEYSTORE_BASE64` | Base64-encoded Android release keystore | +| `APK_KEYSTORE_PASSWORD` | Keystore password | +| `APK_KEY_ALIAS` | Signing key alias | +| `APK_KEY_PASSWORD` | Signing key password | +| `APK_RELEASE_TOKEN` | Token with repository release write access to the fork | + +Reuse the signing key of the currently installed APK if you want an in-place +upgrade. Back up that key securely and keep it unchanged across releases. A new +key cannot upgrade an existing installation signed by another key; uninstalling +first deletes local app data. The workflow never publishes the generated +debug-signed intermediate APK: it re-signs and verifies the final artifact with +the configured release key before uploading. + +## Repository moves + +CI derives both the publication destination and the app's release API from +the current Git server and repository, so transferring to another owner or +renaming the repository needs no source changes. For local builds, set +`T3CODE_APK_REPOSITORY_URL` to the full HTTPS repository URL. Public downloads +need no authentication; the CI token is still required to publish releases and +is never embedded in the APK. + +Already-installed APKs retain their original repository API URL. After a move, +keep the old repository API and release assets reachable long enough to publish +and distribute an APK built for the new repository URL. Keep the same signing key +across the move and ensure the release token has write access to the new owner’s +repository. + +## Publish an update + +Push a tag of the form `apk-` on the commit to release. For example, +`git tag apk-1001` followed by `git push origin apk-1001`. Choose a number greater +than every previously installed build's Android version code, at most 2100000000. Do not reuse tags. The app's display version still comes from +`apps/mobile/app.config.ts`. + +The workflow builds a universal release APK, attaches it and a SHA-256 checksum +to a draft release, then publishes only after both uploads succeed. If an upload +fails, delete the incomplete draft release before rerunning the job; do not +delete its Git tag. Release creation intentionally fails rather than overwriting +an existing release. Signing/build failures publish nothing. + +On Android, open **Settings → Software Update → Check for updates**. The app asks +the public repository API for releases, selects the highest published +`apk-` release with its matching APK, and downloads it into app-owned +cache. It then opens Android’s package installer with the downloaded APK; the user +must confirm installation, and Android may first require permission to install +unknown apps from T3 Code. This is not a silent installer. Downloads require no +repository credentials, and the flow does not depend on the connected T3 +environment. iOS, web, and desktop keep their existing update paths. diff --git a/docs/user/updating.md b/docs/user/updating.md index d72df7382f..4a1593c45e 100644 --- a/docs/user/updating.md +++ b/docs/user/updating.md @@ -58,6 +58,17 @@ update can roll back to the previous version. If the update still fails: ## Mobile updates +For fork Android APK installations, open **Settings → Software Update → +Check for updates**. T3 Code checks its public repository, downloads the newest +compatible APK into app-owned cache, and opens Android's package installer. Confirm +the installation there. Android may first ask you to allow T3 Code to install +unknown apps. Before Android opens, T3 Code verifies that the APK has this app's +package name, the exact version selected from the repository, a newer version code, +and the same signing certificate set as the installed app. Downloads larger than +500 MiB are rejected. A stalled check or download times out so you can retry. The +unchanged signing key preserves your local data. These fork releases do not receive +upstream background updates. Updating the APK does not update your server. + Install App Store or Google Play releases as usual. The mobile app can also download updates in the background and apply them when you next leave the app. It saves drafts and queued messages before restarting. If you keep the app open diff --git a/scripts/build-fork-apk.sh b/scripts/build-fork-apk.sh new file mode 100644 index 0000000000..59863f67a7 --- /dev/null +++ b/scripts/build-fork-apk.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." +: "${T3CODE_APK_RELEASE_TAG:?Set an apk- release tag}" +: "${T3CODE_APK_REPOSITORY_URL:?Set the fork repository URL}" +: "${ANDROID_HOME:?Set ANDROID_HOME to the Android SDK}" +: "${ANDROID_NDK_HOME:?Set ANDROID_NDK_HOME to the Android NDK}" +: "${APK_KEYSTORE_BASE64:?Set the release keystore secret}" +: "${APK_KEYSTORE_PASSWORD:?Set the keystore password secret}" +: "${APK_KEY_ALIAS:?Set the signing key alias}" +: "${APK_KEY_PASSWORD:?Set the signing key password secret}" + +node --input-type=module -e 'import { parseAndroidApkReleaseTag } from "./scripts/lib/android-apk-release.ts"; parseAndroidApkReleaseTag(process.env.T3CODE_APK_RELEASE_TAG)' +export APP_VARIANT=production +export T3CODE_MOBILE_UPDATES_ENABLED=0 +export MOBILE_VERSION_POLICY=appVersion +export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=8192}" + +signing_dir="$(mktemp -d)" +trap 'rm -rf "$signing_dir"' EXIT +printf '%s' "$APK_KEYSTORE_BASE64" | base64 --decode > "$signing_dir/release.keystore" +chmod 600 "$signing_dir/release.keystore" +unset APK_KEYSTORE_BASE64 + +bash apps/mobile/modules/t3-terminal/scripts/build-libghostty-android.sh +( + cd apps/mobile + EXPO_NO_GIT_STATUS=1 node_modules/.bin/expo prebuild --clean --platform android --no-install + cd android + ./gradlew --no-daemon :app:assembleRelease +) + +build_tools="${ANDROID_HOME}/build-tools/${ANDROID_BUILD_TOOLS_VERSION:-36.0.0}" +mkdir -p release +apk="release/t3code-${T3CODE_APK_RELEASE_TAG}.apk" +"$build_tools/apksigner" sign \ + --ks "$signing_dir/release.keystore" \ + --ks-key-alias "$APK_KEY_ALIAS" \ + --ks-pass env:APK_KEYSTORE_PASSWORD \ + --key-pass env:APK_KEY_PASSWORD \ + --out "$apk" \ + apps/mobile/android/app/build/outputs/apk/release/app-release.apk +"$build_tools/apksigner" verify --verbose --print-certs "$apk" +( + cd release + sha256sum "$(basename "$apk")" > "$(basename "$apk").sha256" +) diff --git a/scripts/lib/android-apk-release.ts b/scripts/lib/android-apk-release.ts new file mode 100644 index 0000000000..c9e6f05a19 --- /dev/null +++ b/scripts/lib/android-apk-release.ts @@ -0,0 +1,32 @@ +export function parseAndroidApkReleaseTag(tag: string): number { + const match = /^apk-([1-9]\d*)$/.exec(tag); + const versionCode = match ? Number(match[1]) : NaN; + if (!Number.isSafeInteger(versionCode) || versionCode > 2_100_000_000) { + throw new Error("APK release tags must be apk-, from 1 to 2100000000."); + } + return versionCode; +} + +export function resolveAndroidApkRepository(repositoryUrl: string) { + const url = new URL(repositoryUrl); + const path = url.pathname.replace(/\/+$/, "").replace(/\.git$/, ""); + const parts = path.split("/").filter(Boolean); + if ( + url.protocol !== "https:" || + url.username || + url.password || + url.search || + url.hash || + parts.length < 2 + ) + throw new Error( + "APK repository must be an HTTPS repository URL without credentials or query parameters.", + ); + const repository = parts.slice(-2).join("/"); + const basePath = parts.slice(0, -2).join("/"); + const serverUrl = `${url.origin}${basePath ? `/${basePath}` : ""}`; + return { + releasesUrl: `${serverUrl}/${repository}/releases`, + apiUrl: `${serverUrl}/api/v1/repos/${repository}/releases`, + }; +} diff --git a/scripts/publish-fork-apk.test.ts b/scripts/publish-fork-apk.test.ts new file mode 100644 index 0000000000..4e639ef972 --- /dev/null +++ b/scripts/publish-fork-apk.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + parseAndroidApkReleaseTag, + resolveAndroidApkRepository, +} from "./lib/android-apk-release.ts"; +import { publishForkApk } from "./publish-fork-apk.ts"; + +describe("APK release version codes", () => { + it("accepts Android version codes, including the platform maximum", () => { + expect(parseAndroidApkReleaseTag("apk-42")).toBe(42); + expect(parseAndroidApkReleaseTag("apk-2100000000")).toBe(2100000000); + }); + + it.each([ + "v1.2.3", + "apk-0", + "apk-01", + "apk--1", + "apk-1.5", + "apk-2100000001", + "apk-1/../../secret", + ])("rejects invalid release tag %s", (tag) => + expect(() => parseAndroidApkReleaseTag(tag)).toThrow("APK release tags"), + ); +}); + +describe("fork APK publishing", () => { + const options = { + tag: "apk-42", + commit: "abc123", + token: "test-token", + repositoryUrl: "https://git.example.com/new-owner/renamed-repo", + apk: new Blob(["apk"]), + checksum: new Blob(["checksum"]), + }; + + it("keeps the release in draft until both authenticated uploads finish", async () => { + const request = vi.fn().mockResolvedValue(new Response("{}")); + request.mockResolvedValueOnce(Response.json({ id: 123 })); + + await publishForkApk({ ...options, request }); + + expect(request).toHaveBeenCalledTimes(4); + const [create, apk, checksum, publish] = request.mock.calls; + expect(create?.[0]).toBe( + "https://git.example.com/api/v1/repos/new-owner/renamed-repo/releases", + ); + expect(JSON.parse(String(create?.[1]?.body))).toMatchObject({ + draft: true, + tag_name: "apk-42", + target_commitish: "abc123", + }); + expect(apk?.[0]).toContain("/123/assets?name=t3code-apk-42.apk"); + const attachment = apk?.[1]?.body; + expect(attachment).toBeInstanceOf(FormData); + if (!(attachment instanceof FormData)) throw new Error("Missing upload form"); + expect(attachment.get("attachment")).toBeInstanceOf(Blob); + expect(checksum?.[0]).toContain("t3code-apk-42.apk.sha256"); + expect(publish?.[1]?.method).toBe("PATCH"); + expect(JSON.parse(String(publish?.[1]?.body))).toEqual({ draft: false }); + for (const [, init] of request.mock.calls) { + expect(init?.headers).toMatchObject({ Authorization: "token test-token" }); + expect(init?.redirect).toBe("error"); + } + }); + + it("does not publish an incomplete release after an upload failure", async () => { + const request = vi + .fn() + .mockResolvedValueOnce(Response.json({ id: 123 })) + .mockResolvedValueOnce(new Response("", { status: 500 })); + await expect(publishForkApk({ ...options, request })).rejects.toThrow("HTTP 500"); + expect(request).toHaveBeenCalledTimes(2); + }); + + it("reports authentication failures without exposing credentials", async () => { + const request = vi.fn().mockResolvedValue(new Response("", { status: 401 })); + await expect(publishForkApk({ ...options, request })).rejects.toThrow("HTTP 401"); + expect(request).toHaveBeenCalledTimes(1); + }); + + it("does not upload without a valid release ID", async () => { + const request = vi.fn().mockResolvedValue(Response.json({ id: "../other" })); + await expect(publishForkApk({ ...options, request })).rejects.toThrow("valid release ID"); + expect(request).toHaveBeenCalledTimes(1); + }); +}); + +describe("APK repository location", () => { + it.each(["original-owner", "new-owner"])("derives release locations for %s", (owner) => { + expect(resolveAndroidApkRepository(`https://git.example.com/${owner}/app.git/`)).toEqual({ + releasesUrl: `https://git.example.com/${owner}/app/releases`, + apiUrl: `https://git.example.com/api/v1/repos/${owner}/app/releases`, + }); + }); + + it("supports a Git server hosted under a subpath", () => { + expect(resolveAndroidApkRepository("https://example.com/git/owner/app").apiUrl).toBe( + "https://example.com/git/api/v1/repos/owner/app/releases", + ); + }); + + it.each([ + "http://example.com/owner/app", + "https://token@example.com/owner/app", + "https://example.com/owner", + "https://example.com/owner/app?token=secret", + ])("rejects invalid repository URL %s", (url) => { + expect(() => resolveAndroidApkRepository(url)).toThrow(); + }); +}); diff --git a/scripts/publish-fork-apk.ts b/scripts/publish-fork-apk.ts new file mode 100644 index 0000000000..6d58fbdbc6 --- /dev/null +++ b/scripts/publish-fork-apk.ts @@ -0,0 +1,94 @@ +import * as NodeFSP from "node:fs/promises"; +import * as NodeURL from "node:url"; + +import { + parseAndroidApkReleaseTag, + resolveAndroidApkRepository, +} from "./lib/android-apk-release.ts"; + +export async function publishForkApk(options: { + tag: string; + commit: string; + token: string; + repositoryUrl: string; + apk: Blob; + checksum: Blob; + request?: typeof fetch; +}) { + const versionCode = parseAndroidApkReleaseTag(options.tag); + const request = options.request ?? fetch; + const endpoint = resolveAndroidApkRepository(options.repositoryUrl).apiUrl; + const authorization = `token ${options.token}`; + const send = async (url: string, init: RequestInit) => { + const response = await request(url, { + ...init, + redirect: "error", + headers: { ...init.headers, Authorization: authorization }, + }); + if (!response.ok) throw new Error(`Release request failed: HTTP ${response.status}`); + return response; + }; + + const created = await send(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + tag_name: options.tag, + target_commitish: options.commit, + name: `Android APK · build ${versionCode}`, + body: "Download the APK below and open it on Android to install. This is a signed fork build; updates require the same signing key. The SHA-256 checksum is attached alongside the APK.", + draft: true, + prerelease: false, + }), + }); + const release: unknown = await created.json(); + if ( + typeof release !== "object" || + release === null || + !("id" in release) || + typeof release.id !== "number" || + !Number.isSafeInteger(release.id) || + release.id <= 0 + ) + throw new Error("Release API did not return a valid release ID."); + + const filename = `t3code-${options.tag}.apk`; + for (const [name, file] of [ + [filename, options.apk], + [`${filename}.sha256`, options.checksum], + ] as const) { + const form = new FormData(); + form.append("attachment", file, name); + await send(`${endpoint}/${release.id}/assets?name=${encodeURIComponent(name)}`, { + method: "POST", + body: form, + }); + } + await send(`${endpoint}/${release.id}`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ draft: false }), + }); +} + +if (process.argv[1] && import.meta.url === NodeURL.pathToFileURL(process.argv[1]).href) { + const tag = process.env.T3CODE_APK_RELEASE_TAG; + const token = process.env.APK_RELEASE_TOKEN; + const commit = process.env.APK_RELEASE_COMMIT; + const repositoryUrl = process.env.T3CODE_APK_REPOSITORY_URL; + if (!tag || !token || !commit || !repositoryUrl) + throw new Error("Missing APK release tag, token, commit, or repository URL."); + parseAndroidApkReleaseTag(tag); + await publishForkApk({ + tag, + token, + commit, + repositoryUrl, + apk: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk`)], { + type: "application/vnd.android.package-archive", + }), + checksum: new Blob([await NodeFSP.readFile(`release/t3code-${tag}.apk.sha256`)], { + type: "text/plain", + }), + }); +}