|
| 1 | +/* |
| 2 | + * Copyright 2026 Morphe. |
| 3 | + * https://github.com/MorpheApp/morphe-cli |
| 4 | + */ |
| 5 | + |
| 6 | +package app.morphe.engine.util |
| 7 | + |
| 8 | +import app.morphe.engine.PatchEngine |
| 9 | +import app.morphe.patcher.apk.ApkUtils |
| 10 | +import java.util.logging.Logger |
| 11 | + |
| 12 | +/** |
| 13 | + * Signs an APK with [primary] credentials, falling back to the legacy ("Morphe Key" / empty password) entry. |
| 14 | + * The legacy retry only fires when [allowLegacyFallback] is true AND the keystore file already exists, |
| 15 | + * i.e. the user is on default credentials and we're reading a pre-existing keystore that might predate the current alias. |
| 16 | + * This preserves the exact condition both call sites (CLI + engine) used before. |
| 17 | + * |
| 18 | + * On double failure the PRIMARY exception is thrown (legacy attached as suppressed). |
| 19 | + * The primary error is the meaningful one: the user expects the current Morphe key, |
| 20 | + * so "no 'Morphe' entry" is more actionable than whatever the legacy retry hit. |
| 21 | + * The old behavior threw the *legacy* failure, which surfaced confusing errors. |
| 22 | + * |
| 23 | + * [sign] performs the actual signing; callers wrap this call with their own progress / step-result reporting. |
| 24 | + */ |
| 25 | +fun signWithLegacyFallback( |
| 26 | + primary: ApkUtils.KeyStoreDetails, |
| 27 | + allowLegacyFallback: Boolean, |
| 28 | + logger: Logger, |
| 29 | + sign: (ApkUtils.KeyStoreDetails) -> Unit, |
| 30 | +) { |
| 31 | + try { |
| 32 | + sign(primary) |
| 33 | + } catch (primaryError: Exception) { |
| 34 | + if (!allowLegacyFallback || !primary.keyStore.exists()) throw primaryError |
| 35 | + |
| 36 | + // Never silently swallow the real cause. Always log it before the back-compat path. |
| 37 | + logger.info( |
| 38 | + "Default keystore credentials failed (${primaryError.message}). Retrying with legacy credentials" |
| 39 | + ) |
| 40 | + |
| 41 | + val legacy = ApkUtils.KeyStoreDetails( |
| 42 | + primary.keyStore, |
| 43 | + primary.keyStorePassword, |
| 44 | + PatchEngine.Config.LEGACY_KEYSTORE_ALIAS, |
| 45 | + PatchEngine.Config.LEGACY_KEYSTORE_PASSWORD, |
| 46 | + ) |
| 47 | + try { |
| 48 | + sign(legacy) |
| 49 | + } catch (legacyError: Exception) { |
| 50 | + primaryError.addSuppressed(legacyError) |
| 51 | + throw primaryError |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments