Add Android security Phase 0
This commit is contained in:
@@ -4,6 +4,12 @@ Status: **Plan**. Android already has several useful protections, but it does no
|
||||
|
||||
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
|
||||
|
||||
## Implementation progress (2026-11-03)
|
||||
|
||||
- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification previews and native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials.
|
||||
- Tested: DAV URL policy and attachment-name policy have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite.
|
||||
- Still open: invalid-certificate integration tests, device-level review of the merged release APK, private notification preference UI, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review.
|
||||
|
||||
## Goals and limits
|
||||
|
||||
Protect account credentials and locally cached mail if app files are copied; prevent untrusted mail or renderer content from gaining native capabilities; protect message content in transit; give users control over sensitive previews and local unlock; and bring Android OpenPGP behavior up to the security guarantees already implemented on desktop.
|
||||
|
||||
@@ -25,7 +25,7 @@ npm install
|
||||
npm run android:apk
|
||||
```
|
||||
|
||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk`. Install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`, or open the project in Android Studio with `npm run android:open`. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification previews contain generic text rather than mailbox addresses or message subjects. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||
|
||||
## Run on Windows or Linux
|
||||
|
||||
|
||||
@@ -3,6 +3,20 @@ apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
||||
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
||||
def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE')
|
||||
def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD')
|
||||
def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS')
|
||||
def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD')
|
||||
def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword]
|
||||
def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() }
|
||||
def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() }
|
||||
|
||||
if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) {
|
||||
throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.')
|
||||
}
|
||||
if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) {
|
||||
throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.')
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "studio.daybreak.mail"
|
||||
@@ -10,6 +24,16 @@ android {
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
if (hasCompleteReleaseSigning) {
|
||||
signingConfigs {
|
||||
release {
|
||||
storeFile file(releaseStoreFile)
|
||||
storePassword releaseStorePassword
|
||||
keyAlias releaseKeyAlias
|
||||
keyPassword releaseKeyPassword
|
||||
}
|
||||
}
|
||||
}
|
||||
packaging {
|
||||
resources {
|
||||
pickFirsts += "META-INF/NOTICE.md"
|
||||
@@ -33,6 +57,7 @@ android {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:usesCleartextTraffic="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
@@ -34,15 +36,6 @@
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths"></meta-data>
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -20,6 +20,8 @@ internal object AndroidDavService {
|
||||
private val httpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.followRedirects(false)
|
||||
.followSslRedirects(false)
|
||||
.build()
|
||||
|
||||
fun list(): JSONObject {
|
||||
@@ -36,12 +38,7 @@ internal object AndroidDavService {
|
||||
val serverUrl = input.optString("serverUrl").trim()
|
||||
val username = input.optString("username").trim()
|
||||
val password = input.optString("password")
|
||||
val url = try { URL(serverUrl) } catch (_: Exception) {
|
||||
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
|
||||
}
|
||||
require(url.protocol == "https" || (url.protocol == "http" && url.host in setOf("localhost", "127.0.0.1", "::1"))) {
|
||||
"DAV server URLs must use HTTPS."
|
||||
}
|
||||
val url = DavUrlPolicy.parseServerUrl(serverUrl)
|
||||
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
|
||||
val collections = discoverCollections(url.toString(), username, password, type)
|
||||
require(collections.length() > 0) {
|
||||
@@ -165,13 +162,7 @@ internal object AndroidDavService {
|
||||
body: String?,
|
||||
headers: Map<String, String> = emptyMap()
|
||||
): HttpResult {
|
||||
val target = URL(address)
|
||||
val base = URL(account.optString("serverUrl"))
|
||||
val targetPort = if (target.port >= 0) target.port else target.defaultPort
|
||||
val basePort = if (base.port >= 0) base.port else base.defaultPort
|
||||
require(target.protocol == base.protocol && target.host.equals(base.host, true) && targetPort == basePort) {
|
||||
"The DAV server returned a collection URL on an unexpected host."
|
||||
}
|
||||
DavUrlPolicy.requireSameOrigin(account.optString("serverUrl"), address)
|
||||
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
|
||||
val builder = Request.Builder()
|
||||
.url(address)
|
||||
@@ -394,7 +385,10 @@ internal object AndroidDavService {
|
||||
.put("username", account.optString("username"))
|
||||
.put("collections", account.optJSONArray("collections") ?: JSONArray())
|
||||
|
||||
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav"
|
||||
private fun type(value: String) = when (value) {
|
||||
"caldav", "carddav" -> value
|
||||
else -> throw IllegalArgumentException("Choose a supported CalDAV or CardDAV account.")
|
||||
}
|
||||
|
||||
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
|
||||
for (index in 0 until collections.length()) {
|
||||
|
||||
@@ -351,7 +351,7 @@ internal object AndroidMailService {
|
||||
}
|
||||
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error)
|
||||
android.util.Log.w("EpMailOutbox", "Mail operation remains queued (${error.javaClass.simpleName})")
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -479,7 +479,7 @@ internal object AndroidMailService {
|
||||
inbox.close(true)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error)
|
||||
android.util.Log.e("EpMailRules", "Could not apply a mail rule (${error.javaClass.simpleName})")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -690,12 +690,13 @@ internal object AndroidMailService {
|
||||
}
|
||||
|
||||
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
||||
val safeFilename = AttachmentNamePolicy.sanitize(filename)
|
||||
val mimeType = contentType.substringBefore(';').ifBlank {
|
||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, filename)
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, safeFilename)
|
||||
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
}
|
||||
@@ -703,13 +704,13 @@ internal object AndroidMailService {
|
||||
?: throw IllegalStateException("Could not create the attachment in Downloads.")
|
||||
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
?: throw IllegalStateException("Could not write the attachment.")
|
||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename)
|
||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
|
||||
}
|
||||
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
||||
?: throw IllegalStateException("Downloads storage is not available.")
|
||||
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_"))
|
||||
val file = File(directory, safeFilename)
|
||||
file.writeBytes(bytes)
|
||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename)
|
||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
|
||||
}
|
||||
|
||||
private const val CUSTOM_FOLDER_PREFIX = "Folder:"
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
internal object AttachmentNamePolicy {
|
||||
fun sanitize(value: String): String {
|
||||
val name = value
|
||||
.replace(Regex("[\\\\/:*?\"<>|\\u0000-\\u001f]"), "_")
|
||||
.trim()
|
||||
.take(180)
|
||||
return if (name.isBlank() || name == "." || name == "..") "attachment" else name
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import java.net.URL
|
||||
|
||||
/** Enforces the transport and origin policy for user-configured DAV endpoints. */
|
||||
internal object DavUrlPolicy {
|
||||
fun parseServerUrl(raw: String): URL {
|
||||
val url = try {
|
||||
URL(raw)
|
||||
} catch (_: Exception) {
|
||||
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
|
||||
}
|
||||
require(url.protocol.equals("https", ignoreCase = true) && url.host.isNotBlank()) {
|
||||
"DAV server URLs must use HTTPS."
|
||||
}
|
||||
require(url.userInfo == null && url.ref == null) {
|
||||
"DAV server URLs cannot contain credentials or fragments."
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
fun requireSameOrigin(baseAddress: String, targetAddress: String) {
|
||||
val base = parseServerUrl(baseAddress)
|
||||
val target = parseServerUrl(targetAddress)
|
||||
val basePort = if (base.port >= 0) base.port else base.defaultPort
|
||||
val targetPort = if (target.port >= 0) target.port else target.defaultPort
|
||||
require(target.host.equals(base.host, ignoreCase = true) && targetPort == basePort) {
|
||||
"The DAV server returned a collection URL on an unexpected host."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worke
|
||||
}
|
||||
Result.success()
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error)
|
||||
android.util.Log.w(TAG, "Periodic mail fallback sync failed (${error.javaClass.simpleName})")
|
||||
Result.retry()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ class MailIdleService : Service() {
|
||||
reconcile()
|
||||
if (watchers.isEmpty()) stopSelf(startId)
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.e(TAG, "Could not start mailbox watchers", error)
|
||||
android.util.Log.e(TAG, "Could not start mailbox watchers (${error.javaClass.simpleName})")
|
||||
}
|
||||
}.start()
|
||||
return START_STICKY
|
||||
@@ -102,7 +102,9 @@ class MailIdleService : Service() {
|
||||
)
|
||||
failures = 0
|
||||
} catch (error: Exception) {
|
||||
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error)
|
||||
if (!watcher.stopped.get()) {
|
||||
android.util.Log.w(TAG, "IMAP watcher disconnected (${error.javaClass.simpleName})")
|
||||
}
|
||||
failures += 1
|
||||
} finally {
|
||||
watcher.folder = null
|
||||
@@ -221,7 +223,7 @@ class MailIdleService : Service() {
|
||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||
.setContentTitle(title)
|
||||
.setContentText(email)
|
||||
.setContentText("Open ep-mail to check your inbox")
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(pendingIntent)
|
||||
@@ -229,7 +231,7 @@ class MailIdleService : Service() {
|
||||
try {
|
||||
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
|
||||
} catch (error: SecurityException) {
|
||||
android.util.Log.w(TAG, "Notification permission is unavailable", error)
|
||||
android.util.Log.w(TAG, "Notification permission is unavailable (${error.javaClass.simpleName})")
|
||||
}
|
||||
}
|
||||
val update = JSONObject()
|
||||
@@ -257,7 +259,7 @@ class MailIdleService : Service() {
|
||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||
.setContentTitle("Mail reminder")
|
||||
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
|
||||
.setContentText("A snoozed message is due")
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setContentIntent(appPendingIntentFor(appContext))
|
||||
@@ -268,7 +270,7 @@ class MailIdleService : Service() {
|
||||
notification
|
||||
)
|
||||
} catch (error: SecurityException) {
|
||||
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
|
||||
android.util.Log.w(TAG, "Reminder notification permission is unavailable (${error.javaClass.simpleName})")
|
||||
}
|
||||
}
|
||||
val update = JSONObject()
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<cloud-backup>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="external" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="external" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@@ -0,0 +1,20 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class AttachmentNamePolicyTest {
|
||||
@Test
|
||||
fun stripsPathSeparatorsAndControlCharacters() {
|
||||
assertEquals(".._secret.txt", AttachmentNamePolicy.sanitize("../secret.txt"))
|
||||
assertEquals("folder__secret.txt", AttachmentNamePolicy.sanitize("folder\\/secret.txt"))
|
||||
assertEquals("bad_name.txt", AttachmentNamePolicy.sanitize("bad\u0000name.txt"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun suppliesSafeFallbackAndBoundsLength() {
|
||||
assertEquals("attachment", AttachmentNamePolicy.sanitize(".."))
|
||||
assertEquals("attachment", AttachmentNamePolicy.sanitize(" "))
|
||||
assertEquals(180, AttachmentNamePolicy.sanitize("a".repeat(300)).length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class DavUrlPolicyTest {
|
||||
@Test
|
||||
fun acceptsHttpsServerUrl() {
|
||||
assertEquals("https://dav.example.test/calendar", DavUrlPolicy.parseServerUrl(
|
||||
"https://dav.example.test/calendar"
|
||||
).toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsCleartextAndNonWebSchemes() {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.parseServerUrl("http://localhost:8080/dav")
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.parseServerUrl("ftp://dav.example.test/dav")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsEmbeddedCredentialsAndFragments() {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.parseServerUrl("https://user:pass@dav.example.test/dav")
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.parseServerUrl("https://dav.example.test/dav#fragment")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun allowsSameOriginAndRejectsCrossOriginTargets() {
|
||||
DavUrlPolicy.requireSameOrigin(
|
||||
"https://dav.example.test/root",
|
||||
"https://dav.example.test/calendar/"
|
||||
)
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.requireSameOrigin(
|
||||
"https://dav.example.test/root",
|
||||
"https://attacker.example.test/calendar/"
|
||||
)
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
DavUrlPolicy.requireSameOrigin(
|
||||
"https://dav.example.test/root",
|
||||
"http://dav.example.test/calendar/"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.2",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.2",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||
@@ -25,6 +25,7 @@
|
||||
"android:sync": "npm run build:android-web && cap sync android",
|
||||
"android:open": "npm run android:sync && cap open android",
|
||||
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
|
||||
"android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs",
|
||||
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -13,15 +13,15 @@ const result = spawnSync(gradleWrapper, ['assembleDebug'], {
|
||||
if (result.error) {
|
||||
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
|
||||
process.exitCode = 1;
|
||||
} else if (result.status) {
|
||||
process.exitCode = result.status;
|
||||
} else if (result.status !== 0) {
|
||||
process.exitCode = result.status || 1;
|
||||
} else {
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const { version } = require(path.join(root, 'package.json'));
|
||||
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk');
|
||||
const releaseDir = path.join(root, 'release');
|
||||
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
|
||||
const target = path.join(releaseDir, `ep-mail ${version}-debug.apk`);
|
||||
fs.mkdirSync(releaseDir, { recursive: true });
|
||||
fs.copyFileSync(apk, target);
|
||||
console.log(`APK copied to ${target}`);
|
||||
console.log(`Debug APK copied to ${target}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const path = require('node:path');
|
||||
const fs = require('node:fs');
|
||||
|
||||
const requiredSigningVariables = [
|
||||
'EP_MAIL_ANDROID_STORE_FILE',
|
||||
'EP_MAIL_ANDROID_STORE_PASSWORD',
|
||||
'EP_MAIL_ANDROID_KEY_ALIAS',
|
||||
'EP_MAIL_ANDROID_KEY_PASSWORD'
|
||||
];
|
||||
const missing = requiredSigningVariables.filter(name => !process.env[name]);
|
||||
if (missing.length) {
|
||||
console.error(`Signed Android release requires these environment variables: ${missing.join(', ')}`);
|
||||
process.exitCode = 1;
|
||||
} else if (!path.isAbsolute(process.env.EP_MAIL_ANDROID_STORE_FILE)) {
|
||||
console.error('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.');
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
const androidDir = path.resolve(__dirname, '..', 'android');
|
||||
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
|
||||
const result = spawnSync(gradleWrapper, ['assembleRelease'], {
|
||||
cwd: androidDir,
|
||||
stdio: 'inherit',
|
||||
shell: process.platform === 'win32'
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
|
||||
process.exitCode = 1;
|
||||
} else if (result.status !== 0) {
|
||||
process.exitCode = result.status || 1;
|
||||
} else {
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const { version } = require(path.join(root, 'package.json'));
|
||||
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'release', 'app-release.apk');
|
||||
const releaseDir = path.join(root, 'release');
|
||||
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
|
||||
if (!fs.existsSync(apk)) {
|
||||
console.error(`Gradle did not produce the expected release APK: ${apk}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
fs.mkdirSync(releaseDir, { recursive: true });
|
||||
fs.copyFileSync(apk, target);
|
||||
console.log(`Signed release APK copied to ${target}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'),
|
||||
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
|
||||
const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
|
||||
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
||||
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
|
||||
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
|
||||
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
||||
|
||||
test('package metadata and lockfile share one release version', () => {
|
||||
@@ -32,3 +34,14 @@ test('release scripts and desktop artifact labels use package.json version', ()
|
||||
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
||||
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
||||
});
|
||||
|
||||
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
|
||||
assert.match(androidDebugScript, /assembleDebug/);
|
||||
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
|
||||
assert.match(androidReleaseScript, /assembleRelease/);
|
||||
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_FILE/);
|
||||
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_PASSWORD/);
|
||||
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_ALIAS/);
|
||||
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
|
||||
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user