From 444e22659a8da6627d5f02c81f7e02727b0fcb8c Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 24 Nov 2026 01:46:28 +0000
Subject: [PATCH 01/17] ADFA-7241: Custom IDE Builder core: zip rewrite, bundle
index, keystores, signing
Pure-JVM logic for the plugin, with tests. The raw zip reader and writer copy
the host APK's entries without recompressing, drop the old add-on bundle and
v1 signature, add the chosen add-ons and a new bundled-addons.tsv, and align
stored entries (4 bytes, .so files 16 KB). Also the add-on selection rules,
PKCS12/BKS keystore loading with JKS rejected, the v2 catalog with
minAppVersion filtering and verified downloads from addons.appdevforall.org,
and signing with apksig followed by verification.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../customidebuilder/core/ApkRewriter.kt | 83 ++++
.../customidebuilder/core/Bundle.kt | 48 +++
.../customidebuilder/core/Catalog.kt | 127 ++++++
.../customidebuilder/core/Download.kt | 106 +++++
.../customidebuilder/core/Keystores.kt | 124 ++++++
.../customidebuilder/core/Naming.kt | 15 +
.../customidebuilder/core/Pipeline.kt | 100 +++++
.../customidebuilder/core/Selection.kt | 92 +++++
.../customidebuilder/core/Signing.kt | 58 +++
.../appdevforall/customidebuilder/core/Zip.kt | 363 ++++++++++++++++++
.../customidebuilder/core/ApkRewriterTest.kt | 173 +++++++++
.../customidebuilder/core/BundleIndexTest.kt | 106 +++++
.../customidebuilder/core/CatalogTest.kt | 213 ++++++++++
.../customidebuilder/core/KeystoresTest.kt | 92 +++++
.../customidebuilder/core/NamingTest.kt | 14 +
.../customidebuilder/core/PipelineTest.kt | 144 +++++++
.../customidebuilder/core/SelectionTest.kt | 87 +++++
.../customidebuilder/core/TestSupport.kt | 100 +++++
18 files changed, 2045 insertions(+)
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Bundle.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Catalog.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Keystores.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Naming.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Pipeline.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Selection.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Signing.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/BundleIndexTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/KeystoresTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/NamingTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/PipelineTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/SelectionTest.kt
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/TestSupport.kt
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
new file mode 100644
index 00000000..216fcbfd
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
@@ -0,0 +1,83 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.File
+import java.io.FileOutputStream
+
+/** What [ApkRewriter.rewrite] did, for the screen and the tests. */
+class RewriteReport(
+ val copied: Int,
+ val dropped: List,
+ val added: List,
+ val index: String,
+)
+
+/**
+ * Makes the unsigned APK: every entry of the source APK copied as it is, minus the old add-on
+ * bundle and the old signature, plus the chosen add-ons and a new bundle index.
+ *
+ * Entries are copied without being inflated or deflated, so a 400 MB APK costs one pass of file
+ * IO and no CPU to speak of.
+ */
+object ApkRewriter {
+ /** Entries that belong to the build being replaced: its add-ons, their index and its v1 signature. */
+ fun isDropped(name: String): Boolean {
+ if (name.startsWith("$ASSETS/${AddonKind.PLUGIN.dir}/") || name.startsWith("$ASSETS/${AddonKind.TEMPLATE.dir}/")) return true
+ if (name == INDEX_APK_ENTRY) return true
+ return isV1SignatureFile(name)
+ }
+
+ /** `META-INF/MANIFEST.MF` and the `.SF`, `.RSA`, `.DSA` and `.EC` files directly in `META-INF/`. */
+ fun isV1SignatureFile(name: String): Boolean {
+ val upper = name.uppercase()
+ if (!upper.startsWith("META-INF/")) return false
+ val rest = upper.removePrefix("META-INF/")
+ if ('/' in rest) return false
+ return rest == "MANIFEST.MF" || rest.endsWith(".SF") || rest.endsWith(".RSA") || rest.endsWith(".DSA") || rest.endsWith(".EC")
+ }
+
+ /**
+ * Writes [output] from [source] and [addons]. [onProgress] gets the fraction done, 0 to 1;
+ * [checkCancelled] is called between chunks and may throw to stop.
+ */
+ fun rewrite(
+ source: File,
+ output: File,
+ addons: List,
+ checkCancelled: () -> Unit = {},
+ onProgress: (Double) -> Unit = {},
+ ): RewriteReport {
+ val clash = addons.groupBy { it.apkEntryName }.filterValues { it.size > 1 }.keys
+ if (clash.isNotEmpty()) throw ZipFormatException("two add-ons would be written to ${clash.first()}")
+
+ // Hash first: the index needs every add-on's SHA-256 and the entry needs its CRC before its data.
+ val digests = addons.associateWith { digestOf(it.file) { checkCancelled() } }
+ val index = BundleIndex.render(
+ addons.map { IndexLine(it.kind, it.fileName, digests.getValue(it).size, digests.getValue(it).sha256) },
+ )
+ val indexBytes = index.toByteArray(Charsets.UTF_8)
+
+ val dropped = ArrayList()
+ var copied = 0
+ RawZipFile(source).use { zip ->
+ val keep = zip.entries.filter { e -> if (isDropped(e.name)) { dropped.add(e.name); false } else true }
+ val total = (keep.sumOf { it.compressedSize } + addons.sumOf { digests.getValue(it).size } + indexBytes.size).coerceAtLeast(1)
+ var done = 0L
+ val advance = { n: Int -> done += n; checkCancelled(); onProgress(done.toDouble() / total) }
+ RawZipWriter(FileOutputStream(output)).use { writer ->
+ for (entry in keep) {
+ writer.addRaw(entry) { sink -> zip.copyRaw(entry, sink, advance) }
+ copied++
+ }
+ for (addon in addons) {
+ val d = digests.getValue(addon)
+ writer.addStored(addon.apkEntryName, d.size, d.crc) { sink ->
+ addon.file.inputStream().use { input -> pump(input) { buf, n -> sink.write(buf, 0, n); advance(n) } }
+ }
+ }
+ val crc = java.util.zip.CRC32().apply { update(indexBytes) }.value
+ writer.addStored(INDEX_APK_ENTRY, indexBytes.size.toLong(), crc) { sink -> sink.write(indexBytes) }
+ }
+ }
+ return RewriteReport(copied, dropped, addons.map { it.apkEntryName } + INDEX_APK_ENTRY, index)
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Bundle.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Bundle.kt
new file mode 100644
index 00000000..7d2bac85
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Bundle.kt
@@ -0,0 +1,48 @@
+package org.appdevforall.customidebuilder.core
+
+/**
+ * The two kinds of add-on a build can bundle, each in a folder of its own in the APK assets.
+ * Mirrors `BundledAddonKind` in Code on the Go (BundledAddons.kt); [dir] and [extension] must
+ * stay equal to it, or the host does not find what this plugin bundled.
+ */
+enum class AddonKind(val dir: String, val extension: String) {
+ PLUGIN("plugins", "cgp"),
+ TEMPLATE("templates", "cgt"),
+}
+
+/** An add-on ready to go into the APK: [fileName] is the name inside its folder, [file] the bytes. */
+class StagedAddon(val kind: AddonKind, val fileName: String, val file: java.io.File) {
+ /** `assets/plugins/`: the APK entry the host reads it from. */
+ val apkEntryName: String get() = "$ASSETS/${kind.dir}/$fileName"
+}
+
+/** One line of the bundle index. */
+data class IndexLine(val kind: AddonKind, val fileName: String, val size: Long, val sha256: String)
+
+const val ASSETS = "assets"
+
+/** The bundle index sits beside `plugins/` and `templates/`, so its APK entry is `assets/bundled-addons.tsv`. */
+const val INDEX_FILE = "bundled-addons.tsv"
+const val INDEX_APK_ENTRY = "$ASSETS/$INDEX_FILE"
+
+/** The template the host installs by its own entry; it is never a bundled add-on. */
+const val CORE_TEMPLATE = "core.cgt"
+
+object BundleIndex {
+ /**
+ * The index text exactly as Code on the Go's build writes it (StageBundledAddons in
+ * app/build.gradle.kts): plugins by file name, then templates by file name, one
+ * `/\t\t\n` line each, nothing at all for a thin build. The host
+ * ignores an index it cannot parse and falls back to listing folders by name and size, so a
+ * deviation here costs nothing visible; it is kept exact anyway.
+ */
+ fun render(lines: List): String {
+ val sb = StringBuilder()
+ for (kind in AddonKind.values()) {
+ lines.filter { it.kind == kind }.sortedBy { it.fileName }.forEach {
+ sb.append("${kind.dir}/${it.fileName}\t${it.size}\t${it.sha256}\n")
+ }
+ }
+ return sb.toString()
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Catalog.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Catalog.kt
new file mode 100644
index 00000000..9a8ff4b7
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Catalog.kt
@@ -0,0 +1,127 @@
+package org.appdevforall.customidebuilder.core
+
+import org.json.JSONException
+import org.json.JSONObject
+import java.io.File
+
+/** An entry of the addons catalog this plugin can bundle: a plugin or a template. */
+class CatalogAddon(
+ val kind: AddonKind,
+ val slug: String,
+ val addonId: String,
+ val name: String,
+ val version: String,
+ val summary: String,
+ /** `""` when the addon states no minimum. */
+ val minAppVersion: String,
+ val downloadUrl: String,
+ val sha256: String,
+ val size: Long,
+) {
+ /** The name the download is saved under, which also decides its kind: `.cgp` or `.cgt`. */
+ val fileName: String get() = "$slug.${kind.extension}"
+}
+
+class CatalogException(message: String) : Exception(message)
+
+/** The result of [Catalog.parse]: usable entries, and how many were skipped as malformed. */
+class ParsedCatalog(val addons: List, val skipped: Int)
+
+/** A Code on the Go release number, `YY.ww`, compared segment by segment as integers. */
+object AppVersion {
+ private val NUMBER = Regex("\\d+(\\.\\d+)*")
+
+ /** The first dotted number in [text] (so `v26.45-abc123-release` is 26.45), or null if it has none. */
+ fun parse(text: String?): List? =
+ text?.let { NUMBER.find(it) }?.value?.split('.')?.map { it.toIntOrNull() ?: return null }
+
+ fun compare(a: List, b: List): Int {
+ for (i in 0 until maxOf(a.size, b.size)) {
+ val c = a.getOrElse(i) { 0 }.compareTo(b.getOrElse(i) { 0 })
+ if (c != 0) return c
+ }
+ return 0
+ }
+}
+
+object Catalog {
+ const val URL = "https://addons.appdevforall.org/v2/catalog.json"
+ const val HOST = "addons.appdevforall.org"
+
+ private val SLUG = Regex("[a-z0-9]+(-[a-z0-9]+)*")
+ private val SHA256 = Regex("[a-f0-9]{64}")
+
+ /**
+ * Reads a v2 catalog (site/catalog.v2.schema.json in the addons repository). Snippets and code
+ * actions are not bundled and are left out. An entry missing a required field, with a slug
+ * that is not a file name or a digest that is not SHA-256, is skipped and counted: the
+ * download could not be verified, so it must not be offered.
+ */
+ fun parse(json: String): ParsedCatalog {
+ val root =
+ try {
+ JSONObject(json)
+ } catch (e: JSONException) {
+ throw CatalogException("The catalog is not valid JSON.")
+ }
+ if (root.optInt("schemaVersion", -1) != 2) throw CatalogException("This is not a version 2 catalog.")
+ val array = root.optJSONArray("addons") ?: throw CatalogException("The catalog has no addons list.")
+ val result = ArrayList()
+ var skipped = 0
+ for (i in 0 until array.length()) {
+ val o = array.optJSONObject(i) ?: continue
+ val kind = AddonKind.values().firstOrNull { it.name.equals(o.optString("type"), ignoreCase = true) } ?: continue
+ val download = o.optJSONObject("download")
+ val slug = o.optString("slug")
+ val sha = download?.optString("sha256").orEmpty()
+ val size = download?.optLong("size", -1) ?: -1
+ val url = download?.optString("url").orEmpty()
+ val name = o.optString("name")
+ if (download == null || !SLUG.matches(slug) || !SHA256.matches(sha) || size < 0 || url.isEmpty() || name.isEmpty()) {
+ skipped++
+ continue
+ }
+ result.add(
+ CatalogAddon(
+ kind = kind,
+ slug = slug,
+ addonId = o.optString("addonId"),
+ name = name,
+ version = o.optString("version"),
+ summary = o.optString("summary"),
+ minAppVersion = o.optString("minAppVersion"),
+ downloadUrl = url,
+ sha256 = sha,
+ size = size,
+ ),
+ )
+ }
+ return ParsedCatalog(result, skipped)
+ }
+
+ /** The entries to offer, and whether [hostVersionName] could be read to decide. */
+ class Offer(val addons: List, val hostVersionKnown: Boolean)
+
+ /**
+ * Plugins and templates whose `minAppVersion` is at most the host's version, plugins first, each
+ * kind in name order. If the host's version cannot be read nothing can be ruled out, so
+ * everything is offered and [Offer.hostVersionKnown] is false.
+ */
+ fun offer(addons: List, hostVersionName: String?): Offer {
+ val host = AppVersion.parse(hostVersionName)
+ val fits =
+ addons.filter { a ->
+ val min = AppVersion.parse(a.minAppVersion)
+ host == null || min == null || AppVersion.compare(min, host) <= 0
+ }
+ return Offer(fits.sortedWith(compareBy({ it.kind.ordinal }, { it.name.lowercase() })), host != null)
+ }
+
+ /** Null when [file] is exactly what the catalog promised, else why not. */
+ fun verifyDownload(file: File, addon: CatalogAddon): String? {
+ if (file.length() != addon.size) return "${addon.name}: the download is ${file.length()} bytes, the catalog says ${addon.size}"
+ val actual = digestOf(file).sha256
+ if (actual != addon.sha256) return "${addon.name}: the download does not match the catalog's SHA-256"
+ return null
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
new file mode 100644
index 00000000..8c0aa738
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
@@ -0,0 +1,106 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.File
+import java.io.IOException
+import java.io.InputStream
+import java.net.HttpURLConnection
+import java.net.URI
+import java.net.URL
+
+class DownloadException(message: String, cause: Throwable? = null) : IOException(message, cause)
+
+/** Where bytes come from. The real one is [HttpFetcher]; tests pass a fake. */
+fun interface Fetcher {
+ fun open(url: String): InputStream
+}
+
+/** The only network access this plugin makes: HTTPS to the addons host, nothing else. */
+object DownloadPolicy {
+ fun isAllowed(url: String, host: String = Catalog.HOST): Boolean =
+ try {
+ val uri = URI(url)
+ uri.scheme.equals("https", ignoreCase = true) && uri.host.equals(host, ignoreCase = true) && uri.userInfo == null &&
+ (uri.port == -1 || uri.port == 443)
+ } catch (e: java.net.URISyntaxException) {
+ false
+ }
+}
+
+class HttpFetcher(
+ private val host: String = Catalog.HOST,
+ private val timeoutMs: Int = 20_000,
+) : Fetcher {
+ /** Follows up to three redirects, each of which must pass [DownloadPolicy] too. */
+ override fun open(url: String): InputStream {
+ var current = url
+ repeat(4) {
+ if (!DownloadPolicy.isAllowed(current, host)) throw DownloadException("Refusing to download from $current: only https://$host is allowed.")
+ val connection = URL(current).openConnection() as HttpURLConnection
+ connection.instanceFollowRedirects = false
+ connection.connectTimeout = timeoutMs
+ connection.readTimeout = timeoutMs
+ connection.setRequestProperty("User-Agent", "Custom-IDE-Builder")
+ when (val code = connection.responseCode) {
+ 200 -> return connection.inputStream
+ 301, 302, 303, 307, 308 -> {
+ val next = connection.getHeaderField("Location") ?: throw DownloadException("Redirect without a location from $current")
+ connection.disconnect()
+ current = URI(current).resolve(next).toString()
+ }
+ else -> {
+ connection.disconnect()
+ throw DownloadException("The server answered $code for $current")
+ }
+ }
+ }
+ throw DownloadException("Too many redirects from $url")
+ }
+}
+
+/** Downloads and verifies catalog add-ons. */
+class AddonDownloader(private val fetcher: Fetcher) {
+ /** The catalog text, at most [MAX_CATALOG_BYTES]. */
+ fun fetchCatalog(url: String = Catalog.URL): String =
+ fetcher.open(url).use { input ->
+ val out = java.io.ByteArrayOutputStream()
+ pump(input) { buf, n ->
+ out.write(buf, 0, n)
+ if (out.size() > MAX_CATALOG_BYTES) throw DownloadException("The catalog is larger than expected.")
+ }
+ String(out.toByteArray(), Charsets.UTF_8)
+ }
+
+ /**
+ * Downloads [addon] into [dir] as `.cgp|cgt` and checks its size and SHA-256 against the
+ * catalog; on any mismatch the file is deleted and the call throws. It reads no more than
+ * the promised size plus one byte, so a server cannot make it fill the disk.
+ */
+ fun download(addon: CatalogAddon, dir: File, onBytes: (Long) -> Unit = {}): File {
+ dir.mkdirs()
+ val target = File(dir, addon.fileName)
+ val partial = File(dir, addon.fileName + ".part")
+ try {
+ var total = 0L
+ fetcher.open(addon.downloadUrl).use { input ->
+ partial.outputStream().use { out ->
+ pump(input) { buf, n ->
+ total += n
+ if (total > addon.size) throw DownloadException("${addon.name}: the download is larger than the catalog says (${addon.size} bytes).")
+ out.write(buf, 0, n)
+ onBytes(total)
+ }
+ }
+ }
+ Catalog.verifyDownload(partial, addon)?.let { throw DownloadException(it) }
+ target.delete()
+ if (!partial.renameTo(target)) throw DownloadException("${addon.name}: could not save the download.")
+ return target
+ } finally {
+ partial.delete()
+ }
+ }
+
+ companion object {
+ const val MAX_CATALOG_BYTES = 4 * 1024 * 1024
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Keystores.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Keystores.kt
new file mode 100644
index 00000000..d8bb910f
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Keystores.kt
@@ -0,0 +1,124 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.ByteArrayInputStream
+import java.io.IOException
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.security.PrivateKey
+import java.security.UnrecoverableKeyException
+import java.security.cert.X509Certificate
+
+/** What a keystore file's first bytes say it is. */
+enum class KeystoreFormat { PKCS12_LIKELY, BKS_LIKELY, JKS, JCEKS, UNKNOWN }
+
+object KeystoreFormats {
+ const val CONVERT_JKS =
+ "This is a Java KeyStore (JKS) file, which Android cannot read. Convert it on a computer with " +
+ "keytool -importkeystore -srckeystore old.jks -srcstoretype JKS -destkeystore new.p12 -deststoretype PKCS12 " +
+ "and choose the new .p12 file."
+
+ const val CONVERT_JCEKS =
+ "This is a JCEKS keystore, which Android cannot read. Convert it on a computer with " +
+ "keytool -importkeystore -srckeystore old.jceks -srcstoretype JCEKS -destkeystore new.p12 -deststoretype PKCS12 " +
+ "and choose the new .p12 file."
+
+ /**
+ * JKS starts with the magic `FEEDFEED`, JCEKS with `CECECECE`. A PKCS#12 file is a DER
+ * SEQUENCE, so it starts with `0x30`. A BouncyCastle (BKS) store starts with its version
+ * number as a big-endian int, 1 or 2 in files in use. Anything else is tried as both.
+ */
+ fun sniff(header: ByteArray): KeystoreFormat {
+ if (header.size < 4) return KeystoreFormat.UNKNOWN
+ val b = IntArray(4) { header[it].toInt() and 0xFF }
+ if (b[0] == 0xFE && b[1] == 0xED && b[2] == 0xFE && b[3] == 0xED) return KeystoreFormat.JKS
+ if (b[0] == 0xCE && b[1] == 0xCE && b[2] == 0xCE && b[3] == 0xCE) return KeystoreFormat.JCEKS
+ if (b[0] == 0x30) return KeystoreFormat.PKCS12_LIKELY
+ if (b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] in 1..2) return KeystoreFormat.BKS_LIKELY
+ return KeystoreFormat.UNKNOWN
+ }
+}
+
+sealed class KeystoreOpen {
+ /** [type] is the `KeyStore` type that read the file. */
+ class Opened(val type: String, val store: KeyStore) : KeystoreOpen() {
+ /** Aliases that hold a private key, which is what signing needs, in name order. */
+ val keyAliases: List get() = store.aliases().toList().filter { store.isKeyEntry(it) }.sorted()
+ }
+
+ class Rejected(val message: String) : KeystoreOpen()
+
+ object WrongPassword : KeystoreOpen()
+}
+
+class SigningKey(val alias: String, val privateKey: PrivateKey, val chain: List) {
+ val certificate: X509Certificate get() = chain.first()
+
+ /** SHA-256 of the signing certificate, `AA:BB:..`, to compare between builds. */
+ val fingerprint: String
+ get() = MessageDigest.getInstance("SHA-256").digest(certificate.encoded).joinToString(":") { "%02X".format(it) }
+}
+
+sealed class KeyLoad {
+ class Loaded(val key: SigningKey) : KeyLoad()
+
+ class Failed(val message: String) : KeyLoad()
+}
+
+object Keystores {
+ /** Keystores are a few KB; a file this big is not one. */
+ const val MAX_BYTES = 8 * 1024 * 1024
+
+ private val PASSWORD_HINT = Regex("password|integrity|mac invalid|mac verify|corrupt", RegexOption.IGNORE_CASE)
+
+ /**
+ * Reads [bytes] as PKCS12, then as BKS (in the other order when the header looks like BKS).
+ * Android's own providers read both. A JKS or JCEKS file is rejected with how to convert it.
+ * [password] is not modified.
+ */
+ fun open(bytes: ByteArray, password: CharArray): KeystoreOpen {
+ if (bytes.size > MAX_BYTES) return KeystoreOpen.Rejected("This file is too large to be a keystore.")
+ val order =
+ when (KeystoreFormats.sniff(bytes)) {
+ KeystoreFormat.JKS -> return KeystoreOpen.Rejected(KeystoreFormats.CONVERT_JKS)
+ KeystoreFormat.JCEKS -> return KeystoreOpen.Rejected(KeystoreFormats.CONVERT_JCEKS)
+ KeystoreFormat.BKS_LIKELY -> listOf("BKS", "PKCS12")
+ else -> listOf("PKCS12", "BKS")
+ }
+ var passwordProblem = false
+ for (type in order) {
+ try {
+ val store = KeyStore.getInstance(type)
+ store.load(ByteArrayInputStream(bytes), password)
+ return KeystoreOpen.Opened(type, store)
+ } catch (e: IOException) {
+ if (e.chain().any { it is UnrecoverableKeyException } || e.message.orEmpty().contains(PASSWORD_HINT)) passwordProblem = true
+ } catch (e: java.security.GeneralSecurityException) {
+ // A provider that is not there, or an algorithm it lacks: try the next type.
+ }
+ }
+ return if (passwordProblem) KeystoreOpen.WrongPassword else KeystoreOpen.Rejected("This is not a PKCS12 or BKS keystore, or it is damaged.")
+ }
+
+ /**
+ * The private key and certificate chain under [alias]. A blank [keyPassword] means the store
+ * password, which is how a PKCS12 store is normally made.
+ */
+ fun loadKey(opened: KeystoreOpen.Opened, alias: String, keyPassword: CharArray, storePassword: CharArray): KeyLoad {
+ val password = if (keyPassword.isEmpty()) storePassword else keyPassword
+ val key =
+ try {
+ opened.store.getKey(alias, password)
+ } catch (e: UnrecoverableKeyException) {
+ return KeyLoad.Failed("The key password for \"$alias\" is wrong.")
+ } catch (e: java.security.GeneralSecurityException) {
+ return KeyLoad.Failed("The key \"$alias\" could not be read: ${e.message}")
+ }
+ if (key == null) return KeyLoad.Failed("There is no key named \"$alias\".")
+ if (key !is PrivateKey) return KeyLoad.Failed("\"$alias\" is not a private key.")
+ val chain = opened.store.getCertificateChain(alias)?.filterIsInstance().orEmpty()
+ if (chain.isEmpty()) return KeyLoad.Failed("\"$alias\" has no certificate, so it cannot sign.")
+ return KeyLoad.Loaded(SigningKey(alias, key, chain))
+ }
+
+ private fun Throwable.chain(): Sequence = generateSequence(this) { it.cause }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Naming.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Naming.kt
new file mode 100644
index 00000000..316e3bc0
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Naming.kt
@@ -0,0 +1,15 @@
+package org.appdevforall.customidebuilder.core
+
+object Naming {
+ /**
+ * `--custom.apk`, with every run of characters outside letters,
+ * digits, dot, underscore and dash turned into one dash, so the name has no spaces.
+ */
+ fun outputName(hostLabel: String, versionName: String?): String {
+ val parts = listOf(hostLabel, versionName.orEmpty(), "custom").map { clean(it) }.filter { it.isNotEmpty() }
+ return parts.joinToString("-").take(120) + ".apk"
+ }
+
+ private fun clean(text: String): String =
+ text.replace(Regex("[^A-Za-z0-9._-]+"), "-").trim('-', '.')
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Pipeline.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Pipeline.kt
new file mode 100644
index 00000000..e87ca982
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Pipeline.kt
@@ -0,0 +1,100 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.File
+
+enum class BuildStage(val label: String) {
+ CHECKING("Checking"),
+ REWRITING("Copying the app and the add-ons"),
+ SIGNING("Signing"),
+ VERIFYING("Checking the signature"),
+}
+
+class BuildException(message: String, cause: Throwable? = null) : Exception(message, cause)
+
+class BuildInput(
+ val hostApk: File,
+ /** `ApplicationInfo.splitSourceDirs`; any entry means the host is a split install. */
+ val hostSplitDirs: List,
+ val addons: List,
+ val key: SigningKey,
+ val minSdk: Int,
+ /** Where the intermediate and final files go; created if missing. */
+ val workDir: File,
+ /** The final file's name, inside [workDir]. */
+ val outputName: String,
+)
+
+class BuildOutput(val apk: File, val rewrite: RewriteReport, val verify: VerifyReport)
+
+object Pipeline {
+ /** Room kept beyond the files themselves: signing writes a second copy and apksig buffers. */
+ private const val MARGIN = 64L * 1024 * 1024
+
+ /** Bytes the build needs in [BuildInput.workDir]: the rewritten APK and the signed one, plus margin. */
+ fun spaceNeeded(apkSize: Long, addonBytes: Long): Long = 2 * (apkSize + addonBytes) + MARGIN
+
+ fun run(
+ input: BuildInput,
+ checkCancelled: () -> Unit = {},
+ onProgress: (BuildStage, Double) -> Unit = { _, _ -> },
+ ): BuildOutput {
+ onProgress(BuildStage.CHECKING, 0.0)
+ if (input.hostSplitDirs.isNotEmpty()) {
+ throw BuildException(
+ "This copy of Code on the Go was installed as split APKs, so there is no single APK to copy. " +
+ "Install the universal APK of Code on the Go and try again.",
+ )
+ }
+ if (!input.hostApk.isFile) throw BuildException("The installed app's APK (${input.hostApk.path}) cannot be read.")
+ if (input.hostApk.name.endsWith(".cgp", ignoreCase = true)) {
+ throw BuildException("That is a plugin file, not the Code on the Go APK.")
+ }
+ input.workDir.mkdirs()
+ val addonBytes = input.addons.sumOf { it.file.length() }
+ val needed = spaceNeeded(input.hostApk.length(), addonBytes)
+ if (input.workDir.usableSpace < needed) {
+ throw BuildException(
+ "Not enough free space: the build needs about ${needed / (1024 * 1024)} MB and " +
+ "${input.workDir.usableSpace / (1024 * 1024)} MB is free.",
+ )
+ }
+
+ val unsigned = File(input.workDir, "unsigned.apk.tmp")
+ val signed = File(input.workDir, input.outputName)
+ try {
+ val report =
+ try {
+ ApkRewriter.rewrite(input.hostApk, unsigned, input.addons, checkCancelled) { onProgress(BuildStage.REWRITING, it) }
+ } catch (e: java.io.IOException) {
+ throw BuildException("Copying the app failed: ${e.message}", e)
+ }
+ checkCancelled()
+ onProgress(BuildStage.SIGNING, 0.0)
+ try {
+ Signing.sign(unsigned, signed, input.key, input.minSdk)
+ } catch (e: SigningException) {
+ throw BuildException(e.message ?: "Signing failed", e)
+ }
+ unsigned.delete()
+ checkCancelled()
+ onProgress(BuildStage.VERIFYING, 0.0)
+ val verify = Signing.verify(signed, input.minSdk)
+ if (!verify.verified) {
+ throw BuildException("The signed APK did not verify: ${verify.errors.joinToString("; ").ifEmpty { "unknown reason" }}")
+ }
+ if (!verify.v1 || !verify.v2 || !verify.v3) {
+ throw BuildException("The signed APK is missing a signature scheme (v1=${verify.v1}, v2=${verify.v2}, v3=${verify.v3}).")
+ }
+ val misaligned = ZipAlignment.misaligned(signed)
+ if (misaligned.isNotEmpty()) {
+ throw BuildException("The signed APK has uncompressed files that are not aligned, such as ${misaligned.first()}; Android may refuse to install it.")
+ }
+ return BuildOutput(signed, report, verify)
+ } catch (t: Throwable) {
+ signed.delete()
+ throw t
+ } finally {
+ unsigned.delete()
+ }
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Selection.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Selection.kt
new file mode 100644
index 00000000..4da0785c
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Selection.kt
@@ -0,0 +1,92 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.File
+
+/**
+ * An add-on the user chose, before it is checked. [label] is what the screen calls it (the
+ * picked file's name, or the catalog name); [pluginId] is the `plugin.id` read from a .cgp's
+ * manifest and is null for a template or a .cgp whose manifest could not be read.
+ */
+class PickedAddon(val label: String, val fileName: String, val file: File, val pluginId: String?)
+
+sealed class SelectionResult {
+ class Valid(val staged: List) : SelectionResult()
+
+ class Invalid(val problems: List) : SelectionResult()
+}
+
+object AddonSelection {
+ /** The kind a file name asks for, by extension in any case, or null for anything else. */
+ fun kindOf(fileName: String): AddonKind? =
+ AddonKind.values().firstOrNull { fileName.endsWith(".${it.extension}", ignoreCase = true) }
+
+ /**
+ * The host refuses a plugin ID that is a path, since it names the plugin's folder
+ * (PluginIdTest in Code on the Go). Applying the same rule here catches it before a build.
+ */
+ fun isUsablePluginId(id: String): Boolean =
+ id.isNotEmpty() && id != "." && id != ".." && id.none { it == '/' || it == '\\' || it == '\u0000' } && id.trim() == id
+
+ /** A zip entry name that is safe on every file system and acceptable to the host's own name rule. */
+ fun entryNameFor(base: String): String {
+ val cleaned = base.map { if (it.isLetterOrDigit() && it.code < 128 || it == '.' || it == '_' || it == '-') it else '_' }.joinToString("")
+ return cleaned.trimStart('.').ifEmpty { "addon" }.take(100)
+ }
+
+ /**
+ * Checks the whole selection and assigns entry names, or lists every problem found:
+ * a file that is neither .cgp nor .cgt, `core.cgt`, a plugin without a usable ID, two plugins
+ * with one ID, two templates with one file name. Nothing is dropped silently.
+ */
+ fun validate(picked: List): SelectionResult {
+ val problems = ArrayList()
+ val staged = ArrayList()
+ val pluginIds = HashMap()
+ val templateNames = HashMap()
+ for (p in picked) {
+ val kind = kindOf(p.fileName)
+ if (kind == null) {
+ problems.add("${p.label}: not a .cgp or .cgt file")
+ continue
+ }
+ val stem = p.fileName.substring(0, p.fileName.length - kind.extension.length - 1)
+ when (kind) {
+ AddonKind.PLUGIN -> {
+ val id = p.pluginId
+ if (id == null) {
+ problems.add("${p.label}: could not read the plugin ID from its manifest, so it is not a plugin Code on the Go can install")
+ continue
+ }
+ if (!isUsablePluginId(id)) {
+ problems.add("${p.label}: the plugin ID \"$id\" is not a valid name")
+ continue
+ }
+ val earlier = pluginIds.put(id, p)
+ if (earlier != null) {
+ problems.add("${p.label} and ${earlier.label} are both the plugin $id; include one")
+ continue
+ }
+ staged.add(StagedAddon(kind, entryNameFor(id) + ".cgp", p.file))
+ }
+ AddonKind.TEMPLATE -> {
+ val name = entryNameFor(stem) + ".cgt"
+ if (name.equals(CORE_TEMPLATE, ignoreCase = true)) {
+ problems.add("${p.label}: core.cgt is installed by Code on the Go itself and is never bundled")
+ continue
+ }
+ val earlier = templateNames.put(name.lowercase(), p)
+ if (earlier != null) {
+ problems.add("${p.label} and ${earlier.label} have the same file name; include one")
+ continue
+ }
+ staged.add(StagedAddon(kind, name, p.file))
+ }
+ }
+ }
+ // Two different plugin IDs can still clean up to one entry name.
+ staged.groupBy { it.kind to it.fileName.lowercase() }.filterValues { it.size > 1 }.forEach { (key, _) ->
+ problems.add("two ${key.first.dir} would be stored as ${key.second}; their names differ only in characters a file name cannot hold")
+ }
+ return if (problems.isEmpty()) SelectionResult.Valid(staged) else SelectionResult.Invalid(problems)
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Signing.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Signing.kt
new file mode 100644
index 00000000..efb7bfc9
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Signing.kt
@@ -0,0 +1,58 @@
+package org.appdevforall.customidebuilder.core
+
+import com.android.apksig.ApkSigner
+import com.android.apksig.ApkVerifier
+import java.io.File
+import java.security.MessageDigest
+
+class SigningException(message: String, cause: Throwable? = null) : Exception(message, cause)
+
+class VerifyReport(
+ val verified: Boolean,
+ val v1: Boolean,
+ val v2: Boolean,
+ val v3: Boolean,
+ val signerSha256: String?,
+ val errors: List,
+)
+
+/** Signs and checks an APK with apksig: v1, v2 and v3 together. */
+object Signing {
+ /**
+ * Signs [input] into [output] with [key]. [minSdk] is the lowest Android version the APK
+ * runs on; it is given rather than read from the APK so apksig never has to parse the
+ * manifest, and it decides which schemes are needed (v1 is forced on here regardless).
+ * The old v1 signature files were already dropped by [ApkRewriter]; apksig strips any
+ * signing block itself.
+ */
+ fun sign(input: File, output: File, key: SigningKey, minSdk: Int) {
+ try {
+ val signer = ApkSigner.SignerConfig.Builder("CERT", key.privateKey, key.chain).build()
+ ApkSigner.Builder(listOf(signer))
+ .setInputApk(input)
+ .setOutputApk(output)
+ .setMinSdkVersion(minSdk)
+ .setV1SigningEnabled(true)
+ .setV2SigningEnabled(true)
+ .setV3SigningEnabled(true)
+ .build()
+ .sign()
+ } catch (e: Exception) {
+ throw SigningException("Signing failed: ${e.message ?: e.javaClass.simpleName}", e)
+ }
+ }
+
+ /** Verifies every scheme in [apk]; used on the finished file before it is handed to the user. */
+ fun verify(apk: File, minSdk: Int): VerifyReport {
+ val result = ApkVerifier.Builder(apk).setMinCheckedPlatformVersion(minSdk).build().verify()
+ val signer = result.signerCertificates.firstOrNull()
+ return VerifyReport(
+ verified = result.isVerified,
+ v1 = result.isVerifiedUsingV1Scheme,
+ v2 = result.isVerifiedUsingV2Scheme,
+ v3 = result.isVerifiedUsingV3Scheme,
+ signerSha256 = signer?.let { MessageDigest.getInstance("SHA-256").digest(it.encoded).joinToString(":") { b -> "%02X".format(b) } },
+ errors = result.errors.map { it.toString() },
+ )
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
new file mode 100644
index 00000000..b7411b07
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
@@ -0,0 +1,363 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.BufferedOutputStream
+import java.io.Closeable
+import java.io.File
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.io.RandomAccessFile
+
+/** A zip this code cannot read or write: encrypted, ZIP64, damaged or duplicated entries. */
+class ZipFormatException(message: String) : IOException(message)
+
+/**
+ * One central-directory record of a zip. Everything the writer needs to copy the entry without
+ * touching its compressed bytes: [nameBytes] stay exactly as stored.
+ */
+class RawZipEntry(
+ val nameBytes: ByteArray,
+ val versionMadeBy: Int,
+ val flags: Int,
+ val method: Int,
+ val dosTime: Int,
+ val dosDate: Int,
+ val crc: Long,
+ val compressedSize: Long,
+ val size: Long,
+ val internalAttributes: Int,
+ val externalAttributes: Long,
+ val localHeaderOffset: Long,
+) {
+ val name: String = String(nameBytes, Charsets.UTF_8)
+ val isDirectory: Boolean get() = name.endsWith("/")
+ val isStored: Boolean get() = method == METHOD_STORED
+}
+
+const val METHOD_STORED = 0
+
+private const val SIG_LOCAL = 0x04034b50L
+private const val SIG_CENTRAL = 0x02014b50L
+private const val SIG_EOCD = 0x06054b50L
+private const val SIG_ZIP64_LOCATOR = 0x07064b50L
+private const val FLAG_ENCRYPTED = 0x0001
+private const val FLAG_DATA_DESCRIPTOR = 0x0008
+
+/**
+ * Reads a zip's central directory and hands out entries' compressed bytes as stored. The file is
+ * never inflated and the APK Signing Block between the entries and the central directory is
+ * simply never read, which is why a signed APK can be reused as input.
+ */
+class RawZipFile(private val file: File) : Closeable {
+ private val raf = RandomAccessFile(file, "r")
+ val entries: List
+
+ init {
+ try {
+ entries = readCentralDirectory()
+ } catch (t: Throwable) {
+ raf.close()
+ throw t
+ }
+ }
+
+ private fun readCentralDirectory(): List {
+ val length = raf.length()
+ if (length < 22) throw ZipFormatException("${file.name} is too small to be a zip file")
+ val tailSize = minOf(length, 22L + 0xFFFF).toInt()
+ val tail = ByteArray(tailSize)
+ raf.seek(length - tailSize)
+ raf.readFully(tail)
+ var eocd = -1
+ for (i in tailSize - 22 downTo 0) {
+ if (u32(tail, i) == SIG_EOCD && i + 22 + u16(tail, i + 20) == tailSize) {
+ eocd = i
+ break
+ }
+ }
+ if (eocd < 0) throw ZipFormatException("${file.name} has no zip end record")
+ if (eocd >= 20 && u32(tail, eocd - 20) == SIG_ZIP64_LOCATOR) {
+ throw ZipFormatException("${file.name} is a ZIP64 archive, which is not supported")
+ }
+ val disk = u16(tail, eocd + 4)
+ val cdDisk = u16(tail, eocd + 6)
+ val count = u16(tail, eocd + 10)
+ val cdSize = u32(tail, eocd + 12)
+ val cdOffset = u32(tail, eocd + 16)
+ if (disk != 0 || cdDisk != 0) throw ZipFormatException("${file.name} is a multi-part zip")
+ if (count == 0xFFFF || cdSize == 0xFFFFFFFFL || cdOffset == 0xFFFFFFFFL) {
+ throw ZipFormatException("${file.name} is a ZIP64 archive, which is not supported")
+ }
+ if (cdOffset + cdSize > length) throw ZipFormatException("${file.name} has a damaged central directory")
+ val cd = ByteArray(cdSize.toInt())
+ raf.seek(cdOffset)
+ raf.readFully(cd)
+
+ val result = ArrayList(count)
+ val seen = HashSet()
+ var p = 0
+ repeat(count) {
+ if (p + 46 > cd.size || u32(cd, p) != SIG_CENTRAL) {
+ throw ZipFormatException("${file.name} has a damaged central directory")
+ }
+ val flags = u16(cd, p + 8)
+ val nameLen = u16(cd, p + 28)
+ val extraLen = u16(cd, p + 30)
+ val commentLen = u16(cd, p + 32)
+ val compressed = u32(cd, p + 20)
+ val size = u32(cd, p + 24)
+ val offset = u32(cd, p + 42)
+ if (p + 46 + nameLen + extraLen + commentLen > cd.size) {
+ throw ZipFormatException("${file.name} has a damaged central directory")
+ }
+ val nameBytes = cd.copyOfRange(p + 46, p + 46 + nameLen)
+ val name = String(nameBytes, Charsets.UTF_8)
+ if (flags and FLAG_ENCRYPTED != 0) throw ZipFormatException("$name is encrypted, which is not supported")
+ if (compressed == 0xFFFFFFFFL || size == 0xFFFFFFFFL || offset == 0xFFFFFFFFL) {
+ throw ZipFormatException("$name needs ZIP64, which is not supported")
+ }
+ if (!seen.add(name)) throw ZipFormatException("${file.name} holds $name twice")
+ result.add(
+ RawZipEntry(
+ nameBytes = nameBytes,
+ versionMadeBy = u16(cd, p + 4),
+ flags = flags,
+ method = u16(cd, p + 10),
+ dosTime = u16(cd, p + 12),
+ dosDate = u16(cd, p + 14),
+ crc = u32(cd, p + 16),
+ compressedSize = compressed,
+ size = size,
+ internalAttributes = u16(cd, p + 36),
+ externalAttributes = u32(cd, p + 38),
+ localHeaderOffset = offset,
+ ),
+ )
+ p += 46 + nameLen + extraLen + commentLen
+ }
+ return result
+ }
+
+ /** Where [entry]'s data starts, read from its local header (whose extra field may differ from the central one). */
+ fun dataOffset(entry: RawZipEntry): Long {
+ val header = ByteArray(30)
+ raf.seek(entry.localHeaderOffset)
+ try {
+ raf.readFully(header)
+ } catch (e: java.io.EOFException) {
+ throw ZipFormatException("${entry.name} has a damaged local header")
+ }
+ if (u32(header, 0) != SIG_LOCAL) throw ZipFormatException("${entry.name} has a damaged local header")
+ val start = entry.localHeaderOffset + 30 + u16(header, 26) + u16(header, 28)
+ if (start + entry.compressedSize > raf.length()) throw ZipFormatException("${entry.name} runs past the end of the file")
+ return start
+ }
+
+ /** Copies [entry]'s compressed bytes, unchanged, to [out]. */
+ fun copyRaw(entry: RawZipEntry, out: OutputStream, onBytes: (Int) -> Unit = {}) {
+ raf.seek(dataOffset(entry))
+ val buffer = ByteArray(64 * 1024)
+ var left = entry.compressedSize
+ while (left > 0) {
+ val n = raf.read(buffer, 0, minOf(buffer.size.toLong(), left).toInt())
+ if (n < 0) throw ZipFormatException("${entry.name} runs past the end of the file")
+ out.write(buffer, 0, n)
+ onBytes(n)
+ left -= n
+ }
+ }
+
+ override fun close() = raf.close()
+}
+
+/** What zipalign requires of an entry whose data is stored uncompressed. */
+object ZipAlignment {
+ const val DEFAULT = 4
+ const val SHARED_LIBRARY = 16384
+
+ fun requiredFor(name: String): Int = if (name.endsWith(".so")) SHARED_LIBRARY else DEFAULT
+
+ /** Stored entries of [apk] whose data is not where [requiredFor] says it should start. */
+ fun misaligned(apk: File): List =
+ RawZipFile(apk).use { zip ->
+ zip.entries
+ .filter { it.isStored && !it.isDirectory && it.compressedSize > 0 }
+ .filter { zip.dataOffset(it) % requiredFor(it.name) != 0L }
+ .map { it.name }
+ }
+}
+
+/**
+ * A minimal zip writer that can emit entries whose data is already compressed, which
+ * `java.util.zip.ZipOutputStream` cannot. No ZIP64 (an APK is far below 4 GiB and 65535 entries),
+ * no data descriptors and no archive comment. Stored entries are padded through the local header's
+ * extra field so their data starts where [ZipAlignment.requiredFor] says.
+ */
+class RawZipWriter(output: OutputStream) : Closeable {
+ private class Written(val entry: RawZipEntry, val flags: Int, val offset: Long)
+
+ private val out = BufferedOutputStream(output, 64 * 1024)
+ private val written = ArrayList()
+ private val names = HashSet()
+ private var offset = 0L
+
+ /**
+ * Writes [source] with its method, CRC, sizes and timestamps as they are. [copyData] must write
+ * exactly `source.compressedSize` bytes. The data-descriptor flag is cleared because the sizes
+ * go in the header.
+ */
+ fun addRaw(source: RawZipEntry, copyData: (OutputStream) -> Unit) {
+ val flags = source.flags and FLAG_DATA_DESCRIPTOR.inv()
+ begin(source, flags, copyData)
+ }
+
+ /** Writes a new stored entry of [size] bytes with the given [crc], dated 1 January 1980. */
+ fun addStored(name: String, size: Long, crc: Long, writeData: (OutputStream) -> Unit) {
+ val entry = RawZipEntry(
+ nameBytes = name.toByteArray(Charsets.UTF_8),
+ versionMadeBy = 20,
+ flags = 0x0800,
+ method = METHOD_STORED,
+ dosTime = 0,
+ dosDate = DOS_1980,
+ crc = crc,
+ compressedSize = size,
+ size = size,
+ internalAttributes = 0,
+ externalAttributes = 0,
+ localHeaderOffset = 0,
+ )
+ begin(entry, entry.flags, writeData)
+ }
+
+ private fun begin(entry: RawZipEntry, flags: Int, writeData: (OutputStream) -> Unit) {
+ if (!names.add(entry.name)) throw ZipFormatException("${entry.name} would be written twice")
+ if (written.size >= 0xFFFE) throw ZipFormatException("too many zip entries")
+ val padding =
+ if (entry.isStored && !entry.isDirectory && entry.compressedSize > 0) {
+ val align = ZipAlignment.requiredFor(entry.name)
+ ((align - (offset + 30 + entry.nameBytes.size) % align) % align).toInt()
+ } else {
+ 0
+ }
+ val headerOffset = offset
+ u32(SIG_LOCAL)
+ u16(20)
+ u16(flags)
+ u16(entry.method)
+ u16(entry.dosTime)
+ u16(entry.dosDate)
+ u32(entry.crc)
+ u32(entry.compressedSize)
+ u32(entry.size)
+ u16(entry.nameBytes.size)
+ u16(padding)
+ raw(entry.nameBytes)
+ raw(ByteArray(padding))
+ val dataStart = offset
+ writeData(CountingSink())
+ if (offset - dataStart != entry.compressedSize) {
+ throw ZipFormatException("${entry.name}: wrote ${offset - dataStart} bytes where ${entry.compressedSize} were expected")
+ }
+ written.add(Written(entry, flags, headerOffset))
+ }
+
+ /** Appends the central directory and the end record. The output stream is closed. */
+ override fun close() {
+ val cdStart = offset
+ for (w in written) {
+ val e = w.entry
+ u32(SIG_CENTRAL)
+ u16(e.versionMadeBy)
+ u16(20)
+ u16(w.flags)
+ u16(e.method)
+ u16(e.dosTime)
+ u16(e.dosDate)
+ u32(e.crc)
+ u32(e.compressedSize)
+ u32(e.size)
+ u16(e.nameBytes.size)
+ u16(0)
+ u16(0)
+ u16(0)
+ u16(e.internalAttributes)
+ u32(e.externalAttributes)
+ u32(w.offset)
+ raw(e.nameBytes)
+ }
+ val cdSize = offset - cdStart
+ u32(SIG_EOCD)
+ u16(0)
+ u16(0)
+ u16(written.size)
+ u16(written.size)
+ u32(cdSize)
+ u32(cdStart)
+ u16(0)
+ out.close()
+ }
+
+ private inner class CountingSink : OutputStream() {
+ override fun write(b: Int) {
+ out.write(b)
+ offset++
+ checkRange()
+ }
+
+ override fun write(b: ByteArray, off: Int, len: Int) {
+ out.write(b, off, len)
+ offset += len
+ checkRange()
+ }
+ }
+
+ private fun checkRange() {
+ if (offset > 0xFFFFFFFFL) throw ZipFormatException("the zip would pass 4 GiB, which needs ZIP64")
+ }
+
+ private fun u16(v: Int) {
+ out.write(v and 0xFF)
+ out.write((v ushr 8) and 0xFF)
+ offset += 2
+ }
+
+ private fun u32(v: Long) {
+ for (shift in 0..24 step 8) out.write(((v ushr shift) and 0xFF).toInt())
+ offset += 4
+ }
+
+ private fun raw(bytes: ByteArray) {
+ out.write(bytes)
+ offset += bytes.size
+ }
+
+ private companion object {
+ const val DOS_1980 = 0x0021
+ }
+}
+
+private fun u16(b: ByteArray, i: Int): Int = (b[i].toInt() and 0xFF) or ((b[i + 1].toInt() and 0xFF) shl 8)
+
+private fun u32(b: ByteArray, i: Int): Long = u16(b, i).toLong() or (u16(b, i + 2).toLong() shl 16)
+
+/** A file's size, CRC-32 and SHA-256 (lowercase hex). */
+data class FileDigest(val size: Long, val crc: Long, val sha256: String)
+
+/** Reads [file] once, reporting each chunk, and returns its [FileDigest]. */
+fun digestOf(file: File, onBytes: (Int) -> Unit = {}): FileDigest {
+ val crc = java.util.zip.CRC32()
+ val sha = java.security.MessageDigest.getInstance("SHA-256")
+ var size = 0L
+ file.inputStream().use { input -> pump(input) { buf, n -> crc.update(buf, 0, n); sha.update(buf, 0, n); size += n; onBytes(n) } }
+ return FileDigest(size, crc.value, sha.digest().joinToString("") { "%02x".format(it) })
+}
+
+internal inline fun pump(input: InputStream, each: (ByteArray, Int) -> Unit) {
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ val n = input.read(buffer)
+ if (n < 0) return
+ each(buffer, n)
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
new file mode 100644
index 00000000..0e0a203d
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
@@ -0,0 +1,173 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+import java.util.zip.ZipFile
+
+class ApkRewriterTest {
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ private fun rewriteWith(addons: List): Triple {
+ val source = tmp.newFile("source.apk")
+ TestSupport.syntheticApk(source)
+ val output = tmp.newFile("out.apk")
+ val report = ApkRewriter.rewrite(source, output, addons)
+ return Triple(source, output, report)
+ }
+
+ private fun twoAddons() = listOf(
+ TestSupport.staged(tmp.root, AddonKind.PLUGIN, "org.example.plugin.cgp", TestSupport.noise(1234, 10)),
+ TestSupport.staged(tmp.root, AddonKind.TEMPLATE, "starter.cgt", TestSupport.text(999)),
+ )
+
+ @Test
+ fun dropsTheOldBundleTheOldIndexAndTheV1Signature() {
+ val (_, output, report) = rewriteWith(twoAddons())
+ val names = RawZipFile(output).use { z -> z.entries.map { it.name } }
+ for (gone in listOf("assets/plugins/old.cgp", "assets/templates/old.cgt", "META-INF/MANIFEST.MF", "META-INF/OLD.SF", "META-INF/OLD.RSA")) {
+ assertFalse("$gone should be gone", gone in names)
+ }
+ assertEquals(
+ setOf("assets/plugins/old.cgp", "assets/templates/old.cgt", "assets/bundled-addons.tsv", "META-INF/MANIFEST.MF", "META-INF/OLD.SF", "META-INF/OLD.RSA"),
+ report.dropped.toSet(),
+ )
+ assertTrue("META-INF/services/example.Service" in names)
+ assertTrue("assets/keep.txt" in names)
+ }
+
+ @Test
+ fun copiesEveryOtherEntryByteForByteWithoutRecompressing() {
+ val (source, output, _) = rewriteWith(twoAddons())
+ RawZipFile(source).use { src ->
+ RawZipFile(output).use { out ->
+ val byName = out.entries.associateBy { it.name }
+ val kept = src.entries.filterNot { ApkRewriter.isDropped(it.name) }
+ assertTrue(kept.size > 5)
+ for (s in kept) {
+ val o = byName.getValue(s.name)
+ assertEquals("method of ${s.name}", s.method, o.method)
+ assertEquals("crc of ${s.name}", s.crc, o.crc)
+ assertEquals("size of ${s.name}", s.size, o.size)
+ assertEquals("compressed size of ${s.name}", s.compressedSize, o.compressedSize)
+ assertEquals("time of ${s.name}", s.dosTime, o.dosTime)
+ assertEquals("date of ${s.name}", s.dosDate, o.dosDate)
+ assertArrayEquals("raw bytes of ${s.name}", TestSupport.rawBytes(src, s), TestSupport.rawBytes(out, o))
+ }
+ // The deflated entries really are compressed in the output, not stored.
+ assertEquals(8, byName.getValue("classes.dex").method)
+ assertTrue(byName.getValue("classes.dex").compressedSize < byName.getValue("classes.dex").size / 10)
+ }
+ }
+ }
+
+ @Test
+ fun theOutputIsAZipJavaCanReadWithTheSameContent() {
+ val (_, output, _) = rewriteWith(twoAddons())
+ ZipFile(output).use { zip ->
+ val dex = zip.getInputStream(zip.getEntry("classes.dex")).readBytes()
+ assertArrayEquals(TestSupport.text(200_000), dex)
+ assertArrayEquals(TestSupport.noise(10_001, 3), zip.getInputStream(zip.getEntry("lib/arm64-v8a/libnative.so")).readBytes())
+ }
+ }
+
+ @Test
+ fun storedEntriesAreAlignedAndSharedLibrariesToSixteenKilobytes() {
+ val (_, output, _) = rewriteWith(twoAddons())
+ assertEquals(emptyList(), ZipAlignment.misaligned(output))
+ RawZipFile(output).use { z ->
+ val so = z.entries.first { it.name == "lib/arm64-v8a/libnative.so" }
+ assertEquals(0L, z.dataOffset(so) % 16384)
+ val arsc = z.entries.first { it.name == "resources.arsc" }
+ assertEquals(0L, z.dataOffset(arsc) % 4)
+ for (e in z.entries.filter { it.isStored && it.compressedSize > 0 }) assertEquals(e.name, 0L, z.dataOffset(e) % ZipAlignment.requiredFor(e.name))
+ }
+ }
+
+ @Test
+ fun addsTheChosenAddonsAndAFreshIndex() {
+ val addons = twoAddons()
+ val (_, output, report) = rewriteWith(addons)
+ ZipFile(output).use { zip ->
+ assertArrayEquals(TestSupport.noise(1234, 10), zip.getInputStream(zip.getEntry("assets/plugins/org.example.plugin.cgp")).readBytes())
+ assertArrayEquals(TestSupport.text(999), zip.getInputStream(zip.getEntry("assets/templates/starter.cgt")).readBytes())
+ val index = zip.getInputStream(zip.getEntry("assets/bundled-addons.tsv")).readBytes().toString(Charsets.UTF_8)
+ assertEquals(report.index, index)
+ val lines = index.lines().filter { it.isNotEmpty() }
+ assertEquals(2, lines.size)
+ assertTrue(lines[0].startsWith("plugins/org.example.plugin.cgp\t1234\t"))
+ assertTrue(lines[1].startsWith("templates/starter.cgt\t999\t"))
+ assertFalse("the old index line must not survive", index.contains("old.cgp"))
+ }
+ assertEquals(
+ listOf("assets/plugins/org.example.plugin.cgp", "assets/templates/starter.cgt", "assets/bundled-addons.tsv"),
+ report.added,
+ )
+ }
+
+ @Test
+ fun anEmptySelectionLeavesAnEmptyIndexAndNoAddons() {
+ val (_, output, report) = rewriteWith(emptyList())
+ assertEquals("", report.index)
+ ZipFile(output).use { zip ->
+ assertEquals(0L, zip.getEntry("assets/bundled-addons.tsv").size)
+ assertTrue(zip.entries().asSequence().none { it.name.startsWith("assets/plugins/") || it.name.startsWith("assets/templates/") })
+ }
+ }
+
+ @Test
+ fun whichNamesAreDropped() {
+ for (name in listOf("assets/plugins/a.cgp", "assets/plugins/", "assets/templates/x/y.cgt", "assets/bundled-addons.tsv", "META-INF/MANIFEST.MF", "META-INF/CERT.SF", "META-INF/CERT.RSA", "META-INF/CERT.DSA", "META-INF/CERT.EC", "META-INF/cert.rsa")) {
+ assertTrue(name, ApkRewriter.isDropped(name))
+ }
+ for (name in listOf("assets/other/a.cgp", "assets/pluginsX", "classes.dex", "META-INF/services/a.SF", "META-INF/com/android/build/gradle/app-metadata.properties", "META-INF/CERT.TXT", "lib/x/libplugins.so")) {
+ assertFalse(name, ApkRewriter.isDropped(name))
+ }
+ }
+
+ @Test
+ fun aSourceWithTrailingJunkBetweenEntriesAndDirectoryIsStillCopied() {
+ val source = tmp.newFile("signed-like.apk")
+ TestSupport.syntheticApk(source)
+ // Put 4 KB of junk, like a signing block, between the last entry and the central directory.
+ val bytes = source.readBytes()
+ val eocd = bytes.size - 22
+ val cdOffset = (bytes[eocd + 16].toInt() and 0xFF) or ((bytes[eocd + 17].toInt() and 0xFF) shl 8) or
+ ((bytes[eocd + 18].toInt() and 0xFF) shl 16) or ((bytes[eocd + 19].toInt() and 0xFF) shl 24)
+ val junk = ByteArray(4096) { 0x5A }
+ val patched = bytes.copyOfRange(0, cdOffset) + junk + bytes.copyOfRange(cdOffset, bytes.size)
+ val shift = junk.size
+ // Central directory records hold offsets of local headers, which do not move; only the end record's does.
+ val newCd = cdOffset + shift
+ patched[eocd + shift + 16] = newCd.toByte()
+ patched[eocd + shift + 17] = (newCd ushr 8).toByte()
+ patched[eocd + shift + 18] = (newCd ushr 16).toByte()
+ patched[eocd + shift + 19] = (newCd ushr 24).toByte()
+ source.writeBytes(patched)
+ val out = tmp.newFile("out2.apk")
+ ApkRewriter.rewrite(source, out, emptyList())
+ assertFalse(out.readBytes().toString(Charsets.ISO_8859_1).contains("ZZZZZZZZ"))
+ ZipFile(out).use { assertTrue(it.getEntry("classes.dex") != null) }
+ }
+
+ @Test(expected = ZipFormatException::class)
+ fun twoAddonsForOneEntryAreRefused() {
+ val a = TestSupport.staged(tmp.root, AddonKind.PLUGIN, "same.cgp", TestSupport.text(10))
+ val b = StagedAddon(AddonKind.PLUGIN, "same.cgp", a.file)
+ val source = tmp.newFile("s.apk")
+ TestSupport.syntheticApk(source)
+ ApkRewriter.rewrite(source, tmp.newFile("o.apk"), listOf(a, b))
+ }
+
+ @Test(expected = ZipFormatException::class)
+ fun aFileThatIsNotAZipIsRefused() {
+ val notZip = tmp.newFile("not.apk").also { it.writeBytes(ByteArray(100)) }
+ ApkRewriter.rewrite(notZip, tmp.newFile("o.apk"), emptyList())
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/BundleIndexTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/BundleIndexTest.kt
new file mode 100644
index 00000000..ffcad1d8
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/BundleIndexTest.kt
@@ -0,0 +1,106 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/** Reads the index the way the host does; the logic below is copied from Code on the Go. */
+class BundleIndexTest {
+ // Copied from CodeOnTheGo app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddons.kt
+ // (BundledAddons.parseIndex, isAddonFile, parse and SHA256_HEX), with BundledAddonKind reduced to
+ // its dir and extension. Keep in step with it.
+ private data class HostEntry(val kind: AddonKind, val fileName: String, val size: Long, val sha256: String?)
+
+ private val sha256Hex = Regex("[0-9a-f]{64}")
+
+ private fun hostIsAddonFile(kind: AddonKind, fileName: String): Boolean =
+ '/' !in fileName &&
+ !fileName.startsWith(".") &&
+ fileName.endsWith(".${kind.extension}", ignoreCase = true) &&
+ !(kind == AddonKind.TEMPLATE && fileName.equals("core.cgt", ignoreCase = true))
+
+ private fun hostParse(entryName: String): Pair? {
+ val kind = AddonKind.values().firstOrNull { entryName.startsWith("${it.dir}/") } ?: return null
+ val fileName = entryName.removePrefix("${kind.dir}/")
+ return if (hostIsAddonFile(kind, fileName)) kind to fileName else null
+ }
+
+ private fun hostParseIndex(text: String): List? {
+ val entries =
+ text.lines().filter { it.isNotBlank() }.map { line ->
+ val fields = line.split('\t')
+ if (fields.size != 3) return null
+ val (kind, fileName) = hostParse(fields[0]) ?: return null
+ val size = fields[1].toLongOrNull()?.takeIf { it >= 0 } ?: return null
+ val sha256 = fields[2].takeIf { sha256Hex.matches(it) } ?: return null
+ HostEntry(kind, fileName, size, sha256)
+ }
+ if (entries.distinctBy { "${it.kind.dir}/${it.fileName}" }.size != entries.size) return null
+ return entries.sortedWith(compareBy({ it.kind.ordinal }, { it.fileName }))
+ }
+
+ private fun sha(c: Char) = c.toString().repeat(64)
+
+ @Test
+ fun theHostReadsBackExactlyWhatWasWritten() {
+ val lines = listOf(
+ IndexLine(AddonKind.TEMPLATE, "zeta.cgt", 5, sha('a')),
+ IndexLine(AddonKind.PLUGIN, "org.b.cgp", 10, sha('b')),
+ IndexLine(AddonKind.TEMPLATE, "alpha.cgt", 0, sha('c')),
+ IndexLine(AddonKind.PLUGIN, "org.a.cgp", 99_999_999_999, sha('d')),
+ )
+ val text = BundleIndex.render(lines)
+ val parsed = hostParseIndex(text)
+ assertNotNull("the host must accept the index", parsed)
+ assertEquals(
+ listOf(
+ HostEntry(AddonKind.PLUGIN, "org.a.cgp", 99_999_999_999, sha('d')),
+ HostEntry(AddonKind.PLUGIN, "org.b.cgp", 10, sha('b')),
+ HostEntry(AddonKind.TEMPLATE, "alpha.cgt", 0, sha('c')),
+ HostEntry(AddonKind.TEMPLATE, "zeta.cgt", 5, sha('a')),
+ ),
+ parsed,
+ )
+ }
+
+ @Test
+ fun theTextIsExactlyTheBuildsFormat() {
+ val text = BundleIndex.render(
+ listOf(IndexLine(AddonKind.TEMPLATE, "t.cgt", 2, sha('2')), IndexLine(AddonKind.PLUGIN, "p.cgp", 1, sha('1'))),
+ )
+ assertEquals("plugins/p.cgp\t1\t${sha('1')}\ntemplates/t.cgt\t2\t${sha('2')}\n", text)
+ }
+
+ @Test
+ fun anEmptySelectionIsAnEmptyIndexWhichTheHostTreatsAsAThinBuild() {
+ val text = BundleIndex.render(emptyList())
+ assertEquals("", text)
+ // Not null: null would send the host to listing the folders. An empty list is a thin build.
+ assertEquals(emptyList(), hostParseIndex(text))
+ }
+
+ @Test
+ fun theHostRejectsWhatItShould() {
+ assertNull(hostParseIndex("plugins/a.cgp\t1\tnothex\n"))
+ assertNull(hostParseIndex("templates/core.cgt\t1\t${sha('a')}\n"))
+ }
+
+ @Test
+ fun everyNameTheSelectionAssignsIsAnAddonFileToTheHost() {
+ val picked = listOf(
+ PickedAddon("a", "My Plugin (1).cgp", java.io.File("x"), "org.weird/id with spaces"),
+ PickedAddon("b", "Flutter Starter Kit.CGT", java.io.File("y"), null),
+ )
+ val result = AddonSelection.validate(picked.take(1)) as? SelectionResult.Invalid
+ // A plugin ID that is a path is refused, not turned into a name.
+ assertNotNull(result)
+ val ok = AddonSelection.validate(
+ listOf(
+ PickedAddon("a", "My Plugin (1).cgp", java.io.File("x"), "org.example.plugin"),
+ picked[1],
+ ),
+ ) as SelectionResult.Valid
+ for (s in ok.staged) assertNotNull(s.fileName, hostParse("${s.kind.dir}/${s.fileName}"))
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
new file mode 100644
index 00000000..19f1217b
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
@@ -0,0 +1,213 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.ByteArrayInputStream
+import java.io.File
+import java.io.IOException
+import java.security.MessageDigest
+
+class CatalogTest {
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
+
+ private fun entry(type: String, slug: String, min: String, sha: String = "a".repeat(64), size: Long = 10, url: String = "https://addons.appdevforall.org/dl/$slug.cgp") =
+ """{"type":"$type","slug":"$slug","addonId":"id.$slug","name":"Name $slug","version":"1.0","summary":"s","minAppVersion":"$min","download":{"url":"$url","sha256":"$sha","size":$size}}"""
+
+ private fun catalog(vararg entries: String) = """{"schemaVersion":2,"generated":"x","addons":[${entries.joinToString(",")}]}"""
+
+ @Test
+ fun filtersByMinAppVersionAndType() {
+ val parsed = Catalog.parse(
+ catalog(
+ entry("plugin", "old", "26.17"),
+ entry("plugin", "same", "26.45"),
+ entry("plugin", "newer", "26.46"),
+ entry("template", "tpl", "26.40"),
+ entry("template", "tpl-new", "27.01"),
+ entry("snippet", "snip", "26.01"),
+ entry("code-action", "action", "26.01"),
+ entry("plugin", "nomin", ""),
+ ),
+ )
+ val offer = Catalog.offer(parsed.addons, "26.45")
+ assertTrue(offer.hostVersionKnown)
+ assertEquals(listOf("nomin", "old", "same", "tpl"), offer.addons.map { it.slug }.sorted())
+ assertEquals(listOf(AddonKind.PLUGIN, AddonKind.PLUGIN, AddonKind.PLUGIN, AddonKind.TEMPLATE), offer.addons.map { it.kind })
+ }
+
+ @Test
+ fun hostVersionNamesAreReadLeniently() {
+ val all = Catalog.parse(catalog(entry("plugin", "p", "26.45"))).addons
+ assertEquals(1, Catalog.offer(all, "v26.45-abc123-release").addons.size)
+ assertEquals(0, Catalog.offer(all, "26.44").addons.size)
+ assertEquals(1, Catalog.offer(all, "26.45.1").addons.size)
+ assertEquals(0, Catalog.offer(all, "25.99").addons.size)
+ assertEquals(1, Catalog.offer(all, "100.0").addons.size)
+ }
+
+ @Test
+ fun anUnreadableHostVersionOffersEverythingAndSaysSo() {
+ val all = Catalog.parse(catalog(entry("plugin", "p", "26.45"))).addons
+ for (v in listOf(null, "", "unknown")) {
+ val offer = Catalog.offer(all, v)
+ assertFalse(offer.hostVersionKnown)
+ assertEquals(1, offer.addons.size)
+ }
+ }
+
+ @Test
+ fun versionComparison() {
+ assertTrue(AppVersion.compare(listOf(26, 9), listOf(26, 10)) < 0)
+ assertEquals(0, AppVersion.compare(listOf(26, 45), listOf(26, 45, 0)))
+ assertEquals(listOf(26, 45), AppVersion.parse("v26.45-abc"))
+ }
+
+ @Test
+ fun entriesWithoutAVerifiableDownloadAreSkipped() {
+ val parsed = Catalog.parse(
+ catalog(
+ entry("plugin", "good", ""),
+ entry("plugin", "BadSlug", ""),
+ entry("plugin", "shortsha", "", sha = "abc"),
+ entry("plugin", "upper", "", sha = "A".repeat(64)),
+ entry("plugin", "nosize", "", size = -1),
+ ),
+ )
+ assertEquals(listOf("good"), parsed.addons.map { it.slug })
+ assertEquals(4, parsed.skipped)
+ }
+
+ @Test
+ fun aCatalogOfTheWrongShapeIsAnError() {
+ for (bad in listOf("nope", """{"schemaVersion":1,"addons":[]}""", """{"schemaVersion":2}""")) {
+ try {
+ Catalog.parse(bad)
+ throw AssertionError("accepted: $bad")
+ } catch (e: CatalogException) {
+ // expected
+ }
+ }
+ }
+
+ @Test
+ fun fileNameFollowsTheKind() {
+ val a = Catalog.parse(catalog(entry("plugin", "p", ""), entry("template", "t", ""))).addons
+ assertEquals(listOf("p.cgp", "t.cgt"), a.map { it.fileName })
+ }
+
+ private fun addonFor(bytes: ByteArray, size: Long = bytes.size.toLong(), sha: String = sha(bytes)) =
+ Catalog.parse(catalog(entry("plugin", "dl", "", sha = sha, size = size))).addons.single()
+
+ @Test
+ fun aMatchingDownloadIsSavedAndVerified() {
+ val bytes = TestSupport.noise(100_000)
+ val addon = addonFor(bytes)
+ val file = AddonDownloader { ByteArrayInputStream(bytes) }.download(addon, tmp.newFolder())
+ assertEquals("dl.cgp", file.name)
+ assertEquals(bytes.toList(), file.readBytes().toList())
+ assertNull(Catalog.verifyDownload(file, addon))
+ }
+
+ @Test
+ fun aWrongShaIsRejectedAndNothingIsLeftBehind() {
+ val bytes = TestSupport.noise(1000)
+ val dir = tmp.newFolder()
+ val addon = addonFor(bytes, sha = "b".repeat(64))
+ try {
+ AddonDownloader { ByteArrayInputStream(bytes) }.download(addon, dir)
+ throw AssertionError("accepted")
+ } catch (e: DownloadException) {
+ assertTrue(e.message, e.message!!.contains("SHA-256"))
+ }
+ assertEquals(0, dir.listFiles()!!.size)
+ }
+
+ @Test
+ fun aWrongSizeIsRejected() {
+ val bytes = TestSupport.noise(1000)
+ val dir = tmp.newFolder()
+ for (promised in listOf(999L, 1001L)) {
+ val addon = addonFor(bytes, size = promised)
+ try {
+ AddonDownloader { ByteArrayInputStream(bytes) }.download(addon, dir)
+ throw AssertionError("accepted a promise of $promised")
+ } catch (e: DownloadException) {
+ // expected
+ }
+ assertEquals(0, dir.listFiles()!!.size)
+ }
+ }
+
+ @Test
+ fun aServerThatSendsMoreThanPromisedIsCutOff() {
+ var read = 0L
+ val endless = object : java.io.InputStream() {
+ override fun read(): Int { read++; return 1 }
+ override fun read(b: ByteArray, off: Int, len: Int): Int { read += len; return len }
+ }
+ val addon = addonFor(ByteArray(10), size = 10, sha = "c".repeat(64))
+ try {
+ AddonDownloader { endless }.download(addon, tmp.newFolder())
+ throw AssertionError("accepted")
+ } catch (e: DownloadException) {
+ assertTrue(read < 1_000_000)
+ }
+ }
+
+ @Test
+ fun aNetworkErrorPropagatesAndLeavesNothing() {
+ val dir = tmp.newFolder()
+ try {
+ AddonDownloader { throw IOException("offline") }.download(addonFor(ByteArray(3)), dir)
+ throw AssertionError("accepted")
+ } catch (e: IOException) {
+ assertEquals("offline", e.message)
+ }
+ assertEquals(0, dir.listFiles()!!.size)
+ }
+
+ @Test
+ fun verifyDownloadChecksSizeAndDigest() {
+ val f = File(tmp.root, "x").apply { writeBytes(ByteArray(5) { 1 }) }
+ assertTrue(Catalog.verifyDownload(f, addonFor(ByteArray(5) { 1 }, size = 6))!!.contains("bytes"))
+ assertNull(Catalog.verifyDownload(f, addonFor(ByteArray(5) { 1 })))
+ }
+
+ @Test
+ fun theCatalogTextIsCapped() {
+ val big = object : java.io.InputStream() {
+ override fun read(): Int = 'a'.code
+ override fun read(b: ByteArray, off: Int, len: Int): Int { java.util.Arrays.fill(b, off, off + len, 'a'.code.toByte()); return len }
+ }
+ try {
+ AddonDownloader { big }.fetchCatalog()
+ throw AssertionError("accepted")
+ } catch (e: DownloadException) {
+ // expected
+ }
+ assertEquals("hello", AddonDownloader { ByteArrayInputStream("hello".toByteArray()) }.fetchCatalog())
+ }
+
+ @Test
+ fun onlyHttpsToTheAddonsHostIsAllowed() {
+ assertTrue(DownloadPolicy.isAllowed("https://addons.appdevforall.org/v2/catalog.json"))
+ assertTrue(DownloadPolicy.isAllowed("https://ADDONS.appdevforall.org:443/dl/x.cgp"))
+ for (bad in listOf(
+ "http://addons.appdevforall.org/dl/x.cgp",
+ "https://evil.example/dl/x.cgp",
+ "https://addons.appdevforall.org.evil.example/x",
+ "https://user@addons.appdevforall.org/x",
+ "https://addons.appdevforall.org:8443/x",
+ "file:///etc/passwd",
+ "not a url",
+ )) assertFalse(bad, DownloadPolicy.isAllowed(bad))
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/KeystoresTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/KeystoresTest.kt
new file mode 100644
index 00000000..b70e000e
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/KeystoresTest.kt
@@ -0,0 +1,92 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.ByteArrayOutputStream
+import java.security.KeyStore
+
+class KeystoresTest {
+ private val material = TestSupport.material()
+
+ private fun open(bytes: ByteArray, password: String) = Keystores.open(bytes, password.toCharArray())
+
+ @Test
+ fun readsPkcs12() {
+ val result = open(TestSupport.keystoreBytes("PKCS12", material, "storepw"), "storepw")
+ result as KeystoreOpen.Opened
+ assertEquals("PKCS12", result.type)
+ assertEquals(listOf("key"), result.keyAliases)
+ }
+
+ @Test
+ fun readsBks() {
+ val bytes = TestSupport.keystoreBytes("BKS", material, "storepw")
+ assertEquals(KeystoreFormat.BKS_LIKELY, KeystoreFormats.sniff(bytes))
+ val result = open(bytes, "storepw")
+ result as KeystoreOpen.Opened
+ assertEquals("BKS", result.type)
+ assertEquals(listOf("key"), result.keyAliases)
+ }
+
+ @Test
+ fun rejectsJksWithTheConversionCommand() {
+ val store = KeyStore.getInstance("JKS").apply { load(null, null) }
+ store.setKeyEntry("key", material.key, "pw".toCharArray(), arrayOf(material.cert))
+ val bytes = ByteArrayOutputStream().also { store.store(it, "pw".toCharArray()) }.toByteArray()
+ assertEquals(KeystoreFormat.JKS, KeystoreFormats.sniff(bytes))
+ val result = open(bytes, "pw")
+ result as KeystoreOpen.Rejected
+ assertTrue(result.message, result.message.contains("keytool -importkeystore -srckeystore old.jks -srcstoretype JKS -destkeystore new.p12 -deststoretype PKCS12"))
+ }
+
+ @Test
+ fun rejectsJceks() {
+ val store = KeyStore.getInstance("JCEKS").apply { load(null, null) }
+ val bytes = ByteArrayOutputStream().also { store.store(it, "pw".toCharArray()) }.toByteArray()
+ assertEquals(KeystoreFormat.JCEKS, KeystoreFormats.sniff(bytes))
+ assertTrue(open(bytes, "pw") is KeystoreOpen.Rejected)
+ }
+
+ @Test
+ fun aWrongStorePasswordIsToldApartFromADamagedFile() {
+ assertEquals(KeystoreOpen.WrongPassword, open(TestSupport.keystoreBytes("PKCS12", material, "right"), "wrong"))
+ assertEquals(KeystoreOpen.WrongPassword, open(TestSupport.keystoreBytes("BKS", material, "right"), "wrong"))
+ assertTrue(open(ByteArray(200) { 7 }, "x") is KeystoreOpen.Rejected)
+ assertTrue(open(ByteArray(2), "x") is KeystoreOpen.Rejected)
+ }
+
+ @Test
+ fun loadsTheKeyAndChain() {
+ val opened = open(TestSupport.keystoreBytes("PKCS12", material, "pw"), "pw") as KeystoreOpen.Opened
+ val loaded = Keystores.loadKey(opened, "key", CharArray(0), "pw".toCharArray()) as KeyLoad.Loaded
+ assertEquals(material.cert, loaded.key.certificate)
+ assertEquals(95, loaded.key.fingerprint.length)
+ }
+
+ @Test
+ fun aBlankKeyPasswordMeansTheStorePasswordAndADifferentOneIsHonoured() {
+ val bytes = TestSupport.keystoreBytes("BKS", material, "store", keyPassword = "keypw")
+ val opened = open(bytes, "store") as KeystoreOpen.Opened
+ assertTrue(Keystores.loadKey(opened, "key", "keypw".toCharArray(), "store".toCharArray()) is KeyLoad.Loaded)
+ val wrong = Keystores.loadKey(opened, "key", CharArray(0), "store".toCharArray())
+ assertTrue(wrong is KeyLoad.Failed)
+ assertTrue((wrong as KeyLoad.Failed).message.contains("key password"))
+ }
+
+ @Test
+ fun anUnknownAliasFails() {
+ val opened = open(TestSupport.keystoreBytes("PKCS12", material, "pw"), "pw") as KeystoreOpen.Opened
+ assertTrue(Keystores.loadKey(opened, "nope", CharArray(0), "pw".toCharArray()) is KeyLoad.Failed)
+ }
+
+ @Test
+ fun sniffsHeaders() {
+ assertEquals(KeystoreFormat.PKCS12_LIKELY, KeystoreFormats.sniff(byteArrayOf(0x30, -126, 1, 2)))
+ assertEquals(KeystoreFormat.BKS_LIKELY, KeystoreFormats.sniff(byteArrayOf(0, 0, 0, 2)))
+ assertEquals(KeystoreFormat.BKS_LIKELY, KeystoreFormats.sniff(byteArrayOf(0, 0, 0, 1)))
+ assertEquals(KeystoreFormat.JKS, KeystoreFormats.sniff(byteArrayOf(-2, -19, -2, -19)))
+ assertEquals(KeystoreFormat.UNKNOWN, KeystoreFormats.sniff(byteArrayOf(1, 2, 3, 4)))
+ assertEquals(KeystoreFormat.UNKNOWN, KeystoreFormats.sniff(byteArrayOf(1)))
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/NamingTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/NamingTest.kt
new file mode 100644
index 00000000..5ede5282
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/NamingTest.kt
@@ -0,0 +1,14 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class NamingTest {
+ @Test
+ fun outputNameHasNoSpaces() {
+ assertEquals("Code-on-the-Go-26.45-custom.apk", Naming.outputName("Code on the Go", "26.45"))
+ assertEquals("CodeOnTheGo-v26.45-abc-release-custom.apk", Naming.outputName("CodeOnTheGo", "v26.45-abc-release"))
+ assertEquals("App-custom.apk", Naming.outputName("App", null))
+ assertEquals("custom.apk", Naming.outputName("///", ""))
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/PipelineTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/PipelineTest.kt
new file mode 100644
index 00000000..bde2b29b
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/PipelineTest.kt
@@ -0,0 +1,144 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+import java.util.zip.ZipFile
+
+/** Signs with apksig and checks with apksig's own verifier: the check that matters most. */
+class PipelineTest {
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ private val minSdk = 26
+
+ private fun signedHost(key: SigningKey): File {
+ val unsigned = tmp.newFile("host-unsigned.apk")
+ TestSupport.syntheticApk(unsigned)
+ val signed = tmp.newFile("host.apk")
+ Signing.sign(unsigned, signed, key, minSdk)
+ return signed
+ }
+
+ private fun addons() = listOf(
+ TestSupport.staged(tmp.root, AddonKind.PLUGIN, "org.example.p.cgp", TestSupport.noise(2048, 11)),
+ TestSupport.staged(tmp.root, AddonKind.TEMPLATE, "kit.cgt", TestSupport.text(4096)),
+ )
+
+ @Test
+ fun signsAndVerifiesAllSchemes() {
+ val key = TestSupport.signingKey("Alice")
+ val host = signedHost(key)
+ val report = Signing.verify(host, minSdk)
+ assertTrue(report.errors.toString(), report.verified)
+ assertTrue(report.v1 && report.v2 && report.v3)
+ assertEquals(key.fingerprint, report.signerSha256)
+ }
+
+ @Test
+ fun rebundlesASignedHostWithADifferentKeyAndTheResultVerifies() {
+ val hostKey = TestSupport.signingKey("Host")
+ val userKey = TestSupport.signingKey("User")
+ val host = signedHost(hostKey)
+ val work = tmp.newFolder("work")
+ val progress = ArrayList()
+ val out = Pipeline.run(
+ BuildInput(host, emptyList(), addons(), userKey, minSdk, work, "Code-on-the-Go-1.0-custom.apk"),
+ onProgress = { s, _ -> if (progress.lastOrNull() != s) progress.add(s) },
+ )
+ assertEquals(listOf(BuildStage.CHECKING, BuildStage.REWRITING, BuildStage.SIGNING, BuildStage.VERIFYING), progress)
+ assertTrue(out.verify.verified && out.verify.v1 && out.verify.v2 && out.verify.v3)
+ assertEquals("signed with the user's key, not the host's", userKey.fingerprint, out.verify.signerSha256)
+ assertNotEquals(hostKey.fingerprint, out.verify.signerSha256)
+ assertEquals(emptyList(), ZipAlignment.misaligned(out.apk))
+ assertEquals("only the finished APK is left in the work folder", listOf("Code-on-the-Go-1.0-custom.apk"), work.list()!!.toList())
+
+ ZipFile(out.apk).use { zip ->
+ val names = zip.entries().asSequence().map { it.name }.toSet()
+ assertFalse("the host's old v1 signature is gone", "META-INF/OLD.SF" in names)
+ assertTrue("apksig wrote its own", names.any { it.startsWith("META-INF/") && it.endsWith(".SF") })
+ assertArrayEquals(TestSupport.noise(2048, 11), zip.getInputStream(zip.getEntry("assets/plugins/org.example.p.cgp")).readBytes())
+ assertTrue(zip.getEntry("assets/bundled-addons.tsv").size > 0)
+ assertTrue("assets/plugins/old.cgp" !in names)
+ assertArrayEquals(TestSupport.text(200_000), zip.getInputStream(zip.getEntry("classes.dex")).readBytes())
+ }
+ }
+
+ @Test
+ fun aThinBuildAlsoSignsAndVerifies() {
+ val out = Pipeline.run(BuildInput(signedHost(TestSupport.signingKey("H")), emptyList(), emptyList(), TestSupport.signingKey("U"), minSdk, tmp.newFolder("w"), "thin.apk"))
+ assertTrue(out.verify.verified)
+ ZipFile(out.apk).use { assertEquals(0L, it.getEntry("assets/bundled-addons.tsv").size) }
+ }
+
+ @Test
+ fun aTamperedOutputDoesNotVerify() {
+ val host = signedHost(TestSupport.signingKey("H"))
+ val bytes = host.readBytes()
+ // Flip a byte inside classes.dex's data, well before the central directory.
+ RawZipFile(host).use { z ->
+ val dex = z.entries.first { it.name == "classes.dex" }
+ bytes[(z.dataOffset(dex) + 5).toInt()] = (bytes[(z.dataOffset(dex) + 5).toInt()].toInt() xor 0x55).toByte()
+ }
+ val tampered = tmp.newFile("tampered.apk").also { it.writeBytes(bytes) }
+ assertFalse(Signing.verify(tampered, minSdk).verified)
+ }
+
+ @Test
+ fun splitInstallsAreRefusedWithAClearMessage() {
+ try {
+ Pipeline.run(BuildInput(signedHost(TestSupport.signingKey("H")), listOf("/data/app/split_config.arm64.apk"), emptyList(), TestSupport.signingKey("U"), minSdk, tmp.newFolder("w"), "x.apk"))
+ throw AssertionError("accepted")
+ } catch (e: BuildException) {
+ assertTrue(e.message, e.message!!.contains("split"))
+ }
+ }
+
+ @Test
+ fun aPluginFileIsNotTheHostApk() {
+ val cgp = tmp.newFile("plugin.cgp")
+ try {
+ Pipeline.run(BuildInput(cgp, emptyList(), emptyList(), TestSupport.signingKey("U"), minSdk, tmp.newFolder("w"), "x.apk"))
+ throw AssertionError("accepted")
+ } catch (e: BuildException) {
+ assertTrue(e.message, e.message!!.contains("plugin file"))
+ }
+ }
+
+ @Test
+ fun aMissingHostIsRefused() {
+ try {
+ Pipeline.run(BuildInput(File(tmp.root, "nope.apk"), emptyList(), emptyList(), TestSupport.signingKey("U"), minSdk, tmp.newFolder("w"), "x.apk"))
+ throw AssertionError("accepted")
+ } catch (e: BuildException) {
+ assertTrue(e.message!!.contains("cannot be read"))
+ }
+ }
+
+ @Test
+ fun cancellationStopsTheBuildAndLeavesNoFiles() {
+ val work = tmp.newFolder("w")
+ var calls = 0
+ try {
+ Pipeline.run(
+ BuildInput(signedHost(TestSupport.signingKey("H")), emptyList(), addons(), TestSupport.signingKey("U"), minSdk, work, "x.apk"),
+ checkCancelled = { if (++calls > 3) throw java.util.concurrent.CancellationException("stop") },
+ )
+ throw AssertionError("not cancelled")
+ } catch (e: java.util.concurrent.CancellationException) {
+ // expected
+ }
+ assertEquals(emptyList(), work.list()!!.toList())
+ }
+
+ @Test
+ fun spaceNeededCoversTwoCopies() {
+ assertTrue(Pipeline.spaceNeeded(100, 10) >= 220)
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/SelectionTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/SelectionTest.kt
new file mode 100644
index 00000000..e7866e65
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/SelectionTest.kt
@@ -0,0 +1,87 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+
+class SelectionTest {
+ private fun plugin(label: String, file: String, id: String?) = PickedAddon(label, file, File(file), id)
+
+ private fun template(label: String, file: String) = PickedAddon(label, file, File(file), null)
+
+ private fun problems(vararg picked: PickedAddon): List = (AddonSelection.validate(picked.toList()) as SelectionResult.Invalid).problems
+
+ @Test
+ fun validSelectionGetsEntryNames() {
+ val r = AddonSelection.validate(
+ listOf(plugin("A", "a.cgp", "org.example.a"), plugin("B", "b.CGP", "org.example.b"), template("T", "Starter Kit.cgt")),
+ ) as SelectionResult.Valid
+ assertEquals(
+ listOf("org.example.a.cgp", "org.example.b.cgp", "Starter_Kit.cgt"),
+ r.staged.map { it.fileName },
+ )
+ assertEquals(listOf(AddonKind.PLUGIN, AddonKind.PLUGIN, AddonKind.TEMPLATE), r.staged.map { it.kind })
+ assertEquals("assets/plugins/org.example.a.cgp", r.staged[0].apkEntryName)
+ }
+
+ @Test
+ fun anEmptySelectionIsValid() {
+ assertEquals(0, (AddonSelection.validate(emptyList()) as SelectionResult.Valid).staged.size)
+ }
+
+ @Test
+ fun duplicatePluginIdsAreRejectedWhateverTheFileNames() {
+ val p = problems(plugin("First", "one.cgp", "org.same"), plugin("Second", "two.cgp", "org.same"))
+ assertEquals(1, p.size)
+ assertTrue(p[0], p[0].contains("Second") && p[0].contains("First") && p[0].contains("org.same"))
+ }
+
+ @Test
+ fun duplicateTemplateFileNamesAreRejectedIgnoringCase() {
+ val p = problems(template("One", "kit.cgt"), template("Two", "KIT.CGT"))
+ assertEquals(1, p.size)
+ assertTrue(p[0].contains("same file name"))
+ }
+
+ @Test
+ fun coreCgtIsNeverIncluded() {
+ for (name in listOf("core.cgt", "Core.CGT")) {
+ val p = problems(template("core", name))
+ assertTrue(p[0], p[0].contains("core.cgt"))
+ }
+ }
+
+ @Test
+ fun otherFileTypesAreRejected() {
+ assertTrue(problems(template("x", "thing.zip"))[0].contains("not a .cgp or .cgt"))
+ }
+
+ @Test
+ fun pluginIdProblems() {
+ assertTrue(problems(plugin("n", "n.cgp", null))[0].contains("manifest"))
+ for (bad in listOf("", ".", "..", "a/b", "a\\b", "../files", " x")) {
+ assertTrue("\"$bad\"", problems(plugin("p", "p.cgp", bad))[0].contains("not a valid name"))
+ }
+ }
+
+ @Test
+ fun allProblemsAreReportedAtOnce() {
+ val p = problems(plugin("A", "a.cgp", null), template("core", "core.cgt"), template("w", "w.txt"))
+ assertEquals(3, p.size)
+ }
+
+ @Test
+ fun entryNamesAreCleaned() {
+ assertEquals("a_b_c", AddonSelection.entryNameFor("a b/c"))
+ assertEquals("hidden", AddonSelection.entryNameFor(".hidden"))
+ assertEquals("addon", AddonSelection.entryNameFor("..."))
+ assertEquals("org.example-1_x", AddonSelection.entryNameFor("org.example-1_x"))
+ }
+
+ @Test
+ fun twoIdsThatCleanToOneNameAreCaught() {
+ val p = problems(plugin("A", "a.cgp", "org.a b"), plugin("B", "b.cgp", "org.a_b"))
+ assertTrue(p[0], p[0].contains("differ only in characters"))
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/TestSupport.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/TestSupport.kt
new file mode 100644
index 00000000..a11b0ff4
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/TestSupport.kt
@@ -0,0 +1,100 @@
+package org.appdevforall.customidebuilder.core
+
+import org.bouncycastle.asn1.x500.X500Name
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder
+import org.bouncycastle.jce.provider.BouncyCastleProvider
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.math.BigInteger
+import java.security.KeyPairGenerator
+import java.security.KeyStore
+import java.security.Security
+import java.security.cert.X509Certificate
+import java.util.Date
+import java.util.Random
+import java.util.zip.CRC32
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+object TestSupport {
+ init {
+ if (Security.getProvider("BC") == null) Security.addProvider(BouncyCastleProvider())
+ }
+
+ class Material(val key: java.security.PrivateKey, val cert: X509Certificate)
+
+ fun material(commonName: String = "Test"): Material {
+ val pair = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair()
+ val name = X500Name("CN=$commonName")
+ val now = System.currentTimeMillis()
+ val builder = JcaX509v3CertificateBuilder(name, BigInteger.valueOf(now), Date(now - 86_400_000), Date(now + 86_400_000L * 365), name, pair.public)
+ val signer = JcaContentSignerBuilder("SHA256withRSA").build(pair.private)
+ return Material(pair.private, JcaX509CertificateConverter().getCertificate(builder.build(signer)))
+ }
+
+ fun signingKey(commonName: String = "Test"): SigningKey = material(commonName).let { SigningKey("key", it.key, listOf(it.cert)) }
+
+ fun keystoreBytes(type: String, m: Material, storePassword: String, keyPassword: String = storePassword, alias: String = "key"): ByteArray {
+ val store = if (type == "BKS") KeyStore.getInstance("BKS", "BC") else KeyStore.getInstance(type)
+ store.load(null, null)
+ store.setKeyEntry(alias, m.key, keyPassword.toCharArray(), arrayOf(m.cert))
+ return ByteArrayOutputStream().also { store.store(it, storePassword.toCharArray()) }.toByteArray()
+ }
+
+ /** Deterministic incompressible-ish and compressible content. */
+ fun noise(size: Int, seed: Long = 1): ByteArray = ByteArray(size).also { Random(seed).nextBytes(it) }
+
+ fun text(size: Int): ByteArray = "the quick brown fox jumps over the lazy dog\n".repeat(size / 44 + 1).toByteArray().copyOf(size)
+
+ /**
+ * An APK-shaped zip made with java.util.zip: deflated entries (which ZipOutputStream writes with data
+ * descriptors), stored entries, an old add-on bundle and an old v1 signature.
+ */
+ fun syntheticApk(file: File, extra: Map> = emptyMap()): Map {
+ val content = linkedMapOf>(
+ "AndroidManifest.xml" to (ZipEntry.DEFLATED to text(3000)),
+ "classes.dex" to (ZipEntry.DEFLATED to text(200_000)),
+ "resources.arsc" to (ZipEntry.STORED to noise(5001, 2)),
+ "lib/arm64-v8a/libnative.so" to (ZipEntry.STORED to noise(10_001, 3)),
+ "res/raw/data.bin" to (ZipEntry.STORED to noise(777, 4)),
+ "assets/keep.txt" to (ZipEntry.DEFLATED to text(500)),
+ "assets/plugins/old.cgp" to (ZipEntry.STORED to noise(100, 5)),
+ "assets/templates/old.cgt" to (ZipEntry.DEFLATED to text(100)),
+ "assets/bundled-addons.tsv" to (ZipEntry.DEFLATED to "plugins/old.cgp\t100\t${"0".repeat(64)}\n".toByteArray()),
+ "META-INF/MANIFEST.MF" to (ZipEntry.DEFLATED to "Manifest-Version: 1.0\n".toByteArray()),
+ "META-INF/OLD.SF" to (ZipEntry.DEFLATED to "Signature-Version: 1.0\n".toByteArray()),
+ "META-INF/OLD.RSA" to (ZipEntry.DEFLATED to noise(300, 6)),
+ "META-INF/services/example.Service" to (ZipEntry.DEFLATED to "x\n".toByteArray()),
+ )
+ content.putAll(extra)
+ ZipOutputStream(file.outputStream()).use { zip ->
+ for ((name, pair) in content) {
+ val (method, data) = pair
+ val entry = ZipEntry(name)
+ entry.time = 1_700_000_000_000L
+ if (method == ZipEntry.STORED) {
+ entry.method = ZipEntry.STORED
+ entry.size = data.size.toLong()
+ entry.compressedSize = data.size.toLong()
+ entry.crc = CRC32().apply { update(data) }.value
+ }
+ zip.putNextEntry(entry)
+ zip.write(data)
+ zip.closeEntry()
+ }
+ }
+ return content.mapValues { it.value.second }
+ }
+
+ fun staged(dir: File, kind: AddonKind, fileName: String, bytes: ByteArray): StagedAddon {
+ val f = File(dir, "src-$fileName")
+ f.writeBytes(bytes)
+ return StagedAddon(kind, fileName, f)
+ }
+
+ fun rawBytes(zip: RawZipFile, entry: RawZipEntry): ByteArray =
+ ByteArrayOutputStream().also { zip.copyRaw(entry, it) }.toByteArray()
+
+}
From 3198bd7f5874137aa763cdd4ec3ffa29d0449ce9 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 24 Nov 2026 01:46:29 +0000
Subject: [PATCH 02/17] ADFA-7241: Custom IDE Builder plugin scaffold
Build files, manifest (1.0.0, versionCode 1), addon.json, gallery page, in-IDE
help page, icons, README, and the root README row. apksig 9.3.1 is bundled
into the .cgp.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
README.md | 1 +
plugins/Custom-IDE-Builder/.gitignore | 29 ++++++
plugins/Custom-IDE-Builder/README.md | 35 +++++++
plugins/Custom-IDE-Builder/addon.json | 15 +++
plugins/Custom-IDE-Builder/build.gradle.kts | 85 +++++++++++++++++
.../custom-ide-builder.html | 90 ++++++++++++++++++
plugins/Custom-IDE-Builder/gradle.properties | 4 +
plugins/Custom-IDE-Builder/proguard-rules.pro | 2 +
.../Custom-IDE-Builder/settings.gradle.kts | 30 ++++++
.../src/main/AndroidManifest.xml | 61 ++++++++++++
.../src/main/assets/docs/index.html | 90 ++++++++++++++++++
.../src/main/assets/icon_day.png | Bin 0 -> 1600 bytes
.../src/main/assets/icon_night.png | Bin 0 -> 1593 bytes
13 files changed, 442 insertions(+)
create mode 100644 plugins/Custom-IDE-Builder/.gitignore
create mode 100644 plugins/Custom-IDE-Builder/README.md
create mode 100644 plugins/Custom-IDE-Builder/addon.json
create mode 100644 plugins/Custom-IDE-Builder/build.gradle.kts
create mode 100644 plugins/Custom-IDE-Builder/custom-ide-builder.html
create mode 100644 plugins/Custom-IDE-Builder/gradle.properties
create mode 100644 plugins/Custom-IDE-Builder/proguard-rules.pro
create mode 100644 plugins/Custom-IDE-Builder/settings.gradle.kts
create mode 100644 plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml
create mode 100644 plugins/Custom-IDE-Builder/src/main/assets/docs/index.html
create mode 100644 plugins/Custom-IDE-Builder/src/main/assets/icon_day.png
create mode 100644 plugins/Custom-IDE-Builder/src/main/assets/icon_night.png
diff --git a/README.md b/README.md
index c770de0e..eeabdb5a 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,7 @@ See the official [plugin documentation](https://www.appdevforall.org/codeonthego
| [`plugins/AI-Literacy-Course/`](plugins/AI-Literacy-Course/) | An offline "Introduction to AI" course with lesson videos and activities. |
| [`plugins/Code-Together/`](plugins/Code-Together/) | Pair programming between two devices on the same network. |
| [`plugins/AI-Core/`](plugins/AI-Core/) | The agent chat and the inference router every other AI addon needs. |
+| [`plugins/Custom-IDE-Builder/`](plugins/Custom-IDE-Builder/) | Builds a signed copy of Code on the Go with the add-ons you choose. |
| [`plugins/Favorite-Snippets/`](plugins/Favorite-Snippets/) | Saves your own code snippets and inserts them in the editor. |
| [`plugins/Get-AI-Models/`](plugins/Get-AI-Models/) | Downloads small language models for on-device AI addons. |
| [`plugins/Icons-Repository/`](plugins/Icons-Repository/) | Adds vector icons to a project from inside the editor. |
diff --git a/plugins/Custom-IDE-Builder/.gitignore b/plugins/Custom-IDE-Builder/.gitignore
new file mode 100644
index 00000000..6af499b7
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/.gitignore
@@ -0,0 +1,29 @@
+# Gradle
+.gradle/
+build/
+gradle-app.setting
+!gradle-wrapper.jar
+.gradletasknamecache
+
+# IDE
+.idea/
+*.iml
+*.ipr
+*.iws
+.project
+.classpath
+.settings/
+.kotlin/
+
+# Local configuration
+local.properties
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Logs
+*.log
+
+# Test outputs
+test-results/
diff --git a/plugins/Custom-IDE-Builder/README.md b/plugins/Custom-IDE-Builder/README.md
new file mode 100644
index 00000000..a0e09e5c
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/README.md
@@ -0,0 +1,35 @@
+# Custom IDE Builder
+
+Builds a copy of the installed Code on the Go with a chosen set of plugins (`.cgp`) and templates
+(`.cgt`) bundled inside, signed with the user's own key. Release builds only: the host reads the bundle
+from `assets/plugins/`, `assets/templates/` and `assets/bundled-addons.tsv` in its APK.
+
+## Layout
+
+Everything with logic is in `org.appdevforall.customidebuilder.core` and imports nothing from
+`android.*`, so its tests run on a plain JVM (`../../gradlew testDebugUnitTest`).
+
+| File | Does |
+|---|---|
+| `Zip.kt` | Reads a zip's central directory; writes zips with raw (still compressed) entries, 4-byte aligned when stored (`.so` files 16 KB) |
+| `ApkRewriter.kt` | Copies the host APK entry by entry, drops the old bundle and v1 signature, adds the add-ons and a new index |
+| `Bundle.kt` | The bundle index, byte for byte as Code on the Go's build writes it |
+| `Selection.kt` | Validates the chosen add-ons: duplicate plugin IDs, duplicate template names, `core.cgt`, entry names |
+| `Keystores.kt` | Detects PKCS12 or BKS, rejects JKS with the `keytool` conversion, loads a key |
+| `Signing.kt` | apksig: signs v1, v2 and v3, then verifies |
+| `Catalog.kt`, `Download.kt` | The v2 catalog, `minAppVersion` filtering, verified downloads from `addons.appdevforall.org` only |
+| `Pipeline.kt` | Rewrite, sign, verify, check alignment |
+
+The Android side (`BuilderFragment`, `Session`, `AndroidBits`) is the screen, the file pickers and
+the Storage Access Framework output.
+
+## Mirrors of Code on the Go
+
+`AddonKind` repeats `BundledAddonKind`, and `BundleIndex.render` repeats `StageBundledAddons`
+(`app/build.gradle.kts`). `BundledAddons.parseIndex` is copied into the index test with a comment naming its
+source. If Code on the Go changes the bundle, change these together.
+
+## Signing dependency
+
+`com.android.tools.build:apksig` is bundled into the `.cgp`. Its version is kept equal to the Android Gradle
+plugin's in `settings.gradle.kts`.
diff --git a/plugins/Custom-IDE-Builder/addon.json b/plugins/Custom-IDE-Builder/addon.json
new file mode 100644
index 00000000..b45a48f4
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/addon.json
@@ -0,0 +1,15 @@
+{
+ "summary": "Builds a signed copy of Code on the Go with the add-ons you choose.",
+ "description": "Makes a copy of the Code on the Go installed on this device with the plugins and templates you pick bundled inside, and signs it with your own keystore, so you can hand out a version that arrives ready to use.",
+ "tags": [
+ "signing",
+ "release",
+ "distribution"
+ ],
+ "origin": "appdevforall",
+ "license": "AGPL-3.0-or-later",
+ "author": {
+ "name": "App Dev For All",
+ "url": "https://www.appdevforall.org"
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/build.gradle.kts b/plugins/Custom-IDE-Builder/build.gradle.kts
new file mode 100644
index 00000000..c7e31e41
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/build.gradle.kts
@@ -0,0 +1,85 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+ id("com.android.application")
+ id("com.itsaky.androidide.plugins.build")
+}
+
+pluginBuilder {
+ pluginName = "custom-ide-builder"
+}
+
+android {
+ namespace = "org.appdevforall.customidebuilder"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "org.appdevforall.customidebuilder"
+ minSdk = 26
+ targetSdk = 36
+ versionCode = 1
+ versionName = "1.0.0"
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ packaging {
+ resources {
+ excludes += setOf(
+ "META-INF/versions/9/OSGI-INF/MANIFEST.MF",
+ "META-INF/DEPENDENCIES",
+ "META-INF/LICENSE",
+ "META-INF/LICENSE.txt",
+ "META-INF/NOTICE",
+ "META-INF/NOTICE.txt"
+ )
+ }
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+dependencies {
+ // plugin-api is the IDE-side contract: compile against it, the IDE provides it.
+ compileOnly(files("../../libs/plugin-api.jar"))
+
+ // Code on the Go loads classes parent-first and carries its own AndroidX, so the Fragment and
+ // Activity Result classes this screen uses come from the host, never from a bundled copy.
+ compileOnly("androidx.fragment:fragment:1.8.8")
+
+ implementation("org.jetbrains.kotlin:kotlin-stdlib:2.3.21")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
+
+ // Signs the APK (v1, v2 and v3) and verifies the result. It is the same version as the Android
+ // Gradle plugin in settings.gradle.kts, which publishes apksig beside itself on Google Maven.
+ // Bundled into the .cgp: the host does not carry it.
+ implementation("com.android.tools.build:apksig:9.3.1")
+
+ // Tests run on a computer's Java. There Android's org.json is an empty stub, so they bring their own,
+ // and BouncyCastle writes the BKS keystores that Android's built-in provider reads and makes the test certificates.
+ testImplementation("junit:junit:4.13.2")
+ testImplementation("org.json:json:20240303")
+ testImplementation("org.bouncycastle:bcprov-jdk18on:1.78")
+ testImplementation("org.bouncycastle:bcpkix-jdk18on:1.78")
+}
+
+tasks.matching {
+ it.name.contains("checkDebugAarMetadata") ||
+ it.name.contains("checkReleaseAarMetadata")
+}.configureEach {
+ enabled = false
+}
diff --git a/plugins/Custom-IDE-Builder/custom-ide-builder.html b/plugins/Custom-IDE-Builder/custom-ide-builder.html
new file mode 100644
index 00000000..c28efbb0
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/custom-ide-builder.html
@@ -0,0 +1,90 @@
+
+
+
+
+
+Custom IDE Builder
+
+
+
+
Custom IDE Builder
+
+
Custom IDE Builder makes a copy of the Code on the Go installed on this device, with the
+ plugins and templates you choose bundled inside it, and signs the copy with your own key. Use it to
+ hand out a version of Code on the Go that arrives with the add-ons a class, a team or a community needs
+ already in place.
+
+
+
Read this before you install a copy. The copy is signed with your key, not ours, so Android
+ treats it as a different app. It installs only after Code on the Go has been uninstalled, and
+ uninstalling erases the projects stored in the app's data. Copy your projects out first.
+
+
+
What you need
+
+
A keystore file in PKCS12 (.p12) or BKS format, such as one made by
+ Keystore Generator. A Java KeyStore (.jks) file made by keytool must
+ be converted first, on a computer:
+ keytool -importkeystore -srckeystore old.jks -srcstoretype JKS -destkeystore new.p12 -deststoretype PKCS12.
+
The add-ons: .cgp plugin files and .cgt template files from this device, or
+ downloaded from the add-ons website.
+
A folder to save the finished APK in, and free space for about twice the size of Code on the Go.
+
+
+
How to use it
+
+
Open Custom IDE Builder from the main menu.
+
Add-ons. Tap Add from this device to pick several files at once. Tap
+ Add from the website to choose from the add-ons that work with this version of Code on the Go.
+ Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org
+ and each one is checked against the size and SHA-256 the website publishes.
+
Signing key. Choose the keystore file, type the store password and tap Read keys,
+ then pick the key. Leave the key password blank if it is the same as the store password.
+
Output folder. Choose it once; it is remembered.
+
Tap Build APK. The file is saved as
+ <app name>-<version>-custom.apk.
+
+
+
Good to know
+
+
Use the same key every time. A device that has a build signed with one key cannot update to
+ a build signed with another without being uninstalled first.
+
Passwords are never saved. They are used for the build in front of you and cleared when
+ you leave the screen.
+
Each plugin must have its own plugin ID and each template its own file name; the builder
+ says which add-ons clash. core.cgt is never bundled, because Code on the Go installs it
+ itself.
+
Nothing chosen makes a copy that carries no add-ons.
+
The copy is built from the APK of this installation. It does not work if Code on the Go was
+ installed as split APKs; the screen says so.
+
The app is copied without being recompressed, so building takes about as long as copying the file,
+ plus the time to sign it.
Custom IDE Builder makes a copy of the Code on the Go installed on this device, with the
+ plugins and templates you choose bundled inside it, and signs the copy with your own key. Use it to
+ hand out a version of Code on the Go that arrives with the add-ons a class, a team or a community needs
+ already in place.
+
+
+
Read this before you install a copy. The copy is signed with your key, not ours, so Android
+ treats it as a different app. It installs only after Code on the Go has been uninstalled, and
+ uninstalling erases the projects stored in the app's data. Copy your projects out first.
+
+
+
What you need
+
+
A keystore file in PKCS12 (.p12) or BKS format, such as one made by
+ Keystore Generator. A Java KeyStore (.jks) file made by keytool must
+ be converted first, on a computer:
+ keytool -importkeystore -srckeystore old.jks -srcstoretype JKS -destkeystore new.p12 -deststoretype PKCS12.
+
The add-ons: .cgp plugin files and .cgt template files from this device, or
+ downloaded from the add-ons website.
+
A folder to save the finished APK in, and free space for about twice the size of Code on the Go.
+
+
+
How to use it
+
+
Open Custom IDE Builder from the main menu.
+
Add-ons. Tap Add from this device to pick several files at once. Tap
+ Add from the website to choose from the add-ons that work with this version of Code on the Go.
+ Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org
+ and each one is checked against the size and SHA-256 the website publishes.
+
Signing key. Choose the keystore file, type the store password and tap Read keys,
+ then pick the key. Leave the key password blank if it is the same as the store password.
+
Output folder. Choose it once; it is remembered.
+
Tap Build APK. The file is saved as
+ <app name>-<version>-custom.apk.
+
+
+
Good to know
+
+
Use the same key every time. A device that has a build signed with one key cannot update to
+ a build signed with another without being uninstalled first.
+
Passwords are never saved. They are used for the build in front of you and cleared when
+ you leave the screen.
+
Each plugin must have its own plugin ID and each template its own file name; the builder
+ says which add-ons clash. core.cgt is never bundled, because Code on the Go installs it
+ itself.
+
Nothing chosen makes a copy that carries no add-ons.
+
The copy is built from the APK of this installation. It does not work if Code on the Go was
+ installed as split APKs; the screen says so.
+
The app is copied without being recompressed, so building takes about as long as copying the file,
+ plus the time to sign it.
+
+
+
diff --git a/plugins/Custom-IDE-Builder/src/main/assets/icon_day.png b/plugins/Custom-IDE-Builder/src/main/assets/icon_day.png
new file mode 100644
index 0000000000000000000000000000000000000000..19d71e7319a6c26609719cf77241b042409a0495
GIT binary patch
literal 1600
zcmZ`)dpML?96s~)l@G(rBpS(eW*d~tpsUS@$&3<{a%s2SMk%FGx=p#vr!=W(Xr)pc
zEt*h96g?_4%@k$oK{pkOopv`Nmqx~z%YNFw_xC*K{N8ik_q>0+fBen~PAJRFWR3{{
zz$}=}49B{3Y9TYQJ-lm|5dbrcf|)DU^DYf`b?$i?Ju4`NzH&Daj^!T7z=sg$`TqUL
zb#b>_-^Oo#lXZ=v^1@Ro1N=UA!a%|_%;9@&NUKT5#Wki*PIPD%`ZpDQU~Ei$_UzQ=
zfiYf|Of}u}@WA!Wo)g7*dsgJ}YSmGC>aCwFWoHPoVfrfHOoNX>+1aF~vr-rpIL~x;
zTUTDoh-~=EN=*S<3v;z?)cYRofXs-@?Ya;RvhC*w53ZqtCW7hAyBE#T5&820{Ywb}
z@D^EuC_c}#R^E$=f3)saaxk%7&cK;CkpJ3tihF%GEEL02I%Zq#x+y$&3O{d%!f+69
zzTpBA`NXw~#HBdS92_|%CGBRqaamejIxeEyoNwqCf8cMpf2juHUa73q4St{r7P|8v
z!362oZHar4nD=kR;k_`2x`*F7nCA`=ua0pPgL&oQ
ze_1<2KDf3WR1gdoDntS0fULhA?^sGe+lA%HDfx?lz=QU+Jl7ov#I!Al3&d6J+}g0*
z#1_cwXY1A@)<8Z^i$`Lxdph&(@??7;7tWWJOFfzbcEIR!1eB4$D$4gLasZY@Vpm=CB9E9@sv>9L@k|8sR
z#NsTlce$l`lN$)aZkcnoTuVK7&<(m{G0|*n&1XP&Vsy&Pu5mF73~giWni%rd?}3Ly
zH#4nhh_XoOhn^jOV?~O!mx$s@siGz_5Dq{dN($(@}XSw
z)H@?RnL#kA>g3r>V`==7GoK6W_17%%-s_#`qn|r=fmu$oyMuXQ2
z1mpy5d#0&W^SLHDm(-l38|$-l2ZTtx_n&Ht6S|^s+E#6UCSIzbSJGcTR*sME?<0AE
zFshNwA??~@X3`h01ic!~VHIM7F0LgJ^UNTk&$7);Nwj^yPT2jP9!Himivug$aJ*N`
zKI4@__f+t!*e^-!aeNwMGNqlT)7EQt>7W{gm+HE#2uQPM;g}3TNz3q|FcR=|T?4GE
zg7RV~Qbopqoac%zi27m3EA8^S=|JTK@(bM2kmg#}TR%x31P+(t9XcagPGuK$=`IZ=K7h$8X
ziUqy_*L=0VT!=%xBUqd)=b7$IzsXD|t
z7R4(bVv2f4)SMK+Ri`0bv>8*7FXQI%tbae(L24Hj@INW)i}<%UvG-YtaB|7Ff5wF`
za`u{1WB*DZ$nGfbY%A3J)S{~UXK5F5g_i%@Fc>luXaFPu{HuEs%`?bmrtQ?pP6snARQ#qDiow>pJ<$0r+PVg4`wf%om;VhKTOa~I
z_IJ~0V3mytx(;B2DOn9WKs>L8=JKB%oKPcg-;dUyY>koB1+1=}v{;JE0#?)mv;(G0
zI662!>5o>xL@lWY=jn+d@YGCvb#t^?Tz;&SnZ~taIyMsR
zb9$WGsI#(GF8dTy(nOQyN2_$DA!AORW}ul&6Nc^Yz2`jd`};k=_c`Zz&UwyH5*-yz
zB+v)|0OF>I&=||BoDbC6a>w+g*Z^P+HiZUn6_vm2Q^z`g=oqGLQm2a|(4u>80oH}e
zF3Esxd=sxfQTEl}^>5a_@ypd}5`DP)iI)0zCwXdDF0}iFsi84}ZWIW
z77(*Oi5hf0g5w~m1X4!Xx#{<4K-X%2Jb#z~~OOn+CPEA*^AR8GJR&GOR32^u(0v{CjmDvphxpjhw%3&x~lCoTBke7@xM
z_$dpk3vW0Cd>feKe1hD8;l3m}
zhiAvfaB^p}I26r7YP=rl85j(GBng~h#R{1?;MhML=z6*yDDNgm*uekVBqXD5D}IVhL!T
zRtr&YSn%2)lDHiJcATJ5atA!XQ1SL6_#^b);H>$1y^eus8dSxGx&J44HO+kNorH0r
zTL#L#Pm$t2-LPapj1>2F_eute!0|fTKhG;Q`CVvL{ofdw%ahBmxImD{nt;EmE!2HE
z>>N7~?uf#rBYg(l~^1)1+b|gs6-?7&kh$aUbg#fa6^`S>^!PtH5BEfg{>G{KXK`
zWE{k}WGUYUI&kgnm4&*V5a7B(6Vqlqh$$DSZ#k|$oQtG2P52y@ib=44*W_v5B^hx&
zq7Quq{0iDPe?9Gv+mvXc+KjE3((`Gm=bv}P9N1X%!7jDA!qCaWNe--Q{=rl;Z5kTO
zQQiE8IcwZ-H!NF~3luM<7Q#X?<+!4)2wf)C%=S0lU_#rvq*YBuITNSQu+ZDf;~bWP
zOWKIA=#ii5x9~_5{5^GQNo0~$17Q(9nAnnmcdHnK#M=h)$YllBEo*{gi%g##(z=}
zo2RCxsMuPN8pmR~J0r|JnfIlds9_LDSIC7OzK3P}!lbiS`s%F5PAW#f`UyicJ8Npt
z@!~}EN3{z1(5UMo?YMbHH<&i0$x4dYSgNYPWLz(wjQ}gsN>}H+_yhqDBPrYh#TJk4
zL7KfV`1~A!sZM;L_^5JdD+J`0wK>0#`I}*E%gxTzI)G!|R&AMQCfs#HexCvERmVnR
zb^$*uVaZ&F_|5aG5v$v7`RUz-;;$BSOT(*H@E;~t=QOmJgUWQ8i`qYjo@Y;PN>phz
zWaZIzw`97BcolkoEA`%*SaTyshlrxJ>l%L|)pVm)A>M~D
z_lKi)jSPs|jpk`(3Ig5(BG0w98xN+zDK!~1-?x75GVaeGWe;b8|2BpMO_XiFb_ZljNn|
Qy7|PWjZvXjc!DGU0+;Nv8vp
Date: Tue, 24 Nov 2026 01:46:29 +0000
Subject: [PATCH 03/17] ADFA-7241: Custom IDE Builder screen
The plugin entry with a main-menu item, the screen (add-on picking from the
device and, after an off-device warning, the website; keystore and alias;
output folder through the Storage Access Framework; progress and cancel),
the session that outlives rotation, tooltips and the menu icon.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../customidebuilder/AndroidBits.kt | 143 ++++++++
.../customidebuilder/BuilderFragment.kt | 335 ++++++++++++++++++
.../CustomIdeBuilderPlugin.kt | 76 ++++
.../org/appdevforall/customidebuilder/Help.kt | 71 ++++
.../appdevforall/customidebuilder/Session.kt | 318 +++++++++++++++++
.../res/drawable/ic_custom_ide_builder.xml | 11 +
6 files changed, 954 insertions(+)
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/CustomIdeBuilderPlugin.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Help.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
create mode 100644 plugins/Custom-IDE-Builder/src/main/res/drawable/ic_custom_ide_builder.xml
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
new file mode 100644
index 00000000..bef68f04
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
@@ -0,0 +1,143 @@
+package org.appdevforall.customidebuilder
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.provider.DocumentsContract
+import android.provider.OpenableColumns
+import java.io.File
+import java.io.IOException
+
+/** What the screen needs to know about the Code on the Go that is running. */
+class HostInfo(
+ val apk: File,
+ val splitDirs: List,
+ val label: String,
+ val versionName: String?,
+ val minSdk: Int,
+)
+
+/** The Android-only reads. Everything with logic in it is in `core`, where it can be tested on a JVM. */
+object AndroidBits {
+ const val APK_MIME = "application/vnd.android.package-archive"
+
+ /**
+ * The HOST's APK. The plugin's own context would name the .cgp. `applicationContext` of the
+ * context the host gave the plugin is the host's; [fallback] (the screen's own context, also
+ * the host's) is used if that ever turns out to be the plugin file.
+ */
+ fun hostInfo(pluginContext: Context?, fallback: Context): HostInfo {
+ var app = (pluginContext ?: fallback).applicationContext
+ if (app.applicationInfo.sourceDir.endsWith(".cgp", ignoreCase = true)) app = fallback.applicationContext
+ val info = app.applicationInfo
+ val pm = app.packageManager
+ @Suppress("DEPRECATION")
+ val versionName = pm.getPackageInfo(app.packageName, 0).versionName
+ return HostInfo(
+ apk = File(info.sourceDir),
+ splitDirs = info.splitSourceDirs?.toList().orEmpty(),
+ label = pm.getApplicationLabel(info).toString(),
+ versionName = versionName,
+ minSdk = info.minSdkVersion,
+ )
+ }
+
+ /**
+ * The `plugin.id` in a .cgp's manifest, the way the host reads it (PluginLoader.getPluginMetadata):
+ * the meta-data entry, else the package name. Null when the file is not an APK or lacks
+ * `plugin.main_class`, which the host also requires.
+ */
+ fun readPluginId(context: Context, file: File): String? {
+ val pm = context.packageManager
+ val info =
+ try {
+ if (Build.VERSION.SDK_INT >= 33) {
+ pm.getPackageArchiveInfo(file.path, PackageManager.PackageInfoFlags.of(PackageManager.GET_META_DATA.toLong()))
+ } else {
+ @Suppress("DEPRECATION")
+ pm.getPackageArchiveInfo(file.path, PackageManager.GET_META_DATA)
+ }
+ } catch (e: Exception) {
+ null
+ } ?: return null
+ val meta = info.applicationInfo?.metaData ?: return null
+ if (meta.getString("plugin.main_class").isNullOrEmpty()) return null
+ return meta.getString("plugin.id") ?: info.packageName
+ }
+
+ fun displayName(context: Context, uri: Uri): String? =
+ try {
+ context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
+ if (it.moveToFirst()) it.getString(0) else null
+ }
+ } catch (e: Exception) {
+ null
+ }
+
+ /** Copies what [uri] holds into [target], stopping at [limit] bytes. */
+ fun copyToFile(context: Context, uri: Uri, target: File, limit: Long = Long.MAX_VALUE) {
+ target.parentFile?.mkdirs()
+ val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open $uri")
+ input.use { source ->
+ target.outputStream().use { out ->
+ val buffer = ByteArray(64 * 1024)
+ var total = 0L
+ while (true) {
+ val n = source.read(buffer)
+ if (n < 0) break
+ total += n
+ if (total > limit) throw IOException("The file is larger than expected.")
+ out.write(buffer, 0, n)
+ }
+ }
+ }
+ }
+
+ fun readBytes(context: Context, uri: Uri, limit: Int): ByteArray {
+ val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open $uri")
+ input.use { source ->
+ val out = java.io.ByteArrayOutputStream()
+ val buffer = ByteArray(8192)
+ while (true) {
+ val n = source.read(buffer)
+ if (n < 0) break
+ out.write(buffer, 0, n)
+ if (out.size() > limit) throw IOException("The file is larger than expected.")
+ }
+ return out.toByteArray()
+ }
+ }
+
+ /** Creates [name] in the folder [tree] (a tree URI from ACTION_OPEN_DOCUMENT_TREE) and returns its URI. */
+ fun createInTree(context: Context, tree: Uri, name: String): Uri {
+ val parent = DocumentsContract.buildDocumentUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
+ return DocumentsContract.createDocument(context.contentResolver, parent, APK_MIME, name)
+ ?: throw IOException("The folder would not create $name. Choose the folder again.")
+ }
+
+ fun copyFileTo(context: Context, source: File, target: Uri, onBytes: (Long) -> Unit) {
+ val out = context.contentResolver.openOutputStream(target, "w") ?: throw IOException("Cannot write to the folder.")
+ out.use { sink ->
+ source.inputStream().use { input ->
+ val buffer = ByteArray(64 * 1024)
+ var total = 0L
+ while (true) {
+ val n = input.read(buffer)
+ if (n < 0) break
+ sink.write(buffer, 0, n)
+ total += n
+ onBytes(total)
+ }
+ }
+ }
+ }
+
+ /** A readable name for a tree URI, such as `Download/Builds`. */
+ fun treeLabel(tree: Uri): String =
+ try {
+ DocumentsContract.getTreeDocumentId(tree).substringAfter(':').ifEmpty { "the storage root" }
+ } catch (e: Exception) {
+ tree.toString()
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
new file mode 100644
index 00000000..bb4a5991
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
@@ -0,0 +1,335 @@
+package org.appdevforall.customidebuilder
+
+import android.app.AlertDialog
+import android.content.Context
+import android.content.Intent
+import android.content.SharedPreferences
+import android.net.Uri
+import android.os.Bundle
+import android.text.InputType
+import android.util.TypedValue
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.AdapterView
+import android.widget.ArrayAdapter
+import android.widget.Button
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.ProgressBar
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.fragment.app.Fragment
+import org.appdevforall.customidebuilder.core.AddonKind
+import org.appdevforall.customidebuilder.core.Catalog
+
+/**
+ * The Custom IDE Builder screen. Views are built in code, so there is no layout to inflate against the
+ * host's resources, and every text size is in sp and every gap in dp, inside a ScrollView, so the screen
+ * holds up at 2x font scale. State that must outlive the screen is in [Session].
+ */
+class BuilderFragment : Fragment() {
+ private lateinit var prefs: SharedPreferences
+ private lateinit var itemsBox: LinearLayout
+ private lateinit var keystoreLabel: TextView
+ private lateinit var storePassword: EditText
+ private lateinit var keyPassword: EditText
+ private lateinit var aliasSpinner: Spinner
+ private lateinit var fingerprint: TextView
+ private lateinit var folderLabel: TextView
+ private lateinit var progress: ProgressBar
+ private lateinit var stageLabel: TextView
+ private lateinit var messageLabel: TextView
+ private lateinit var cancelButton: Button
+ private val actionButtons = ArrayList
-
What you need
+
Core functionality
+
+
Bundle swap. The plugins (.cgp) and templates (.cgt) you choose
+ replace the add-ons bundled in the copy. Choosing nothing makes a copy that carries no add-ons.
+
Add-ons from two places. Pick files from this device, or choose from the add-ons website,
+ which lists the ones that work with this version of Code on the Go.
+
Signing. The copy is signed with a key from your own keystore, and the signature is checked
+ before the file is saved.
+
Output folder. The finished APK is saved to a folder you choose, as
+ <app name>-<version>-custom.apk.
+
Release builds only. It is made for the release build of Code on the Go, which reads its
+ bundled add-ons from assets/plugins/ and assets/templates/ in its APK.
+
Installing the copy. It installs only after Code on the Go is uninstalled, because it is signed
+ with a different key.
+
+
+
Technical architecture
+
+
The installed app's APK is copied entry by entry without being recompressed. The old bundle
+ (assets/plugins/, assets/templates/ and the index
+ assets/bundled-addons.tsv) and the old signature are dropped, then your add-ons and a new
+ index are added, in the layout Code on the Go itself reads.
+
Each add-on gets a clean file name inside the APK. A plugin is named after its plugin ID, a template
+ after its file name, and two that would clash are refused before the build starts.
+
The APK is signed with the Android signing library (apksig) and then verified with it,
+ and its alignment is checked.
+
Files you pick are copied into this plugin's own private folder under a fixed name, whatever the file
+ is called, before they are checked. Downloads from the website come only from
+ addons.appdevforall.org over HTTPS and are checked against the size and SHA-256 the
+ website publishes.
+
Passwords are held only in the screen's fields and in the one running build, and are cleared when it
+ ends. The plugin asks for permission to read and write files and to use the network (for the website
+ list only).
+
+
+
Usage
+
What you need
A keystore file in PKCS12 (.p12) or BKS format, such as one made by
Keystore Generator. A Java KeyStore (.jks) file made by keytool must
@@ -57,19 +95,30 @@
What you need
A folder to save the finished APK in, and free space for about twice the size of Code on the Go.
-
How to use it
+
How to use it
Open Custom IDE Builder from the main menu.
Add-ons. Tap Add from this device to pick several files at once. Tap
Add from the website to choose from the add-ons that work with this version of Code on the Go.
Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org
- and each one is checked against the size and SHA-256 the website publishes.
+ and each one is checked against the size and SHA-256 the website publishes. Tap Remove beside an
+ add-on to take it off the list.
Signing key. Choose the keystore file, type the store password and tap Read keys,
then pick the key. Leave the key password blank if it is the same as the store password.
Output folder. Choose it once; it is remembered.
-
Tap Build APK. The file is saved as
- <app name>-<version>-custom.apk.
+
Tap Build APK. Tap Cancel to stop it; nothing is saved from a cancelled build.
+
Long-press any button or field on the screen for a short explanation.
+
+
Key benefits
+
+
Hand out one APK that arrives with the plugins and templates a group needs, with nothing to install
+ afterwards.
+
It is signed with your key, so you decide who the publisher is.
+
It works offline once you have the files, and does not need a computer.
+
Every download and every selection is checked before it goes into the copy.
+
Your passwords are never saved.
+
Good to know
diff --git a/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml b/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml
index a651b418..b14ab93c 100644
--- a/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml
+++ b/plugins/Custom-IDE-Builder/src/main/AndroidManifest.xml
@@ -35,10 +35,14 @@
android:name="plugin.author"
android:value="App Dev for All" />
-
+
+ android:value="26.48" />
+
+
Custom IDE Builder
+
Executive overview
Custom IDE Builder makes a copy of the Code on the Go installed on this device, with the
plugins and templates you choose bundled inside it, and signs the copy with your own key. Use it to
hand out a version of Code on the Go that arrives with the add-ons a class, a team or a community needs
@@ -46,7 +48,43 @@
Custom IDE Builder
uninstalling erases the projects stored in the app's data. Copy your projects out first.
-
What you need
+
Core functionality
+
+
Bundle swap. The plugins (.cgp) and templates (.cgt) you choose
+ replace the add-ons bundled in the copy. Choosing nothing makes a copy that carries no add-ons.
+
Add-ons from two places. Pick files from this device, or choose from the add-ons website,
+ which lists the ones that work with this version of Code on the Go.
+
Signing. The copy is signed with a key from your own keystore, and the signature is checked
+ before the file is saved.
+
Output folder. The finished APK is saved to a folder you choose, as
+ <app name>-<version>-custom.apk.
+
Release builds only. It is made for the release build of Code on the Go, which reads its
+ bundled add-ons from assets/plugins/ and assets/templates/ in its APK.
+
Installing the copy. It installs only after Code on the Go is uninstalled, because it is signed
+ with a different key.
+
+
+
Technical architecture
+
+
The installed app's APK is copied entry by entry without being recompressed. The old bundle
+ (assets/plugins/, assets/templates/ and the index
+ assets/bundled-addons.tsv) and the old signature are dropped, then your add-ons and a new
+ index are added, in the layout Code on the Go itself reads.
+
Each add-on gets a clean file name inside the APK. A plugin is named after its plugin ID, a template
+ after its file name, and two that would clash are refused before the build starts.
+
The APK is signed with the Android signing library (apksig) and then verified with it,
+ and its alignment is checked.
+
Files you pick are copied into this plugin's own private folder under a fixed name, whatever the file
+ is called, before they are checked. Downloads from the website come only from
+ addons.appdevforall.org over HTTPS and are checked against the size and SHA-256 the
+ website publishes.
+
Passwords are held only in the screen's fields and in the one running build, and are cleared when it
+ ends. The plugin asks for permission to read and write files and to use the network (for the website
+ list only).
+
+
+
Usage
+
What you need
A keystore file in PKCS12 (.p12) or BKS format, such as one made by
Keystore Generator. A Java KeyStore (.jks) file made by keytool must
@@ -57,19 +95,30 @@
What you need
A folder to save the finished APK in, and free space for about twice the size of Code on the Go.
-
How to use it
+
How to use it
Open Custom IDE Builder from the main menu.
Add-ons. Tap Add from this device to pick several files at once. Tap
Add from the website to choose from the add-ons that work with this version of Code on the Go.
Nothing is downloaded until you confirm; the downloads come from addons.appdevforall.org
- and each one is checked against the size and SHA-256 the website publishes.
+ and each one is checked against the size and SHA-256 the website publishes. Tap Remove beside an
+ add-on to take it off the list.
Signing key. Choose the keystore file, type the store password and tap Read keys,
then pick the key. Leave the key password blank if it is the same as the store password.
Output folder. Choose it once; it is remembered.
-
Tap Build APK. The file is saved as
- <app name>-<version>-custom.apk.
+
Tap Build APK. Tap Cancel to stop it; nothing is saved from a cancelled build.
+
Long-press any button or field on the screen for a short explanation.
+
+
Key benefits
+
+
Hand out one APK that arrives with the plugins and templates a group needs, with nothing to install
+ afterwards.
+
It is signed with your key, so you decide who the publisher is.
+
It works offline once you have the files, and does not need a computer.
+
Every download and every selection is checked before it goes into the copy.
+
Your passwords are never saved.
+
Good to know
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
index bb4a5991..00f30c4a 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
@@ -93,7 +93,7 @@ class BuilderFragment : Fragment() {
keystoreLabel = text(ctx, "", 14f)
column.addView(keystoreLabel)
column.addView(action(ctx, "Choose keystore file", Help.KEYSTORE) { pickKeystore.launch(arrayOf("*/*")) })
- storePassword = passwordField(ctx, "Store password")
+ storePassword = passwordField(ctx, "Store password", Help.STORE_PASSWORD)
column.addView(storePassword)
column.addView(action(ctx, "Read keys", Help.KEYSTORE) {
val chars = charsOf(storePassword)
@@ -101,6 +101,7 @@ class BuilderFragment : Fragment() {
refresh()
})
aliasSpinner = Spinner(ctx)
+ withTooltip(aliasSpinner, Help.KEY_ALIAS)
aliasSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Session.selectedAlias = Session.aliases.getOrNull(position)
@@ -112,7 +113,7 @@ class BuilderFragment : Fragment() {
column.addView(aliasSpinner)
fingerprint = text(ctx, "", 12f)
column.addView(fingerprint)
- keyPassword = passwordField(ctx, "Key password (blank: same as store password)")
+ keyPassword = passwordField(ctx, "Key password (blank: same as store password)", Help.KEY_PASSWORD)
column.addView(keyPassword)
column.addView(heading(ctx, "3. Output folder"))
@@ -129,6 +130,7 @@ class BuilderFragment : Fragment() {
cancelButton = Button(ctx).apply {
this.text = "Cancel"
setOnClickListener { Session.cancel() }
+ withTooltip(this, Help.CANCEL)
}
column.addView(cancelButton)
messageLabel = text(ctx, "", 14f).apply { setTextIsSelectable(true) }
@@ -186,6 +188,7 @@ class BuilderFragment : Fragment() {
this.text = "Remove"
isEnabled = !busy
setOnClickListener { Session.remove(chosen) }
+ withTooltip(this, Help.REMOVE)
})
itemsBox.addView(row)
}
@@ -313,14 +316,23 @@ class BuilderFragment : Fragment() {
private fun action(ctx: Context, label: String, tooltip: String, onClick: () -> Unit) = Button(ctx).apply {
text = label
setOnClickListener { onClick() }
- setOnLongClickListener { v ->
- CustomIdeBuilderPlugin.tooltips()?.showTooltip(v, Help.CATEGORY, tooltip)
- true
- }
+ withTooltip(this, tooltip)
actionButtons.add(this)
}
- private fun passwordField(ctx: Context, hintText: String) = EditText(ctx).apply {
+ /**
+ * Long-press shows the tooltip. [consume] false lets the press carry on to the view's own
+ * long-press (a text field's paste menu).
+ */
+ private fun withTooltip(view: View, tag: String, consume: Boolean = true) {
+ view.setOnLongClickListener { v ->
+ CustomIdeBuilderPlugin.tooltips()?.showTooltip(v, Help.CATEGORY, tag)
+ consume
+ }
+ }
+
+ private fun passwordField(ctx: Context, hintText: String, tooltip: String) = EditText(ctx).apply {
+ withTooltip(this, tooltip, consume = false)
hint = hintText
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/CustomIdeBuilderPlugin.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/CustomIdeBuilderPlugin.kt
index c6c5690e..5aa3e787 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/CustomIdeBuilderPlugin.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/CustomIdeBuilderPlugin.kt
@@ -28,7 +28,7 @@ class CustomIdeBuilderPlugin : IPlugin, UIExtension, DocumentationExtension {
override fun deactivate(): Boolean = true
override fun dispose() {
- Session.cancel()
+ Session.end()
Session.clearItems()
context = null
}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Help.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Help.kt
index 78552b2d..961fe2a4 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Help.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Help.kt
@@ -16,6 +16,11 @@ object Help {
const val KEYSTORE = "customidebuilder.keystore"
const val FOLDER = "customidebuilder.folder"
const val BUILD = "customidebuilder.build"
+ const val REMOVE = "customidebuilder.remove"
+ const val CANCEL = "customidebuilder.cancel"
+ const val STORE_PASSWORD = "customidebuilder.storepassword"
+ const val KEY_PASSWORD = "customidebuilder.keypassword"
+ const val KEY_ALIAS = "customidebuilder.keyalias"
private val more = listOf(PluginTooltipButton(description = "About Custom IDE Builder", uri = "index.html", order = 0))
@@ -67,5 +72,41 @@ object Help {
"copying the file, plus the time to sign it.",
more,
),
+ PluginTooltipEntry(
+ REMOVE,
+ "Take this add-on off the list.",
+ "
Removes it from the copy you are about to build and deletes the copy this plugin made of the " +
+ "file. The original file is not touched.
",
+ more,
+ ),
+ PluginTooltipEntry(
+ CANCEL,
+ "Stop the build or download in progress.",
+ "
Nothing is saved to your output folder from a cancelled build, and the temporary files are " +
+ "deleted. Your add-on list and keystore choice stay as they are.
",
+ more,
+ ),
+ PluginTooltipEntry(
+ STORE_PASSWORD,
+ "The password that opens the keystore file.",
+ "
Used to read the keys and again for the build. It is never saved, and it is cleared when you " +
+ "leave this screen.
",
+ more,
+ ),
+ PluginTooltipEntry(
+ KEY_PASSWORD,
+ "The password of the chosen key. Leave it blank if it is the store password.",
+ "
PKCS12 keystores usually use one password for both. It is never saved, and it is cleared when " +
+ "you leave this screen.
",
+ more,
+ ),
+ PluginTooltipEntry(
+ KEY_ALIAS,
+ "Which key in the keystore signs the copy.",
+ "
Shown after you tap Read keys. The line below the list is the certificate fingerprint " +
+ "(SHA-256) of the chosen key, so you can check it is the key you used before. Use the same key " +
+ "for every build.
",
+ more,
+ ),
)
}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
index cc8055d6..870628da 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
@@ -28,6 +28,7 @@ import org.appdevforall.customidebuilder.core.Naming
import org.appdevforall.customidebuilder.core.PickedAddon
import org.appdevforall.customidebuilder.core.Pipeline
import org.appdevforall.customidebuilder.core.SelectionResult
+import org.appdevforall.customidebuilder.core.Staging
import java.io.File
import java.security.MessageDigest
import java.security.cert.X509Certificate
@@ -60,7 +61,7 @@ object Session {
var progress: Int = 0
private val main = Handler(Looper.getMainLooper())
- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
+ private var scope: CoroutineScope? = null
private var job: Job? = null
private var counter = 0
private val listeners = ArrayList<() -> Unit>()
@@ -80,40 +81,59 @@ object Session {
changed()
}
+ /** Deletes [file] only if it is under the staging folder, so a bad path can never remove anything else. */
+ private fun discard(file: File) {
+ val staging = stagingDir() ?: return
+ if (Staging.isInside(staging, file)) file.delete()
+ }
+
fun remove(chosen: Chosen) {
items.remove(chosen)
- chosen.picked.file.delete()
+ discard(chosen.picked.file)
changed()
}
fun clearItems() {
- items.toList().forEach { it.picked.file.delete() }
+ items.toList().forEach { discard(it.picked.file) }
items.clear()
}
+ /** Stops the running job (the Cancel button). The Session can start another afterwards. */
fun cancel() {
job?.cancel()
}
+ /** Called when the plugin is disposed: stops the job and the scope it ran in, and drops queued screen updates. */
+ fun end() {
+ job?.cancel()
+ job = null
+ scope?.cancel()
+ scope = null
+ main.removeCallbacksAndMessages(null)
+ busy = false
+ }
+
/** Copies the chosen files into the plugin's folder and adds each one that passes [AddonSelection.validate]. */
fun addFromDevice(context: Context, uris: List) {
val staging = stagingDir() ?: return report("The plugin's storage is not available.")
launch("Adding add-ons") {
val problems = ArrayList()
for (uri in uris) {
+ // The reported name is untrusted: it is the label and the source of the entry name, never a path.
val name = AndroidBits.displayName(context, uri) ?: "add-on"
- if (AddonSelection.kindOf(name) == null) {
- problems.add("$name: not a .cgp or .cgt file")
+ val label = Staging.label(name)
+ val file = Staging.stagedFile(staging, counter++, name)
+ if (file == null) {
+ problems.add("$label: not a .cgp or .cgt file")
continue
}
- val file = File(staging, "${counter++}/$name")
val added =
try {
withContext(Dispatchers.IO) { AndroidBits.copyToFile(context, uri, file) }
- accept(context, name, name, file, "this device")
+ accept(context, label, name, file, "this device")
} catch (e: java.io.IOException) {
- file.delete()
- "$name: ${e.message}"
+ discard(file)
+ "$label: ${e.message}"
}
if (added != null) problems.add(added)
}
@@ -147,10 +167,15 @@ object Session {
stage = "Downloading ${addon.name} (${i + 1} of ${wanted.size})"
progress = 0
changed()
+ val dir = File(staging, "${counter++}")
+ if (!Staging.isInside(staging, File(dir, addon.fileName))) {
+ problems.add("${Staging.label(addon.name)}: its file name is not usable")
+ continue
+ }
val file =
try {
withContext(Dispatchers.IO) {
- downloader.download(addon, File(staging, "${counter++}")) { got ->
+ downloader.download(addon, dir) { got ->
main.post { progress = (got * 1000 / addon.size.coerceAtLeast(1)).toInt(); changed() }
}
}
@@ -168,7 +193,7 @@ object Session {
private suspend fun accept(context: Context, label: String, fileName: String, file: File, source: String): String? {
val id = if (AddonSelection.kindOf(fileName) == AddonKind.PLUGIN) withContext(Dispatchers.IO) { AndroidBits.readPluginId(context, file) } else null
if (AddonSelection.kindOf(fileName) == AddonKind.TEMPLATE && !looksLikeZip(file)) {
- file.delete()
+ discard(file)
return "$label: not a template bundle (it is not a zip file)"
}
val picked = PickedAddon(label, fileName, file, id)
@@ -178,7 +203,7 @@ object Session {
null
}
is SelectionResult.Invalid -> {
- file.delete()
+ discard(file)
r.problems.firstOrNull { label in it } ?: r.problems.first()
}
}
@@ -304,7 +329,7 @@ object Session {
progress = 0
message = ""
changed()
- job = scope.launch {
+ job = (scope ?: CoroutineScope(SupervisorJob() + Dispatchers.Main).also { scope = it }).launch {
try {
block()
} finally {
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Staging.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Staging.kt
new file mode 100644
index 00000000..3d5903cc
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Staging.kt
@@ -0,0 +1,32 @@
+package org.appdevforall.customidebuilder.core
+
+import java.io.File
+
+/**
+ * Where a picked file is copied before it is checked. The name a document provider reports is
+ * untrusted (it can be "../../x.cgp"), so it never becomes a path: the file on disk is always
+ * `/addon.`, and the reported name stays only as the label and the source of the
+ * bundled entry name (which [AddonSelection.entryNameFor] cleans).
+ */
+object Staging {
+ /** `addon.cgp` or `addon.cgt` for a reported name with one of those extensions, else null. */
+ fun stagedFileName(reportedName: String): String? = AddonSelection.kindOf(reportedName)?.let { "addon.${it.extension}" }
+
+ /** The reported name as shown on screen: control characters removed, at most 100 characters. */
+ fun label(reportedName: String): String = reportedName.filter { !it.isISOControl() }.take(100).ifBlank { "add-on" }
+
+ /** The file to copy into for the [index]th add-on, or null for a name that is not an add-on or a path outside [root]. */
+ fun stagedFile(root: File, index: Int, reportedName: String): File? {
+ val name = stagedFileName(reportedName) ?: return null
+ return File(File(root, index.toString()), name).takeIf { isInside(root, it) }
+ }
+
+ /** True if [file] resolves, symbolic links included, to a place strictly under [root]. */
+ fun isInside(root: File, file: File): Boolean =
+ try {
+ val base = root.canonicalFile.path
+ file.canonicalFile.path.startsWith(base + File.separator)
+ } catch (e: java.io.IOException) {
+ false
+ }
+}
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/StagingTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/StagingTest.kt
new file mode 100644
index 00000000..972a54dc
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/StagingTest.kt
@@ -0,0 +1,79 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+
+class StagingTest {
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ private val hostile = listOf("../../x.cgp", "a/b.cgp", "/abs.cgp", "..\\..\\x.cgt", "a\u0000.cgp", "x.cgp\u0000")
+
+ @Test
+ fun aNormalNameStagesUnderAFixedName() {
+ assertEquals("addon.cgp", Staging.stagedFileName("My Plugin.cgp"))
+ assertEquals("addon.cgt", Staging.stagedFileName("Kit.CGT"))
+ }
+
+ @Test
+ fun aNameThatIsNotAnAddOnStagesNothing() {
+ assertNull(Staging.stagedFileName(".."))
+ assertNull(Staging.stagedFileName("notes.txt"))
+ assertNull(Staging.stagedFileName(""))
+ }
+
+ @Test
+ fun hostileNamesNeverReachThePath() {
+ val root = tmp.newFolder("staging")
+ for (name in hostile) {
+ val name2 = Staging.stagedFileName(name)
+ assertTrue(name, name2 == "addon.cgp" || name2 == "addon.cgt" || name2 == null)
+ val file = Staging.stagedFile(root, 3, name)
+ if (file != null) {
+ assertEquals(name, File(File(root, "3"), name2!!).path, file.path)
+ assertTrue(name, Staging.isInside(root, file))
+ }
+ }
+ assertNull(Staging.stagedFile(root, 0, ".."))
+ }
+
+ @Test
+ fun theLabelHasNoControlCharacters() {
+ assertEquals("a.cgp", Staging.label("a\u0000.cgp"))
+ assertFalse(Staging.label("x\u0000\n.cgp").any { it.isISOControl() })
+ assertEquals("add-on", Staging.label("\u0000"))
+ assertEquals(100, Staging.label("a".repeat(500)).length)
+ }
+
+ @Test
+ fun containmentRejectsEscapes() {
+ val root = tmp.newFolder("staging2")
+ assertTrue(Staging.isInside(root, File(root, "1/addon.cgp")))
+ assertFalse(Staging.isInside(root, File(root, "../outside.cgp")))
+ assertFalse(Staging.isInside(root, File(root, "1/../../outside.cgp")))
+ assertFalse(Staging.isInside(root, File("/abs.cgp")))
+ assertFalse("the root itself is not a file inside it", Staging.isInside(root, root))
+ assertFalse(Staging.isInside(root, File(root.path + "-sibling/addon.cgp")))
+ }
+
+ @Test
+ fun containmentFollowsSymbolicLinks() {
+ val root = tmp.newFolder("staging3")
+ val outside = tmp.newFolder("outside")
+ val link = File(root, "link")
+ try {
+ java.nio.file.Files.createSymbolicLink(link.toPath(), outside.toPath())
+ } catch (e: Exception) {
+ return
+ }
+ assertNotNull(link)
+ assertFalse(Staging.isInside(root, File(link, "addon.cgp")))
+ }
+}
From 6077b68cf8ac07f923711f1fa242630d49641b1d Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 25 Nov 2026 07:42:24 +0000
Subject: [PATCH 06/17] ADFA-7241: Import CoroutineScope.cancel in Session
Session.end() calls scope?.cancel(), an extension function that needs
its import; the real Kotlin compiler stopped on it at Session.kt.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../src/main/kotlin/org/appdevforall/customidebuilder/Session.kt | 1 +
1 file changed, 1 insertion(+)
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
index 870628da..2b04936b 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/Session.kt
@@ -8,6 +8,7 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
From f388f811526fec7f0cd3ac9dc5f283d2f56c99ef Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 25 Nov 2026 09:20:01 +0000
Subject: [PATCH 07/17] ADFA-7241: Honour cancellation in downloads; malformed
redirects are DownloadExceptions
The downloader checks a passed cancellation check between reads and before
verification and rename (the .part file is still removed). A Location that
URI.resolve rejects now throws DownloadException with the cause instead of an
unchecked IllegalArgumentException that no caller catches.
CodeRabbit F8, F9 on PR 179.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../customidebuilder/core/Download.kt | 24 +++++++++--
.../customidebuilder/core/CatalogTest.kt | 40 +++++++++++++++++++
2 files changed, 60 insertions(+), 4 deletions(-)
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
index 8c0aa738..a31be9e1 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Download.kt
@@ -45,7 +45,7 @@ class HttpFetcher(
301, 302, 303, 307, 308 -> {
val next = connection.getHeaderField("Location") ?: throw DownloadException("Redirect without a location from $current")
connection.disconnect()
- current = URI(current).resolve(next).toString()
+ current = resolveRedirect(current, next)
}
else -> {
connection.disconnect()
@@ -57,13 +57,24 @@ class HttpFetcher(
}
}
+/** The URL a redirect from [current] to [location] points at. A malformed `Location` is a [DownloadException], not an unchecked one. */
+internal fun resolveRedirect(current: String, location: String): String =
+ try {
+ URI(current).resolve(location).toString()
+ } catch (e: IllegalArgumentException) {
+ throw DownloadException("Redirect from $current to an address that is not valid", e)
+ } catch (e: java.net.URISyntaxException) {
+ throw DownloadException("Redirect from $current to an address that is not valid", e)
+ }
+
/** Downloads and verifies catalog add-ons. */
class AddonDownloader(private val fetcher: Fetcher) {
- /** The catalog text, at most [MAX_CATALOG_BYTES]. */
- fun fetchCatalog(url: String = Catalog.URL): String =
+ /** The catalog text, at most [MAX_CATALOG_BYTES]. [checkCancelled] is called between reads and may throw to stop. */
+ fun fetchCatalog(url: String = Catalog.URL, checkCancelled: () -> Unit = {}): String =
fetcher.open(url).use { input ->
val out = java.io.ByteArrayOutputStream()
pump(input) { buf, n ->
+ checkCancelled()
out.write(buf, 0, n)
if (out.size() > MAX_CATALOG_BYTES) throw DownloadException("The catalog is larger than expected.")
}
@@ -74,8 +85,10 @@ class AddonDownloader(private val fetcher: Fetcher) {
* Downloads [addon] into [dir] as `.cgp|cgt` and checks its size and SHA-256 against the
* catalog; on any mismatch the file is deleted and the call throws. It reads no more than
* the promised size plus one byte, so a server cannot make it fill the disk.
+ * [checkCancelled] is called between reads and before the check and the rename, and may throw to
+ * stop; the partial file is deleted then too.
*/
- fun download(addon: CatalogAddon, dir: File, onBytes: (Long) -> Unit = {}): File {
+ fun download(addon: CatalogAddon, dir: File, checkCancelled: () -> Unit = {}, onBytes: (Long) -> Unit = {}): File {
dir.mkdirs()
val target = File(dir, addon.fileName)
val partial = File(dir, addon.fileName + ".part")
@@ -84,6 +97,7 @@ class AddonDownloader(private val fetcher: Fetcher) {
fetcher.open(addon.downloadUrl).use { input ->
partial.outputStream().use { out ->
pump(input) { buf, n ->
+ checkCancelled()
total += n
if (total > addon.size) throw DownloadException("${addon.name}: the download is larger than the catalog says (${addon.size} bytes).")
out.write(buf, 0, n)
@@ -91,7 +105,9 @@ class AddonDownloader(private val fetcher: Fetcher) {
}
}
}
+ checkCancelled()
Catalog.verifyDownload(partial, addon)?.let { throw DownloadException(it) }
+ checkCancelled()
target.delete()
if (!partial.renameTo(target)) throw DownloadException("${addon.name}: could not save the download.")
return target
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
index 19f1217b..2f33b2b8 100644
--- a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/CatalogTest.kt
@@ -174,6 +174,46 @@ class CatalogTest {
assertEquals(0, dir.listFiles()!!.size)
}
+ @Test
+ fun cancellingAtAnyCheckStopsTheDownloadAndLeavesNothing() {
+ val bytes = TestSupport.noise(1000)
+ val addon = addonFor(bytes)
+ // Call 1 is after the only chunk is read, 2 before the verification, 3 before the rename.
+ for (stopAt in 1..3) {
+ val dir = tmp.newFolder()
+ var calls = 0
+ try {
+ AddonDownloader { ByteArrayInputStream(bytes) }.download(addon, dir, checkCancelled = { if (++calls == stopAt) throw java.util.concurrent.CancellationException("stop") })
+ throw AssertionError("finished although cancelled at check $stopAt")
+ } catch (e: java.util.concurrent.CancellationException) {
+ assertEquals(stopAt, calls)
+ }
+ assertEquals("check $stopAt", 0, dir.listFiles()!!.size)
+ }
+ }
+
+ @Test
+ fun cancellingStopsTheCatalogRead() {
+ try {
+ AddonDownloader { ByteArrayInputStream("hello".toByteArray()) }.fetchCatalog(checkCancelled = { throw java.util.concurrent.CancellationException("stop") })
+ throw AssertionError("finished")
+ } catch (e: java.util.concurrent.CancellationException) {
+ // expected
+ }
+ }
+
+ @Test
+ fun aMalformedRedirectLocationIsADownloadExceptionWithItsCause() {
+ try {
+ resolveRedirect("https://addons.appdevforall.org/a", "/bad path")
+ throw AssertionError("accepted")
+ } catch (e: DownloadException) {
+ assertTrue(e.cause is IllegalArgumentException || e.cause is java.net.URISyntaxException)
+ }
+ assertEquals("https://addons.appdevforall.org/b/c", resolveRedirect("https://addons.appdevforall.org/a", "/b/c"))
+ assertEquals("https://addons.appdevforall.org/a/d", resolveRedirect("https://addons.appdevforall.org/a/x", "d"))
+ }
+
@Test
fun verifyDownloadChecksSizeAndDigest() {
val f = File(tmp.root, "x").apply { writeBytes(ByteArray(5) { 1 }) }
From 358b9350d82560cf9dfd8b601a64f421d5160803 Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 25 Nov 2026 09:20:01 +0000
Subject: [PATCH 08/17] ADFA-7241: Fix zip writer edge cases and the rewriter
filter
- Drop top-level META-INF/SIG-* files too, so no signature block outlives its .SF.
- Report progress 1.0 only after the writer has closed.
- Align empty stored non-directory entries in the writer and in
ZipAlignment.misaligned together.
- Refuse a ZIP32 offset or size that reaches the reserved 0xFFFFFFFF, including
header-only entries and the central directory, instead of wrapping.
- Close the output stream when finishing the archive throws, keeping the error.
- ApkRewriterTest builds its expected retained set from the fixture and an
explicit removal list.
CodeRabbit F6, F7, F10, F11, F12, F15 on PR 179.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../customidebuilder/core/ApkRewriter.kt | 6 +-
.../appdevforall/customidebuilder/core/Zip.kt | 40 ++++-
.../customidebuilder/core/ApkRewriterTest.kt | 49 +++++-
.../customidebuilder/core/ZipTest.kt | 150 ++++++++++++++++++
4 files changed, 232 insertions(+), 13 deletions(-)
create mode 100644 plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ZipTest.kt
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
index 216fcbfd..8b4b8c47 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/ApkRewriter.kt
@@ -26,13 +26,13 @@ object ApkRewriter {
return isV1SignatureFile(name)
}
- /** `META-INF/MANIFEST.MF` and the `.SF`, `.RSA`, `.DSA` and `.EC` files directly in `META-INF/`. */
+ /** `META-INF/MANIFEST.MF`, the `.SF`, `.RSA`, `.DSA` and `.EC` files and the reserved `SIG-*` names, directly in `META-INF/`. */
fun isV1SignatureFile(name: String): Boolean {
val upper = name.uppercase()
if (!upper.startsWith("META-INF/")) return false
val rest = upper.removePrefix("META-INF/")
if ('/' in rest) return false
- return rest == "MANIFEST.MF" || rest.endsWith(".SF") || rest.endsWith(".RSA") || rest.endsWith(".DSA") || rest.endsWith(".EC")
+ return rest == "MANIFEST.MF" || rest.startsWith("SIG-") || rest.endsWith(".SF") || rest.endsWith(".RSA") || rest.endsWith(".DSA") || rest.endsWith(".EC")
}
/**
@@ -77,6 +77,8 @@ object ApkRewriter {
val crc = java.util.zip.CRC32().apply { update(indexBytes) }.value
writer.addStored(INDEX_APK_ENTRY, indexBytes.size.toLong(), crc) { sink -> sink.write(indexBytes) }
}
+ // Only now: the writer has finished the central directory, so a failure there is not reported as done.
+ onProgress(1.0)
}
return RewriteReport(copied, dropped, addons.map { it.apkEntryName } + INDEX_APK_ENTRY, index)
}
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
index b7411b07..3bab32a0 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/core/Zip.kt
@@ -181,7 +181,7 @@ object ZipAlignment {
fun misaligned(apk: File): List =
RawZipFile(apk).use { zip ->
zip.entries
- .filter { it.isStored && !it.isDirectory && it.compressedSize > 0 }
+ .filter { it.isStored && !it.isDirectory }
.filter { zip.dataOffset(it) % requiredFor(it.name) != 0L }
.map { it.name }
}
@@ -233,8 +233,10 @@ class RawZipWriter(output: OutputStream) : Closeable {
private fun begin(entry: RawZipEntry, flags: Int, writeData: (OutputStream) -> Unit) {
if (!names.add(entry.name)) throw ZipFormatException("${entry.name} would be written twice")
if (written.size >= 0xFFFE) throw ZipFormatException("too many zip entries")
+ requireZip32(entry.compressedSize, "${entry.name}'s size")
+ requireZip32(entry.size, "${entry.name}'s size")
val padding =
- if (entry.isStored && !entry.isDirectory && entry.compressedSize > 0) {
+ if (entry.isStored && !entry.isDirectory) {
val align = ZipAlignment.requiredFor(entry.name)
((align - (offset + 30 + entry.nameBytes.size) % align) % align).toInt()
} else {
@@ -254,6 +256,7 @@ class RawZipWriter(output: OutputStream) : Closeable {
u16(padding)
raw(entry.nameBytes)
raw(ByteArray(padding))
+ checkRange()
val dataStart = offset
writeData(CountingSink())
if (offset - dataStart != entry.compressedSize) {
@@ -262,9 +265,27 @@ class RawZipWriter(output: OutputStream) : Closeable {
written.add(Written(entry, flags, headerOffset))
}
- /** Appends the central directory and the end record. The output stream is closed. */
+ /**
+ * Appends the central directory and the end record. The output stream is closed, also when this
+ * throws; the error that stopped the writing is the one that is thrown.
+ */
override fun close() {
+ try {
+ finish()
+ } catch (e: Throwable) {
+ try {
+ out.close()
+ } catch (closing: Throwable) {
+ e.addSuppressed(closing)
+ }
+ throw e
+ }
+ out.close()
+ }
+
+ private fun finish() {
val cdStart = offset
+ requireZip32(cdStart, "the central directory's offset")
for (w in written) {
val e = w.entry
u32(SIG_CENTRAL)
@@ -287,6 +308,8 @@ class RawZipWriter(output: OutputStream) : Closeable {
raw(e.nameBytes)
}
val cdSize = offset - cdStart
+ requireZip32(cdSize, "the central directory's size")
+ checkRange()
u32(SIG_EOCD)
u16(0)
u16(0)
@@ -295,7 +318,6 @@ class RawZipWriter(output: OutputStream) : Closeable {
u32(cdSize)
u32(cdStart)
u16(0)
- out.close()
}
private inner class CountingSink : OutputStream() {
@@ -312,9 +334,8 @@ class RawZipWriter(output: OutputStream) : Closeable {
}
}
- private fun checkRange() {
- if (offset > 0xFFFFFFFFL) throw ZipFormatException("the zip would pass 4 GiB, which needs ZIP64")
- }
+ /** The header, the padding and the data must all end below the reserved 0xFFFFFFFF, or later offsets no longer fit. */
+ private fun checkRange() = requireZip32(offset, "the zip's length")
private fun u16(v: Int) {
out.write(v and 0xFF)
@@ -353,6 +374,11 @@ fun digestOf(file: File, onBytes: (Int) -> Unit = {}): FileDigest {
return FileDigest(size, crc.value, sha.digest().joinToString("") { "%02x".format(it) })
}
+/** A ZIP32 field holds 0 to 0xFFFFFFFE; 0xFFFFFFFF means "see the ZIP64 record". Throws when [value] does not fit. */
+internal fun requireZip32(value: Long, what: String) {
+ if (value < 0 || value >= 0xFFFFFFFFL) throw ZipFormatException("$what would pass 4 GiB, which needs ZIP64")
+}
+
internal inline fun pump(input: InputStream, each: (ByteArray, Int) -> Unit) {
val buffer = ByteArray(64 * 1024)
while (true) {
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
index 0e0a203d..b0690022 100644
--- a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ApkRewriterTest.kt
@@ -48,8 +48,19 @@ class ApkRewriterTest {
RawZipFile(source).use { src ->
RawZipFile(output).use { out ->
val byName = out.entries.associateBy { it.name }
- val kept = src.entries.filterNot { ApkRewriter.isDropped(it.name) }
- assertTrue(kept.size > 5)
+ // Expected from the fixture and a written-out list, not from ApkRewriter.isDropped, so a wrongly
+ // dropped entry (the manifest, say) cannot hide in both sides.
+ val removed = setOf("assets/plugins/old.cgp", "assets/templates/old.cgt", "assets/bundled-addons.tsv", "META-INF/MANIFEST.MF", "META-INF/OLD.SF", "META-INF/OLD.RSA")
+ val fixture = src.entries.map { it.name }
+ assertTrue("the fixture should hold the removed names", fixture.containsAll(removed))
+ val expected = fixture.filterNot { it in removed }
+ assertEquals(
+ setOf("AndroidManifest.xml", "classes.dex", "resources.arsc", "lib/arm64-v8a/libnative.so", "res/raw/data.bin", "assets/keep.txt", "META-INF/services/example.Service"),
+ expected.toSet(),
+ )
+ val kept = src.entries.filter { it.name in expected }
+ assertEquals(expected.size, kept.size)
+ for (name in expected) assertTrue("$name is missing from the output", name in byName)
for (s in kept) {
val o = byName.getValue(s.name)
assertEquals("method of ${s.name}", s.method, o.method)
@@ -123,14 +134,44 @@ class ApkRewriterTest {
@Test
fun whichNamesAreDropped() {
- for (name in listOf("assets/plugins/a.cgp", "assets/plugins/", "assets/templates/x/y.cgt", "assets/bundled-addons.tsv", "META-INF/MANIFEST.MF", "META-INF/CERT.SF", "META-INF/CERT.RSA", "META-INF/CERT.DSA", "META-INF/CERT.EC", "META-INF/cert.rsa")) {
+ for (name in listOf("assets/plugins/a.cgp", "assets/plugins/", "assets/templates/x/y.cgt", "assets/bundled-addons.tsv", "META-INF/SIG-OLD.SF", "META-INF/SIG-OLD.XYZ", "META-INF/sig-x.abc", "META-INF/MANIFEST.MF", "META-INF/CERT.SF", "META-INF/CERT.RSA", "META-INF/CERT.DSA", "META-INF/CERT.EC", "META-INF/cert.rsa")) {
assertTrue(name, ApkRewriter.isDropped(name))
}
- for (name in listOf("assets/other/a.cgp", "assets/pluginsX", "classes.dex", "META-INF/services/a.SF", "META-INF/com/android/build/gradle/app-metadata.properties", "META-INF/CERT.TXT", "lib/x/libplugins.so")) {
+ for (name in listOf("META-INF/sub/SIG-X.ABC", "META-INF/SIGN.TXT", "assets/other/a.cgp", "assets/pluginsX", "classes.dex", "META-INF/services/a.SF", "META-INF/com/android/build/gradle/app-metadata.properties", "META-INF/CERT.TXT", "lib/x/libplugins.so")) {
assertFalse(name, ApkRewriter.isDropped(name))
}
}
+ @Test
+ fun aTopLevelSigFileLosesItsBlockToo() {
+ val source = tmp.newFile("sig.apk")
+ TestSupport.syntheticApk(
+ source,
+ mapOf(
+ "META-INF/SIG-OLD.SF" to (java.util.zip.ZipEntry.DEFLATED to "x".toByteArray()),
+ "META-INF/SIG-OLD.XYZ" to (java.util.zip.ZipEntry.DEFLATED to "y".toByteArray()),
+ "META-INF/sub/SIG-KEEP.XYZ" to (java.util.zip.ZipEntry.DEFLATED to "z".toByteArray()),
+ ),
+ )
+ val output = tmp.newFile("sig-out.apk")
+ ApkRewriter.rewrite(source, output, emptyList())
+ val names = RawZipFile(output).use { z -> z.entries.map { it.name } }
+ assertFalse("META-INF/SIG-OLD.SF" in names)
+ assertFalse("META-INF/SIG-OLD.XYZ" in names)
+ assertTrue("META-INF/sub/SIG-KEEP.XYZ" in names)
+ }
+
+ @Test
+ fun progressEndsAtExactlyOneOnlyAfterTheZipIsClosed() {
+ val source = tmp.newFile("p.apk")
+ TestSupport.syntheticApk(source)
+ val seen = ArrayList()
+ ApkRewriter.rewrite(source, tmp.newFile("p-out.apk"), twoAddons(), onProgress = { seen.add(it) })
+ assertTrue(seen.isNotEmpty())
+ assertEquals(1.0, seen.last(), 0.0)
+ assertTrue("1.0 is reported once, at the end", seen.dropLast(1).all { it < 1.0 })
+ }
+
@Test
fun aSourceWithTrailingJunkBetweenEntriesAndDirectoryIsStillCopied() {
val source = tmp.newFile("signed-like.apk")
diff --git a/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ZipTest.kt b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ZipTest.kt
new file mode 100644
index 00000000..fcb60ad1
--- /dev/null
+++ b/plugins/Custom-IDE-Builder/src/test/kotlin/org/appdevforall/customidebuilder/core/ZipTest.kt
@@ -0,0 +1,150 @@
+package org.appdevforall.customidebuilder.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.File
+import java.io.IOException
+import java.io.OutputStream
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class ZipTest {
+ @get:Rule
+ val tmp = TemporaryFolder()
+
+ /** Takes the bytes and drops them; records whether it was closed and can be made to fail. */
+ private class Sink : OutputStream() {
+ var closed = false
+ var failWrites = false
+
+ override fun write(b: Int) {
+ if (failWrites) throw IOException("disk full")
+ }
+
+ override fun write(b: ByteArray, off: Int, len: Int) {
+ if (failWrites) throw IOException("disk full")
+ }
+
+ override fun close() {
+ closed = true
+ }
+ }
+
+ private fun zeros(count: Long): (OutputStream) -> Unit = { sink ->
+ val block = ByteArray(64 * 1024)
+ var left = count
+ while (left > 0) {
+ val n = minOf(block.size.toLong(), left).toInt()
+ sink.write(block, 0, n)
+ left -= n
+ }
+ }
+
+ /** "ab" has a 32-byte header, already aligned, so this ends the data at 0xFFFFFFFE, the last offset a ZIP32 field can hold. */
+ private fun RawZipWriter.fillToTheLastOffset() = addStored("ab", 0xFFFFFFFEL - 32, 0, zeros(0xFFFFFFFEL - 32))
+
+ @Test
+ fun emptyStoredFilesAreAlignedLikeAnyOtherStoredFile() {
+ val file = tmp.newFile("w.zip")
+ RawZipWriter(file.outputStream()).use { w ->
+ w.addStored("a", 1, 0) { it.write(1) }
+ w.addStored("empty.bin", 0, 0) {}
+ w.addStored("b", 1, 0) { it.write(1) }
+ w.addStored("empty.so", 0, 0) {}
+ w.addStored("dir/", 0, 0) {}
+ }
+ RawZipFile(file).use { z ->
+ for (e in z.entries.filter { it.isStored && !it.isDirectory }) assertEquals(e.name, 0L, z.dataOffset(e) % ZipAlignment.requiredFor(e.name))
+ assertEquals(2, z.entries.count { it.compressedSize == 0L && !it.isDirectory })
+ }
+ assertEquals(emptyList(), ZipAlignment.misaligned(file))
+ }
+
+ @Test
+ fun theAlignmentCheckReportsAMisalignedEmptyStoredFile() {
+ val file = tmp.newFile("m.zip")
+ ZipOutputStream(file.outputStream()).use { zip ->
+ for ((name, data) in listOf("a" to byteArrayOf(1), "empty" to ByteArray(0))) {
+ zip.putNextEntry(
+ ZipEntry(name).apply {
+ method = ZipEntry.STORED
+ size = data.size.toLong()
+ compressedSize = data.size.toLong()
+ crc = java.util.zip.CRC32().apply { update(data) }.value
+ },
+ )
+ zip.write(data)
+ zip.closeEntry()
+ }
+ }
+ assertTrue("empty" in ZipAlignment.misaligned(file))
+ }
+
+ @Test
+ fun aValueMustFitBelowTheReservedAllOnes() {
+ requireZip32(0, "x")
+ requireZip32(0xFFFFFFFEL, "x")
+ for (bad in listOf(0xFFFFFFFFL, 0x1_0000_001DL, -1L)) {
+ try {
+ requireZip32(bad, "x")
+ throw AssertionError("accepted $bad")
+ } catch (e: ZipFormatException) {
+ // expected
+ }
+ }
+ }
+
+ @Test
+ fun headerBytesThatPassTheLastOffsetAreRefusedNotWrittenAsAWrapAround() {
+ val writer = RawZipWriter(Sink())
+ writer.fillToTheLastOffset()
+ try {
+ writer.addStored("b", 0, 0) {}
+ throw AssertionError("wrote an entry whose offset no longer fits")
+ } catch (e: ZipFormatException) {
+ assertTrue(e.message, e.message!!.contains("ZIP64"))
+ }
+ }
+
+ @Test
+ fun aCentralDirectoryThatPassesTheLastOffsetIsRefusedAndTheStreamStillClosed() {
+ val sink = Sink()
+ val writer = RawZipWriter(sink)
+ writer.fillToTheLastOffset()
+ try {
+ writer.close()
+ throw AssertionError("wrote an end record that points to the wrong bytes")
+ } catch (e: ZipFormatException) {
+ assertTrue(e.message, e.message!!.contains("ZIP64"))
+ }
+ assertTrue(sink.closed)
+ }
+
+ @Test
+ fun theStreamIsClosedAndTheWriteErrorKeptWhenTheCentralDirectoryCannotBeWritten() {
+ val sink = Sink()
+ val writer = RawZipWriter(sink)
+ // Enough entries that the central directory alone is bigger than the writer's buffer.
+ for (i in 0 until 1500) writer.addStored("entry-%05d".format(i), 0, 0) {}
+ sink.failWrites = true
+ try {
+ writer.close()
+ throw AssertionError("close succeeded")
+ } catch (e: IOException) {
+ assertEquals("disk full", e.message)
+ }
+ assertTrue("the output stream must be closed after a failed finish", sink.closed)
+ }
+
+ @Test
+ fun aSmallArchiveStillRoundTrips() {
+ val file = File(tmp.root, "ok.zip")
+ RawZipWriter(file.outputStream()).use { it.addStored("x", 3, java.util.zip.CRC32().apply { update(byteArrayOf(1, 2, 3)) }.value) { s -> s.write(byteArrayOf(1, 2, 3)) } }
+ java.util.zip.ZipFile(file).use { assertEquals(listOf(1, 2, 3), it.getInputStream(it.getEntry("x")).readBytes().toList()) }
+ assertFalse(file.length() == 0L)
+ }
+}
From d6b69a237ea897b19a67a42960a89c8ec80c2aba Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 25 Nov 2026 09:20:01 +0000
Subject: [PATCH 09/17] ADFA-7241: Make cancel, save and password handling
match what the help says
- SAF import and save loops check cancellation between buffers; a save that
fails or is cancelled deletes the output document (NonCancellable).
- Session.launch reports unexpected exceptions on screen instead of letting
them reach the host process; CancellationException still propagates.
- The screen clears both password fields when a build ends, and reconciles the
alias spinner and fingerprint with Session.selectedAlias on every refresh.
- Help text and both copies of the docs say exactly that.
CodeRabbit F1, F2, F3, F4, F5, F13, F14 on PR 179. Android-side code is not
compiled in this environment.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw
---
.../custom-ide-builder.html | 11 ++++--
.../src/main/assets/docs/index.html | 11 ++++--
.../customidebuilder/AndroidBits.kt | 23 +++++++++--
.../customidebuilder/BuilderFragment.kt | 13 ++++++-
.../org/appdevforall/customidebuilder/Help.kt | 12 +++---
.../appdevforall/customidebuilder/Session.kt | 39 ++++++++++++++++---
6 files changed, 85 insertions(+), 24 deletions(-)
diff --git a/plugins/Custom-IDE-Builder/custom-ide-builder.html b/plugins/Custom-IDE-Builder/custom-ide-builder.html
index 6ff11576..4d8b9270 100644
--- a/plugins/Custom-IDE-Builder/custom-ide-builder.html
+++ b/plugins/Custom-IDE-Builder/custom-ide-builder.html
@@ -78,8 +78,9 @@
Technical architecture
is called, before they are checked. Downloads from the website come only from
addons.appdevforall.org over HTTPS and are checked against the size and SHA-256 the
website publishes.
-
Passwords are held only in the screen's fields and in the one running build, and are cleared when it
- ends. The plugin asks for permission to read and write files and to use the network (for the website
+
Passwords are held only in the screen's fields and in the one running build. The build's copies are
+ zeroed, and the fields are emptied, when a build ends, however it ends; the fields are also emptied when
+ you leave the screen. The plugin asks for permission to read and write files and to use the network (for the website
list only).
@@ -106,7 +107,9 @@
How to use it
Signing key. Choose the keystore file, type the store password and tap Read keys,
then pick the key. Leave the key password blank if it is the same as the store password.
Output folder. Choose it once; it is remembered.
-
Tap Build APK. Tap Cancel to stop it; nothing is saved from a cancelled build.
+
Tap Build APK. Tap Cancel to stop it. A cancelled or failed
+ build saves nothing: if it had already begun writing the APK to your folder, that unfinished file is
+ deleted.
Long-press any button or field on the screen for a short explanation.
@@ -125,7 +128,7 @@
Good to know
Use the same key every time. A device that has a build signed with one key cannot update to
a build signed with another without being uninstalled first.
Passwords are never saved. They are used for the build in front of you and cleared when
- you leave the screen.
+ a build ends and when you leave the screen.
Each plugin must have its own plugin ID and each template its own file name; the builder
says which add-ons clash. core.cgt is never bundled, because Code on the Go installs it
itself.
is called, before they are checked. Downloads from the website come only from
addons.appdevforall.org over HTTPS and are checked against the size and SHA-256 the
website publishes.
-
Passwords are held only in the screen's fields and in the one running build, and are cleared when it
- ends. The plugin asks for permission to read and write files and to use the network (for the website
+
Passwords are held only in the screen's fields and in the one running build. The build's copies are
+ zeroed, and the fields are emptied, when a build ends, however it ends; the fields are also emptied when
+ you leave the screen. The plugin asks for permission to read and write files and to use the network (for the website
list only).
@@ -106,7 +107,9 @@
How to use it
Signing key. Choose the keystore file, type the store password and tap Read keys,
then pick the key. Leave the key password blank if it is the same as the store password.
Output folder. Choose it once; it is remembered.
-
Tap Build APK. Tap Cancel to stop it; nothing is saved from a cancelled build.
+
Tap Build APK. Tap Cancel to stop it. A cancelled or failed
+ build saves nothing: if it had already begun writing the APK to your folder, that unfinished file is
+ deleted.
Long-press any button or field on the screen for a short explanation.
@@ -125,7 +128,7 @@
Good to know
Use the same key every time. A device that has a build signed with one key cannot update to
a build signed with another without being uninstalled first.
Passwords are never saved. They are used for the build in front of you and cleared when
- you leave the screen.
+ a build ends and when you leave the screen.
Each plugin must have its own plugin ID and each template its own file name; the builder
says which add-ons clash. core.cgt is never bundled, because Code on the Go installs it
itself.
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
index bef68f04..c6751221 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/AndroidBits.kt
@@ -75,8 +75,11 @@ object AndroidBits {
null
}
- /** Copies what [uri] holds into [target], stopping at [limit] bytes. */
- fun copyToFile(context: Context, uri: Uri, target: File, limit: Long = Long.MAX_VALUE) {
+ /**
+ * Copies what [uri] holds into [target], stopping at [limit] bytes. [checkCancelled] is called
+ * between buffers and may throw to stop; [target] is then left partly written for the caller to delete.
+ */
+ fun copyToFile(context: Context, uri: Uri, target: File, limit: Long = Long.MAX_VALUE, checkCancelled: () -> Unit = {}) {
target.parentFile?.mkdirs()
val input = context.contentResolver.openInputStream(uri) ?: throw IOException("Cannot open $uri")
input.use { source ->
@@ -84,6 +87,7 @@ object AndroidBits {
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
+ checkCancelled()
val n = source.read(buffer)
if (n < 0) break
total += n
@@ -116,13 +120,18 @@ object AndroidBits {
?: throw IOException("The folder would not create $name. Choose the folder again.")
}
- fun copyFileTo(context: Context, source: File, target: Uri, onBytes: (Long) -> Unit) {
+ /**
+ * Copies [source] into the document [target]. [checkCancelled] is called between buffers and may
+ * throw to stop; [target] then holds a partial file, which the caller removes with [deleteDocument].
+ */
+ fun copyFileTo(context: Context, source: File, target: Uri, checkCancelled: () -> Unit = {}, onBytes: (Long) -> Unit) {
val out = context.contentResolver.openOutputStream(target, "w") ?: throw IOException("Cannot write to the folder.")
out.use { sink ->
source.inputStream().use { input ->
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
+ checkCancelled()
val n = input.read(buffer)
if (n < 0) break
sink.write(buffer, 0, n)
@@ -133,6 +142,14 @@ object AndroidBits {
}
}
+ /** Removes the document [uri]; false if the provider would not (a failed cleanup is not worth a second error). */
+ fun deleteDocument(context: Context, uri: Uri): Boolean =
+ try {
+ DocumentsContract.deleteDocument(context.contentResolver, uri)
+ } catch (e: Exception) {
+ false
+ }
+
/** A readable name for a tree URI, such as `Download/Builds`. */
fun treeLabel(tree: Uri): String =
try {
diff --git a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
index 00f30c4a..306e4604 100644
--- a/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
+++ b/plugins/Custom-IDE-Builder/src/main/kotlin/org/appdevforall/customidebuilder/BuilderFragment.kt
@@ -45,6 +45,7 @@ class BuilderFragment : Fragment() {
private lateinit var cancelButton: Button
private val actionButtons = ArrayList