diff --git a/LICENSE b/LICENSE
index f63ae77..a2b880d 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,201 +1,416 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for describing the origin of the Work and
- reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may accept and charge a
- fee for, acceptance of support, warranty, indemnity, or other
- liability obligations and/or rights consistent with this License.
- However, in accepting such obligations, You may act only on Your
- own behalf and on Your sole responsibility, not on behalf of any
- other Contributor, and only if You agree to indemnify, defend,
- and hold each Contributor harmless for any liability incurred by,
- or claims asserted against, such Contributor by reason of your
- accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2026 Joseph James (iamjosephmj)
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied. See the License for the specific language governing
- permissions and limitations under the License.
+DeviceIntelligence — Copyright (c) 2026 Joseph James (github.com/iamjosephmj)
+
+Licensed under the Creative Commons Attribution-NoDerivatives 4.0
+International License (CC BY-ND 4.0).
+
+You are FREE to:
+ - Use it for ANY purpose, including COMMERCIALLY.
+ - Share — copy and redistribute VERBATIM copies in any medium or format.
+
+Under the following terms:
+ - Attribution — you must give appropriate credit.
+ - NoDerivatives — if you remix, transform, or build upon the material, you
+ may NOT distribute the modified material.
+
+You may fork and modify DeviceIntelligence for your own use and to submit contributions
+back upstream; you may NOT publish or distribute modified versions.
+
+Human-readable summary: https://creativecommons.org/licenses/by-nd/4.0/
+Full legal code (also reproduced below):
+ https://creativecommons.org/licenses/by-nd/4.0/legalcode
+
+=======================================================================
+
+Attribution-NoDerivatives 4.0 International
+
+=======================================================================
+
+Creative Commons Corporation ("Creative Commons") is not a law firm and
+does not provide legal services or legal advice. Distribution of
+Creative Commons public licenses does not create a lawyer-client or
+other relationship. Creative Commons makes its licenses and related
+information available on an "as-is" basis. Creative Commons gives no
+warranties regarding its licenses, any material licensed under their
+terms and conditions, or any related information. Creative Commons
+disclaims all liability for damages resulting from their use to the
+fullest extent possible.
+
+Using Creative Commons Public Licenses
+
+Creative Commons public licenses provide a standard set of terms and
+conditions that creators and other rights holders may use to share
+original works of authorship and other material subject to copyright
+and certain other rights specified in the public license below. The
+following considerations are for informational purposes only, are not
+exhaustive, and do not form part of our licenses.
+
+ Considerations for licensors: Our public licenses are
+ intended for use by those authorized to give the public
+ permission to use material in ways otherwise restricted by
+ copyright and certain other rights. Our licenses are
+ irrevocable. Licensors should read and understand the terms
+ and conditions of the license they choose before applying it.
+ Licensors should also secure all rights necessary before
+ applying our licenses so that the public can reuse the
+ material as expected. Licensors should clearly mark any
+ material not subject to the license. This includes other CC-
+ licensed material, or material used under an exception or
+ limitation to copyright. More considerations for licensors:
+ wiki.creativecommons.org/Considerations_for_licensors
+
+ Considerations for the public: By using one of our public
+ licenses, a licensor grants the public permission to use the
+ licensed material under specified terms and conditions. If
+ the licensor's permission is not necessary for any reason--for
+ example, because of any applicable exception or limitation to
+ copyright--then that use is not regulated by the license. Our
+ licenses grant only permissions under copyright and certain
+ other rights that a licensor has authority to grant. Use of
+ the licensed material may still be restricted for other
+ reasons, including because others have copyright or other
+ rights in the material. A licensor may make special requests,
+ such as asking that all changes be marked or described.
+ Although not required by our licenses, you are encouraged to
+ respect those requests where reasonable. More considerations
+ for the public:
+ wiki.creativecommons.org/Considerations_for_licensees
+
+
+=======================================================================
+
+Creative Commons Attribution-NoDerivatives 4.0 International Public
+License
+
+By exercising the Licensed Rights (defined below), You accept and agree
+to be bound by the terms and conditions of this Creative Commons
+Attribution-NoDerivatives 4.0 International Public License ("Public
+License"). To the extent this Public License may be interpreted as a
+contract, You are granted the Licensed Rights in consideration of Your
+acceptance of these terms and conditions, and the Licensor grants You
+such rights in consideration of benefits the Licensor receives from
+making the Licensed Material available under these terms and
+conditions.
+
+
+Section 1 -- Definitions.
+
+ a. Adapted Material means material subject to Copyright and Similar
+ Rights that is derived from or based upon the Licensed Material
+ and in which the Licensed Material is translated, altered,
+ arranged, transformed, or otherwise modified in a manner requiring
+ permission under the Copyright and Similar Rights held by the
+ Licensor. For purposes of this Public License, where the Licensed
+ Material is a musical work, performance, or sound recording,
+ Adapted Material is always produced where the Licensed Material is
+ synched in timed relation with a moving image.
+
+ b. Copyright and Similar Rights means copyright and/or similar rights
+ closely related to copyright including, without limitation,
+ performance, broadcast, sound recording, and Sui Generis Database
+ Rights, without regard to how the rights are labeled or
+ categorized. For purposes of this Public License, the rights
+ specified in Section 2(b)(1)-(2) are not Copyright and Similar
+ Rights.
+
+ c. Effective Technological Measures means those measures that, in the
+ absence of proper authority, may not be circumvented under laws
+ fulfilling obligations under Article 11 of the WIPO Copyright
+ Treaty adopted on December 20, 1996, and/or similar international
+ agreements.
+
+ d. Exceptions and Limitations means fair use, fair dealing, and/or
+ any other exception or limitation to Copyright and Similar Rights
+ that applies to Your use of the Licensed Material.
+
+ e. Licensed Material means the artistic or literary work, database,
+ or other material to which the Licensor applied this Public
+ License.
+
+ f. Licensed Rights means the rights granted to You subject to the
+ terms and conditions of this Public License, which are limited to
+ all Copyright and Similar Rights that apply to Your use of the
+ Licensed Material and that the Licensor has authority to license.
+
+ g. Licensor means the individual(s) or entity(ies) granting rights
+ under this Public License.
+
+ h. Share means to provide material to the public by any means or
+ process that requires permission under the Licensed Rights, such
+ as reproduction, public display, public performance, distribution,
+ dissemination, communication, or importation, and to make material
+ available to the public including in ways that members of the
+ public may access the material from a place and at a time
+ individually chosen by them.
+
+ i. Sui Generis Database Rights means rights other than copyright
+ resulting from Directive 96/9/EC of the European Parliament and of
+ the Council of 11 March 1996 on the legal protection of databases,
+ as amended and/or succeeded, as well as other essentially
+ equivalent rights anywhere in the world.
+
+ j. You means the individual or entity exercising the Licensed Rights
+ under this Public License. Your has a corresponding meaning.
+
+
+Section 2 -- Scope.
+
+ a. License grant.
+
+ 1. Subject to the terms and conditions of this Public License,
+ the Licensor hereby grants You a worldwide, royalty-free,
+ non-sublicensable, non-exclusive, irrevocable license to
+ exercise the Licensed Rights in the Licensed Material to:
+
+ a. reproduce and Share the Licensed Material, in whole or
+ in part; and
+
+ b. produce and reproduce, but not Share, Adapted Material.
+
+ 2. Exceptions and Limitations. For the avoidance of doubt, where
+ Exceptions and Limitations apply to Your use, this Public
+ License does not apply, and You do not need to comply with
+ its terms and conditions.
+
+ 3. Term. The term of this Public License is specified in Section
+ 6(a).
+
+ 4. Media and formats; technical modifications allowed. The
+ Licensor authorizes You to exercise the Licensed Rights in
+ all media and formats whether now known or hereafter created,
+ and to make technical modifications necessary to do so. The
+ Licensor waives and/or agrees not to assert any right or
+ authority to forbid You from making technical modifications
+ necessary to exercise the Licensed Rights, including
+ technical modifications necessary to circumvent Effective
+ Technological Measures. For purposes of this Public License,
+ simply making modifications authorized by this Section 2(a)
+ (4) never produces Adapted Material.
+
+ 5. Downstream recipients.
+
+ a. Offer from the Licensor -- Licensed Material. Every
+ recipient of the Licensed Material automatically
+ receives an offer from the Licensor to exercise the
+ Licensed Rights under the terms and conditions of this
+ Public License.
+
+ b. No downstream restrictions. You may not offer or impose
+ any additional or different terms or conditions on, or
+ apply any Effective Technological Measures to, the
+ Licensed Material if doing so restricts exercise of the
+ Licensed Rights by any recipient of the Licensed
+ Material.
+
+ 6. No endorsement. Nothing in this Public License constitutes or
+ may be construed as permission to assert or imply that You
+ are, or that Your use of the Licensed Material is, connected
+ with, or sponsored, endorsed, or granted official status by,
+ the Licensor or others designated to receive attribution as
+ provided in Section 3(a)(1)(A)(i).
+
+ b. Other rights.
+
+ 1. Moral rights, such as the right of integrity, are not
+ licensed under this Public License, nor are publicity,
+ privacy, and/or other similar personality rights; however, to
+ the extent possible, the Licensor waives and/or agrees not to
+ assert any such rights held by the Licensor to the limited
+ extent necessary to allow You to exercise the Licensed
+ Rights, but not otherwise.
+
+ 2. Patent and trademark rights are not licensed under this
+ Public License.
+
+ 3. To the extent possible, the Licensor waives any right to
+ collect royalties from You for the exercise of the Licensed
+ Rights, whether directly or through a collecting society
+ under any voluntary or waivable statutory or compulsory
+ licensing scheme. In all other cases the Licensor expressly
+ reserves any right to collect such royalties.
+
+
+Section 3 -- License Conditions.
+
+Your exercise of the Licensed Rights is expressly made subject to the
+following conditions.
+
+ a. Attribution.
+
+ 1. If You Share the Licensed Material, You must:
+
+ a. retain the following if it is supplied by the Licensor
+ with the Licensed Material:
+
+ i. identification of the creator(s) of the Licensed
+ Material and any others designated to receive
+ attribution, in any reasonable manner requested by
+ the Licensor (including by pseudonym if
+ designated);
+
+ ii. a copyright notice;
+
+ iii. a notice that refers to this Public License;
+
+ iv. a notice that refers to the disclaimer of
+ warranties;
+
+ v. a URI or hyperlink to the Licensed Material to the
+ extent reasonably practicable;
+
+ b. indicate if You modified the Licensed Material and
+ retain an indication of any previous modifications; and
+
+ c. indicate the Licensed Material is licensed under this
+ Public License, and include the text of, or the URI or
+ hyperlink to, this Public License.
+
+ For the avoidance of doubt, You do not have permission under
+ this Public License to Share Adapted Material.
+
+ 2. You may satisfy the conditions in Section 3(a)(1) in any
+ reasonable manner based on the medium, means, and context in
+ which You Share the Licensed Material. For example, it may be
+ reasonable to satisfy the conditions by providing a URI or
+ hyperlink to a resource that includes the required
+ information.
+
+ 3. If requested by the Licensor, You must remove any of the
+ information required by Section 3(a)(1)(A) to the extent
+ reasonably practicable.
+
+
+Section 4 -- Sui Generis Database Rights.
+
+Where the Licensed Rights include Sui Generis Database Rights that
+apply to Your use of the Licensed Material:
+
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right
+ to extract, reuse, reproduce, and Share all or a substantial
+ portion of the contents of the database, provided You do not Share
+ Adapted Material;
+
+ b. if You include all or a substantial portion of the database
+ contents in a database in which You have Sui Generis Database
+ Rights, then the database in which You have Sui Generis Database
+ Rights (but not its individual contents) is Adapted Material; and
+
+ c. You must comply with the conditions in Section 3(a) if You Share
+ all or a substantial portion of the contents of the database.
+
+For the avoidance of doubt, this Section 4 supplements and does not
+replace Your obligations under this Public License where the Licensed
+Rights include other Copyright and Similar Rights.
+
+
+Section 5 -- Disclaimer of Warranties and Limitation of Liability.
+
+ a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
+ EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
+ AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
+ ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
+ IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
+ WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
+ PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
+ ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
+ KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
+ ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
+
+ b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
+ TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
+ NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
+ INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
+ COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
+ USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
+ ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
+ DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
+ IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
+
+ c. The disclaimer of warranties and limitation of liability provided
+ above shall be interpreted in a manner that, to the extent
+ possible, most closely approximates an absolute disclaimer and
+ waiver of all liability.
+
+
+Section 6 -- Term and Termination.
+
+ a. This Public License applies for the term of the Copyright and
+ Similar Rights licensed here. However, if You fail to comply with
+ this Public License, then Your rights under this Public License
+ terminate automatically.
+
+ b. Where Your right to use the Licensed Material has terminated under
+ Section 6(a), it reinstates:
+
+ 1. automatically as of the date the violation is cured, provided
+ it is cured within 30 days of Your discovery of the
+ violation; or
+
+ 2. upon express reinstatement by the Licensor.
+
+ For the avoidance of doubt, this Section 6(b) does not affect any
+ right the Licensor may have to seek remedies for Your violations
+ of this Public License.
+
+ c. For the avoidance of doubt, the Licensor may also offer the
+ Licensed Material under separate terms or conditions or stop
+ distributing the Licensed Material at any time; however, doing so
+ will not terminate this Public License.
+
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
+ License.
+
+
+Section 7 -- Other Terms and Conditions.
+
+ a. The Licensor shall not be bound by any additional or different
+ terms or conditions communicated by You unless expressly agreed.
+
+ b. Any arrangements, understandings, or agreements regarding the
+ Licensed Material not stated herein are separate from and
+ independent of the terms and conditions of this Public License.
+
+
+Section 8 -- Interpretation.
+
+ a. For the avoidance of doubt, this Public License does not, and
+ shall not be interpreted to, reduce, limit, restrict, or impose
+ conditions on any use of the Licensed Material that could lawfully
+ be made without permission under this Public License.
+
+ b. To the extent possible, if any provision of this Public License is
+ deemed unenforceable, it shall be automatically reformed to the
+ minimum extent necessary to make it enforceable. If the provision
+ cannot be reformed, it shall be severed from this Public License
+ without affecting the enforceability of the remaining terms and
+ conditions.
+
+ c. No term or condition of this Public License will be waived and no
+ failure to comply consented to unless expressly agreed to by the
+ Licensor.
+
+ d. Nothing in this Public License constitutes or may be interpreted
+ as a limitation upon, or waiver of, any privileges and immunities
+ that apply to the Licensor or You, including from the legal
+ processes of any jurisdiction or authority.
+
+=======================================================================
+
+Creative Commons is not a party to its public
+licenses. Notwithstanding, Creative Commons may elect to apply one of
+its public licenses to material it publishes and in those instances
+will be considered the “Licensor.” The text of the Creative Commons
+public licenses is dedicated to the public domain under the CC0 Public
+Domain Dedication. Except for the limited purpose of indicating that
+material is shared under a Creative Commons public license or as
+otherwise permitted by the Creative Commons policies published at
+creativecommons.org/policies, Creative Commons does not authorize the
+use of the trademark "Creative Commons" or any other trademark or logo
+of Creative Commons without its prior written consent including,
+without limitation, in connection with any unauthorized modifications
+to any of its public licenses or any other arrangements,
+understandings, or agreements concerning use of licensed material. For
+the avoidance of doubt, this paragraph does not form part of the
+public licenses.
+
+Creative Commons may be contacted at creativecommons.org.
+
diff --git a/README.md b/README.md
index 5f68c41..c34700e 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
-
+
@@ -190,4 +190,5 @@ The SDK makes **zero network calls** and reads no GAID, `ANDROID_ID`, IMEI/IMSI,
## License
-Apache 2.0 — see [`LICENSE`](LICENSE).
+**Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)** — see [`LICENSE`](LICENSE).
+Commercial use and verbatim redistribution are permitted with attribution; redistributing **modified** copies is not (a source-available, not OSI-approved, license).
diff --git a/deviceintelligence-gradle/build.gradle.kts b/deviceintelligence-gradle/build.gradle.kts
index 59a0caa..bd5dbc9 100644
--- a/deviceintelligence-gradle/build.gradle.kts
+++ b/deviceintelligence-gradle/build.gradle.kts
@@ -51,6 +51,13 @@ dependencies {
// without shelling out to `apksigner`. This is the same library that
// AGP itself uses internally.
implementation("com.android.tools.build:apksig:8.13.2")
+
+ // JUnit 5 for plugin unit tests
+ testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
+}
+
+tasks.named("test") {
+ useJUnitPlatform()
}
gradlePlugin {
@@ -129,8 +136,8 @@ afterEvaluate {
url.set("https://github.com/iamjosephmj/DeviceIntelligence")
licenses {
license {
- name.set("The Apache License, Version 2.0")
- url.set("https://www.apache.org/licenses/LICENSE-2.0.txt")
+ name.set("Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)")
+ url.set("https://creativecommons.org/licenses/by-nd/4.0/legalcode")
distribution.set("repo")
}
}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt
new file mode 100644
index 0000000..33321d1
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt
@@ -0,0 +1,34 @@
+package io.ssemaj.deviceintelligence.gradle
+
+import org.gradle.api.provider.Property
+import org.gradle.api.provider.SetProperty
+
+/**
+ * Opt-in App Bundle integrity ("bundle mode").
+ *
+ * When [enabled], the plugin bakes a bundle-mode fingerprint (decompressed
+ * dex/`.so` hashes + signer pins) into the AAB's base assets and re-signs the
+ * AAB, instead of instrumenting the APK. The runtime then hashes those entries'
+ * decompressed bodies across `sourceDir ∪ splitSourceDirs` and checks the
+ * installed signer is a member of the baked allow-set.
+ *
+ * APK mode and bundle mode are mutually exclusive per variant.
+ */
+abstract class AppBundleOptions {
+ /** Enable bundle mode for AAB builds. Default `false`. */
+ abstract val enabled: Property
+
+ /**
+ * Play App Signing certificate SHA-256(s) to include in the signer
+ * allow-set, normalized to lowercase hex with `:` separators stripped.
+ * Under Play App Signing, Google re-signs delivered APKs with the app
+ * signing key, so the runtime must accept that signer in addition to the
+ * upload key. Empty = only the upload-key cert is in the allow-set.
+ */
+ abstract val playSigningCertSha256: SetProperty
+
+ /** DSL sugar: `appBundle { playSigningCertSha256("AB:CD:...") }`. */
+ fun playSigningCertSha256(vararg hex: String) {
+ for (h in hex) playSigningCertSha256.add(h.replace(":", "").lowercase())
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt
index 0224d7c..1d71ce7 100644
--- a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt
@@ -1,7 +1,9 @@
package io.ssemaj.deviceintelligence.gradle
+import org.gradle.api.Action
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
+import org.gradle.api.tasks.Nested
/**
* Consumer-facing DSL block. Real options (reaction policy, detector set,
@@ -81,4 +83,15 @@ abstract class DeviceIntelligenceExtension {
* `-Pdeviceintelligence.disableAutoRuntimeDependency=true`.
*/
abstract val disableAutoRuntimeDependency: Property
+
+ /**
+ * Opt-in App Bundle integrity ("bundle mode"). When `appBundle.enabled`
+ * is `true`, the plugin bakes a bundle-mode fingerprint into the AAB and
+ * re-signs it instead of instrumenting the APK.
+ */
+ @get:Nested
+ abstract val appBundle: AppBundleOptions
+
+ /** DSL sugar: `deviceIntelligence { appBundle { enabled = true } }`. */
+ fun appBundle(action: Action) = action.execute(appBundle)
}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt
index ab7c191..2544967 100644
--- a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt
@@ -7,6 +7,7 @@ import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import io.ssemaj.deviceintelligence.gradle.internal.PluginCoordinates
import io.ssemaj.deviceintelligence.gradle.tasks.BakeFingerprintTask
+import io.ssemaj.deviceintelligence.gradle.tasks.BundleIntegrityTask
import io.ssemaj.deviceintelligence.gradle.tasks.ComputeFingerprintTask
import io.ssemaj.deviceintelligence.gradle.tasks.GenerateKeyChunksTask
import io.ssemaj.deviceintelligence.gradle.tasks.GenerateOptionalManifestTask
@@ -40,6 +41,8 @@ class DeviceIntelligencePlugin : Plugin {
enableVpnDetection.convention(false)
enableBiometricsDetection.convention(false)
disableAutoRuntimeDependency.convention(false)
+ appBundle.enabled.convention(false)
+ appBundle.playSigningCertSha256.convention(emptySet())
}
// Auto-apply the matching runtime AAR. Eager registration (not
@@ -181,9 +184,6 @@ class DeviceIntelligencePlugin : Plugin {
val variantTitle = variant.name.replaceFirstChar { it.uppercase() }
val genKeyTaskName = "generate${variantTitle}DeviceIntelligenceKeyChunks"
- val computeTaskName = "compute${variantTitle}DeviceIntelligenceFingerprint"
- val bakeTaskName = "bake${variantTitle}DeviceIntelligenceFingerprint"
- val instrumentTaskName = "instrument${variantTitle}DeviceIntelligenceApk"
val intermediatesDir = project.layout.buildDirectory
.dir("intermediates/io.ssemaj/${variant.name}")
@@ -193,6 +193,8 @@ class DeviceIntelligencePlugin : Plugin {
// 1) Codegen task — runs FIRST, no deps. Produces:
// - key.bin (build-private 32B key)
// - KeyChunkN.kt + KeyAssembler.kt (consumed by kotlin compile)
+ // Registered here (before the bundle-mode gate) so BOTH the
+ // bundle branch and the APK branch can reference it.
val genKeyTask = project.tasks.register(genKeyTaskName) {
group = "io.ssemaj"
description = "Generates the per-build XOR key + KeyChunkN/KeyAssembler codegen for variant '${variant.name}'."
@@ -230,6 +232,55 @@ class DeviceIntelligencePlugin : Plugin {
dependsOn(genKeyTask)
}
+ // App Bundle mode and APK instrumentation are mutually exclusive.
+ // When bundle mode is enabled, register BundleIntegrityTask on
+ // SingleArtifact.BUNDLE and skip the APK transform for this variant.
+ val bundleModeEnabled = ext.appBundle.enabled.getOrElse(false)
+ if (bundleModeEnabled) {
+ project.logger.lifecycle(
+ "io.ssemaj: appBundle.enabled=true — APK integrity transform skipped " +
+ "for variant '${variant.name}'; bundle-mode integrity applies"
+ )
+ val bundleTask = project.tasks.register(
+ "bundle${variantTitle}DeviceIntelligenceIntegrity",
+ ) {
+ group = "io.ssemaj"
+ description = "Bakes bundle-mode fingerprint into the AAB and re-signs it " +
+ "(variant '${variant.name}')."
+
+ keyFile.set(genKeyTask.flatMap { it.keyFile })
+ keystoreFile.fileValue(cfgStoreFile)
+ keystorePassword.set(cfgStorePassword)
+ keyAlias.set(cfgKeyAlias)
+ if (cfgKeyPassword != null) keyPassword.set(cfgKeyPassword)
+ if (!cfgStoreType.isNullOrBlank()) keystoreType.set(cfgStoreType)
+ playSigningCertSha256.set(ext.appBundle.playSigningCertSha256)
+ variantName.set(variant.name)
+ applicationId.set(variant.applicationId)
+ pluginVersion.set(PLUGIN_VERSION)
+ }
+
+ variant.artifacts.use(bundleTask)
+ .wiredWithFiles(
+ BundleIntegrityTask::inputAab,
+ BundleIntegrityTask::outputAab,
+ )
+ .toTransform(SingleArtifact.BUNDLE)
+
+ project.afterEvaluate {
+ if (ext.verbose.getOrElse(false)) {
+ project.logger.lifecycle(
+ "io.ssemaj: registered ${bundleTask.name} (BUNDLE transform)"
+ )
+ }
+ }
+ return@onVariants // skip APK transform for this variant
+ }
+
+ val computeTaskName = "compute${variantTitle}DeviceIntelligenceFingerprint"
+ val bakeTaskName = "bake${variantTitle}DeviceIntelligenceFingerprint"
+ val instrumentTaskName = "instrument${variantTitle}DeviceIntelligenceApk"
+
// 2) Compute task — runs after package${Variant}; reads the signed
// APK (which by now contains classes.dex with KeyChunk classes)
// and emits fingerprint.json + fingerprint.cbo.
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt
new file mode 100644
index 0000000..2c80744
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt
@@ -0,0 +1,57 @@
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipFile
+
+/**
+ * Reads an Android App Bundle (`.aab`) and returns the SHA-256 of the
+ * DECOMPRESSED body of every `classes*.dex` and `.so` entry under `lib//`
+ * in the base module, keyed by the APK-relative path the runtime sees on-device:
+ *
+ * `base/dex/classes.dex` → `classes.dex`
+ * `base/lib/arm64-v8a/libdicore.so` → `lib/arm64-v8a/libdicore.so`
+ *
+ * We hash the decompressed bytes (not the compressed body, as APK mode does)
+ * because Play re-encodes split APKs during delivery — only the inflated
+ * payload is stable between build time and the installed device.
+ *
+ * Resources and the manifest are intentionally excluded: they are covered
+ * transitively by the signer pin, and Play rewrites `resources.pb` to binary
+ * `resources.arsc` so a byte hash would never match.
+ */
+internal object AabHasher {
+
+ fun bundleEntryHashes(aab: File): Map {
+ val out = LinkedHashMap()
+ ZipFile(aab).use { zf ->
+ val entries = zf.entries()
+ while (entries.hasMoreElements()) {
+ val e = entries.nextElement()
+ if (e.isDirectory) continue
+ val apkPath = when {
+ e.name.startsWith("base/dex/") && e.name.endsWith(".dex") ->
+ e.name.removePrefix("base/dex/") // classes.dex
+ e.name.startsWith("base/lib/") && e.name.endsWith(".so") ->
+ e.name.removePrefix("base/") // lib//.so
+ else -> null
+ } ?: continue
+
+ val md = MessageDigest.getInstance("SHA-256")
+ // ZipFile.getInputStream yields the DECOMPRESSED bytes regardless of
+ // the entry's compression method — this is what we want.
+ zf.getInputStream(e).use { ins ->
+ val buf = ByteArray(64 * 1024)
+ while (true) {
+ val n = ins.read(buf)
+ if (n < 0) break
+ md.update(buf, 0, n)
+ }
+ }
+ out[apkPath] = md.digest().joinToString("") { b -> "%02x".format(b) }
+ }
+ }
+ return out
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt
new file mode 100644
index 0000000..ebe29ba
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt
@@ -0,0 +1,49 @@
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import jdk.security.jarsigner.JarSigner
+import java.io.File
+import java.io.FileOutputStream
+import java.security.PrivateKey
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import java.util.zip.ZipFile
+
+/**
+ * JAR-signs (v1 / "JAR signing") a modified `.aab` so `bundletool validate`
+ * and Play accept it after the plugin injects the bundle-mode fingerprint asset.
+ *
+ * Uses the JDK's in-process [JarSigner] (module `jdk.jartool`). The input
+ * `.aab` must contain ONLY file entries — bundletool rejects directory entries.
+ * [BundleIntegrityTask] is responsible for emitting a clean repack;
+ * this signer copies entries through verbatim.
+ *
+ * Single-signer only (matching [InstrumentApkTask]).
+ */
+internal object AabSigner {
+
+ fun sign(aab: File, key: PrivateKey, certs: List) {
+ require(certs.isNotEmpty()) { "no signer certificates supplied for $aab" }
+ val certPath = CertificateFactory.getInstance("X.509").generateCertPath(certs)
+ val signer = JarSigner.Builder(key, certPath)
+ .digestAlgorithm("SHA-256")
+ .signerName("DI")
+ .build()
+
+ // JarSigner requires distinct input/output streams. Sign to a temp
+ // sibling then atomically replace the original.
+ val signed = File(aab.parentFile, "${aab.name}.signed")
+ try {
+ ZipFile(aab).use { zf ->
+ FileOutputStream(signed).use { out -> signer.sign(zf, out) }
+ }
+ if (!signed.renameTo(aab)) {
+ signed.copyTo(aab, overwrite = true)
+ signed.delete()
+ }
+ } catch (t: Throwable) {
+ signed.delete()
+ throw t
+ }
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt
index d1ee4dd..347344d 100644
--- a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt
@@ -52,15 +52,25 @@ internal data class Fingerprint(
* pre-load `.so` replacement (Component 3 / Vector G2).
*/
val dicoreTextSha256ByAbi: Map = emptyMap(),
+ /** v3 — true when baked for an App Bundle build (split-aware, decompressed hashing). */
+ val bundleMode: Boolean = false,
+ /**
+ * v3 — APK-relative entry path -> SHA-256 hex of the entry's DECOMPRESSED body,
+ * for `classes*.dex` + `.so` files under `lib//`. Used only in bundle mode;
+ * `entries` is left empty in bundle mode because Play re-deflates, making
+ * compressed-byte hashes unstable.
+ */
+ val bundleEntryHashes: Map = emptyMap(),
) {
companion object {
/**
- * Bumped from 1 to 2 to add `nativeLibInventoryByAbi`,
- * `nativeLibHashesByAbi`, and `dicoreTextSha256ByAbi`. The
- * runtime decoder accepts both 1 and 2; v1 blobs simply
- * leave the new fields empty.
+ * Bumped from 1 to 2 to add `nativeLibInventoryByAbi`, `nativeLibHashesByAbi`,
+ * and `dicoreTextSha256ByAbi`.
+ * Bumped from 2 to 3 to add `bundleMode` and `bundleEntryHashes` for App Bundle
+ * integrity support. Runtime decoder accepts v1/v2/v3; older blobs leave the new
+ * fields at their defaults (bundleMode=false, bundleEntryHashes=emptyMap()).
*/
- const val SCHEMA_VERSION: Int = 2
+ const val SCHEMA_VERSION: Int = 3
const val ASSET_PATH: String = "assets/io.ssemaj.deviceintelligence/fingerprint.bin"
val DEFAULT_IGNORED_ENTRY_PREFIXES: List = listOf("META-INF/")
val DEFAULT_IGNORED_ENTRIES: List = listOf(ASSET_PATH)
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt
index e5c3704..5557a77 100644
--- a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt
@@ -2,6 +2,7 @@ package io.ssemaj.deviceintelligence.gradle.internal
import java.io.DataInputStream
import java.io.DataOutputStream
+import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
@@ -42,6 +43,11 @@ import java.io.OutputStream
* uint32 abiTextHashCount
* utf8 abi
* utf8 dicoreTextSha256Hex
+ * --- v3 additions below ---
+ * uint8 bundleMode (0/1)
+ * uint32 bundleEntryCount
+ * utf8 entryName [bundleEntryCount times, sorted]
+ * utf8 sha256Hex [bundleEntryCount times]
*
* The format is intentionally trivial: no length-prefixed envelopes, no CBOR
* tags, no varints. The runtime decoder mirrors this byte-for-byte using
@@ -63,7 +69,7 @@ internal object FingerprintCodec {
const val MAGIC: Int = 0x52615370 // 'DeviceIntelligence'
/** Newest wire format produced by the encoder. */
- const val FORMAT_VERSION: Int = 2
+ const val FORMAT_VERSION: Int = 3
/** Minimum wire format the decoder understands. */
const val MIN_SUPPORTED_FORMAT_VERSION: Int = 1
@@ -132,6 +138,15 @@ internal object FingerprintCodec {
writeUTF(fp.dicoreTextSha256ByAbi.getValue(abi))
}
+ // v3 tail — sorted by entry name for byte-deterministic output.
+ writeBoolean(fp.bundleMode)
+ val bundleKeys = fp.bundleEntryHashes.keys.sorted()
+ writeInt(bundleKeys.size)
+ for (k in bundleKeys) {
+ writeUTF(k)
+ writeUTF(fp.bundleEntryHashes.getValue(k))
+ }
+
flush()
}
}
@@ -190,6 +205,8 @@ internal object FingerprintCodec {
var inventoryByAbi: Map> = emptyMap()
var hashesByAbi: Map> = emptyMap()
var textHashByAbi: Map = emptyMap()
+ var bundleMode = false
+ var bundleEntryHashes: Map = emptyMap()
if (formatVersion >= 2) {
val invCount = readInt()
inventoryByAbi = LinkedHashMap>(invCount).apply {
@@ -227,6 +244,19 @@ internal object FingerprintCodec {
}
}
+ // v3 tail — absent on v1/v2 blobs; fields stay at their defaults.
+ if (formatVersion >= 3) {
+ bundleMode = readBoolean()
+ val bundleCount = readNonNegative(readInt(), "bundleEntryCount")
+ bundleEntryHashes = LinkedHashMap(bundleCount).apply {
+ repeat(bundleCount) {
+ val name = readUTF()
+ val sha = readUTF()
+ put(name, sha)
+ }
+ }
+ }
+
return Fingerprint(
schemaVersion = schemaVersion,
builtAtEpochMs = builtAtEpochMs,
@@ -242,7 +272,14 @@ internal object FingerprintCodec {
nativeLibInventoryByAbi = inventoryByAbi,
nativeLibHashesByAbi = hashesByAbi,
dicoreTextSha256ByAbi = textHashByAbi,
+ bundleMode = bundleMode,
+ bundleEntryHashes = bundleEntryHashes,
)
}
}
+
+ private fun readNonNegative(value: Int, field: String): Int {
+ if (value < 0) throw IOException("$field: negative count $value (corrupt blob)")
+ return value
+ }
}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt
new file mode 100644
index 0000000..b4cbeb5
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt
@@ -0,0 +1,77 @@
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import java.io.File
+import java.io.FileInputStream
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.security.PrivateKey
+import java.security.cert.X509Certificate
+
+/**
+ * Shared keystore-load helper shared between [InstrumentApkTask] and
+ * [BundleIntegrityTask]. Extracted here so both tasks load signing material
+ * identically without duplicating the PKCS12 / JKS fallback logic.
+ */
+internal object KeystoreSigning {
+
+ data class Material(
+ val privateKey: PrivateKey,
+ val certs: List,
+ val certHashes: List,
+ )
+
+ /**
+ * Load [Material] from [keystoreFile]. Tries [configuredType] first (if non-null),
+ * then PKCS12, then JKS. Throws [IllegalStateException] if none succeeds.
+ */
+ fun load(
+ keystoreFile: File,
+ configuredType: String?,
+ keystorePassword: String,
+ alias: String,
+ entryPassword: String?,
+ ): Material {
+ require(keystoreFile.isFile) { "keystore not found: $keystoreFile" }
+
+ val candidates = buildList {
+ if (!configuredType.isNullOrEmpty()) add(configuredType.uppercase())
+ add("PKCS12")
+ add("JKS")
+ }.distinct()
+
+ var ks: KeyStore? = null
+ var lastError: Throwable? = null
+ for (type in candidates) {
+ try {
+ val candidate = KeyStore.getInstance(type)
+ FileInputStream(keystoreFile).use { candidate.load(it, keystorePassword.toCharArray()) }
+ ks = candidate
+ break
+ } catch (e: Throwable) {
+ lastError = e
+ }
+ }
+ ks ?: throw IllegalStateException(
+ "Failed to load keystore $keystoreFile as any of $candidates",
+ lastError,
+ )
+
+ val pwd = (entryPassword ?: keystorePassword).toCharArray()
+ val privateKey = ks.getKey(alias, pwd) as? PrivateKey
+ ?: error("alias '$alias' has no PrivateKey entry in $keystoreFile")
+ val rawChain = ks.getCertificateChain(alias)
+ ?: ks.getCertificate(alias)?.let { arrayOf(it) }
+ ?: error("alias '$alias' has no certificate in $keystoreFile")
+ val certs = rawChain.map {
+ require(it is X509Certificate) { "non-X.509 cert in chain: ${it::class}" }
+ it
+ }
+ val md = MessageDigest.getInstance("SHA-256")
+ val certHashes = certs.map { cert ->
+ md.reset()
+ md.digest(cert.encoded).joinToString("") { b -> "%02x".format(b) }
+ }
+ return Material(privateKey, certs, certHashes)
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt
new file mode 100644
index 0000000..0ba9f94
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt
@@ -0,0 +1,104 @@
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.AabHasher
+import io.ssemaj.deviceintelligence.gradle.internal.Fingerprint
+import io.ssemaj.deviceintelligence.gradle.internal.FingerprintCodec
+import io.ssemaj.deviceintelligence.gradle.internal.NativeLibInventory
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.zip.ZipFile
+
+/**
+ * Pure builder for the bundle-mode fingerprint blob baked into an AAB's base
+ * assets. Kept free of AGP/Gradle types so it can be unit-tested directly.
+ *
+ * Encryption: `XOR(encode(fp), key)` — the same scheme APK mode uses
+ * ([InstrumentApkTask] reads `key.bin` from [GenerateKeyChunksTask] and XORs).
+ * At runtime [KeyResolver.assembleKey] returns the same key; [FingerprintDecoder]
+ * XOR-decrypts and passes to [FingerprintCodec.decode].
+ *
+ * DI divergence from RASP: RASP uses `DiBaker.fpKey(seed)` producing a
+ * `seed ‖ ciphertext` envelope. DI has no DiBaker — the caller passes `key`
+ * (the 32-byte `key.bin`) and the output is simply `XOR(cbo, key)`.
+ */
+internal object BundleFingerprintBuilder {
+
+ /**
+ * Build the encrypted bundle-mode fingerprint blob for [aab].
+ *
+ * @param aab The `.aab` file (AGP-built, before injection).
+ * @param key The 32-byte per-build XOR key from `GenerateKeyChunksTask.keyFile`.
+ * @param signerCertHashes SHA-256 hex hashes of the upload-key cert(s).
+ * @param playPins Play App Signing cert SHA-256(s) declared in `appBundle.playSigningCertSha256`.
+ * @param pluginVersion Plugin version string baked into the fingerprint.
+ * @param variant AGP variant name (e.g. `"release"`).
+ * @param appId Application ID.
+ * @return `XOR(FingerprintCodec.encode(fp), key)` as a byte array.
+ */
+ fun build(
+ aab: File,
+ key: ByteArray,
+ signerCertHashes: List,
+ playPins: Collection,
+ pluginVersion: String,
+ variant: String,
+ appId: String,
+ ): ByteArray {
+ require(key.size == 32) { "key must be 32 bytes, got ${key.size}" }
+ val bundleEntries = AabHasher.bundleEntryHashes(aab)
+ val nativeFp = NativeLibInventory.walkRawEntries(aabBaseLibEntries(aab))
+
+ // Membership allow-set: upload-key cert(s) ∪ Play App Signing pins, de-duped.
+ val signerAllowSet = (signerCertHashes + playPins).distinct()
+
+ val fp = Fingerprint(
+ schemaVersion = Fingerprint.SCHEMA_VERSION,
+ builtAtEpochMs = System.currentTimeMillis(),
+ pluginVersion = pluginVersion,
+ variantName = variant,
+ applicationId = appId,
+ signerCertSha256 = signerAllowSet,
+ // Bundle mode does not bake compressed-byte entry hashes — Play re-deflates.
+ entries = emptyMap(),
+ ignoredEntries = emptyList(),
+ ignoredEntryPrefixes = emptyList(),
+ expectedSourceDirPrefix = "/data/app/",
+ expectedInstallerWhitelist = emptyList(),
+ nativeLibInventoryByAbi = nativeFp.inventoryByAbi,
+ nativeLibHashesByAbi = nativeFp.fileHashesByAbi,
+ dicoreTextSha256ByAbi = nativeFp.dicoreTextSha256ByAbi,
+ bundleMode = true,
+ bundleEntryHashes = bundleEntries,
+ )
+
+ val cbo = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ return ByteArray(cbo.size).also { out ->
+ for (i in cbo.indices) {
+ out[i] = (cbo[i].toInt() xor key[i % key.size].toInt()).toByte()
+ }
+ }
+ }
+
+ /**
+ * Stream the AAB's `base/lib//.so` entries as
+ * `lib//.so` (APK-relative) path + decompressed body pairs,
+ * so [NativeLibInventory.walkRawEntries] computes the ELF `.text`
+ * baseline identically to APK mode.
+ */
+ private fun aabBaseLibEntries(aab: File): Sequence> {
+ val list = ArrayList>()
+ ZipFile(aab).use { zf ->
+ val it = zf.entries()
+ while (it.hasMoreElements()) {
+ val e = it.nextElement()
+ if (e.isDirectory) continue
+ if (!e.name.startsWith("base/lib/") || !e.name.endsWith(".so")) continue
+ val apkPath = e.name.removePrefix("base/") // lib//.so
+ val bytes = zf.getInputStream(e).use { s -> s.readBytes() }
+ list += apkPath to bytes
+ }
+ }
+ return list.asSequence()
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt
new file mode 100644
index 0000000..853f25e
--- /dev/null
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt
@@ -0,0 +1,171 @@
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.AabSigner
+import io.ssemaj.deviceintelligence.gradle.internal.KeystoreSigning
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.provider.SetProperty
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.InputFile
+import org.gradle.api.tasks.Optional
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+import java.io.File
+import java.util.zip.CRC32
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
+
+/**
+ * App Bundle ("bundle mode") integrity transform over [SingleArtifact.BUNDLE].
+ *
+ * AGP hands us the just-built, AGP-signed `.aab`; we:
+ * 1. Bake the v3 bundle-mode fingerprint blob (decompressed dex/`.so` hashes +
+ * signer allow-set) with [BundleFingerprintBuilder].
+ * 2. Repack the AAB with `base/assets/io.ssemaj.deviceintelligence/fingerprint.bin`
+ * injected as a STORED entry, stripping the old `META-INF/` signature and any
+ * pre-existing fingerprint. ONLY file entries are emitted — bundletool rejects
+ * directory entries in a re-packed AAB.
+ * 3. JAR-re-sign the result with [AabSigner].
+ *
+ * Encryption: `XOR(encode(fp), key)` using the per-build `key.bin` from
+ * [GenerateKeyChunksTask]. At runtime [FingerprintDecoder] decrypts with the
+ * same key recovered via [KeyResolver.assembleKey].
+ */
+abstract class BundleIntegrityTask : DefaultTask() {
+
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val inputAab: RegularFileProperty
+
+ @get:OutputFile
+ abstract val outputAab: RegularFileProperty
+
+ /** Per-build XOR key from [GenerateKeyChunksTask]. */
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val keyFile: RegularFileProperty
+
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val keystoreFile: RegularFileProperty
+
+ @get:Input
+ @get:Optional
+ abstract val keystoreType: Property
+
+ @get:Input
+ abstract val keystorePassword: Property
+
+ @get:Input
+ abstract val keyAlias: Property
+
+ @get:Input
+ @get:Optional
+ abstract val keyPassword: Property
+
+ /** Play App Signing cert SHA-256 pins to include in the signer allow-set. */
+ @get:Input
+ abstract val playSigningCertSha256: SetProperty
+
+ @get:Input
+ abstract val variantName: Property
+
+ @get:Input
+ abstract val applicationId: Property
+
+ @get:Input
+ abstract val pluginVersion: Property
+
+ @TaskAction
+ fun run() {
+ val key = keyFile.get().asFile.readBytes()
+ require(key.size == KEY_SIZE) {
+ "key.bin is wrong size: ${key.size}B (expected $KEY_SIZE)"
+ }
+
+ val signing = KeystoreSigning.load(
+ keystoreFile = keystoreFile.get().asFile,
+ configuredType = keystoreType.orNull,
+ keystorePassword = keystorePassword.get(),
+ alias = keyAlias.get(),
+ entryPassword = keyPassword.orNull,
+ )
+
+ val input = inputAab.get().asFile
+ val output = outputAab.get().asFile.apply { parentFile?.mkdirs() }
+
+ val blob = BundleFingerprintBuilder.build(
+ aab = input,
+ key = key,
+ signerCertHashes = signing.certHashes,
+ playPins = playSigningCertSha256.getOrElse(emptySet()),
+ pluginVersion = pluginVersion.get(),
+ variant = variantName.get(),
+ appId = applicationId.get(),
+ )
+ logger.lifecycle(
+ "io.ssemaj: bundle-mode fingerprint '${variantName.get()}': " +
+ "signerLeaf=${signing.certHashes.firstOrNull()}, " +
+ "playPins=${playSigningCertSha256.getOrElse(emptySet()).size}, " +
+ "bundleEntries=${blob.size}B"
+ )
+
+ injectAsset(input, output, BUNDLE_ASSET_PATH to blob)
+ AabSigner.sign(output, signing.privateKey, signing.certs)
+
+ logger.lifecycle(
+ "io.ssemaj: bundle-mode integrity → ${output.relativeTo(project.rootDir)} (asset injected, re-signed)"
+ )
+ }
+
+ /**
+ * Copies every file entry from [input] to [output], DROPPING `META-INF/`
+ * (old signature), any pre-existing fingerprint asset, and all directory
+ * entries (bundletool rejects them in a re-packed AAB); then appends
+ * [additional] as a STORED entry.
+ */
+ private fun injectAsset(input: File, output: File, additional: Pair) {
+ if (output.exists()) output.delete()
+ ZipFile(input).use { zf ->
+ ZipOutputStream(output.outputStream().buffered()).use { zos ->
+ val it = zf.entries()
+ while (it.hasMoreElements()) {
+ val e = it.nextElement()
+ if (e.isDirectory) continue
+ if (e.name.startsWith("META-INF/")) continue
+ if (e.name == additional.first) continue
+ val bytes = zf.getInputStream(e).use { s -> s.readBytes() }
+ val method = if (e.method == ZipEntry.STORED) ZipEntry.STORED else ZipEntry.DEFLATED
+ writeEntry(zos, e.name, bytes, method, e.time)
+ }
+ writeEntry(zos, additional.first, additional.second, ZipEntry.STORED, 0L)
+ }
+ }
+ }
+
+ private fun writeEntry(zos: ZipOutputStream, name: String, data: ByteArray, method: Int, time: Long) {
+ val entry = ZipEntry(name).apply {
+ this.method = method
+ this.time = time
+ if (method == ZipEntry.STORED) {
+ size = data.size.toLong()
+ compressedSize = data.size.toLong()
+ crc = CRC32().apply { update(data) }.value
+ }
+ }
+ zos.putNextEntry(entry)
+ zos.write(data)
+ zos.closeEntry()
+ }
+
+ private companion object {
+ /** Fingerprint asset path inside the AAB's base module. */
+ const val BUNDLE_ASSET_PATH = "base/assets/io.ssemaj.deviceintelligence/fingerprint.bin"
+ const val KEY_SIZE: Int = 32
+ }
+}
diff --git a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt
index 7045ab3..7fd94e0 100644
--- a/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt
+++ b/deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt
@@ -5,6 +5,7 @@ import com.android.build.api.artifact.ArtifactTransformationRequest
import io.ssemaj.deviceintelligence.gradle.internal.ApkHasher
import io.ssemaj.deviceintelligence.gradle.internal.Fingerprint
import io.ssemaj.deviceintelligence.gradle.internal.FingerprintCodec
+import io.ssemaj.deviceintelligence.gradle.internal.KeystoreSigning
import io.ssemaj.deviceintelligence.gradle.internal.NativeLibInventory
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
@@ -21,14 +22,9 @@ import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import java.io.ByteArrayOutputStream
import java.io.File
-import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FilterOutputStream
import java.io.OutputStream
-import java.security.KeyStore
-import java.security.MessageDigest
-import java.security.PrivateKey
-import java.security.cert.X509Certificate
import java.util.zip.CRC32
import java.util.zip.Deflater
import java.util.zip.ZipEntry
@@ -146,7 +142,7 @@ abstract class InstrumentApkTask : DefaultTask() {
"key.bin is the wrong size: ${key.size} (expected $KEY_SIZE)"
}
- val signing = loadSigningMaterial(
+ val signing = KeystoreSigning.load(
keystoreFile = keystoreFile.get().asFile,
configuredType = keystoreType.orNull,
keystorePassword = keystorePassword.get(),
@@ -170,7 +166,7 @@ abstract class InstrumentApkTask : DefaultTask() {
input: File,
output: File,
key: ByteArray,
- signing: SigningMaterial,
+ signing: KeystoreSigning.Material,
) {
// 1. Read input APK entries (decompressed) into memory. Strip META-INF/*
// (apksig will regenerate the v1 manifest+signatures during sign()),
@@ -426,77 +422,6 @@ abstract class InstrumentApkTask : DefaultTask() {
}
}
- // ---- Signing material -------------------------------------------------
-
- private data class SigningMaterial(
- val privateKey: PrivateKey,
- val certs: List,
- val certHashes: List,
- )
-
- private fun loadSigningMaterial(
- keystoreFile: File,
- configuredType: String?,
- keystorePassword: String,
- alias: String,
- entryPassword: String?,
- ): SigningMaterial {
- require(keystoreFile.isFile) { "keystore not found: $keystoreFile" }
-
- // Mirror CertHasher: try the configured type first, then PKCS12, then
- // JKS. Older debug keystores are JKS; newer ones default to PKCS12.
- val candidates = buildList {
- if (!configuredType.isNullOrEmpty()) add(configuredType.uppercase())
- add("PKCS12")
- add("JKS")
- }.distinct()
- var ks: KeyStore? = null
- var lastError: Throwable? = null
- for (type in candidates) {
- try {
- val candidate = KeyStore.getInstance(type)
- FileInputStream(keystoreFile).use {
- candidate.load(it, keystorePassword.toCharArray())
- }
- ks = candidate
- break
- } catch (e: Throwable) {
- lastError = e
- }
- }
- ks ?: throw IllegalStateException(
- "Failed to load keystore $keystoreFile as any of $candidates",
- lastError,
- )
-
- val pwd = (entryPassword ?: keystorePassword).toCharArray()
- val privateKey = ks.getKey(alias, pwd) as? PrivateKey
- ?: error("alias '$alias' has no PrivateKey entry in $keystoreFile")
- val rawChain = ks.getCertificateChain(alias)
- ?: ks.getCertificate(alias)?.let { arrayOf(it) }
- ?: error("alias '$alias' has no certificate in $keystoreFile")
- val certs = rawChain.map {
- require(it is X509Certificate) { "non-X.509 cert in chain: ${it::class}" }
- it
- }
- val md = MessageDigest.getInstance("SHA-256")
- val certHashes = certs.map { cert ->
- md.reset()
- md.digest(cert.encoded).toHex()
- }
- return SigningMaterial(privateKey, certs, certHashes)
- }
-
- private fun ByteArray.toHex(): String {
- val hex = "0123456789abcdef".toCharArray()
- val out = CharArray(size * 2)
- for (i in indices) {
- out[i * 2] = hex[(this[i].toInt() shr 4) and 0xF]
- out[i * 2 + 1] = hex[this[i].toInt() and 0xF]
- }
- return String(out)
- }
-
private companion object {
const val KEY_SIZE: Int = 32
const val META_INF_PREFIX: String = "META-INF/"
diff --git a/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt
new file mode 100644
index 0000000..cac5b8d
--- /dev/null
+++ b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt
@@ -0,0 +1,53 @@
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.io.TempDir
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class AabHasherTest {
+
+ @Test fun normalizesPathsAndHashesDecompressedBytes(@TempDir dir: File) {
+ val dex = "DEXBYTES_UNIQUE_CONTENT_12345".toByteArray()
+ val so = "SOBYTES_UNIQUE_CONTENT_67890".toByteArray()
+ val aab = File(dir, "app.aab")
+
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/dex/classes.dex")); z.write(dex); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/dex/classes2.dex")); z.write("C2".toByteArray()); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/lib/arm64-v8a/libdicore.so")); z.write(so); z.closeEntry()
+ // These must be excluded:
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("RESOURCES".toByteArray()); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/manifest/AndroidManifest.xml")); z.write("XML".toByteArray()); z.closeEntry()
+ }
+
+ val result = AabHasher.bundleEntryHashes(aab)
+
+ // Entry names use installed-APK keys, not bundle keys.
+ assertEquals(
+ setOf("classes.dex", "classes2.dex", "lib/arm64-v8a/libdicore.so"),
+ result.keys,
+ )
+ // Hash is the decompressed (inflated) SHA-256.
+ assertEquals(sha256Hex(dex), result["classes.dex"])
+ assertEquals(sha256Hex(so), result["lib/arm64-v8a/libdicore.so"])
+ // Resources and manifest are excluded.
+ assertFalse("base/resources.pb" in result.keys)
+ assertFalse("resources.pb" in result.keys)
+ }
+
+ @Test fun emptyAabProducesEmptyMap(@TempDir dir: File) {
+ val aab = File(dir, "empty.aab")
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("R".toByteArray()); z.closeEntry()
+ }
+ assertEquals(emptyMap(), AabHasher.bundleEntryHashes(aab))
+ }
+
+ private fun sha256Hex(b: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+}
diff --git a/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt
new file mode 100644
index 0000000..4f963fa
--- /dev/null
+++ b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt
@@ -0,0 +1,117 @@
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.DataOutputStream
+
+class FingerprintCodecTest {
+
+ /** A v3 bundle-mode fingerprint round-trips through encode → decode. */
+ @Test fun bundleModeRoundTrip() {
+ val fp = baseFingerprint().copy(
+ bundleMode = true,
+ bundleEntryHashes = mapOf(
+ "classes.dex" to "aabbccddeeff0011",
+ "lib/arm64-v8a/libdicore.so" to "00112233445566778899",
+ ),
+ )
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ assertEquals(true, back.bundleMode)
+ assertEquals(fp.bundleEntryHashes, back.bundleEntryHashes)
+ assertEquals(3, FingerprintCodec.FORMAT_VERSION)
+ }
+
+ /** A v3 APK-mode fingerprint (bundleMode=false) also round-trips. */
+ @Test fun apkModeRoundTripStillWorks() {
+ val fp = baseFingerprint() // bundleMode=false by default
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ assertEquals(false, back.bundleMode)
+ assertEquals(emptyMap(), back.bundleEntryHashes)
+ assertEquals("release", back.variantName)
+ }
+
+ /**
+ * A genuine raw v2 binary blob (no v3 tail) decodes with bundleMode=false
+ * and empty bundleEntryHashes. This proves the `if (formatVersion >= 3)`
+ * guard in the decoder correctly skips the v3 section for real v2 blobs.
+ */
+ @Test fun rawV2BlobDecodesWithNoBundleFields() {
+ val bytes = ByteArrayOutputStream().also { bos ->
+ DataOutputStream(bos).also { dos ->
+ dos.writeInt(FingerprintCodec.MAGIC) // magic
+ dos.writeInt(2) // formatVersion = 2 (no v3 tail)
+ dos.writeInt(Fingerprint.SCHEMA_VERSION) // schemaVersion
+ dos.writeLong(1_000_000L) // builtAtEpochMs
+ dos.writeUTF("5.0.0") // pluginVersion
+ dos.writeUTF("release") // variantName
+ dos.writeUTF("io.ssemaj.sample") // applicationId
+ // signerCerts
+ dos.writeInt(1)
+ dos.writeUTF("deadbeef01234567")
+ // entries (empty)
+ dos.writeInt(0)
+ // ignoredEntries (empty)
+ dos.writeInt(0)
+ // ignoredEntryPrefixes (empty)
+ dos.writeInt(0)
+ // expectedSourceDirPrefix
+ dos.writeUTF("/data/app/")
+ // installerWhitelist (empty)
+ dos.writeInt(0)
+ // v2 tail: abiInventoryCount, abiFileHashCount, abiTextHashCount (all empty)
+ dos.writeInt(0)
+ dos.writeInt(0)
+ dos.writeInt(0)
+ dos.flush()
+ }
+ }.toByteArray()
+
+ val decoded = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ assertEquals(false, decoded.bundleMode)
+ assertTrue(decoded.bundleEntryHashes.isEmpty())
+ assertEquals(Fingerprint.SCHEMA_VERSION, decoded.schemaVersion)
+ assertEquals("release", decoded.variantName)
+ }
+
+ /** bundleEntryHashes keys are sorted on encode; order is stable. */
+ @Test fun bundleEntryHashesSortedOnEncode() {
+ val fp = baseFingerprint().copy(
+ bundleMode = true,
+ bundleEntryHashes = mapOf(
+ "lib/arm64-v8a/libfoo.so" to "cc",
+ "classes.dex" to "aa",
+ "classes2.dex" to "bb",
+ ),
+ )
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ // Sorted order: classes.dex, classes2.dex, lib/arm64-v8a/libfoo.so
+ val keys = back.bundleEntryHashes.keys.toList()
+ assertEquals(listOf("classes.dex", "classes2.dex", "lib/arm64-v8a/libfoo.so"), keys)
+ }
+
+ private fun baseFingerprint() = Fingerprint(
+ schemaVersion = Fingerprint.SCHEMA_VERSION,
+ builtAtEpochMs = 1_000_000L,
+ pluginVersion = "5.0.0",
+ variantName = "release",
+ applicationId = "io.ssemaj.sample",
+ signerCertSha256 = listOf("deadbeef01234567"),
+ entries = mapOf("classes.dex" to "hash0"),
+ ignoredEntries = listOf("assets/io.ssemaj.deviceintelligence/fingerprint.bin"),
+ ignoredEntryPrefixes = listOf("META-INF/"),
+ expectedSourceDirPrefix = "/data/app/",
+ expectedInstallerWhitelist = emptyList(),
+ nativeLibInventoryByAbi = mapOf("arm64-v8a" to listOf("libdicore.so")),
+ dicoreTextSha256ByAbi = mapOf("arm64-v8a" to "texthash"),
+ )
+}
diff --git a/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt
new file mode 100644
index 0000000..72994f4
--- /dev/null
+++ b/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt
@@ -0,0 +1,56 @@
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.FingerprintCodec
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.io.TempDir
+import java.io.ByteArrayInputStream
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class BundleFingerprintBuilderTest {
+
+ @Test fun blobDecodesToBundleModeWithMergedSigners(@TempDir dir: File) {
+ val dex = "DEXBYTES".toByteArray()
+ val so = "SOBYTES".toByteArray()
+ val aab = File(dir, "app.aab")
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/dex/classes.dex")); z.write(dex); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/lib/arm64-v8a/libother.so")); z.write(so); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("R".toByteArray()); z.closeEntry()
+ }
+
+ val key = ByteArray(32) { it.toByte() } // deterministic test key
+
+ val blob = BundleFingerprintBuilder.build(
+ aab = aab,
+ key = key,
+ signerCertHashes = listOf("aa11"),
+ playPins = listOf("bb22", "aa11"), // overlap must be de-duplicated
+ pluginVersion = "5.0.0",
+ variant = "release",
+ appId = "io.ssemaj.sample",
+ )
+
+ // Decrypt: XOR with the same key.
+ val plain = ByteArray(blob.size) { i -> (blob[i].toInt() xor key[i % 32].toInt()).toByte() }
+ val fp = FingerprintCodec.decode(ByteArrayInputStream(plain))
+
+ assertTrue(fp.bundleMode)
+ assertEquals(sha256Hex(dex), fp.bundleEntryHashes["classes.dex"])
+ assertEquals(sha256Hex(so), fp.bundleEntryHashes["lib/arm64-v8a/libother.so"])
+ assertFalse("base/resources.pb" in fp.bundleEntryHashes.keys)
+ // De-duplicated merged signer allow-set.
+ assertEquals(setOf("aa11", "bb22"), fp.signerCertSha256.toSet())
+ assertEquals("io.ssemaj.sample", fp.applicationId)
+ // APK-mode entries is empty in bundle mode.
+ assertTrue(fp.entries.isEmpty())
+ }
+
+ private fun sha256Hex(b: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+}
diff --git a/deviceintelligence/build.gradle.kts b/deviceintelligence/build.gradle.kts
index c75f00a..0b9181a 100644
--- a/deviceintelligence/build.gradle.kts
+++ b/deviceintelligence/build.gradle.kts
@@ -230,8 +230,8 @@ afterEvaluate {
url.set("https://github.com/iamjosephmj/DeviceIntelligence")
licenses {
license {
- name.set("The Apache License, Version 2.0")
- url.set("https://www.apache.org/licenses/LICENSE-2.0.txt")
+ name.set("Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)")
+ url.set("https://creativecommons.org/licenses/by-nd/4.0/legalcode")
distribution.set("repo")
}
}
diff --git a/deviceintelligence/src/main/cpp/CMakeLists.txt b/deviceintelligence/src/main/cpp/CMakeLists.txt
index 4086d44..6a77ca9 100644
--- a/deviceintelligence/src/main/cpp/CMakeLists.txt
+++ b/deviceintelligence/src/main/cpp/CMakeLists.txt
@@ -63,10 +63,12 @@ endif()
find_library(log-lib log)
find_library(android-lib android)
+find_library(z-lib z)
target_link_libraries(dicore
${log-lib}
${android-lib}
+ ${z-lib}
dl
)
diff --git a/deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp b/deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp
index 72a6ec7..25b5fe4 100644
--- a/deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp
+++ b/deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp
@@ -1,4 +1,5 @@
#include "apkmap.h"
+#include "hex.h"
#include "log.h"
#include "sha256.h"
#include "sigblock_parser.h"
@@ -101,6 +102,42 @@ Java_io_ssemaj_deviceintelligence_internal_NativeBridge_apkSignerCertHashes(
return strings_to_jarray(env, certs.cert_sha256_hex);
}
+JNIEXPORT jstring JNICALL
+Java_io_ssemaj_deviceintelligence_internal_NativeBridge_apkEntryDecompressedHash(
+ JNIEnv* env, jclass, jstring jpath, jstring jentry) {
+ if (!jpath || !jentry) return nullptr;
+
+ const char* path = env->GetStringUTFChars(jpath, nullptr);
+ if (!path) return nullptr;
+ const char* entry = env->GetStringUTFChars(jentry, nullptr);
+ if (!entry) {
+ env->ReleaseStringUTFChars(jpath, path);
+ return nullptr;
+ }
+
+ ApkMap apk;
+ bool ok = apk.open(path);
+ env->ReleaseStringUTFChars(jpath, path);
+ if (!ok) {
+ RLOGE("apkEntryDecompressedHash: open failed for entry '%s'", entry);
+ env->ReleaseStringUTFChars(jentry, entry);
+ return nullptr;
+ }
+
+ zip::CentralDirInfo cdi;
+ if (!zip::find_central_directory(apk, &cdi)) {
+ env->ReleaseStringUTFChars(jentry, entry);
+ return nullptr;
+ }
+
+ uint8_t md[sha::kDigestLen];
+ bool found = zip::hash_entry_decompressed(apk, cdi, entry, md);
+ env->ReleaseStringUTFChars(jentry, entry);
+ if (!found) return nullptr;
+
+ return make_jstring(env, hex::encode(md, sha::kDigestLen));
+}
+
} // extern "C"
} // namespace dicore
diff --git a/deviceintelligence/src/main/cpp/dicore/sha256.cpp b/deviceintelligence/src/main/cpp/dicore/sha256.cpp
index 8c8f496..5a6653a 100644
--- a/deviceintelligence/src/main/cpp/dicore/sha256.cpp
+++ b/deviceintelligence/src/main/cpp/dicore/sha256.cpp
@@ -83,41 +83,84 @@ bool ensure_initialized() {
return true;
}
-bool sha256(const void* data, size_t len, uint8_t out[kDigestLen]) {
- uint32_t state[8];
- std::memcpy(state, H0, sizeof(H0));
+// ---------------------------------------------------------------------------
+// Incremental SHA-256 implementation
+// ---------------------------------------------------------------------------
+
+void sha256_init(Sha256Ctx* ctx) {
+ std::memcpy(ctx->state, H0, sizeof(H0));
+ ctx->total_bits = 0;
+ ctx->buf_len = 0;
+}
+void sha256_update(Sha256Ctx* ctx, const void* data, size_t len) {
const uint8_t* p = static_cast(data);
- size_t remaining = len;
+ ctx->total_bits += static_cast(len) * 8u;
+
+ // If there's a partial block buffered, top it up first.
+ if (ctx->buf_len > 0) {
+ size_t need = 64 - ctx->buf_len;
+ size_t take = (len < need) ? len : need;
+ std::memcpy(ctx->buf + ctx->buf_len, p, take);
+ ctx->buf_len += take;
+ p += take;
+ len -= take;
+ if (ctx->buf_len == 64) {
+ compress(ctx->state, ctx->buf);
+ ctx->buf_len = 0;
+ }
+ }
- while (remaining >= 64) {
- compress(state, p);
- p += 64;
- remaining -= 64;
+ // Process full blocks directly from the caller's buffer.
+ while (len >= 64) {
+ compress(ctx->state, p);
+ p += 64;
+ len -= 64;
}
+ // Buffer the remainder (0..63 bytes).
+ if (len > 0) {
+ std::memcpy(ctx->buf, p, len);
+ ctx->buf_len = len;
+ }
+}
+
+void sha256_final(Sha256Ctx* ctx, uint8_t out[kDigestLen]) {
+ // Build and compress the padding block(s).
uint8_t tail[128];
std::memset(tail, 0, sizeof(tail));
- if (remaining > 0) std::memcpy(tail, p, remaining);
- tail[remaining] = 0x80;
+ if (ctx->buf_len > 0) {
+ std::memcpy(tail, ctx->buf, ctx->buf_len);
+ }
+ tail[ctx->buf_len] = 0x80;
- // Trailing length is in bits, big-endian, in the last 8 bytes of the
- // padded message. Padded length is 64 if remaining < 56, else 128.
- size_t pad_end = (remaining < 56) ? 64 : 128;
- uint64_t bit_len = static_cast(len) * 8u;
+ size_t pad_end = (ctx->buf_len < 56) ? 64 : 128;
+ uint64_t bit_len = ctx->total_bits;
for (int i = 0; i < 8; ++i) {
tail[pad_end - 1 - i] = static_cast(bit_len >> (i * 8));
}
- compress(state, tail);
- if (pad_end == 128) compress(state, tail + 64);
+ compress(ctx->state, tail);
+ if (pad_end == 128) compress(ctx->state, tail + 64);
for (int i = 0; i < 8; ++i) {
- out[i * 4 + 0] = static_cast(state[i] >> 24);
- out[i * 4 + 1] = static_cast(state[i] >> 16);
- out[i * 4 + 2] = static_cast(state[i] >> 8);
- out[i * 4 + 3] = static_cast(state[i]);
+ out[i * 4 + 0] = static_cast(ctx->state[i] >> 24);
+ out[i * 4 + 1] = static_cast(ctx->state[i] >> 16);
+ out[i * 4 + 2] = static_cast(ctx->state[i] >> 8);
+ out[i * 4 + 3] = static_cast(ctx->state[i]);
}
+}
+
+// ---------------------------------------------------------------------------
+// One-shot convenience — routed through the incremental API so behavior is
+// identical by construction.
+// ---------------------------------------------------------------------------
+
+bool sha256(const void* data, size_t len, uint8_t out[kDigestLen]) {
+ Sha256Ctx ctx;
+ sha256_init(&ctx);
+ sha256_update(&ctx, data, len);
+ sha256_final(&ctx, out);
return true;
}
diff --git a/deviceintelligence/src/main/cpp/dicore/sha256.h b/deviceintelligence/src/main/cpp/dicore/sha256.h
index 01f79e6..11b597f 100644
--- a/deviceintelligence/src/main/cpp/dicore/sha256.h
+++ b/deviceintelligence/src/main/cpp/dicore/sha256.h
@@ -17,4 +17,26 @@ bool ensure_initialized();
// Returns false if the backend failed to initialize. Thread-safe.
bool sha256(const void* data, size_t len, uint8_t out[kDigestLen]);
+// ---------------------------------------------------------------------------
+// Incremental (streaming) SHA-256 API.
+// Allows feeding data in arbitrarily-sized chunks; useful when the full input
+// is not available in a contiguous buffer (e.g. inflate fixed-buffer loop).
+// ---------------------------------------------------------------------------
+
+struct Sha256Ctx {
+ uint32_t state[8]; // running hash state
+ uint64_t total_bits; // total message length in bits (updated on each call)
+ uint8_t buf[64]; // partial-block buffer
+ size_t buf_len; // bytes currently buffered (0..63)
+};
+
+// Reset ctx to the SHA-256 initial state. Must be called before sha256_update.
+void sha256_init (Sha256Ctx* ctx);
+
+// Feed len bytes of data into ctx. May be called any number of times.
+void sha256_update(Sha256Ctx* ctx, const void* data, size_t len);
+
+// Finalize the digest and write 32 bytes into out. ctx is unusable afterward.
+void sha256_final (Sha256Ctx* ctx, uint8_t out[kDigestLen]);
+
} // namespace dicore::sha
diff --git a/deviceintelligence/src/main/cpp/dicore/zip_parser.cpp b/deviceintelligence/src/main/cpp/dicore/zip_parser.cpp
index 59162de..92d81eb 100644
--- a/deviceintelligence/src/main/cpp/dicore/zip_parser.cpp
+++ b/deviceintelligence/src/main/cpp/dicore/zip_parser.cpp
@@ -5,6 +5,7 @@
#include "sha256.h"
#include
+#include
namespace dicore::zip {
@@ -21,6 +22,12 @@ constexpr size_t kLfhMinSize = 30;
// Max ZIP comment length (per spec).
constexpr size_t kMaxComment = 0xFFFFu;
+// Maximum decompressed entry size accepted by hash_entry_decompressed.
+// Entries larger than this are skipped (fail-closed). 64 MB covers the
+// largest realistic dex/so in production; a real tamper attempt has no
+// incentive to inflate to this size.
+constexpr size_t kMaxInflateBytes = 64u * 1024u * 1024u;
+
inline uint16_t rd16(const uint8_t* p) {
return (uint16_t)(p[0] | (p[1] << 8));
}
@@ -172,4 +179,141 @@ size_t hash_all_entries(const ApkMap& apk,
return hashed;
}
+bool hash_entry_decompressed(const ApkMap& apk,
+ const CentralDirInfo& cdi,
+ const char* entry_name,
+ uint8_t out32[32]) {
+ if (!cdi.present || !entry_name) return false;
+
+ const uint8_t* cd = apk.range((size_t)cdi.cd_offset, (size_t)cdi.cd_size);
+ if (!cd) return false;
+
+ size_t cd_off = 0;
+ for (uint64_t i = 0; i < cdi.total_entries; ++i) {
+ if (cd_off + kCdfhMinSize > (size_t)cdi.cd_size) break;
+ const uint8_t* p = cd + cd_off;
+ if (rd32(p) != kCdfhMagic) break;
+
+ uint16_t method = rd16(p + 10);
+ uint32_t comp = rd32(p + 20);
+ uint32_t uncomp = rd32(p + 24);
+ uint16_t name_len = rd16(p + 28);
+ uint16_t extra_len = rd16(p + 30);
+ uint16_t cmt_len = rd16(p + 32);
+ uint32_t lfh_off = rd32(p + 42);
+
+ size_t total_var = (size_t)name_len + extra_len + cmt_len;
+ if (cd_off + kCdfhMinSize + total_var > (size_t)cdi.cd_size) break;
+
+ std::string_view name(reinterpret_cast(p + kCdfhMinSize), name_len);
+
+ if (name == entry_name) {
+ // ZIP64 sentinel guard — skip rather than misinterpret.
+ if (comp == 0xFFFFFFFFu || uncomp == 0xFFFFFFFFu) {
+ RLOGW("zip: hash_entry_decompressed: ZIP64 entry '%s', skipping", entry_name);
+ return false;
+ }
+
+ // Resolve body offset via LFH (LFH and CDFH extra fields may differ).
+ const uint8_t* lfh = apk.range(lfh_off, kLfhMinSize);
+ if (!lfh || rd32(lfh) != kLfhMagic) return false;
+ uint16_t lfh_name_len = rd16(lfh + 26);
+ uint16_t lfh_extra_len = rd16(lfh + 28);
+ uint64_t body_off = (uint64_t)lfh_off + kLfhMinSize
+ + lfh_name_len + lfh_extra_len;
+
+ // M-2: 32-bit body_off narrowing guard — reject before any size_t cast.
+ if (body_off > (uint64_t)apk.size()) return false;
+ if ((uint64_t)comp > (uint64_t)apk.size() - body_off) return false;
+
+ if (method == 0 /* STORED */) {
+ const uint8_t* body = apk.range((size_t)body_off, (size_t)comp);
+ if (!body) return false;
+ return sha::sha256(body, (size_t)comp, out32);
+ }
+
+ if (method == 8 /* DEFLATED */) {
+ // I-2: bound the compressed size symmetrically with the uncomp cap.
+ if (comp > kMaxInflateBytes) {
+ RLOGW("zip: hash_entry_decompressed: comp_size %u > limit for '%s'",
+ comp, entry_name);
+ return false;
+ }
+ if (uncomp > kMaxInflateBytes) {
+ RLOGW("zip: hash_entry_decompressed: uncomp_size %u > limit for '%s'",
+ uncomp, entry_name);
+ return false;
+ }
+
+ const uint8_t* comp_body = apk.range((size_t)body_off, (size_t)comp);
+ if (!comp_body) return false;
+
+ // I-1: Fixed-buffer streaming inflate + incremental SHA-256.
+ // Peak memory: O(64 KiB), independent of entry size.
+ constexpr size_t kBufSize = 64u * 1024u;
+ uint8_t out_buf[kBufSize];
+
+ sha::Sha256Ctx sha_ctx;
+ sha::sha256_init(&sha_ctx);
+
+ z_stream zs{};
+ // -MAX_WBITS = raw deflate (no zlib/gzip header).
+ if (inflateInit2(&zs, -MAX_WBITS) != Z_OK) return false;
+
+ zs.next_in = const_cast(comp_body);
+ zs.avail_in = comp;
+
+ size_t total_inflated = 0;
+ int ret = Z_OK;
+
+ while (ret != Z_STREAM_END) {
+ zs.next_out = out_buf;
+ zs.avail_out = (uInt)kBufSize;
+
+ ret = inflate(&zs, Z_NO_FLUSH);
+
+ // Guard: no-progress with no pending input → infinite-loop risk.
+ if (ret == Z_BUF_ERROR
+ && zs.avail_out == (uInt)kBufSize
+ && zs.avail_in == 0) {
+ inflateEnd(&zs);
+ RLOGW("zip: hash_entry_decompressed: inflate no-progress for '%s'",
+ entry_name);
+ return false;
+ }
+
+ if (ret != Z_OK && ret != Z_STREAM_END) {
+ inflateEnd(&zs);
+ RLOGW("zip: hash_entry_decompressed: inflate ret=%d for '%s'",
+ ret, entry_name);
+ return false;
+ }
+
+ size_t produced = kBufSize - (size_t)zs.avail_out;
+ total_inflated += produced;
+ if (total_inflated > kMaxInflateBytes) {
+ inflateEnd(&zs);
+ RLOGW("zip: hash_entry_decompressed: inflate exceeded limit for '%s'",
+ entry_name);
+ return false;
+ }
+
+ sha::sha256_update(&sha_ctx, out_buf, produced);
+ }
+
+ inflateEnd(&zs);
+ sha::sha256_final(&sha_ctx, out32);
+ return true;
+ }
+
+ RLOGW("zip: hash_entry_decompressed: unsupported method %u for '%s'",
+ method, entry_name);
+ return false;
+ }
+
+ cd_off += kCdfhMinSize + total_var;
+ }
+ return false; // entry not found
+}
+
} // namespace dicore::zip
diff --git a/deviceintelligence/src/main/cpp/dicore/zip_parser.h b/deviceintelligence/src/main/cpp/dicore/zip_parser.h
index b7a83a3..885b3fb 100644
--- a/deviceintelligence/src/main/cpp/dicore/zip_parser.h
+++ b/deviceintelligence/src/main/cpp/dicore/zip_parser.h
@@ -43,4 +43,16 @@ size_t hash_all_entries(const ApkMap& apk,
const CentralDirInfo& cdi,
const std::function& sink);
+// Hash the DECOMPRESSED body of the ZIP entry named `entry_name`.
+// For STORED entries, SHA-256 the raw body directly.
+// For DEFLATED entries, inflate via NDK zlib (raw deflate, inflateInit2(-MAX_WBITS))
+// into a bounded buffer and SHA-256 the inflated bytes.
+// Writes 32 bytes to out32 on success and returns true.
+// Returns false (fail-closed, no crash) if: entry not found, null entry_name,
+// ZIP64 sentinel, zlib error, inflated size > 64 MB guard, or body out of range.
+bool hash_entry_decompressed(const ApkMap& apk,
+ const CentralDirInfo& cdi,
+ const char* entry_name,
+ uint8_t out32[32]);
+
} // namespace dicore::zip
diff --git a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt
index 62fb4bb..2b7853a 100644
--- a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt
+++ b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt
@@ -9,6 +9,82 @@ import io.ssemaj.deviceintelligence.Finding
import io.ssemaj.deviceintelligence.Severity
import android.content.Context
+internal sealed class BundleEval {
+ data class Ok(val findings: List) : BundleEval()
+ object SignerUnavailable : BundleEval()
+}
+
+/**
+ * Pure decision logic for bundle-mode integrity. No JNI calls — all native
+ * results are supplied as parameters, making this fully unit-testable.
+ */
+internal fun evaluateBundleIntegrity(
+ observedSignerCerts: List?,
+ allowSet: Set,
+ bundleEntryHashes: Map,
+ resolveDecompressedHash: (entryName: String) -> String?,
+ packageName: String = "",
+): BundleEval {
+ val findings = mutableListOf()
+
+ if (allowSet.isNotEmpty()) {
+ if (observedSignerCerts == null) return BundleEval.SignerUnavailable
+ for (cert in observedSignerCerts) {
+ if (cert !in allowSet) {
+ findings += Finding(
+ kind = "apk_signer_mismatch",
+ severity = Severity.CRITICAL,
+ subject = packageName.ifEmpty { null },
+ message = "Bundle signer cert is not in the build-time allow-set",
+ details = mapOf(
+ "allow_set" to allowSet.joinToString(","),
+ "observed" to cert,
+ ),
+ )
+ }
+ }
+ }
+
+ for ((entryName, expectedHash) in bundleEntryHashes) {
+ val observedHash = resolveDecompressedHash(entryName)
+ when {
+ observedHash == null -> {
+ // ABI-split native libs (lib//*.so) are conditionally delivered by Play:
+ // only the device-ABI split is installed, so other ABIs baked into the
+ // fingerprint will legitimately be absent. Treat as not-applicable — emit NO
+ // finding. A *present-but-patched* .so still fires apk_entry_modified below
+ // (tamper detection is preserved). A removed *active* .so is self-defeating
+ // since the app cannot load it. Non-ABI entries (e.g. classes*.dex) always
+ // live in the base module and are never conditionally stripped, so they
+ // continue to produce apk_entry_removed when absent.
+ if (entryName.startsWith("lib/") && entryName.endsWith(".so")) {
+ // Conditionally-delivered ABI split — skip, not a tamper signal.
+ } else {
+ findings += Finding(
+ kind = "apk_entry_removed",
+ severity = Severity.HIGH,
+ subject = entryName,
+ message = "Bundle entry was present at build time but is absent across all splits",
+ details = mapOf("expected_hash" to expectedHash),
+ )
+ }
+ }
+ observedHash != expectedHash -> findings += Finding(
+ kind = "apk_entry_modified",
+ severity = Severity.CRITICAL,
+ subject = entryName,
+ message = "Bundle entry's decompressed bytes differ from build time",
+ details = mapOf(
+ "expected_hash" to expectedHash,
+ "observed_hash" to observedHash,
+ ),
+ )
+ }
+ }
+
+ return BundleEval.Ok(findings)
+}
+
/**
* `integrity.apk` — APK integrity detector.
*
@@ -107,112 +183,163 @@ internal class ApkIntegrityDetector : Detector {
durationMs = dur(),
)
- val runtimeCerts = NativeBridge.apkSignerCertHashes(apkPath)
- ?: return inconclusive(
- id = id,
- reason = "apk_unreadable",
- message = "apkSignerCertHashes returned null for $apkPath",
- durationMs = dur(),
- )
+ val findings = ArrayList(8)
- val runtimeEntriesArr = NativeBridge.apkEntries(apkPath)
- ?: return inconclusive(
- id = id,
- reason = "apk_unreadable",
- message = "apkEntries returned null for $apkPath",
- durationMs = dur(),
- )
- val runtimeEntries = parseEntryArray(runtimeEntriesArr)
-
- // 3. Diff. Findings stack independently.
- val findings = ArrayList(4)
- val expectedCerts = baked.signerCertSha256.toSet()
- val observedCerts = runtimeCerts.toSet()
- if (observedCerts != expectedCerts) {
- findings += Finding(
- kind = "apk_signer_mismatch",
- severity = Severity.CRITICAL,
- subject = context.packageName,
- message = "APK signer cert(s) differ from the build-time baked set",
- details = mapOf(
- "expected" to baked.signerCertSha256.joinToString(","),
- "observed" to runtimeCerts.joinToString(","),
- ),
- )
- }
+ if (baked.bundleMode) {
+ // ---- Bundle mode: signer membership + decompressed entry diff across splits ----
- if (!apkPath.startsWith(baked.expectedSourceDirPrefix)) {
- findings += Finding(
- kind = "apk_source_dir_unexpected",
- severity = Severity.MEDIUM,
- subject = apkPath,
- message = "Installed APK lives outside the expected path prefix",
- details = mapOf(
- "expected_prefix" to baked.expectedSourceDirPrefix,
- "observed_path" to apkPath,
- ),
- )
- }
+ val allowSet = baked.signerCertSha256.toHashSet()
+ // Only call NativeBridge when there is an allow-set to check against; empty
+ // allow-set is a documented fail-open (dex/so hashing becomes the sole anchor).
+ val observedSignerCerts: List? = if (allowSet.isNotEmpty()) {
+ NativeBridge.apkSignerCertHashes(apkPath)?.toList()
+ } else {
+ emptyList()
+ }
+
+ val splitPaths: List =
+ context.applicationInfo.splitSourceDirs?.toList() ?: emptyList()
+ val searchPaths: List = listOf(apkPath) + splitPaths
+
+ when (val eval = evaluateBundleIntegrity(
+ observedSignerCerts = observedSignerCerts,
+ allowSet = allowSet,
+ bundleEntryHashes = baked.bundleEntryHashes,
+ resolveDecompressedHash = { entryName ->
+ searchPaths.firstNotNullOfOrNull { splitPath ->
+ NativeBridge.apkEntryDecompressedHash(splitPath, entryName)
+ }
+ },
+ packageName = context.packageName,
+ )) {
+ is BundleEval.SignerUnavailable -> return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkSignerCertHashes returned null for $apkPath",
+ durationMs = dur(),
+ )
+ is BundleEval.Ok -> findings += eval.findings
+ }
- if (baked.expectedInstallerWhitelist.isNotEmpty()) {
- val installer = readInstallerPackageName(context)
- if (installer == null || installer !in baked.expectedInstallerWhitelist) {
+ // Source-dir prefix check (same as APK mode).
+ if (!apkPath.startsWith(baked.expectedSourceDirPrefix)) {
findings += Finding(
- kind = "installer_not_whitelisted",
+ kind = "apk_source_dir_unexpected",
severity = Severity.MEDIUM,
- subject = installer,
- message = "Installer package is not in the baked whitelist",
+ subject = apkPath,
+ message = "Installed APK lives outside the expected path prefix",
details = mapOf(
- "whitelist" to baked.expectedInstallerWhitelist.joinToString(","),
- "observed_installer" to (installer ?: ""),
+ "expected_prefix" to baked.expectedSourceDirPrefix,
+ "observed_path" to apkPath,
),
)
}
- }
- // Entry-level diff. Filter the runtime view through baked
- // ignore rules so the comparison is apples-to-apples.
- val ignoredEntries = baked.ignoredEntries.toHashSet()
- val ignoredPrefixes = baked.ignoredEntryPrefixes
- val filteredRuntime = HashMap(runtimeEntries.size)
- for ((name, hash) in runtimeEntries) {
- if (name in ignoredEntries) continue
- if (ignoredPrefixes.any { name.startsWith(it) }) continue
- filteredRuntime[name] = hash
- }
+ } else {
+ // ---- APK mode: existing equality checks (unchanged) ----
+ val runtimeCerts = NativeBridge.apkSignerCertHashes(apkPath)
+ ?: return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkSignerCertHashes returned null for $apkPath",
+ durationMs = dur(),
+ )
- for ((name, expectedHash) in baked.entries) {
- val observedHash = filteredRuntime[name]
- when {
- observedHash == null -> findings += Finding(
- kind = "apk_entry_removed",
- severity = Severity.HIGH,
- subject = name,
- message = "APK entry was present at build time but is missing at runtime",
- details = mapOf("expected_hash" to expectedHash),
+ val runtimeEntriesArr = NativeBridge.apkEntries(apkPath)
+ ?: return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkEntries returned null for $apkPath",
+ durationMs = dur(),
)
- observedHash != expectedHash -> findings += Finding(
- kind = "apk_entry_modified",
+ val runtimeEntries = parseEntryArray(runtimeEntriesArr)
+
+ val expectedCerts = baked.signerCertSha256.toSet()
+ val observedCerts = runtimeCerts.toSet()
+ if (observedCerts != expectedCerts) {
+ findings += Finding(
+ kind = "apk_signer_mismatch",
severity = Severity.CRITICAL,
- subject = name,
- message = "APK entry exists but its bytes differ from build time",
+ subject = context.packageName,
+ message = "APK signer cert(s) differ from the build-time baked set",
details = mapOf(
- "expected_hash" to expectedHash,
- "observed_hash" to observedHash,
+ "expected" to baked.signerCertSha256.joinToString(","),
+ "observed" to runtimeCerts.joinToString(","),
),
)
}
- }
- for ((name, observedHash) in filteredRuntime) {
- if (name !in baked.entries) {
+
+ if (!apkPath.startsWith(baked.expectedSourceDirPrefix)) {
findings += Finding(
- kind = "apk_entry_added",
- severity = Severity.HIGH,
- subject = name,
- message = "APK entry exists at runtime but wasn't present at build time",
- details = mapOf("observed_hash" to observedHash),
+ kind = "apk_source_dir_unexpected",
+ severity = Severity.MEDIUM,
+ subject = apkPath,
+ message = "Installed APK lives outside the expected path prefix",
+ details = mapOf(
+ "expected_prefix" to baked.expectedSourceDirPrefix,
+ "observed_path" to apkPath,
+ ),
)
}
+
+ if (baked.expectedInstallerWhitelist.isNotEmpty()) {
+ val installer = readInstallerPackageName(context)
+ if (installer == null || installer !in baked.expectedInstallerWhitelist) {
+ findings += Finding(
+ kind = "installer_not_whitelisted",
+ severity = Severity.MEDIUM,
+ subject = installer,
+ message = "Installer package is not in the baked whitelist",
+ details = mapOf(
+ "whitelist" to baked.expectedInstallerWhitelist.joinToString(","),
+ "observed_installer" to (installer ?: ""),
+ ),
+ )
+ }
+ }
+
+ val ignoredEntries = baked.ignoredEntries.toHashSet()
+ val ignoredPrefixes = baked.ignoredEntryPrefixes
+ val filteredRuntime = HashMap(runtimeEntries.size)
+ for ((name, hash) in runtimeEntries) {
+ if (name in ignoredEntries) continue
+ if (ignoredPrefixes.any { name.startsWith(it) }) continue
+ filteredRuntime[name] = hash
+ }
+
+ for ((name, expectedHash) in baked.entries) {
+ val observedHash = filteredRuntime[name]
+ when {
+ observedHash == null -> findings += Finding(
+ kind = "apk_entry_removed",
+ severity = Severity.HIGH,
+ subject = name,
+ message = "APK entry was present at build time but is missing at runtime",
+ details = mapOf("expected_hash" to expectedHash),
+ )
+ observedHash != expectedHash -> findings += Finding(
+ kind = "apk_entry_modified",
+ severity = Severity.CRITICAL,
+ subject = name,
+ message = "APK entry exists but its bytes differ from build time",
+ details = mapOf(
+ "expected_hash" to expectedHash,
+ "observed_hash" to observedHash,
+ ),
+ )
+ }
+ }
+ for ((name, observedHash) in filteredRuntime) {
+ if (name !in baked.entries) {
+ findings += Finding(
+ kind = "apk_entry_added",
+ severity = Severity.HIGH,
+ subject = name,
+ message = "APK entry exists at runtime but wasn't present at build time",
+ details = mapOf("observed_hash" to observedHash),
+ )
+ }
+ }
}
return ok(id, findings, dur())
diff --git a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt
index 5268460..826a6ed 100644
--- a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt
+++ b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt
@@ -54,10 +54,17 @@ internal data class Fingerprint(
* pre-load `.so` replacement (Component 3 of the design doc).
*/
val dicoreTextSha256ByAbi: Map = emptyMap(),
+ /** v3 — true when baked for an App Bundle build (split-aware, decompressed hashing). */
+ val bundleMode: Boolean = false,
+ /**
+ * v3 — APK-relative entry path -> SHA-256 hex of the entry's DECOMPRESSED body,
+ * for `classes*.dex` + `.so` files under `lib//`. Used only in bundle mode.
+ */
+ val bundleEntryHashes: Map = emptyMap(),
) {
companion object {
/** Schema currently produced by the plugin. Must match plugin SCHEMA_VERSION. */
- const val SCHEMA_VERSION: Int = 2
+ const val SCHEMA_VERSION: Int = 3
/**
* Path of the encrypted blob inside the APK as written by F8's
diff --git a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt
index c50668a..50b4c7d 100644
--- a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt
+++ b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt
@@ -29,6 +29,11 @@ import java.io.InputStream
* uint32 abiInventoryCount + (utf8 abi, uint32 fileCount, utf8 filename[])[]
* uint32 abiFileHashCount + (utf8 abi, uint32 entryCount, (utf8 filename, utf8 sha)[])[]
* uint32 abiTextHashCount + (utf8 abi, utf8 sha)[]
+ * --- v3 additions ---
+ * uint8 bundleMode (0/1)
+ * uint32 bundleEntryCount
+ * utf8 entryName [bundleEntryCount times, sorted]
+ * utf8 sha256Hex [bundleEntryCount times]
*
* Decode-only: the runtime never re-encodes a fingerprint, so we drop the
* encoder half to keep the AAR small and remove the temptation to mutate
@@ -40,7 +45,7 @@ internal object FingerprintCodec {
const val MAGIC: Int = 0x52615370
/** Newest wire format the decoder understands. */
- const val FORMAT_VERSION: Int = 2
+ const val FORMAT_VERSION: Int = 3
/**
* Oldest wire format the decoder accepts. Kept at 1 so apps
@@ -109,6 +114,8 @@ internal object FingerprintCodec {
var inventoryByAbi: Map> = emptyMap()
var hashesByAbi: Map> = emptyMap()
var textHashByAbi: Map = emptyMap()
+ var bundleMode = false
+ var bundleEntryHashes: Map = emptyMap()
if (formatVersion >= 2) {
val invCount = readNonNegative(din.readInt(), "abiInventoryCount")
inventoryByAbi = LinkedHashMap>(invCount).apply {
@@ -148,6 +155,18 @@ internal object FingerprintCodec {
}
}
+ if (formatVersion >= 3) {
+ bundleMode = din.readBoolean()
+ val bundleCount = readNonNegative(din.readInt(), "bundleEntryCount")
+ bundleEntryHashes = LinkedHashMap(bundleCount).apply {
+ repeat(bundleCount) {
+ val name = din.readUTF()
+ val sha = din.readUTF()
+ put(name, sha)
+ }
+ }
+ }
+
return Fingerprint(
schemaVersion = schemaVersion,
builtAtEpochMs = builtAtEpochMs,
@@ -163,6 +182,8 @@ internal object FingerprintCodec {
nativeLibInventoryByAbi = inventoryByAbi,
nativeLibHashesByAbi = hashesByAbi,
dicoreTextSha256ByAbi = textHashByAbi,
+ bundleMode = bundleMode,
+ bundleEntryHashes = bundleEntryHashes,
)
}
diff --git a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt
index 6de0bc8..b119a4d 100644
--- a/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt
+++ b/deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt
@@ -55,6 +55,16 @@ internal object NativeBridge {
@JvmStatic
external fun apkSignerCertHashes(path: String): Array?
+ /**
+ * Returns the SHA-256 hex of the DECOMPRESSED body of the ZIP entry named
+ * [entryName] inside the APK/split at [path]. Returns null if the entry
+ * is not found, the APK can't be opened, or inflate fails (fail-closed to
+ * not-found, not a crash). Used by [ApkIntegrityDetector] in bundle mode
+ * to compare decompressed code entry hashes across base + split APKs.
+ */
+ @JvmStatic
+ external fun apkEntryDecompressedHash(path: String, entryName: String): String?
+
/**
* Reads a single Android system property via `__system_property_get`
* (the same syscall behind `getprop` on the shell). Returns null
diff --git a/deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp b/deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp
new file mode 100644
index 0000000..4383cfd
--- /dev/null
+++ b/deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp
@@ -0,0 +1,220 @@
+// Host test for dicore::zip::hash_entry_decompressed.
+// Compile: see step 2. Run on x86_64 Android emulator via ADB.
+#include "dicore/zip_parser.h"
+#include "dicore/apkmap.h"
+#include "dicore/sha256.h"
+#include "dicore/hex.h"
+
+#include
+#include
+#include
+#include
+#include
+
+using namespace dicore;
+
+// ---- Minimal ZIP writer -----------------------------------------------
+static void w16(std::vector& v, uint16_t x) { v.push_back(x&0xFF); v.push_back(x>>8); }
+static void w32(std::vector& v, uint32_t x) { for(int i=0;i<4;i++){v.push_back(x&0xFF);x>>=8;} }
+
+struct CdEntry { std::string name; uint32_t lfh_off, comp_sz, uncomp_sz, crc32v; uint16_t method; };
+
+static uint32_t crc32_buf(const uint8_t* p, size_t n) {
+ return (uint32_t)::crc32(::crc32(0L, Z_NULL, 0), p, (uInt)n);
+}
+
+static void emit_lfh(std::vector& v, CdEntry& e) {
+ e.lfh_off = (uint32_t)v.size();
+ w32(v,0x04034b50u); w16(v,20); w16(v,0); w16(v,e.method);
+ w16(v,0); w16(v,0);
+ w32(v,e.crc32v); w32(v,e.comp_sz); w32(v,e.uncomp_sz);
+ w16(v,(uint16_t)e.name.size()); w16(v,0);
+ for(char c:e.name) v.push_back((uint8_t)c);
+}
+
+static std::vector build_zip(
+ const char* stored_name, const uint8_t* stored_data, uint32_t stored_len,
+ const char* deflated_name, const uint8_t* plain, uint32_t plain_len)
+{
+ std::vector zip;
+ std::vector entries;
+
+ // STORED entry
+ {
+ CdEntry e; e.name=stored_name; e.method=0;
+ e.uncomp_sz=stored_len; e.comp_sz=stored_len;
+ e.crc32v=crc32_buf(stored_data,stored_len);
+ emit_lfh(zip,e);
+ for(uint32_t i=0;i comp(compressBound(plain_len));
+ z_stream zs{}; deflateInit2(&zs,Z_DEFAULT_COMPRESSION,Z_DEFLATED,-MAX_WBITS,8,Z_DEFAULT_STRATEGY);
+ zs.next_in=const_cast(plain); zs.avail_in=plain_len;
+ zs.next_out=comp.data(); zs.avail_out=(uInt)comp.size();
+ deflate(&zs,Z_FINISH); uint32_t csz=(uint32_t)zs.total_out; deflateEnd(&zs);
+
+ CdEntry e; e.name=deflated_name; e.method=8;
+ e.uncomp_sz=plain_len; e.comp_sz=csz;
+ e.crc32v=crc32_buf(plain,plain_len);
+ emit_lfh(zip,e);
+ for(uint32_t i=0;i& data) {
+ FILE* f=fopen(path,"wb"); assert(f);
+ fwrite(data.data(),1,data.size(),f); fclose(f);
+}
+
+int main() {
+ // Init SHA backend (dlopen BoringSSL on Android)
+ assert(sha::ensure_initialized());
+
+ const char STORED_DATA[] = "STORED_PAYLOAD_BYTES_FOR_TESTING";
+ const uint32_t STORED_LEN = (uint32_t)strlen(STORED_DATA);
+ const char DEFLATED_DATA[] = "DEFLATED_PAYLOAD_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+ const uint32_t DEFLATED_LEN = (uint32_t)strlen(DEFLATED_DATA);
+
+ auto zip = build_zip(
+ "stored.txt", (const uint8_t*)STORED_DATA, STORED_LEN,
+ "deflated.txt", (const uint8_t*)DEFLATED_DATA, DEFLATED_LEN
+ );
+ const char* path = "/data/local/tmp/di_test_inflate.zip";
+ write_file(path, zip);
+
+ ApkMap apk; assert(apk.open(path));
+ zip::CentralDirInfo cdi; assert(zip::find_central_directory(apk, &cdi));
+
+ // Test 1: STORED entry — hash equals SHA-256 of the plain bytes
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "stored.txt", out);
+ assert(ok);
+ std::string want = sha256_hex_of(STORED_DATA, STORED_LEN);
+ std::string got = hex::encode(out, 32);
+ assert(want == got && "Test1 STORED hash mismatch");
+ printf("PASS test1: STORED hash = %s\n", got.c_str());
+ }
+
+ // Test 2: DEFLATED entry — hash equals SHA-256 of the INFLATED (plain) bytes
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "deflated.txt", out);
+ assert(ok);
+ std::string want = sha256_hex_of(DEFLATED_DATA, DEFLATED_LEN);
+ std::string got = hex::encode(out, 32);
+ assert(want == got && "Test2 DEFLATED hash mismatch (got compressed hash?)");
+ printf("PASS test2: DEFLATED decompressed hash = %s\n", got.c_str());
+ }
+
+ // Test 3: missing entry returns false, no crash
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "does_not_exist.bin", out);
+ assert(!ok && "Test3 missing entry should return false");
+ printf("PASS test3: missing entry returns false\n");
+ }
+
+ // Test 4: null entry_name returns false, no crash
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, nullptr, out);
+ assert(!ok && "Test4 null entry_name should return false");
+ printf("PASS test4: null entry_name returns false\n");
+ }
+
+ // Test 5: garbage file (not a ZIP) — find_central_directory fails
+ {
+ const char* bad = "/data/local/tmp/di_garbage.bin";
+ {FILE* f=fopen(bad,"wb"); const uint8_t g[]={0xDE,0xAD,0xBE,0xEF,0x00}; fwrite(g,1,4,f); fclose(f);}
+ ApkMap bad_apk; bad_apk.open(bad);
+ zip::CentralDirInfo bad_cdi;
+ bool has_cd = zip::find_central_directory(bad_apk, &bad_cdi);
+ if (has_cd) {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(bad_apk, bad_cdi, "anything", out);
+ assert(!ok);
+ }
+ printf("PASS test5: garbage file handled safely (has_cd=%d)\n", (int)has_cd);
+ }
+
+ // Test 6 (M-3): valid-shaped ZIP with a DEFLATED entry whose body bytes are
+ // garbage (not a valid deflate stream). hash_entry_decompressed must return
+ // false and must not crash.
+ {
+ // Build a ZIP with a DEFLATED entry whose compressed body is random garbage.
+ const char* garbage_body_path = "/data/local/tmp/di_garbage_body.zip";
+ {
+ std::vector zip6;
+ // Garbage compressed bytes — not a valid raw deflate stream.
+ const uint8_t garbage[] = {0xFF, 0xFE, 0xAB, 0xCD, 0x12, 0x34, 0x56, 0x78};
+ const uint32_t garbage_len = (uint32_t)sizeof(garbage);
+ // Claim uncomp_size = 100 (any plausible value ≤ kMaxInflateBytes).
+ const uint32_t fake_uncomp = 100u;
+
+ CdEntry e6;
+ e6.name = "bad_deflate.bin";
+ e6.method = 8; // DEFLATED
+ e6.comp_sz = garbage_len;
+ e6.uncomp_sz = fake_uncomp;
+ e6.crc32v = 0xDEADBEEFu; // deliberately wrong — inflate will fail first
+
+ emit_lfh(zip6, e6);
+ for (uint32_t i = 0; i < garbage_len; ++i) zip6.push_back(garbage[i]);
+
+ // Central directory
+ uint32_t cd6_start = (uint32_t)zip6.size();
+ w32(zip6,0x02014b50u); w16(zip6,20); w16(zip6,20); w16(zip6,0); w16(zip6,e6.method);
+ w16(zip6,0); w16(zip6,0);
+ w32(zip6,e6.crc32v); w32(zip6,e6.comp_sz); w32(zip6,e6.uncomp_sz);
+ w16(zip6,(uint16_t)e6.name.size()); w16(zip6,0); w16(zip6,0);
+ w16(zip6,0); w16(zip6,0); w32(zip6,0); w32(zip6,e6.lfh_off);
+ for (char c : e6.name) zip6.push_back((uint8_t)c);
+ uint32_t cd6_sz = (uint32_t)zip6.size() - cd6_start;
+
+ // EOCD
+ w32(zip6,0x06054b50u); w16(zip6,0); w16(zip6,0);
+ w16(zip6,1); w16(zip6,1);
+ w32(zip6,cd6_sz); w32(zip6,cd6_start); w16(zip6,0);
+
+ write_file(garbage_body_path, zip6);
+ }
+
+ ApkMap apk6; assert(apk6.open(garbage_body_path));
+ zip::CentralDirInfo cdi6; assert(zip::find_central_directory(apk6, &cdi6));
+ uint8_t out6[32];
+ bool ok6 = zip::hash_entry_decompressed(apk6, cdi6, "bad_deflate.bin", out6);
+ assert(!ok6 && "Test6: garbage deflate body must return false");
+ printf("PASS test6: garbage deflate body returns false (no crash)\n");
+ }
+
+ printf("ALL TESTS PASSED\n");
+ return 0;
+}
diff --git a/deviceintelligence/src/test/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetectorBundleTest.kt b/deviceintelligence/src/test/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetectorBundleTest.kt
new file mode 100644
index 0000000..acc1512
--- /dev/null
+++ b/deviceintelligence/src/test/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetectorBundleTest.kt
@@ -0,0 +1,142 @@
+package io.ssemaj.deviceintelligence.internal
+
+import io.ssemaj.deviceintelligence.Severity
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ApkIntegrityDetectorBundleTest {
+
+ private val certA = "aabbcc"
+ private val certB = "ddeeff"
+ private val entryName = "classes.dex"
+ private val bakedHash = "deadbeef"
+
+ // Case 1: cert in allow-set → no signer finding
+ @Test
+ fun `cert in allow-set produces no signer finding`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = listOf(certA),
+ allowSet = setOf(certA),
+ bundleEntryHashes = emptyMap(),
+ resolveDecompressedHash = { null },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertTrue(findings.none { it.kind == "apk_signer_mismatch" })
+ }
+
+ // Case 2: cert not in allow-set → apk_signer_mismatch CRITICAL
+ @Test
+ fun `cert not in allow-set emits apk_signer_mismatch CRITICAL`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = listOf(certB),
+ allowSet = setOf(certA),
+ bundleEntryHashes = emptyMap(),
+ resolveDecompressedHash = { null },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertEquals(1, findings.size)
+ assertEquals("apk_signer_mismatch", findings[0].kind)
+ assertEquals(Severity.CRITICAL, findings[0].severity)
+ }
+
+ // Case 3: empty allow-set → zero findings (fail-open)
+ @Test
+ fun `empty allow-set skips signer check and produces no findings`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = listOf(certB),
+ allowSet = emptySet(),
+ bundleEntryHashes = emptyMap(),
+ resolveDecompressedHash = { null },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertTrue(findings.isEmpty())
+ }
+
+ // Case 4: resolver returns null for a dex entry → apk_entry_removed HIGH
+ // (dex lives in the base module and is never conditionally stripped)
+ @Test
+ fun `resolver returning null for dex emits apk_entry_removed HIGH`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = emptySet(),
+ bundleEntryHashes = mapOf(entryName to bakedHash),
+ resolveDecompressedHash = { null },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertEquals(1, findings.size)
+ assertEquals("apk_entry_removed", findings[0].kind)
+ assertEquals(Severity.HIGH, findings[0].severity)
+ }
+
+ // Case 4b: resolver returns null for an ABI-split .so → NO finding
+ // (Play delivers only the device-ABI config split; other ABIs baked into
+ // the fingerprint are legitimately absent — this must not be flagged)
+ @Test
+ fun `resolver returning null for non-device-ABI so emits no finding`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = emptySet(),
+ bundleEntryHashes = mapOf("lib/x86_64/libfoo.so" to bakedHash),
+ resolveDecompressedHash = { null },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertTrue("Expected no findings for absent ABI-split .so, got: $findings", findings.isEmpty())
+ }
+
+ // Case 4c: present-but-mismatched .so → apk_entry_modified CRITICAL
+ // (tamper detection is preserved even with the ABI-split skip rule)
+ @Test
+ fun `resolver returning mismatched hash for so emits apk_entry_modified CRITICAL`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = emptySet(),
+ bundleEntryHashes = mapOf("lib/arm64-v8a/libfoo.so" to bakedHash),
+ resolveDecompressedHash = { "00000000" },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertEquals(1, findings.size)
+ assertEquals("apk_entry_modified", findings[0].kind)
+ assertEquals(Severity.CRITICAL, findings[0].severity)
+ }
+
+ // Case 5: resolver returns a mismatched hash → apk_entry_modified CRITICAL
+ @Test
+ fun `resolver returning mismatched hash emits apk_entry_modified CRITICAL`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = emptySet(),
+ bundleEntryHashes = mapOf(entryName to bakedHash),
+ resolveDecompressedHash = { "00000000" },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertEquals(1, findings.size)
+ assertEquals("apk_entry_modified", findings[0].kind)
+ assertEquals(Severity.CRITICAL, findings[0].severity)
+ }
+
+ // Case 6: resolver returns the matching hash → no finding
+ @Test
+ fun `resolver returning matching hash produces no finding`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = emptySet(),
+ bundleEntryHashes = mapOf(entryName to bakedHash),
+ resolveDecompressedHash = { bakedHash },
+ )
+ val findings = (eval as BundleEval.Ok).findings
+ assertTrue(findings.isEmpty())
+ }
+
+ // SignerUnavailable path: non-empty allow-set + null certs → SignerUnavailable
+ @Test
+ fun `null signer certs with non-empty allow-set returns SignerUnavailable`() {
+ val eval = evaluateBundleIntegrity(
+ observedSignerCerts = null,
+ allowSet = setOf(certA),
+ bundleEntryHashes = emptyMap(),
+ resolveDecompressedHash = { null },
+ )
+ assertTrue(eval is BundleEval.SignerUnavailable)
+ }
+}
diff --git a/docs/superpowers/plans/2026-06-29-app-bundle-integrity.md b/docs/superpowers/plans/2026-06-29-app-bundle-integrity.md
new file mode 100644
index 0000000..361a497
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-29-app-bundle-integrity.md
@@ -0,0 +1,2154 @@
+# App Bundle (AAB) Bundle-Mode Integrity Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Port AAB bundle-mode integrity from DeviceIntelligenceRASP into DeviceIntelligence — baking a v3 fingerprint (decompressed dex/`.so` hashes + signer allow-set) into the `.aab`, re-signing it, and checking it at runtime across base split + splitSourceDirs via native NDK-zlib inflate.
+
+**Architecture:** A separate plugin transform (`BundleIntegrityTask`) wires to `SingleArtifact.BUNDLE` and is mutually exclusive with the existing APK transform per variant; `AppBundleOptions.enabled` is the gate. Native decompressed hashing lives in `zip_parser.cpp` via NDK zlib and is exposed to Kotlin through a new JNI entry point `apkEntryDecompressedHash`; the runtime decision (signer membership + entry diff) stays in Kotlin inside `ApkIntegrityDetector`. Schema/codec bumped to v3 additively — existing APK blobs (v1/v2) decode unchanged.
+
+**Tech Stack:** Kotlin + Gradle Plugin API (AGP 8.x), JDK `jdk.security.jarsigner.JarSigner` (re-sign AAB), NDK r27 C++17 + zlib (inflate in native), JUnit 5 (plugin unit tests), Android x86_64 emulator (native host C++ test via ADB).
+
+## Global Constraints
+
+- Schema v3 is **additive**: `MIN_SUPPORTED_FORMAT_VERSION` stays 1 in both plugin and runtime codec; v1/v2 blobs decode with `bundleMode=false`, `bundleEntryHashes=emptyMap()`.
+- APK path is **byte-for-byte unchanged** when `appBundle.enabled` is false (default). All new code is guarded by the opt-in flag.
+- Bundle mode is **opt-in**: `appBundle { enabled = true }`. No code runs at all for variants that don't set this.
+- Entry-name normalization: `base/dex/` → ``; `base/lib//` → `lib//`. Both `AabHasher` (build-time) and the runtime loop use this form.
+- **JAVA_HOME**: `export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2` — JDK 23 (Temurin). JDK 26 breaks Gradle 8.13.
+- **Native build flags**: `-Wall -Wextra -Werror` (already in `CMakeLists.txt`).
+- **Host C++ test compiler**: `$HOME/Android/Sdk/ndk/27.0.12077973/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android35-clang++` (cross-compiles for Android x86_64; run on emulator via ADB — `clang++` is not installed on the host).
+- **DI encryption divergence from RASP**: RASP uses `seed ‖ XOR(cbo, DiBaker.fpKey(seed))`; DI uses `XOR(cbo, key)` where `key` is the 32-byte `key.bin` produced by `GenerateKeyChunksTask`. `BundleFingerprintBuilder` in DI takes `key: ByteArray` directly and produces the same XOR-only envelope. No seed prefix is added.
+- `fingerprint_asset_missing` remains fail-open (a `Finding`, not a crash).
+- `jdk.security.jarsigner.JarSigner` is available on JDK 9+; no bundletool dependency is added.
+- No `apk_entry_added` check in bundle mode (splits carry legitimate extra entries).
+
+---
+
+## File Map
+
+### Created
+| File | Responsibility |
+|---|---|
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt` | Consumer DSL: `enabled`, `playSigningCertSha256` |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt` | Shared keystore-load + cert-hash helper (extracted from `InstrumentApkTask`) |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt` | Compute decompressed SHA-256 of base-module dex/`.so` entries |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt` | Re-sign `.aab` with JDK JarSigner |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt` | Build the v3 encrypted fingerprint blob from the `.aab` |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt` | AGP `BUNDLE` transform task |
+| `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt` | v3 round-trip + v2 backward-compat codec test |
+| `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt` | Key-normalization + decompressed-hash correctness |
+| `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt` | Blob decodes to `bundleMode=true` + merged signer allow-set |
+| `deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp` | Native C++ host test: STORED + DEFLATED + missing + garbage |
+
+### Modified
+| File | Change |
+|---|---|
+| `deviceintelligence-gradle/build.gradle.kts` | Add `testImplementation(junit-jupiter)` + `useJUnitPlatform()` |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt` | Add `@Nested appBundle: AppBundleOptions` + DSL sugar |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt` | Add `bundleMode`, `bundleEntryHashes`; bump `SCHEMA_VERSION` 2→3 |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt` | Bump `FORMAT_VERSION` 2→3; add v3 encode + decode tail |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt` | Replace inline `SigningMaterial`/`loadSigningMaterial` with `KeystoreSigning` |
+| `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt` | Add bundle-mode gate + `BundleIntegrityTask` wiring; add `appBundle.enabled.convention(false)` |
+| `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt` | Add `bundleMode`, `bundleEntryHashes`; bump `SCHEMA_VERSION` 2→3 |
+| `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt` | Bump `FORMAT_VERSION` 2→3; add v3 decode branch |
+| `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt` | Add `external fun apkEntryDecompressedHash(path: String, entryName: String): String?` |
+| `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt` | Add bundle branch in `evaluate()` |
+| `deviceintelligence/src/main/cpp/CMakeLists.txt` | Add `find_library(z-lib z)` + link zlib |
+| `deviceintelligence/src/main/cpp/dicore/zip_parser.h` | Add `hash_entry_decompressed` declaration |
+| `deviceintelligence/src/main/cpp/dicore/zip_parser.cpp` | Add `hash_entry_decompressed` implementation + `#include ` |
+| `deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp` | Add `apkEntryDecompressedHash` JNI function |
+
+---
+
+### Task 1: DSL — AppBundleOptions + DeviceIntelligenceExtension
+
+**Files:**
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt`
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt` (lines 11–84)
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt` (line 43 — `apply()` conventions)
+
+**Interfaces:**
+- Consumes: nothing (first task)
+- Produces: `AppBundleOptions` (abstract class) with `enabled: Property`, `playSigningCertSha256: SetProperty`, `fun playSigningCertSha256(vararg hex: String)`. `DeviceIntelligenceExtension.appBundle: AppBundleOptions`. Both consumed by Task 4.
+
+- [ ] **Step 1: Write the failing test**
+
+There is no automated test for the DSL itself (Gradle property wiring is an integration concern). Instead, verify the DSL compiles and the convention is wired by building the sample. Skip ahead — the first failing test is in Task 2.
+
+- [ ] **Step 2: Create `AppBundleOptions.kt`**
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt
+package io.ssemaj.deviceintelligence.gradle
+
+import org.gradle.api.provider.Property
+import org.gradle.api.provider.SetProperty
+
+/**
+ * Opt-in App Bundle integrity ("bundle mode").
+ *
+ * When [enabled], the plugin bakes a bundle-mode fingerprint (decompressed
+ * dex/`.so` hashes + signer pins) into the AAB's base assets and re-signs the
+ * AAB, instead of instrumenting the APK. The runtime then hashes those entries'
+ * decompressed bodies across `sourceDir ∪ splitSourceDirs` and checks the
+ * installed signer is a member of the baked allow-set.
+ *
+ * APK mode and bundle mode are mutually exclusive per variant.
+ */
+abstract class AppBundleOptions {
+ /** Enable bundle mode for AAB builds. Default `false`. */
+ abstract val enabled: Property
+
+ /**
+ * Play App Signing certificate SHA-256(s) to include in the signer
+ * allow-set, normalized to lowercase hex with `:` separators stripped.
+ * Under Play App Signing, Google re-signs delivered APKs with the app
+ * signing key, so the runtime must accept that signer in addition to the
+ * upload key. Empty = only the upload-key cert is in the allow-set.
+ */
+ abstract val playSigningCertSha256: SetProperty
+
+ /** DSL sugar: `appBundle { playSigningCertSha256("AB:CD:...") }`. */
+ fun playSigningCertSha256(vararg hex: String) {
+ for (h in hex) playSigningCertSha256.add(h.replace(":", "").lowercase())
+ }
+}
+```
+
+- [ ] **Step 3: Modify `DeviceIntelligenceExtension.kt`**
+
+Add at the end of the class body (before the closing brace at line 84):
+
+```kotlin
+ /**
+ * Opt-in App Bundle integrity ("bundle mode"). When `appBundle.enabled`
+ * is `true`, the plugin bakes a bundle-mode fingerprint into the AAB and
+ * re-signs it instead of instrumenting the APK.
+ */
+ @get:org.gradle.api.tasks.Nested
+ abstract val appBundle: AppBundleOptions
+
+ /** DSL sugar: `deviceIntelligence { appBundle { enabled = true } }`. */
+ fun appBundle(action: org.gradle.api.Action) = action.execute(appBundle)
+```
+
+- [ ] **Step 4: Wire the `appBundle.enabled` convention in `DeviceIntelligencePlugin.apply()`**
+
+In `DeviceIntelligencePlugin.kt`, the `apply()` method creates the extension at line 37. After `disableAutoRuntimeDependency.convention(false)` (currently the last convention, line 43), add:
+
+```kotlin
+ appBundle.enabled.convention(false)
+ appBundle.playSigningCertSha256.convention(emptySet())
+```
+
+- [ ] **Step 5: Verify compilation**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+cd /home/joseph/AndroidStudioProjects/DeviceIntelligence
+./gradlew :deviceintelligence-gradle:compileKotlin
+```
+
+Expected: BUILD SUCCESSFUL. Fix any compile errors before continuing.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/AppBundleOptions.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligenceExtension.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt
+git commit -m "feat(bundle): add AppBundleOptions DSL + extension wire"
+```
+
+---
+
+### Task 2: Fingerprint v3 + Codec v3 (plugin + runtime) + codec unit tests
+
+**Files:**
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt` (line 63: SCHEMA_VERSION=2)
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt` (line 66: FORMAT_VERSION=2)
+- Modify: `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt` (line 60: SCHEMA_VERSION=2)
+- Modify: `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt` (line 43: FORMAT_VERSION=2)
+- Modify: `deviceintelligence-gradle/build.gradle.kts` (add test deps + JUnit platform)
+- Create: `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt`
+
+**Interfaces:**
+- Consumes: nothing new (extends existing types)
+- Produces:
+ - Plugin `Fingerprint(bundleMode: Boolean = false, bundleEntryHashes: Map = emptyMap())` (new default fields)
+ - Plugin `FingerprintCodec.FORMAT_VERSION = 3`, `encode()` writes v3 tail, `decode()` reads v3 tail when `formatVersion >= 3`
+ - Runtime `Fingerprint.bundleMode: Boolean`, `Fingerprint.bundleEntryHashes: Map` (same defaults)
+ - Runtime `FingerprintCodec.FORMAT_VERSION = 3` (accepts 1..3, reads v3 tail)
+ - All consumed by Tasks 3, 4, 6.
+
+- [ ] **Step 1: Set up test infrastructure in `build.gradle.kts`**
+
+In `deviceintelligence-gradle/build.gradle.kts`, add the test dependency and JUnit platform configuration. After the existing `dependencies {}` block:
+
+```kotlin
+dependencies {
+ // (existing entries unchanged)
+ compileOnly("com.android.tools.build:gradle-api:8.13.2")
+ implementation("com.android.tools.build:apksig:8.13.2")
+
+ // JUnit 5 for plugin unit tests
+ testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
+}
+
+tasks.named("test") {
+ useJUnitPlatform()
+}
+```
+
+Create the test source directory:
+```bash
+mkdir -p /home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal
+```
+
+- [ ] **Step 2: Write the failing codec test**
+
+Create `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt`:
+
+```kotlin
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+
+class FingerprintCodecTest {
+
+ /** A v3 bundle-mode fingerprint round-trips through encode → decode. */
+ @Test fun bundleModeRoundTrip() {
+ val fp = baseFingerprint().copy(
+ bundleMode = true,
+ bundleEntryHashes = mapOf(
+ "classes.dex" to "aabbccddeeff0011",
+ "lib/arm64-v8a/libdicore.so" to "00112233445566778899",
+ ),
+ )
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ assertEquals(true, back.bundleMode)
+ assertEquals(fp.bundleEntryHashes, back.bundleEntryHashes)
+ assertEquals(3, FingerprintCodec.FORMAT_VERSION)
+ }
+
+ /** A v3 APK-mode fingerprint (bundleMode=false) also round-trips. */
+ @Test fun apkModeRoundTripStillWorks() {
+ val fp = baseFingerprint() // bundleMode=false by default
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ assertEquals(false, back.bundleMode)
+ assertEquals(emptyMap(), back.bundleEntryHashes)
+ assertEquals("release", back.variantName)
+ }
+
+ /** bundleEntryHashes keys are sorted on encode; order is stable. */
+ @Test fun bundleEntryHashesSortedOnEncode() {
+ val fp = baseFingerprint().copy(
+ bundleMode = true,
+ bundleEntryHashes = mapOf(
+ "lib/arm64-v8a/libfoo.so" to "cc",
+ "classes.dex" to "aa",
+ "classes2.dex" to "bb",
+ ),
+ )
+ val bytes = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ val back = FingerprintCodec.decode(ByteArrayInputStream(bytes))
+
+ // Sorted order: classes.dex, classes2.dex, lib/arm64-v8a/libfoo.so
+ val keys = back.bundleEntryHashes.keys.toList()
+ assertEquals(listOf("classes.dex", "classes2.dex", "lib/arm64-v8a/libfoo.so"), keys)
+ }
+
+ private fun baseFingerprint() = Fingerprint(
+ schemaVersion = Fingerprint.SCHEMA_VERSION,
+ builtAtEpochMs = 1_000_000L,
+ pluginVersion = "5.0.0",
+ variantName = "release",
+ applicationId = "io.ssemaj.sample",
+ signerCertSha256 = listOf("deadbeef01234567"),
+ entries = mapOf("classes.dex" to "hash0"),
+ ignoredEntries = listOf("assets/io.ssemaj.deviceintelligence/fingerprint.bin"),
+ ignoredEntryPrefixes = listOf("META-INF/"),
+ expectedSourceDirPrefix = "/data/app/",
+ expectedInstallerWhitelist = emptyList(),
+ nativeLibInventoryByAbi = mapOf("arm64-v8a" to listOf("libdicore.so")),
+ dicoreTextSha256ByAbi = mapOf("arm64-v8a" to "texthash"),
+ )
+}
+```
+
+- [ ] **Step 3: Run the test to verify it fails (missing fields)**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+cd /home/joseph/AndroidStudioProjects/DeviceIntelligence
+./gradlew :deviceintelligence-gradle:test --tests "*.FingerprintCodecTest" 2>&1 | tail -30
+```
+
+Expected: FAILED — compilation error because `Fingerprint` has no `bundleMode`/`bundleEntryHashes` field and `FORMAT_VERSION` is 2.
+
+- [ ] **Step 4: Modify plugin `Fingerprint.kt` — add v3 fields + bump SCHEMA_VERSION**
+
+In `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt`:
+
+After `val dicoreTextSha256ByAbi: Map = emptyMap(),` (line 54), add:
+
+```kotlin
+ /** v3 — true when baked for an App Bundle build (split-aware, decompressed hashing). */
+ val bundleMode: Boolean = false,
+ /**
+ * v3 — APK-relative entry path -> SHA-256 hex of the entry's DECOMPRESSED body,
+ * for `classes*.dex` + `.so` files under `lib//`. Used only in bundle mode;
+ * `entries` is left empty in bundle mode because Play re-deflates, making
+ * compressed-byte hashes unstable.
+ */
+ val bundleEntryHashes: Map = emptyMap(),
+```
+
+Change `const val SCHEMA_VERSION: Int = 2` to `const val SCHEMA_VERSION: Int = 3`.
+
+Update the KDoc comment for SCHEMA_VERSION:
+```kotlin
+ /**
+ * Bumped from 1 to 2 to add `nativeLibInventoryByAbi`, `nativeLibHashesByAbi`,
+ * and `dicoreTextSha256ByAbi`.
+ * Bumped from 2 to 3 to add `bundleMode` and `bundleEntryHashes` for App Bundle
+ * integrity support. Runtime decoder accepts v1/v2/v3; older blobs leave the new
+ * fields at their defaults (bundleMode=false, bundleEntryHashes=emptyMap()).
+ */
+ const val SCHEMA_VERSION: Int = 3
+```
+
+- [ ] **Step 5: Modify plugin `FingerprintCodec.kt` — bump FORMAT_VERSION, add v3 encode + decode**
+
+Change `const val FORMAT_VERSION: Int = 2` to `const val FORMAT_VERSION: Int = 3`.
+
+In `encode()`, after the v2 tail block (after the closing brace of the `textAbis` loop, just before `flush()`), add:
+
+```kotlin
+ // v3 tail — sorted by entry name for byte-deterministic output.
+ writeBoolean(fp.bundleMode)
+ val bundleKeys = fp.bundleEntryHashes.keys.sorted()
+ writeInt(bundleKeys.size)
+ for (k in bundleKeys) {
+ writeUTF(k)
+ writeUTF(fp.bundleEntryHashes.getValue(k))
+ }
+```
+
+In `decode()`, declare the v3 variables alongside the v2 variables. Find the block starting `var inventoryByAbi: Map> = emptyMap()` (line 190) and add two more lines after `var textHashByAbi: Map = emptyMap()`:
+
+```kotlin
+ var bundleMode = false
+ var bundleEntryHashes: Map = emptyMap()
+```
+
+After the `if (formatVersion >= 2) { ... }` block (after its closing brace, before `return Fingerprint(`), add:
+
+```kotlin
+ // v3 tail — absent on v1/v2 blobs; fields stay at their defaults.
+ if (formatVersion >= 3) {
+ bundleMode = readBoolean()
+ val bundleCount = readInt()
+ bundleEntryHashes = LinkedHashMap(bundleCount).apply {
+ repeat(bundleCount) {
+ val name = readUTF()
+ val sha = readUTF()
+ put(name, sha)
+ }
+ }
+ }
+```
+
+In the `return Fingerprint(...)` call, add the two new fields (after `dicoreTextSha256ByAbi = textHashByAbi,`):
+
+```kotlin
+ bundleMode = bundleMode,
+ bundleEntryHashes = bundleEntryHashes,
+```
+
+Also update the wire-format comment at the top of `FingerprintCodec.kt` to append:
+```
+ * --- v3 additions below ---
+ * uint8 bundleMode (0/1)
+ * uint32 bundleEntryCount
+ * utf8 entryName [bundleEntryCount times, sorted]
+ * utf8 sha256Hex [bundleEntryCount times]
+```
+
+- [ ] **Step 6: Run the test to verify it passes**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence-gradle:test --tests "*.FingerprintCodecTest" 2>&1 | tail -20
+```
+
+Expected: 3 tests, BUILD SUCCESSFUL.
+
+- [ ] **Step 7: Modify runtime `Fingerprint.kt` — add v3 fields + bump SCHEMA_VERSION**
+
+In `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt`:
+
+After `val dicoreTextSha256ByAbi: Map = emptyMap(),` (line 56), add:
+
+```kotlin
+ /** v3 — true when baked for an App Bundle build (split-aware, decompressed hashing). */
+ val bundleMode: Boolean = false,
+ /**
+ * v3 — APK-relative entry path -> SHA-256 hex of the entry's DECOMPRESSED body,
+ * for `classes*.dex` + `.so` files under `lib//`. Used only in bundle mode.
+ */
+ val bundleEntryHashes: Map = emptyMap(),
+```
+
+Change `const val SCHEMA_VERSION: Int = 2` to `const val SCHEMA_VERSION: Int = 3`.
+
+- [ ] **Step 8: Modify runtime `FingerprintCodec.kt` — bump FORMAT_VERSION, add v3 decode**
+
+Change `const val FORMAT_VERSION: Int = 2` to `const val FORMAT_VERSION: Int = 3`.
+
+Declare v3 variables alongside the v2 variables. Find the block starting `var inventoryByAbi:` (line 109) and add after `var textHashByAbi: Map = emptyMap()`:
+
+```kotlin
+ var bundleMode = false
+ var bundleEntryHashes: Map = emptyMap()
+```
+
+After the `if (formatVersion >= 2) { ... }` block's closing brace (line 149), add:
+
+```kotlin
+ if (formatVersion >= 3) {
+ bundleMode = din.readBoolean()
+ val bundleCount = readNonNegative(din.readInt(), "bundleEntryCount")
+ bundleEntryHashes = LinkedHashMap(bundleCount).apply {
+ repeat(bundleCount) {
+ val name = din.readUTF()
+ val sha = din.readUTF()
+ put(name, sha)
+ }
+ }
+ }
+```
+
+In the `return Fingerprint(...)` call, add (after `dicoreTextSha256ByAbi = textHashByAbi,`):
+
+```kotlin
+ bundleMode = bundleMode,
+ bundleEntryHashes = bundleEntryHashes,
+```
+
+Also update `FORMAT_VERSION` range in the decode require (it becomes `1..3` automatically because `FORMAT_VERSION` is now 3).
+
+Update the wire-format comment at the top to include the v3 tail entries.
+
+- [ ] **Step 9: Verify runtime module compiles**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence:compileReleaseKotlin 2>&1 | tail -20
+```
+
+Expected: BUILD SUCCESSFUL.
+
+- [ ] **Step 10: Commit**
+
+```bash
+git add \
+ deviceintelligence-gradle/build.gradle.kts \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/Fingerprint.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodec.kt \
+ deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/FingerprintCodecTest.kt \
+ deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/Fingerprint.kt \
+ deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/FingerprintCodec.kt
+git commit -m "feat(bundle): bump schema+codec to v3 — bundleMode + bundleEntryHashes"
+```
+
+---
+
+### Task 3: KeystoreSigning + AabHasher + AabSigner + BundleFingerprintBuilder
+
+**Files:**
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt`
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt`
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt`
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt`
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt` (replace inline `SigningMaterial` + `loadSigningMaterial()` with `KeystoreSigning`)
+- Create: `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt`
+- Create: `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt`
+
+**Interfaces:**
+- Consumes: `Fingerprint` v3, `FingerprintCodec` v3, `NativeLibInventory.walkRawEntries()` (unchanged).
+- Produces:
+ - `KeystoreSigning.load(keystoreFile, configuredType, keystorePassword, alias, entryPassword): KeystoreSigning.Material` where `Material(privateKey: PrivateKey, certs: List, certHashes: List)`
+ - `AabHasher.bundleEntryHashes(aab: File): Map` — keyed by normalized installed-APK entry name
+ - `AabSigner.sign(aab: File, key: PrivateKey, certs: List)`
+ - `BundleFingerprintBuilder.build(aab: File, key: ByteArray, signerCertHashes: List, playPins: Collection, pluginVersion: String, variant: String, appId: String): ByteArray`
+ - All consumed by Task 4 (`BundleIntegrityTask`).
+
+- [ ] **Step 1: Write the failing `AabHasherTest`**
+
+Create `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt`:
+
+```kotlin
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.io.TempDir
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class AabHasherTest {
+
+ @Test fun normalizesPathsAndHashesDecompressedBytes(@TempDir dir: File) {
+ val dex = "DEXBYTES_UNIQUE_CONTENT_12345".toByteArray()
+ val so = "SOBYTES_UNIQUE_CONTENT_67890".toByteArray()
+ val aab = File(dir, "app.aab")
+
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/dex/classes.dex")); z.write(dex); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/dex/classes2.dex")); z.write("C2".toByteArray()); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/lib/arm64-v8a/libdicore.so")); z.write(so); z.closeEntry()
+ // These must be excluded:
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("RESOURCES".toByteArray()); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/manifest/AndroidManifest.xml")); z.write("XML".toByteArray()); z.closeEntry()
+ }
+
+ val result = AabHasher.bundleEntryHashes(aab)
+
+ // Entry names use installed-APK keys, not bundle keys.
+ assertEquals(
+ setOf("classes.dex", "classes2.dex", "lib/arm64-v8a/libdicore.so"),
+ result.keys,
+ )
+ // Hash is the decompressed (inflated) SHA-256.
+ assertEquals(sha256Hex(dex), result["classes.dex"])
+ assertEquals(sha256Hex(so), result["lib/arm64-v8a/libdicore.so"])
+ // Resources and manifest are excluded.
+ assertFalse("base/resources.pb" in result.keys)
+ assertFalse("resources.pb" in result.keys)
+ }
+
+ @Test fun emptyAabProducesEmptyMap(@TempDir dir: File) {
+ val aab = File(dir, "empty.aab")
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("R".toByteArray()); z.closeEntry()
+ }
+ assertEquals(emptyMap(), AabHasher.bundleEntryHashes(aab))
+ }
+
+ private fun sha256Hex(b: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+}
+```
+
+- [ ] **Step 2: Run to confirm FAIL**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence-gradle:test --tests "*.AabHasherTest" 2>&1 | tail -20
+```
+
+Expected: FAILED — `AabHasher` not found.
+
+- [ ] **Step 3: Create `KeystoreSigning.kt`**
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import java.io.File
+import java.io.FileInputStream
+import java.security.KeyStore
+import java.security.MessageDigest
+import java.security.PrivateKey
+import java.security.cert.X509Certificate
+
+/**
+ * Shared keystore-load helper shared between [InstrumentApkTask] and
+ * [BundleIntegrityTask]. Extracted here so both tasks load signing material
+ * identically without duplicating the PKCS12 / JKS fallback logic.
+ */
+internal object KeystoreSigning {
+
+ data class Material(
+ val privateKey: PrivateKey,
+ val certs: List,
+ val certHashes: List,
+ )
+
+ /**
+ * Load [Material] from [keystoreFile]. Tries [configuredType] first (if non-null),
+ * then PKCS12, then JKS. Throws [IllegalStateException] if none succeeds.
+ */
+ fun load(
+ keystoreFile: File,
+ configuredType: String?,
+ keystorePassword: String,
+ alias: String,
+ entryPassword: String?,
+ ): Material {
+ require(keystoreFile.isFile) { "keystore not found: $keystoreFile" }
+
+ val candidates = buildList {
+ if (!configuredType.isNullOrEmpty()) add(configuredType.uppercase())
+ add("PKCS12")
+ add("JKS")
+ }.distinct()
+
+ var ks: KeyStore? = null
+ var lastError: Throwable? = null
+ for (type in candidates) {
+ try {
+ val candidate = KeyStore.getInstance(type)
+ FileInputStream(keystoreFile).use { candidate.load(it, keystorePassword.toCharArray()) }
+ ks = candidate
+ break
+ } catch (e: Throwable) {
+ lastError = e
+ }
+ }
+ ks ?: throw IllegalStateException(
+ "Failed to load keystore $keystoreFile as any of $candidates",
+ lastError,
+ )
+
+ val pwd = (entryPassword ?: keystorePassword).toCharArray()
+ val privateKey = ks.getKey(alias, pwd) as? PrivateKey
+ ?: error("alias '$alias' has no PrivateKey entry in $keystoreFile")
+ val rawChain = ks.getCertificateChain(alias)
+ ?: ks.getCertificate(alias)?.let { arrayOf(it) }
+ ?: error("alias '$alias' has no certificate in $keystoreFile")
+ val certs = rawChain.map {
+ require(it is X509Certificate) { "non-X.509 cert in chain: ${it::class}" }
+ it
+ }
+ val md = MessageDigest.getInstance("SHA-256")
+ val certHashes = certs.map { cert ->
+ md.reset()
+ md.digest(cert.encoded).joinToString("") { b -> "%02x".format(b) }
+ }
+ return Material(privateKey, certs, certHashes)
+ }
+}
+```
+
+- [ ] **Step 4: Refactor `InstrumentApkTask.kt` to use `KeystoreSigning`**
+
+In `InstrumentApkTask.kt`:
+
+Remove the private `data class SigningMaterial(...)` (lines 431–435) and the private `fun loadSigningMaterial(...)` (lines 437–488).
+
+Change the call site at line 149:
+```kotlin
+ val signing = loadSigningMaterial(
+ keystoreFile = keystoreFile.get().asFile,
+ configuredType = keystoreType.orNull,
+ keystorePassword = keystorePassword.get(),
+ alias = keyAlias.get(),
+ entryPassword = keyPassword.orNull,
+ )
+```
+to:
+```kotlin
+ val signing = KeystoreSigning.load(
+ keystoreFile = keystoreFile.get().asFile,
+ configuredType = keystoreType.orNull,
+ keystorePassword = keystorePassword.get(),
+ alias = keyAlias.get(),
+ entryPassword = keyPassword.orNull,
+ )
+```
+
+Replace all remaining uses of `signing.privateKey`, `signing.certs`, `signing.certHashes` — these names are the same in `KeystoreSigning.Material`, so no further changes are needed.
+
+Remove the `import` for `FileInputStream` if it's no longer used directly in `InstrumentApkTask` (check remaining usages first).
+
+- [ ] **Step 5: Create `AabHasher.kt`**
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipFile
+
+/**
+ * Reads an Android App Bundle (`.aab`) and returns the SHA-256 of the
+ * DECOMPRESSED body of every `classes*.dex` and `.so` entry under `lib//`
+ * in the base module, keyed by the APK-relative path the runtime sees on-device:
+ *
+ * `base/dex/classes.dex` → `classes.dex`
+ * `base/lib/arm64-v8a/libdicore.so` → `lib/arm64-v8a/libdicore.so`
+ *
+ * We hash the decompressed bytes (not the compressed body, as APK mode does)
+ * because Play re-encodes split APKs during delivery — only the inflated
+ * payload is stable between build time and the installed device.
+ *
+ * Resources and the manifest are intentionally excluded: they are covered
+ * transitively by the signer pin, and Play rewrites `resources.pb` to binary
+ * `resources.arsc` so a byte hash would never match.
+ */
+internal object AabHasher {
+
+ fun bundleEntryHashes(aab: File): Map {
+ val out = LinkedHashMap()
+ ZipFile(aab).use { zf ->
+ val entries = zf.entries()
+ while (entries.hasMoreElements()) {
+ val e = entries.nextElement()
+ if (e.isDirectory) continue
+ val apkPath = when {
+ e.name.startsWith("base/dex/") && e.name.endsWith(".dex") ->
+ e.name.removePrefix("base/dex/") // classes.dex
+ e.name.startsWith("base/lib/") && e.name.endsWith(".so") ->
+ e.name.removePrefix("base/") // lib//.so
+ else -> null
+ } ?: continue
+
+ val md = MessageDigest.getInstance("SHA-256")
+ // ZipFile.getInputStream yields the DECOMPRESSED bytes regardless of
+ // the entry's compression method — this is what we want.
+ zf.getInputStream(e).use { ins ->
+ val buf = ByteArray(64 * 1024)
+ while (true) {
+ val n = ins.read(buf)
+ if (n < 0) break
+ md.update(buf, 0, n)
+ }
+ }
+ out[apkPath] = md.digest().joinToString("") { b -> "%02x".format(b) }
+ }
+ }
+ return out
+ }
+}
+```
+
+- [ ] **Step 6: Create `AabSigner.kt`**
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt
+package io.ssemaj.deviceintelligence.gradle.internal
+
+import jdk.security.jarsigner.JarSigner
+import java.io.File
+import java.io.FileOutputStream
+import java.security.PrivateKey
+import java.security.cert.CertificateFactory
+import java.security.cert.X509Certificate
+import java.util.zip.ZipFile
+
+/**
+ * JAR-signs (v1 / "JAR signing") a modified `.aab` so `bundletool validate`
+ * and Play accept it after the plugin injects the bundle-mode fingerprint asset.
+ *
+ * Uses the JDK's in-process [JarSigner] (module `jdk.jartool`). The input
+ * `.aab` must contain ONLY file entries — bundletool rejects directory entries.
+ * [BundleIntegrityTask] is responsible for emitting a clean repack;
+ * this signer copies entries through verbatim.
+ *
+ * Single-signer only (matching [InstrumentApkTask]).
+ */
+internal object AabSigner {
+
+ fun sign(aab: File, key: PrivateKey, certs: List) {
+ require(certs.isNotEmpty()) { "no signer certificates supplied for $aab" }
+ val certPath = CertificateFactory.getInstance("X.509").generateCertPath(certs)
+ val signer = JarSigner.Builder(key, certPath)
+ .digestAlgorithm("SHA-256")
+ .signerName("DI")
+ .build()
+
+ // JarSigner requires distinct input/output streams. Sign to a temp
+ // sibling then atomically replace the original.
+ val signed = File(aab.parentFile, "${aab.name}.signed")
+ ZipFile(aab).use { zf ->
+ FileOutputStream(signed).use { out -> signer.sign(zf, out) }
+ }
+ if (!signed.renameTo(aab)) {
+ signed.copyTo(aab, overwrite = true)
+ signed.delete()
+ }
+ }
+}
+```
+
+- [ ] **Step 7: Create `BundleFingerprintBuilder.kt`**
+
+**DI-specific adaptation:** RASP's `BundleFingerprintBuilder` calls `DiBaker.fpKey(seed)` and produces a `seed ‖ XOR(cbo, fpKey(seed))` envelope. DI has no `DiBaker`; it uses the pre-shared `key.bin` from `GenerateKeyChunksTask`. The builder here takes `key: ByteArray` directly and produces `XOR(cbo, key)` — the same format `FingerprintDecoder.decode()` already decrypts at runtime.
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.AabHasher
+import io.ssemaj.deviceintelligence.gradle.internal.Fingerprint
+import io.ssemaj.deviceintelligence.gradle.internal.FingerprintCodec
+import io.ssemaj.deviceintelligence.gradle.internal.NativeLibInventory
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.zip.ZipFile
+
+/**
+ * Pure builder for the bundle-mode fingerprint blob baked into an AAB's base
+ * assets. Kept free of AGP/Gradle types so it can be unit-tested directly.
+ *
+ * Encryption: `XOR(encode(fp), key)` — the same scheme APK mode uses
+ * ([InstrumentApkTask] reads `key.bin` from [GenerateKeyChunksTask] and XORs).
+ * At runtime [KeyResolver.assembleKey] returns the same key; [FingerprintDecoder]
+ * XOR-decrypts and passes to [FingerprintCodec.decode].
+ *
+ * DI divergence from RASP: RASP uses `DiBaker.fpKey(seed)` producing a
+ * `seed ‖ ciphertext` envelope. DI has no DiBaker — the caller passes `key`
+ * (the 32-byte `key.bin`) and the output is simply `XOR(cbo, key)`.
+ */
+internal object BundleFingerprintBuilder {
+
+ /**
+ * Build the encrypted bundle-mode fingerprint blob for [aab].
+ *
+ * @param aab The `.aab` file (AGP-built, before injection).
+ * @param key The 32-byte per-build XOR key from `GenerateKeyChunksTask.keyFile`.
+ * @param signerCertHashes SHA-256 hex hashes of the upload-key cert(s).
+ * @param playPins Play App Signing cert SHA-256(s) declared in `appBundle.playSigningCertSha256`.
+ * @param pluginVersion Plugin version string baked into the fingerprint.
+ * @param variant AGP variant name (e.g. `"release"`).
+ * @param appId Application ID.
+ * @return `XOR(FingerprintCodec.encode(fp), key)` as a byte array.
+ */
+ fun build(
+ aab: File,
+ key: ByteArray,
+ signerCertHashes: List,
+ playPins: Collection,
+ pluginVersion: String,
+ variant: String,
+ appId: String,
+ ): ByteArray {
+ val bundleEntries = AabHasher.bundleEntryHashes(aab)
+ val nativeFp = NativeLibInventory.walkRawEntries(aabBaseLibEntries(aab))
+
+ // Membership allow-set: upload-key cert(s) ∪ Play App Signing pins, de-duped.
+ val signerAllowSet = (signerCertHashes + playPins).distinct()
+
+ val fp = Fingerprint(
+ schemaVersion = Fingerprint.SCHEMA_VERSION,
+ builtAtEpochMs = System.currentTimeMillis(),
+ pluginVersion = pluginVersion,
+ variantName = variant,
+ applicationId = appId,
+ signerCertSha256 = signerAllowSet,
+ // Bundle mode does not bake compressed-byte entry hashes — Play re-deflates.
+ entries = emptyMap(),
+ ignoredEntries = emptyList(),
+ ignoredEntryPrefixes = emptyList(),
+ expectedSourceDirPrefix = "/data/app/",
+ expectedInstallerWhitelist = emptyList(),
+ nativeLibInventoryByAbi = nativeFp.inventoryByAbi,
+ nativeLibHashesByAbi = nativeFp.fileHashesByAbi,
+ dicoreTextSha256ByAbi = nativeFp.dicoreTextSha256ByAbi,
+ bundleMode = true,
+ bundleEntryHashes = bundleEntries,
+ )
+
+ val cbo = ByteArrayOutputStream().apply { FingerprintCodec.encode(fp, this) }.toByteArray()
+ return ByteArray(cbo.size).also { out ->
+ for (i in cbo.indices) {
+ out[i] = (cbo[i].toInt() xor key[i % key.size].toInt()).toByte()
+ }
+ }
+ }
+
+ /**
+ * Stream the AAB's `base/lib//.so` entries as
+ * `lib//.so` (APK-relative) path + decompressed body pairs,
+ * so [NativeLibInventory.walkRawEntries] computes the ELF `.text`
+ * baseline identically to APK mode.
+ */
+ private fun aabBaseLibEntries(aab: File): Sequence> {
+ val list = ArrayList>()
+ ZipFile(aab).use { zf ->
+ val it = zf.entries()
+ while (it.hasMoreElements()) {
+ val e = it.nextElement()
+ if (e.isDirectory) continue
+ if (!e.name.startsWith("base/lib/") || !e.name.endsWith(".so")) continue
+ val apkPath = e.name.removePrefix("base/") // lib//.so
+ val bytes = zf.getInputStream(e).use { s -> s.readBytes() }
+ list += apkPath to bytes
+ }
+ }
+ return list.asSequence()
+ }
+}
+```
+
+- [ ] **Step 8: Write `BundleFingerprintBuilderTest`**
+
+Create `deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt`.
+
+First, create the directory:
+```bash
+mkdir -p /home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks
+```
+
+```kotlin
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.FingerprintCodec
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Assertions.assertFalse
+import org.junit.jupiter.api.Assertions.assertTrue
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.io.TempDir
+import java.io.ByteArrayInputStream
+import java.io.File
+import java.security.MessageDigest
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class BundleFingerprintBuilderTest {
+
+ @Test fun blobDecodesToBundleModeWithMergedSigners(@TempDir dir: File) {
+ val dex = "DEXBYTES".toByteArray()
+ val so = "SOBYTES".toByteArray()
+ val aab = File(dir, "app.aab")
+ ZipOutputStream(aab.outputStream()).use { z ->
+ z.putNextEntry(ZipEntry("base/dex/classes.dex")); z.write(dex); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/lib/arm64-v8a/libother.so")); z.write(so); z.closeEntry()
+ z.putNextEntry(ZipEntry("base/resources.pb")); z.write("R".toByteArray()); z.closeEntry()
+ }
+
+ val key = ByteArray(32) { it.toByte() } // deterministic test key
+
+ val blob = BundleFingerprintBuilder.build(
+ aab = aab,
+ key = key,
+ signerCertHashes = listOf("aa11"),
+ playPins = listOf("bb22", "aa11"), // overlap must be de-duplicated
+ pluginVersion = "5.0.0",
+ variant = "release",
+ appId = "io.ssemaj.sample",
+ )
+
+ // Decrypt: XOR with the same key.
+ val plain = ByteArray(blob.size) { i -> (blob[i].toInt() xor key[i % 32].toInt()).toByte() }
+ val fp = FingerprintCodec.decode(ByteArrayInputStream(plain))
+
+ assertTrue(fp.bundleMode)
+ assertEquals(sha256Hex(dex), fp.bundleEntryHashes["classes.dex"])
+ assertEquals(sha256Hex(so), fp.bundleEntryHashes["lib/arm64-v8a/libother.so"])
+ assertFalse("base/resources.pb" in fp.bundleEntryHashes.keys)
+ // De-duplicated merged signer allow-set.
+ assertEquals(setOf("aa11", "bb22"), fp.signerCertSha256.toSet())
+ assertEquals("io.ssemaj.sample", fp.applicationId)
+ // APK-mode entries is empty in bundle mode.
+ assertTrue(fp.entries.isEmpty())
+ }
+
+ private fun sha256Hex(b: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+}
+```
+
+- [ ] **Step 9: Run all plugin tests**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence-gradle:test 2>&1 | tail -30
+```
+
+Expected: all tests pass (`FingerprintCodecTest` × 3, `AabHasherTest` × 2, `BundleFingerprintBuilderTest` × 1). BUILD SUCCESSFUL.
+
+- [ ] **Step 10: Commit**
+
+```bash
+git add \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/KeystoreSigning.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasher.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabSigner.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilder.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/InstrumentApkTask.kt \
+ deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/internal/AabHasherTest.kt \
+ deviceintelligence-gradle/src/test/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleFingerprintBuilderTest.kt
+git commit -m "feat(bundle): KeystoreSigning, AabHasher, AabSigner, BundleFingerprintBuilder"
+```
+
+---
+
+### Task 4: BundleIntegrityTask + Plugin Gate
+
+**Files:**
+- Create: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt`
+- Modify: `deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt`
+
+**Interfaces:**
+- Consumes: `BundleFingerprintBuilder.build(...)`, `AabSigner.sign(...)`, `KeystoreSigning.load(...)`, `GenerateKeyChunksTask.keyFile`, `AppBundleOptions.enabled`, `AppBundleOptions.playSigningCertSha256`.
+- Produces: wired `SingleArtifact.BUNDLE` transform on the consumer's AAB. The APK transform (`InstrumentApkTask`) is skipped entirely for variants where `bundleMode=true`.
+
+- [ ] **Step 1: Create `BundleIntegrityTask.kt`**
+
+```kotlin
+// deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt
+package io.ssemaj.deviceintelligence.gradle.tasks
+
+import io.ssemaj.deviceintelligence.gradle.internal.AabSigner
+import io.ssemaj.deviceintelligence.gradle.internal.Fingerprint
+import io.ssemaj.deviceintelligence.gradle.internal.KeystoreSigning
+import org.gradle.api.DefaultTask
+import org.gradle.api.file.RegularFileProperty
+import org.gradle.api.provider.Property
+import org.gradle.api.provider.SetProperty
+import org.gradle.api.tasks.Input
+import org.gradle.api.tasks.InputFile
+import org.gradle.api.tasks.Optional
+import org.gradle.api.tasks.OutputFile
+import org.gradle.api.tasks.PathSensitive
+import org.gradle.api.tasks.PathSensitivity
+import org.gradle.api.tasks.TaskAction
+import java.io.File
+import java.util.zip.CRC32
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
+
+/**
+ * App Bundle ("bundle mode") integrity transform over [SingleArtifact.BUNDLE].
+ *
+ * AGP hands us the just-built, AGP-signed `.aab`; we:
+ * 1. Bake the v3 bundle-mode fingerprint blob (decompressed dex/`.so` hashes +
+ * signer allow-set) with [BundleFingerprintBuilder].
+ * 2. Repack the AAB with `base/assets/io.ssemaj.deviceintelligence/fingerprint.bin`
+ * injected as a STORED entry, stripping the old `META-INF/` signature and any
+ * pre-existing fingerprint. ONLY file entries are emitted — bundletool rejects
+ * directory entries in a re-packed AAB.
+ * 3. JAR-re-sign the result with [AabSigner].
+ *
+ * Encryption: `XOR(encode(fp), key)` using the per-build `key.bin` from
+ * [GenerateKeyChunksTask]. At runtime [FingerprintDecoder] decrypts with the
+ * same key recovered via [KeyResolver.assembleKey].
+ */
+abstract class BundleIntegrityTask : DefaultTask() {
+
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val inputAab: RegularFileProperty
+
+ @get:OutputFile
+ abstract val outputAab: RegularFileProperty
+
+ /** Per-build XOR key from [GenerateKeyChunksTask]. */
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val keyFile: RegularFileProperty
+
+ @get:InputFile
+ @get:PathSensitive(PathSensitivity.NONE)
+ abstract val keystoreFile: RegularFileProperty
+
+ @get:Input
+ @get:Optional
+ abstract val keystoreType: Property
+
+ @get:Input
+ abstract val keystorePassword: Property
+
+ @get:Input
+ abstract val keyAlias: Property
+
+ @get:Input
+ @get:Optional
+ abstract val keyPassword: Property
+
+ /** Play App Signing cert SHA-256 pins to include in the signer allow-set. */
+ @get:Input
+ abstract val playSigningCertSha256: SetProperty
+
+ @get:Input
+ abstract val variantName: Property
+
+ @get:Input
+ abstract val applicationId: Property
+
+ @get:Input
+ abstract val pluginVersion: Property
+
+ @TaskAction
+ fun run() {
+ val key = keyFile.get().asFile.readBytes()
+ require(key.size == KEY_SIZE) {
+ "key.bin is wrong size: ${key.size}B (expected $KEY_SIZE)"
+ }
+
+ val signing = KeystoreSigning.load(
+ keystoreFile = keystoreFile.get().asFile,
+ configuredType = keystoreType.orNull,
+ keystorePassword = keystorePassword.get(),
+ alias = keyAlias.get(),
+ entryPassword = keyPassword.orNull,
+ )
+
+ val input = inputAab.get().asFile
+ val output = outputAab.get().asFile.apply { parentFile?.mkdirs() }
+
+ val blob = BundleFingerprintBuilder.build(
+ aab = input,
+ key = key,
+ signerCertHashes = signing.certHashes,
+ playPins = playSigningCertSha256.getOrElse(emptySet()),
+ pluginVersion = pluginVersion.get(),
+ variant = variantName.get(),
+ appId = applicationId.get(),
+ )
+ logger.lifecycle(
+ "io.ssemaj: bundle-mode fingerprint '${variantName.get()}': " +
+ "signerLeaf=${signing.certHashes.firstOrNull()}, " +
+ "playPins=${playSigningCertSha256.getOrElse(emptySet()).size}, " +
+ "bundleEntries=${blob.size}B"
+ )
+
+ injectAsset(input, output, BUNDLE_ASSET_PATH to blob)
+ AabSigner.sign(output, signing.privateKey, signing.certs)
+
+ logger.lifecycle(
+ "io.ssemaj: bundle-mode integrity → ${output.relativeTo(project.rootDir)} (asset injected, re-signed)"
+ )
+ }
+
+ /**
+ * Copies every file entry from [input] to [output], DROPPING `META-INF/`
+ * (old signature), any pre-existing fingerprint asset, and all directory
+ * entries (bundletool rejects them in a re-packed AAB); then appends
+ * [additional] as a STORED entry.
+ */
+ private fun injectAsset(input: File, output: File, additional: Pair) {
+ if (output.exists()) output.delete()
+ ZipFile(input).use { zf ->
+ ZipOutputStream(output.outputStream().buffered()).use { zos ->
+ val it = zf.entries()
+ while (it.hasMoreElements()) {
+ val e = it.nextElement()
+ if (e.isDirectory) continue
+ if (e.name.startsWith("META-INF/")) continue
+ if (e.name == additional.first) continue
+ val bytes = zf.getInputStream(e).use { s -> s.readBytes() }
+ val method = if (e.method == ZipEntry.STORED) ZipEntry.STORED else ZipEntry.DEFLATED
+ writeEntry(zos, e.name, bytes, method, e.time)
+ }
+ writeEntry(zos, additional.first, additional.second, ZipEntry.STORED, 0L)
+ }
+ }
+ }
+
+ private fun writeEntry(zos: ZipOutputStream, name: String, data: ByteArray, method: Int, time: Long) {
+ val entry = ZipEntry(name).apply {
+ this.method = method
+ this.time = time
+ if (method == ZipEntry.STORED) {
+ size = data.size.toLong()
+ compressedSize = data.size.toLong()
+ crc = CRC32().apply { update(data) }.value
+ }
+ }
+ zos.putNextEntry(entry)
+ zos.write(data)
+ zos.closeEntry()
+ }
+
+ private companion object {
+ /** Fingerprint asset path inside the AAB's base module. */
+ val BUNDLE_ASSET_PATH: String = "base/" + Fingerprint.ASSET_PATH
+ const val KEY_SIZE: Int = 32
+ }
+}
+```
+
+- [ ] **Step 2: Wire `BundleIntegrityTask` in `DeviceIntelligencePlugin.kt`**
+
+In `DeviceIntelligencePlugin.kt`, add an import at the top:
+
+```kotlin
+import io.ssemaj.deviceintelligence.gradle.tasks.BundleIntegrityTask
+```
+
+Inside `wireApplication()`, after the signing-material null-checks (after the block ending `return@onVariants` at line 180) but **before** the existing variant title / task-name lines (line 182), insert the bundle-mode gate:
+
+```kotlin
+ // App Bundle mode and APK instrumentation are mutually exclusive.
+ // When bundle mode is enabled, register BundleIntegrityTask on
+ // SingleArtifact.BUNDLE and skip the APK transform for this variant.
+ val bundleModeEnabled = ext.appBundle.enabled.getOrElse(false)
+ if (bundleModeEnabled) {
+ project.logger.lifecycle(
+ "io.ssemaj: appBundle.enabled=true — APK integrity transform skipped " +
+ "for variant '${variant.name}'; bundle-mode integrity applies"
+ )
+ val bundleTitle = variant.name.replaceFirstChar { it.uppercase() }
+ val bundleTask = project.tasks.register(
+ "bundle${bundleTitle}DeviceIntelligenceIntegrity",
+ ) {
+ group = "io.ssemaj"
+ description = "Bakes bundle-mode fingerprint into the AAB and re-signs it " +
+ "(variant '${variant.name}')."
+
+ keyFile.set(genKeyTask.flatMap { it.keyFile })
+ keystoreFile.fileValue(cfgStoreFile)
+ keystorePassword.set(cfgStorePassword)
+ keyAlias.set(cfgKeyAlias)
+ if (cfgKeyPassword != null) keyPassword.set(cfgKeyPassword)
+ if (!cfgStoreType.isNullOrBlank()) keystoreType.set(cfgStoreType)
+ playSigningCertSha256.set(ext.appBundle.playSigningCertSha256)
+ variantName.set(variant.name)
+ applicationId.set(variant.applicationId)
+ pluginVersion.set(PLUGIN_VERSION)
+ }
+
+ variant.artifacts.use(bundleTask)
+ .wiredWithFiles(
+ BundleIntegrityTask::inputAab,
+ BundleIntegrityTask::outputAab,
+ )
+ .toTransform(SingleArtifact.BUNDLE)
+
+ project.afterEvaluate {
+ if (ext.verbose.getOrElse(false)) {
+ project.logger.lifecycle(
+ "io.ssemaj: registered ${bundleTask.name} (BUNDLE transform)"
+ )
+ }
+ }
+ return@onVariants // skip APK transform for this variant
+ }
+```
+
+Note: `genKeyTask` is declared later in the method (line ~196). You must move `genKeyTask` registration to **before** the bundle-mode gate. Specifically, move the `val genKeyTask = project.tasks.register(...)` block and its source-set wiring up to immediately after the signing-material null-checks but before the bundle-mode gate. The gate then references `genKeyTask` (for `keyFile`); the `return@onVariants` exits so the downstream APK tasks are never registered for bundle-mode variants.
+
+- [ ] **Step 3: Verify the plugin compiles**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence-gradle:compileKotlin 2>&1 | tail -20
+```
+
+Expected: BUILD SUCCESSFUL.
+
+- [ ] **Step 4: Verify all plugin tests still pass**
+
+```bash
+./gradlew :deviceintelligence-gradle:test 2>&1 | tail -20
+```
+
+Expected: BUILD SUCCESSFUL (same 6 tests).
+
+- [ ] **Step 5: Smoke-test in the sample (APK mode, no regression)**
+
+```bash
+./gradlew :samples:minimal:assembleDebug 2>&1 | tail -20
+```
+
+Expected: BUILD SUCCESSFUL. The sample's debug build uses APK mode (no `appBundle.enabled`); this verifies the plugin gate doesn't break the existing path.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/tasks/BundleIntegrityTask.kt \
+ deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/DeviceIntelligencePlugin.kt
+git commit -m "feat(bundle): BundleIntegrityTask + plugin gate (SingleArtifact.BUNDLE transform)"
+```
+
+---
+
+### Task 5: Native — zlib inflate path + JNI + NativeBridge + host C++ test
+
+**Files:**
+- Modify: `deviceintelligence/src/main/cpp/CMakeLists.txt` (lines 64–71)
+- Modify: `deviceintelligence/src/main/cpp/dicore/zip_parser.h`
+- Modify: `deviceintelligence/src/main/cpp/dicore/zip_parser.cpp`
+- Modify: `deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp`
+- Modify: `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt`
+- Create: `deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp`
+
+**Interfaces:**
+- Consumes: existing `ApkMap`, `find_central_directory`, `sha::sha256`, `hex::encode`.
+- Produces:
+ - C++: `bool dicore::zip::hash_entry_decompressed(const ApkMap& apk, const CentralDirInfo& cdi, const char* entry_name, uint8_t out32[32])`
+ - JNI: `Java_io_ssemaj_deviceintelligence_internal_NativeBridge_apkEntryDecompressedHash` → `String?`
+ - Kotlin: `external fun apkEntryDecompressedHash(path: String, entryName: String): String?`
+ - All consumed by Task 6 (`ApkIntegrityDetector`).
+
+- [ ] **Step 1: Write the host C++ test first**
+
+Create `deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp`:
+
+```cpp
+// Host test for dicore::zip::hash_entry_decompressed.
+// Compile: see step 2. Run on x86_64 Android emulator via ADB.
+#include "dicore/zip_parser.h"
+#include "dicore/apkmap.h"
+#include "dicore/sha256.h"
+#include "dicore/hex.h"
+
+#include
+#include
+#include
+#include
+#include
+
+using namespace dicore;
+
+// ---- Minimal ZIP writer -----------------------------------------------
+static void w16(std::vector& v, uint16_t x) { v.push_back(x&0xFF); v.push_back(x>>8); }
+static void w32(std::vector& v, uint32_t x) { for(int i=0;i<4;i++){v.push_back(x&0xFF);x>>=8;} }
+
+struct CdEntry { std::string name; uint32_t lfh_off, comp_sz, uncomp_sz, crc32v; uint16_t method; };
+
+static uint32_t crc32_buf(const uint8_t* p, size_t n) {
+ return (uint32_t)::crc32(::crc32(0L, Z_NULL, 0), p, (uInt)n);
+}
+
+static void emit_lfh(std::vector& v, CdEntry& e) {
+ e.lfh_off = (uint32_t)v.size();
+ w32(v,0x04034b50u); w16(v,20); w16(v,0); w16(v,e.method);
+ w16(v,0); w16(v,0);
+ w32(v,e.crc32v); w32(v,e.comp_sz); w32(v,e.uncomp_sz);
+ w16(v,(uint16_t)e.name.size()); w16(v,0);
+ for(char c:e.name) v.push_back((uint8_t)c);
+}
+
+static std::vector build_zip(
+ const char* stored_name, const uint8_t* stored_data, uint32_t stored_len,
+ const char* deflated_name, const uint8_t* plain, uint32_t plain_len)
+{
+ std::vector zip;
+ std::vector entries;
+
+ // STORED entry
+ {
+ CdEntry e; e.name=stored_name; e.method=0;
+ e.uncomp_sz=stored_len; e.comp_sz=stored_len;
+ e.crc32v=crc32_buf(stored_data,stored_len);
+ emit_lfh(zip,e);
+ for(uint32_t i=0;i comp(compressBound(plain_len));
+ z_stream zs{}; deflateInit2(&zs,Z_DEFAULT_COMPRESSION,Z_DEFLATED,-MAX_WBITS,8,Z_DEFAULT_STRATEGY);
+ zs.next_in=const_cast(plain); zs.avail_in=plain_len;
+ zs.next_out=comp.data(); zs.avail_out=(uInt)comp.size();
+ deflate(&zs,Z_FINISH); uint32_t csz=(uint32_t)zs.total_out; deflateEnd(&zs);
+
+ CdEntry e; e.name=deflated_name; e.method=8;
+ e.uncomp_sz=plain_len; e.comp_sz=csz;
+ e.crc32v=crc32_buf(plain,plain_len);
+ emit_lfh(zip,e);
+ for(uint32_t i=0;i& data) {
+ FILE* f=fopen(path,"wb"); assert(f);
+ fwrite(data.data(),1,data.size(),f); fclose(f);
+}
+
+int main() {
+ // Init SHA backend (dlopen BoringSSL on Android)
+ assert(sha::ensure_initialized());
+
+ const char STORED_DATA[] = "STORED_PAYLOAD_BYTES_FOR_TESTING";
+ const uint32_t STORED_LEN = (uint32_t)strlen(STORED_DATA);
+ const char DEFLATED_DATA[] = "DEFLATED_PAYLOAD_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+ const uint32_t DEFLATED_LEN = (uint32_t)strlen(DEFLATED_DATA);
+
+ auto zip = build_zip(
+ "stored.txt", (const uint8_t*)STORED_DATA, STORED_LEN,
+ "deflated.txt", (const uint8_t*)DEFLATED_DATA, DEFLATED_LEN
+ );
+ const char* path = "/data/local/tmp/di_test_inflate.zip";
+ write_file(path, zip);
+
+ ApkMap apk; assert(apk.open(path));
+ zip::CentralDirInfo cdi; assert(zip::find_central_directory(apk, &cdi));
+
+ // Test 1: STORED entry — hash equals SHA-256 of the plain bytes
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "stored.txt", out);
+ assert(ok);
+ std::string want = sha256_hex_of(STORED_DATA, STORED_LEN);
+ std::string got = hex::encode(out, 32);
+ assert(want == got && "Test1 STORED hash mismatch");
+ printf("PASS test1: STORED hash = %s\n", got.c_str());
+ }
+
+ // Test 2: DEFLATED entry — hash equals SHA-256 of the INFLATED (plain) bytes
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "deflated.txt", out);
+ assert(ok);
+ std::string want = sha256_hex_of(DEFLATED_DATA, DEFLATED_LEN);
+ std::string got = hex::encode(out, 32);
+ assert(want == got && "Test2 DEFLATED hash mismatch (got compressed hash?)");
+ printf("PASS test2: DEFLATED decompressed hash = %s\n", got.c_str());
+ }
+
+ // Test 3: missing entry returns false, no crash
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, "does_not_exist.bin", out);
+ assert(!ok && "Test3 missing entry should return false");
+ printf("PASS test3: missing entry returns false\n");
+ }
+
+ // Test 4: null entry_name returns false, no crash
+ {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(apk, cdi, nullptr, out);
+ assert(!ok && "Test4 null entry_name should return false");
+ printf("PASS test4: null entry_name returns false\n");
+ }
+
+ // Test 5: garbage file (not a ZIP) — find_central_directory fails
+ {
+ const char* bad = "/data/local/tmp/di_garbage.bin";
+ {FILE* f=fopen(bad,"wb"); const char g[]={0xDE,0xAD,0xBE,0xEF,0x00}; fwrite(g,1,4,f); fclose(f);}
+ ApkMap bad_apk; bad_apk.open(bad);
+ zip::CentralDirInfo bad_cdi;
+ bool has_cd = zip::find_central_directory(bad_apk, &bad_cdi);
+ if (has_cd) {
+ uint8_t out[32];
+ bool ok = zip::hash_entry_decompressed(bad_apk, bad_cdi, "anything", out);
+ assert(!ok);
+ }
+ printf("PASS test5: garbage file handled safely (has_cd=%d)\n", (int)has_cd);
+ }
+
+ printf("ALL TESTS PASSED\n");
+ return 0;
+}
+```
+
+- [ ] **Step 2: Compile and run the test (expect FAIL — `hash_entry_decompressed` not yet declared)**
+
+```bash
+CLANG=$HOME/Android/Sdk/ndk/27.0.12077973/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android35-clang++
+SRC=/home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence/src/main/cpp
+TSRC=/home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence/src/test/cpp
+mkdir -p $TSRC
+$CLANG -std=c++17 -Wall -Wextra -Werror \
+ -I$SRC \
+ $SRC/dicore/zip_parser.cpp \
+ $SRC/dicore/apkmap.cpp \
+ $SRC/dicore/sha256.cpp \
+ $SRC/dicore/hex.cpp \
+ $SRC/dicore/syscalls.cpp \
+ $TSRC/test_hash_entry_decompressed.cpp \
+ -llog -lz -pie -fPIE \
+ -o /tmp/di_test_inflate 2>&1 | tail -20
+```
+
+Expected: compile error — `hash_entry_decompressed` not declared.
+
+- [ ] **Step 3: Modify `CMakeLists.txt` — link zlib**
+
+In `deviceintelligence/src/main/cpp/CMakeLists.txt`, after `find_library(android-lib android)` (line 65), add:
+
+```cmake
+find_library(z-lib z)
+```
+
+In the `target_link_libraries(dicore ...)` block (lines 67–70), add `${z-lib}`:
+
+```cmake
+target_link_libraries(dicore
+ ${log-lib}
+ ${android-lib}
+ ${z-lib}
+ dl
+)
+```
+
+- [ ] **Step 4: Add `hash_entry_decompressed` declaration to `zip_parser.h`**
+
+In `deviceintelligence/src/main/cpp/dicore/zip_parser.h`, after the `hash_all_entries` declaration (line 44), add:
+
+```cpp
+// Hash the DECOMPRESSED body of the ZIP entry named `entry_name`.
+// For STORED entries, SHA-256 the raw body directly.
+// For DEFLATED entries, inflate via NDK zlib (raw deflate, inflateInit2(-MAX_WBITS))
+// into a bounded buffer and SHA-256 the inflated bytes.
+// Writes 32 bytes to out32 on success and returns true.
+// Returns false (fail-closed, no crash) if: entry not found, null entry_name,
+// ZIP64 sentinel, zlib error, inflated size > 64 MB guard, or body out of range.
+bool hash_entry_decompressed(const ApkMap& apk,
+ const CentralDirInfo& cdi,
+ const char* entry_name,
+ uint8_t out32[32]);
+```
+
+- [ ] **Step 5: Implement `hash_entry_decompressed` in `zip_parser.cpp`**
+
+At the top of `zip_parser.cpp`, after `#include `, add:
+
+```cpp
+#include
+#include
+```
+
+Inside the anonymous namespace in `zip_parser.cpp`, add the inflate guard constant:
+
+```cpp
+// Maximum decompressed entry size accepted by hash_entry_decompressed.
+// Entries larger than this are skipped (fail-closed). 64 MB covers the
+// largest realistic dex/so in production; a real tamper attempt has no
+// incentive to inflate to this size.
+constexpr size_t kMaxInflateBytes = 64u * 1024u * 1024u;
+```
+
+After the closing brace of `hash_all_entries` (line 173), before the closing `} // namespace dicore::zip`, add:
+
+```cpp
+bool hash_entry_decompressed(const ApkMap& apk,
+ const CentralDirInfo& cdi,
+ const char* entry_name,
+ uint8_t out32[32]) {
+ if (!cdi.present || !entry_name) return false;
+
+ const uint8_t* cd = apk.range((size_t)cdi.cd_offset, (size_t)cdi.cd_size);
+ if (!cd) return false;
+
+ size_t cd_off = 0;
+ for (uint64_t i = 0; i < cdi.total_entries; ++i) {
+ if (cd_off + kCdfhMinSize > (size_t)cdi.cd_size) break;
+ const uint8_t* p = cd + cd_off;
+ if (rd32(p) != kCdfhMagic) break;
+
+ uint16_t method = rd16(p + 10);
+ uint32_t comp = rd32(p + 20);
+ uint32_t uncomp = rd32(p + 24);
+ uint16_t name_len = rd16(p + 28);
+ uint16_t extra_len = rd16(p + 30);
+ uint16_t cmt_len = rd16(p + 32);
+ uint32_t lfh_off = rd32(p + 42);
+
+ size_t total_var = (size_t)name_len + extra_len + cmt_len;
+ if (cd_off + kCdfhMinSize + total_var > (size_t)cdi.cd_size) break;
+
+ std::string_view name(reinterpret_cast(p + kCdfhMinSize), name_len);
+
+ if (name == entry_name) {
+ // ZIP64 sentinel guard — skip rather than misinterpret.
+ if (comp == 0xFFFFFFFFu || uncomp == 0xFFFFFFFFu) {
+ RLOGW("zip: hash_entry_decompressed: ZIP64 entry '%s', skipping", entry_name);
+ return false;
+ }
+
+ // Resolve body offset via LFH (LFH and CDFH extra fields may differ).
+ const uint8_t* lfh = apk.range(lfh_off, kLfhMinSize);
+ if (!lfh || rd32(lfh) != kLfhMagic) return false;
+ uint16_t lfh_name_len = rd16(lfh + 26);
+ uint16_t lfh_extra_len = rd16(lfh + 28);
+ uint64_t body_off = (uint64_t)lfh_off + kLfhMinSize
+ + lfh_name_len + lfh_extra_len;
+
+ if (method == 0 /* STORED */) {
+ const uint8_t* body = apk.range((size_t)body_off, (size_t)comp);
+ if (!body) return false;
+ return sha::sha256(body, (size_t)comp, out32);
+ }
+
+ if (method == 8 /* DEFLATED */) {
+ if (uncomp > kMaxInflateBytes) {
+ RLOGW("zip: hash_entry_decompressed: uncomp_size %u > limit for '%s'",
+ uncomp, entry_name);
+ return false;
+ }
+
+ const uint8_t* comp_body = apk.range((size_t)body_off, (size_t)comp);
+ if (!comp_body) return false;
+
+ std::vector inflated((size_t)uncomp);
+
+ z_stream zs{};
+ // -MAX_WBITS = raw deflate (no zlib/gzip header).
+ if (inflateInit2(&zs, -MAX_WBITS) != Z_OK) return false;
+
+ zs.next_in = const_cast(comp_body);
+ zs.avail_in = comp;
+ zs.next_out = inflated.data();
+ zs.avail_out = uncomp;
+
+ int ret = inflate(&zs, Z_FINISH);
+ inflateEnd(&zs);
+
+ if (ret != Z_STREAM_END) {
+ RLOGW("zip: hash_entry_decompressed: inflate ret=%d for '%s'",
+ ret, entry_name);
+ return false;
+ }
+ if (zs.total_out != (uLong)uncomp) {
+ RLOGW("zip: hash_entry_decompressed: inflate wrote %lu of %u for '%s'",
+ (unsigned long)zs.total_out, uncomp, entry_name);
+ return false;
+ }
+
+ return sha::sha256(inflated.data(), (size_t)uncomp, out32);
+ }
+
+ RLOGW("zip: hash_entry_decompressed: unsupported method %u for '%s'",
+ method, entry_name);
+ return false;
+ }
+
+ cd_off += kCdfhMinSize + total_var;
+ }
+ return false; // entry not found
+}
+```
+
+- [ ] **Step 6: Compile the test and verify it builds**
+
+```bash
+CLANG=$HOME/Android/Sdk/ndk/27.0.12077973/toolchains/llvm/prebuilt/linux-x86_64/bin/x86_64-linux-android35-clang++
+SRC=/home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence/src/main/cpp
+TSRC=/home/joseph/AndroidStudioProjects/DeviceIntelligence/deviceintelligence/src/test/cpp
+$CLANG -std=c++17 -Wall -Wextra -Werror \
+ -I$SRC \
+ $SRC/dicore/zip_parser.cpp \
+ $SRC/dicore/apkmap.cpp \
+ $SRC/dicore/sha256.cpp \
+ $SRC/dicore/hex.cpp \
+ $SRC/dicore/syscalls.cpp \
+ $TSRC/test_hash_entry_decompressed.cpp \
+ -llog -lz -pie -fPIE \
+ -o /tmp/di_test_inflate 2>&1
+```
+
+Expected: clean compile, no errors/warnings. The `-Werror` flag treats all warnings as errors.
+
+- [ ] **Step 7: Push and run on x86_64 emulator**
+
+Ensure an x86_64 Android emulator is running, then:
+
+```bash
+adb push /tmp/di_test_inflate /data/local/tmp/
+adb shell chmod +x /data/local/tmp/di_test_inflate
+adb shell /data/local/tmp/di_test_inflate
+```
+
+Expected output:
+```
+PASS test1: STORED hash = <64-char hex>
+PASS test2: DEFLATED decompressed hash = <64-char hex>
+PASS test3: missing entry returns false
+PASS test4: null entry_name returns false
+PASS test5: garbage file handled safely (has_cd=0)
+ALL TESTS PASSED
+```
+
+If `test2`'s hash matches `test1`'s, the function is accidentally hashing the compressed bytes — debug the inflate path.
+
+- [ ] **Step 8: Add `apkEntryDecompressedHash` JNI function to `jni_bridge.cpp`**
+
+In `deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp`, after the closing brace of `Java_io_ssemaj_deviceintelligence_internal_NativeBridge_apkSignerCertHashes` (currently the last function, around line 102), before `} // extern "C"`, add:
+
+```cpp
+JNIEXPORT jstring JNICALL
+Java_io_ssemaj_deviceintelligence_internal_NativeBridge_apkEntryDecompressedHash(
+ JNIEnv* env, jclass, jstring jpath, jstring jentry) {
+ if (!jpath || !jentry) return nullptr;
+
+ const char* path = env->GetStringUTFChars(jpath, nullptr);
+ if (!path) return nullptr;
+ const char* entry = env->GetStringUTFChars(jentry, nullptr);
+ if (!entry) {
+ env->ReleaseStringUTFChars(jpath, path);
+ return nullptr;
+ }
+
+ ApkMap apk;
+ bool ok = apk.open(path);
+ env->ReleaseStringUTFChars(jpath, path);
+ if (!ok) {
+ RLOGE("apkEntryDecompressedHash: open failed for entry '%s'", entry);
+ env->ReleaseStringUTFChars(jentry, entry);
+ return nullptr;
+ }
+
+ zip::CentralDirInfo cdi;
+ if (!zip::find_central_directory(apk, &cdi)) {
+ env->ReleaseStringUTFChars(jentry, entry);
+ return nullptr;
+ }
+
+ uint8_t md[sha::kDigestLen];
+ bool found = zip::hash_entry_decompressed(apk, cdi, entry, md);
+ env->ReleaseStringUTFChars(jentry, entry);
+ if (!found) return nullptr;
+
+ return make_jstring(env, hex::encode(md, sha::kDigestLen));
+}
+```
+
+- [ ] **Step 9: Add `apkEntryDecompressedHash` to `NativeBridge.kt`**
+
+In `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt`, after the `apkSignerCertHashes` declaration (around line 56), add:
+
+```kotlin
+ /**
+ * Returns the SHA-256 hex of the DECOMPRESSED body of the ZIP entry named
+ * [entryName] inside the APK/split at [path]. Returns null if the entry
+ * is not found, the APK can't be opened, or inflate fails (fail-closed to
+ * not-found, not a crash). Used by [ApkIntegrityDetector] in bundle mode
+ * to compare decompressed code entry hashes across base + split APKs.
+ */
+ @JvmStatic
+ external fun apkEntryDecompressedHash(path: String, entryName: String): String?
+```
+
+- [ ] **Step 10: Verify the full native build succeeds**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :samples:minimal:assembleDebug 2>&1 | tail -30
+```
+
+Expected: BUILD SUCCESSFUL. Check that `libdicore.so` is built without warnings (the `-Werror` flag catches silent issues).
+
+- [ ] **Step 11: Commit**
+
+```bash
+git add \
+ deviceintelligence/src/main/cpp/CMakeLists.txt \
+ deviceintelligence/src/main/cpp/dicore/zip_parser.h \
+ deviceintelligence/src/main/cpp/dicore/zip_parser.cpp \
+ deviceintelligence/src/main/cpp/dicore/jni_bridge.cpp \
+ deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/NativeBridge.kt \
+ deviceintelligence/src/test/cpp/test_hash_entry_decompressed.cpp
+git commit -m "feat(bundle): native hash_entry_decompressed via NDK zlib + JNI apkEntryDecompressedHash"
+```
+
+---
+
+### Task 6: Runtime `ApkIntegrityDetector` Bundle Branch
+
+**Files:**
+- Modify: `deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt`
+
+**Interfaces:**
+- Consumes: `Fingerprint.bundleMode`, `Fingerprint.bundleEntryHashes`, `Fingerprint.signerCertSha256` (allow-set semantics), `NativeBridge.apkSignerCertHashes()`, `NativeBridge.apkEntryDecompressedHash()`, `applicationInfo.sourceDir`, `applicationInfo.splitSourceDirs`.
+- Produces: `Finding("apk_signer_mismatch", CRITICAL)` when an observed cert is not in the allow-set; `Finding("apk_entry_modified", CRITICAL)` on hash mismatch; `Finding("apk_entry_removed", HIGH)` when an entry is absent across all splits.
+
+- [ ] **Step 1: Identify the insertion point in `ApkIntegrityDetector.evaluate()`**
+
+Read the current `evaluate()` method. The APK path is read at line 102. The signer and entry reads follow at lines 110–125. The diff at lines 128–218 uses APK-mode equality checks. The bundle branch must replace lines 110–218 entirely when `baked.bundleMode == true`.
+
+The insertion structure:
+
+```
+val apkPath = context.applicationInfo.sourceDir ?: return inconclusive(...)
+// [NEW] branch here:
+if (baked.bundleMode) {
+ // bundle branch (new code)
+ return ok(id, findings, dur())
+} else {
+ // existing APK-mode code (lines 110–218, unchanged)
+}
+```
+
+- [ ] **Step 2: Write the bundle branch**
+
+In `ApkIntegrityDetector.kt`, after the `val apkPath = ...` line (around line 102), replace the existing code from `val runtimeCerts = NativeBridge.apkSignerCertHashes(apkPath)` down through `return ok(id, findings, dur())` with the following if-else:
+
+```kotlin
+ val findings = ArrayList(8)
+
+ if (baked.bundleMode) {
+ // ---- Bundle mode: signer membership + decompressed entry diff across splits ----
+
+ // Signal 1 — signer membership. Each cert observed in base.apk
+ // must be a member of the baked allow-set. If the allow-set is
+ // empty (developer baked no certs), the check is skipped — documented
+ // fail-open for that edge case; dex/so hashing is then the sole anchor.
+ if (baked.signerCertSha256.isNotEmpty()) {
+ val allowSet = baked.signerCertSha256.toHashSet()
+ val observedCerts = NativeBridge.apkSignerCertHashes(apkPath)
+ ?: return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkSignerCertHashes returned null for $apkPath",
+ durationMs = dur(),
+ )
+ for (cert in observedCerts) {
+ if (cert !in allowSet) {
+ findings += Finding(
+ kind = "apk_signer_mismatch",
+ severity = Severity.CRITICAL,
+ subject = context.packageName,
+ message = "Bundle signer cert is not in the build-time allow-set",
+ details = mapOf(
+ "allow_set" to baked.signerCertSha256.joinToString(","),
+ "observed_cert" to cert,
+ ),
+ )
+ }
+ }
+ }
+
+ // Source-dir prefix check (same as APK mode).
+ if (!apkPath.startsWith(baked.expectedSourceDirPrefix)) {
+ findings += Finding(
+ kind = "apk_source_dir_unexpected",
+ severity = Severity.MEDIUM,
+ subject = apkPath,
+ message = "Installed APK lives outside the expected path prefix",
+ details = mapOf(
+ "expected_prefix" to baked.expectedSourceDirPrefix,
+ "observed_path" to apkPath,
+ ),
+ )
+ }
+
+ // Signal 2 — decompressed code-entry integrity across base + all splits.
+ // For each baked entry (key = APK-relative name, value = expected SHA-256),
+ // search base.apk then every split APK for the first non-null decompressed hash.
+ val splitPaths: List =
+ context.applicationInfo.splitSourceDirs?.toList() ?: emptyList()
+ val searchPaths: List = listOf(apkPath) + splitPaths
+
+ for ((entryName, expectedHash) in baked.bundleEntryHashes) {
+ val observedHash: String? = searchPaths.firstNotNullOfOrNull { splitPath ->
+ NativeBridge.apkEntryDecompressedHash(splitPath, entryName)
+ }
+ when {
+ observedHash == null -> findings += Finding(
+ kind = "apk_entry_removed",
+ severity = Severity.HIGH,
+ subject = entryName,
+ message = "Bundle entry was present at build time but is absent across all splits",
+ details = mapOf("expected_hash" to expectedHash),
+ )
+ observedHash != expectedHash -> findings += Finding(
+ kind = "apk_entry_modified",
+ severity = Severity.CRITICAL,
+ subject = entryName,
+ message = "Bundle entry's decompressed bytes differ from build time",
+ details = mapOf(
+ "expected_hash" to expectedHash,
+ "observed_hash" to observedHash,
+ ),
+ )
+ }
+ }
+
+ } else {
+ // ---- APK mode: existing equality checks (unchanged) ----
+ val runtimeCerts = NativeBridge.apkSignerCertHashes(apkPath)
+ ?: return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkSignerCertHashes returned null for $apkPath",
+ durationMs = dur(),
+ )
+
+ val runtimeEntriesArr = NativeBridge.apkEntries(apkPath)
+ ?: return inconclusive(
+ id = id,
+ reason = "apk_unreadable",
+ message = "apkEntries returned null for $apkPath",
+ durationMs = dur(),
+ )
+ val runtimeEntries = parseEntryArray(runtimeEntriesArr)
+
+ val expectedCerts = baked.signerCertSha256.toSet()
+ val observedCerts = runtimeCerts.toSet()
+ if (observedCerts != expectedCerts) {
+ findings += Finding(
+ kind = "apk_signer_mismatch",
+ severity = Severity.CRITICAL,
+ subject = context.packageName,
+ message = "APK signer cert(s) differ from the build-time baked set",
+ details = mapOf(
+ "expected" to baked.signerCertSha256.joinToString(","),
+ "observed" to runtimeCerts.joinToString(","),
+ ),
+ )
+ }
+
+ if (!apkPath.startsWith(baked.expectedSourceDirPrefix)) {
+ findings += Finding(
+ kind = "apk_source_dir_unexpected",
+ severity = Severity.MEDIUM,
+ subject = apkPath,
+ message = "Installed APK lives outside the expected path prefix",
+ details = mapOf(
+ "expected_prefix" to baked.expectedSourceDirPrefix,
+ "observed_path" to apkPath,
+ ),
+ )
+ }
+
+ if (baked.expectedInstallerWhitelist.isNotEmpty()) {
+ val installer = readInstallerPackageName(context)
+ if (installer == null || installer !in baked.expectedInstallerWhitelist) {
+ findings += Finding(
+ kind = "installer_not_whitelisted",
+ severity = Severity.MEDIUM,
+ subject = installer,
+ message = "Installer package is not in the baked whitelist",
+ details = mapOf(
+ "whitelist" to baked.expectedInstallerWhitelist.joinToString(","),
+ "observed_installer" to (installer ?: ""),
+ ),
+ )
+ }
+ }
+
+ val ignoredEntries = baked.ignoredEntries.toHashSet()
+ val ignoredPrefixes = baked.ignoredEntryPrefixes
+ val filteredRuntime = HashMap(runtimeEntries.size)
+ for ((name, hash) in runtimeEntries) {
+ if (name in ignoredEntries) continue
+ if (ignoredPrefixes.any { name.startsWith(it) }) continue
+ filteredRuntime[name] = hash
+ }
+
+ for ((name, expectedHash) in baked.entries) {
+ val observedHash = filteredRuntime[name]
+ when {
+ observedHash == null -> findings += Finding(
+ kind = "apk_entry_removed",
+ severity = Severity.HIGH,
+ subject = name,
+ message = "APK entry was present at build time but is missing at runtime",
+ details = mapOf("expected_hash" to expectedHash),
+ )
+ observedHash != expectedHash -> findings += Finding(
+ kind = "apk_entry_modified",
+ severity = Severity.CRITICAL,
+ subject = name,
+ message = "APK entry exists but its bytes differ from build time",
+ details = mapOf(
+ "expected_hash" to expectedHash,
+ "observed_hash" to observedHash,
+ ),
+ )
+ }
+ }
+ for ((name, observedHash) in filteredRuntime) {
+ if (name !in baked.entries) {
+ findings += Finding(
+ kind = "apk_entry_added",
+ severity = Severity.HIGH,
+ subject = name,
+ message = "APK entry exists at runtime but wasn't present at build time",
+ details = mapOf("observed_hash" to observedHash),
+ )
+ }
+ }
+ }
+
+ return ok(id, findings, dur())
+```
+
+Also delete the now-redundant `val findings = ArrayList(4)` line that was previously at line 128 (we replaced it with `val findings = ArrayList(8)` at the top of the new branch).
+
+- [ ] **Step 3: Verify the runtime module compiles**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :deviceintelligence:compileReleaseKotlin 2>&1 | tail -20
+```
+
+Expected: BUILD SUCCESSFUL.
+
+- [ ] **Step 4: Verify the full sample builds (APK mode regression check)**
+
+```bash
+./gradlew :samples:minimal:assembleRelease 2>&1 | tail -30
+```
+
+Expected: BUILD SUCCESSFUL with `instrument*` tasks running (not bundle tasks).
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/ApkIntegrityDetector.kt
+git commit -m "feat(bundle): ApkIntegrityDetector bundle branch — signer membership + decompressed entry diff"
+```
+
+---
+
+### Task 7: On-Device Validation (User / Device Task)
+
+**This task is entirely manual. No code is written or committed.**
+
+**Prerequisites:** Tasks 1–6 merged to main. The attached test device (clean Xiaomi 2512BPNDAG, API 36) or the x86_64 emulator. `bundletool` installed and on `$PATH` (`bundletool --version` prints without error). The `samples/minimal` project configured with a valid release signing config (`signingConfigs.release`) and `appBundle { enabled = true }` in its `deviceintelligence` block.
+
+**Step A: Configure the sample for bundle mode**
+
+In `samples/minimal/build.gradle.kts` (or your consumer app), add under `deviceintelligence { ... }`:
+
+```kotlin
+deviceintelligence {
+ appBundle {
+ enabled = true
+ // Add Play App Signing cert if you have it. For local bundletool testing,
+ // the upload key is used for both signing and installation — it is in
+ // the allow-set by default (via signerCertHashes in BundleFingerprintBuilder).
+ // playSigningCertSha256("YOUR_PLAY_SIGNING_CERT_SHA256")
+ }
+}
+```
+
+**Step B: Build the `.aab`**
+
+```bash
+export JAVA_HOME=/home/joseph/.jdks/temurin-23.0.2
+./gradlew :samples:minimal:bundleRelease
+```
+
+Verify the task `bundleReleaseDeviceIntelligenceIntegrity` ran (check gradle output). Locate the output AAB:
+```
+samples/minimal/build/outputs/bundle/release/minimal-release.aab
+```
+
+**Step C: Install via bundletool (local testing — upload key signs)**
+
+```bash
+bundletool build-apks \
+ --bundle=samples/minimal/build/outputs/bundle/release/minimal-release.aab \
+ --output=/tmp/minimal.apks \
+ --ks= \
+ --ks-pass=pass: \
+ --ks-key-alias= \
+ --key-pass=pass: \
+ --local-testing
+
+bundletool install-apks --apks=/tmp/minimal.apks
+```
+
+(Alternatively: `--mode=universal` → `install-apks` → single universal APK sideloaded.)
+
+**Step D: Launch and observe — zero false positives**
+
+Launch the sample on device. Open Logcat, filter by `DeviceIntelligence`:
+
+```bash
+adb logcat -s DeviceIntelligence.ApkIntegrity
+```
+
+Expected: no `fingerprint_asset_missing`, no `apk_signer_mismatch`, no `apk_entry_modified`, no `apk_entry_removed`. The telemetry report should be CLEAN.
+
+**Step E: Tamper test — verify detection**
+
+Two options (pick one):
+
+**Option 1: Flip a baked hash.** After `bundleRelease`, in the emitted AAB, locate the `base/assets/io.ssemaj.deviceintelligence/fingerprint.bin`, corrupt it (e.g., flip a byte at offset 64), re-pack, re-sign with a test key. Reinstall. Expected: `fingerprint_bad_magic` or `fingerprint_corrupt` CRITICAL finding.
+
+**Option 2: Patch a dex in a split.** Using `bundletool build-apks --mode=universal`, extract the universal APK, patch one byte inside `classes.dex` using a hex editor, repack and sideload. Expected: `apk_entry_modified` CRITICAL finding for `classes.dex`.
+
+**Verify detection in Logcat:**
+```bash
+adb logcat -s DeviceIntelligence.ApkIntegrity | grep -E "CRITICAL|entry_modified|signer_mismatch"
+```
+
+Expected: at least one CRITICAL finding matching the tamper. No false positives on the clean install (Step D).
+
+---
+
+## Self-Review
+
+### Spec Coverage Check
+
+| Spec requirement | Task covering it |
+|---|---|
+| AppBundleOptions DSL: `enabled`, `playSigningCertSha256(vararg)`, normalize (strip `:`, lowercase) | Task 1 |
+| `DeviceIntelligenceExtension` `@Nested appBundle` + DSL sugar | Task 1 |
+| Plugin `Fingerprint` v3: `bundleMode`, `bundleEntryHashes`, SCHEMA_VERSION 2→3 | Task 2 |
+| Plugin `FingerprintCodec` FORMAT_VERSION 2→3, v3 encode + decode | Task 2 |
+| Runtime `Fingerprint` v3 fields | Task 2 |
+| Runtime `FingerprintCodec` FORMAT_VERSION 2→3, v3 decode | Task 2 |
+| `MIN_SUPPORTED_FORMAT_VERSION` stays 1 | Task 2 (verified by existing v2-blob test) |
+| `AabHasher.bundleEntryHashes` — decompressed SHA-256, normalization | Task 3 |
+| `AabSigner.sign` — JDK JarSigner, no bundletool | Task 3 |
+| `KeystoreSigning` shared helper (DRY) | Task 3 |
+| `BundleFingerprintBuilder.build` — DI XOR encryption | Task 3 |
+| `BundleIntegrityTask` — BUNDLE transform, repack (no dir entries), sign | Task 4 |
+| Plugin gate: `bundleMode=true` → skip APK transform | Task 4 |
+| Plugin gate: `bundleMode=false` → unchanged APK path | Task 4 (smoke test) |
+| CMake: `find_library(z-lib z)` + link | Task 5 |
+| `hash_entry_decompressed`: STORED path | Task 5 |
+| `hash_entry_decompressed`: DEFLATED path via `inflateInit2(-MAX_WBITS)` | Task 5 |
+| `hash_entry_decompressed`: bounds-check, fail-closed (no crash) | Task 5 |
+| `hash_entry_decompressed`: 64 MB inflate guard | Task 5 |
+| JNI `apkEntryDecompressedHash` | Task 5 |
+| `NativeBridge.apkEntryDecompressedHash` | Task 5 |
+| Host C++ test: STORED + DEFLATED + missing + garbage | Task 5 |
+| Runtime bundle branch: signer membership (skip if allow-set empty) | Task 6 |
+| Runtime bundle branch: decompressed entry diff across `sourceDir + splitSourceDirs` | Task 6 |
+| Runtime: `apk_signer_mismatch` CRITICAL on non-member cert | Task 6 |
+| Runtime: `apk_entry_modified` CRITICAL on hash mismatch | Task 6 |
+| Runtime: `apk_entry_removed` HIGH on absent entry | Task 6 |
+| Runtime: keep `expectedSourceDirPrefix` check | Task 6 |
+| Runtime: keep `dicoreTextSha256ByAbi` / `nativeLibInventoryByAbi` push unchanged | Task 6 (not touched) |
+| Device validation: zero false positives with bundletool local install | Task 7 |
+| Tamper test: `apk_entry_modified` CRITICAL fires | Task 7 |
+| No `apk_entry_added` in bundle mode | Task 6 (bundle branch has no added-entry loop) |
+| Resources/manifest not byte-pinned in bundle mode | AabHasher excludes them (Task 3) |
+
+### Placeholder Scan
+
+No "TBD", "TODO", or "implement later" present. All code steps include complete implementation. All test steps include the exact assertion and command. All file paths are absolute or relative from the repo root with enough context to locate them.
+
+### Type Consistency Verification
+
+- `KeystoreSigning.Material.privateKey: PrivateKey` → consumed by `AabSigner.sign(aab, key, certs)` (Task 3) and `BundleIntegrityTask.run()` (Task 4). ✓
+- `KeystoreSigning.Material.certs: List` → same consumers. ✓
+- `KeystoreSigning.Material.certHashes: List` → `BundleFingerprintBuilder.build(signerCertHashes=...)` (Task 3, 4). ✓
+- `BundleFingerprintBuilder.build(key: ByteArray, ...)` → `BundleIntegrityTask` passes `keyFile.get().asFile.readBytes()` (Task 4). ✓
+- `AabHasher.bundleEntryHashes(aab: File): Map` → consumed by `BundleFingerprintBuilder.build` (Task 3). ✓
+- `AabSigner.sign(aab: File, key: PrivateKey, certs: List)` → `BundleIntegrityTask.run()` (Task 4). ✓
+- `Fingerprint.bundleMode: Boolean` → `ApkIntegrityDetector.evaluate()` checks `baked.bundleMode` (Task 6). ✓
+- `Fingerprint.bundleEntryHashes: Map` → `ApkIntegrityDetector` iterates (Task 6). ✓
+- `NativeBridge.apkEntryDecompressedHash(path: String, entryName: String): String?` → `ApkIntegrityDetector` calls (Task 6). ✓
+- `zip::hash_entry_decompressed(apk, cdi, entry_name, out32)` → JNI function calls it (Task 5). ✓
+- Plugin `FingerprintCodec.FORMAT_VERSION = 3` → runtime `FingerprintCodec.FORMAT_VERSION = 3`; both accept 1..3. ✓
+- `BundleIntegrityTask.BUNDLE_ASSET_PATH = "base/" + Fingerprint.ASSET_PATH` → `injectAsset` injects at that path; runtime `FingerprintAssetReader.readEncryptedBytes(context)` reads `Fingerprint.ASSET_PATH` from APK assets (deployed from base module). ✓
diff --git a/docs/superpowers/specs/2026-06-29-app-bundle-integrity-design.md b/docs/superpowers/specs/2026-06-29-app-bundle-integrity-design.md
new file mode 100644
index 0000000..01e7f68
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-29-app-bundle-integrity-design.md
@@ -0,0 +1,192 @@
+# App Bundle (AAB) bundle-mode integrity — design
+
+Status: approved design (v1). Date: 2026-06-29.
+Port of the bundle-mode integrity feature from DeviceIntelligenceRASP (shipped there in 4.0.0)
+into the original DeviceIntelligence library, adapted to this repo's layout.
+
+## Summary
+
+DeviceIntelligence's build-baked APK-integrity layer (the `fingerprint.bin`: signer-cert
+pin + ZIP-entry hashes) is **APK-only**. When an app ships as an **Android App Bundle
+(`.aab`)** through Google Play, Play re-splits, **re-encodes**, and **re-signs** the
+delivered APKs — which breaks the integrity layer three ways. This feature adds a parallel
+**bundle mode** that produces integrity coverage which survives Play's pipeline, with no
+false positives, while leaving the existing APK path unchanged.
+
+The runtime cloner detector (`runtime.cloner`, `/proc`-based) is already AAB-agnostic and
+is untouched. This feature concerns the **build-baked integrity / repackage defense** only.
+
+## Motivation — the three APK-only failure modes (current code)
+
+1. **Transform never runs for AAB.** The fingerprint transform is wired only to
+ `SingleArtifact.APK` (`deviceintelligence-gradle/.../DeviceIntelligencePlugin.kt:308`,
+ `toTransformMany(SingleArtifact.APK)`). `bundleRelease` never injects `fingerprint.bin`
+ → runtime `fingerprint_asset_missing` CRITICAL (`.../internal/ApkIntegrityDetector.kt:221-232`).
+2. **Signer pin is the upload key.** The baseline pins the developer's upload-key cert
+ (`InstrumentApkTask.kt:437-488` → `signerCertSha256`). Play re-signs splits with the
+ **app-signing key**, so the runtime signer check fails → `apk_signer_mismatch` on every
+ Play install.
+3. **Entry hashes are compressed bytes.** Both `ApkHasher.kt:59-66` and native
+ `zip_parser.cpp hash_all_entries` (lines 83-173) hash the **compressed** on-disk body of
+ each ZIP entry. Play re-deflates split APKs, so the compressed bytes differ → mass
+ `apk_entry_modified` CRITICAL.
+
+## Design (v1) — bundle mode, native decompressed hashing (Option A)
+
+A separate **bundle-mode** path, mutually exclusive with APK mode per variant, enabled by
+the developer. It pins what is **stable across Play's pipeline**:
+
+### Signal 1 — signer membership (anti repackage/resign)
+Bake an **allow-set** of signer certs = the upload-keystore cert ∪ the developer-supplied
+Play **app-signing** cert SHA-256(s). At runtime every cert observed in the installed
+`base.apk` signing block must be a **member** of the allow-set (membership, not the
+APK-mode equality). A repackager who resigns under their own key is not in the set →
+`apk_signer_mismatch` CRITICAL. (If the allow-set is empty, the signer check is skipped —
+documented fail-open; dex/.so hashing is then the sole anchor.)
+
+### Signal 2 — decompressed code-entry integrity across splits (anti code-patch)
+Bake the **decompressed** SHA-256 of every code-bearing entry — `classes*.dex` and
+`lib//*.so` — from the bundle's base module. At runtime, for each baked entry, locate
+it across `base.apk` **+ all `splitSourceDirs`** and compare its **decompressed** SHA-256.
+Mismatch → `apk_entry_modified` CRITICAL; absent everywhere → `apk_entry_removed` HIGH. No
+`apk_entry_added` check (splits legitimately carry many non-baked entries). Resources /
+manifest are not byte-pinned in bundle mode (Play re-encodes them) — they are covered
+transitively by the signer pin (editing them requires re-signing).
+
+**Why decompressed:** Play re-deflates entries, so only the **inflated payload** is stable
+between build time and the installed device. DI currently hashes compressed bytes and has
+**no inflater in native** — so a native inflate path is net-new (Option A, chosen for parity
+with DI's existing native APK-mode hashing and its tamper-resistance posture).
+
+### Entry-name normalization (build vs runtime keys)
+The bundle's base module stores code at `base/dex/classes*.dex` and `base/lib//*.so`.
+The **installed** base/split APKs expose those same files as `classes*.dex` and
+`lib//*.so`. `AabHasher` therefore keys `bundleEntryHashes` by the **installed-APK
+entry name**: `base/dex/` → ``, `base/lib//` → `lib//`. (Mirror the
+RASP `AabHasher.kt` mapping.)
+
+## Components / files
+
+### Plugin (`deviceintelligence-gradle/src/main/kotlin/io/ssemaj/deviceintelligence/gradle/`)
+- **Create** `internal/AppBundleOptions.kt` — `@Nested` DSL: `enabled: Property`
+ (default false) + `playSigningCertSha256: SetProperty` with a
+ `fun playSigningCertSha256(vararg hex: String)` that normalizes (strip `:`, lowercase).
+- **Modify** `DeviceIntelligenceExtension.kt` (currently lines 11-84) — add a `@Nested`
+ `appBundle: AppBundleOptions` + `fun appBundle(action: Action)`.
+- **Modify** `internal/Fingerprint.kt` — add v3 fields `bundleMode: Boolean = false`,
+ `bundleEntryHashes: Map = emptyMap()`; bump `SCHEMA_VERSION` 2 → 3 (line 63).
+- **Modify** `internal/FingerprintCodec.kt` — bump `FORMAT_VERSION` 2 → 3 (line 66); append a
+ v3 tail in `encode()` (after the v2 tail, ~line 133): `writeBoolean(bundleMode)` then sorted
+ `bundleEntryHashes`; in `decode()` add `if (formatVersion >= 3) { ... }` (after ~line 228).
+ `MIN_SUPPORTED_FORMAT_VERSION` stays 1 (v1/v2 blobs decode, fields default).
+- **Create** `internal/AabHasher.kt` — read the `.aab` zip; for `base/dex/classes*.dex` and
+ `base/lib//*.so`, compute **decompressed** SHA-256 (`ZipFile.getInputStream` inflates),
+ keyed by normalized installed-entry name (above). (Mirror RASP `AabHasher.kt`.)
+- **Create** `internal/AabSigner.kt` — re-sign the modified `.aab` with JDK
+ `jdk.security.jarsigner.JarSigner` (SHA-256), reusing the existing `PrivateKey` +
+ `List` from `InstrumentApkTask.loadSigningMaterial()` (lines 437-488).
+ apksig cannot sign `.aab`; no bundletool dependency is added. (Mirror RASP `AabSigner.kt`.)
+- **Create** `internal/BundleFingerprintBuilder.kt` — assemble the v3 `Fingerprint`:
+ `bundleMode=true`, `entries=emptyMap()`, `bundleEntryHashes` from `AabHasher`,
+ `signerCertSha256 = (uploadCertHashes + playPins).distinct()`, and the existing
+ `nativeLibInventoryByAbi` / `dicoreTextSha256ByAbi` (read from the bundle's `base/lib/`).
+ Encrypt with the **same** `seed ‖ XOR(encode(fp), key(seed))` envelope and per-build key
+ chunks as APK mode. (Mirror RASP `BundleFingerprintBuilder.kt`.)
+- **Create** `tasks/BundleIntegrityTask.kt` — `DefaultTask` wired to `SingleArtifact.BUNDLE`
+ (single-file `.use(task).wiredWith(inputFile,outputFile).toTransform(SingleArtifact.BUNDLE)`):
+ (1) `BundleFingerprintBuilder.build`, (2) inject `base/assets/io.ssemaj.deviceintelligence/fingerprint.bin`
+ (STORED) into the `.aab` — full repack, drop `META-INF/` + any old fingerprint, **no
+ directory entries** (bundletool rejects them), (3) `AabSigner.sign`. (Mirror RASP
+ `BundleIntegrityTask.kt`.)
+- **Modify** `DeviceIntelligencePlugin.kt` — at variant time read `ext.appBundle.enabled`. If
+ true: register `BundleIntegrityTask` on `SingleArtifact.BUNDLE` and **skip** the APK
+ `InstrumentApkTask` transform (lines 303-311) for that variant; reuse the same key-chunk
+ generation + signing-material resolution (lines 159-180). If false: unchanged.
+
+### Native (`deviceintelligence/src/main/cpp/dicore/`)
+- **Modify** `CMakeLists.txt` — add `find_library(z-lib z)` and link it (next to log/android/dl,
+ ~lines 64-71). NDK ships zlib.
+- **Modify** `zip_parser.{h,cpp}` — add `hash_entry_decompressed(map, count, entryName, out32)`:
+ locate the entry via the central directory; if STORED, SHA-256 the raw body; if DEFLATED,
+ `inflate` (raw-deflate, `inflateInit2(-MAX_WBITS)`) into a bounded streaming buffer and
+ SHA-256 the inflated bytes. Bounds-checked against the mapped file size; fail-closed to
+ "not found"/empty on any zlib error (caller treats as not-found → fail-open).
+- **Modify** `jni_bridge.cpp` + `NativeBridge.kt` — add
+ `external fun apkEntryDecompressedHash(path: String, entryName: String): String?`
+ (mmap the apk, call `hash_entry_decompressed`, return hex or null). Looped per entry in
+ Kotlin; no multi-path JNI needed.
+
+### Runtime (`deviceintelligence/src/main/kotlin/io/ssemaj/deviceintelligence/internal/`)
+- **Modify** `ApkIntegrityDetector.kt` — after decoding the fingerprint, if `fp.bundleMode`
+ take a **bundle branch instead of** the APK-mode entry diff:
+ - **Signer membership:** observed certs (`NativeBridge.apkSignerCertHashes(base)`) each must
+ be in `fp.signerCertSha256` (skip if the baked set is empty) → else `apk_signer_mismatch`
+ CRITICAL.
+ - **Entry integrity:** `paths = [applicationInfo.sourceDir] + (applicationInfo.splitSourceDirs ?: [])`;
+ for each `(name -> hash)` in `fp.bundleEntryHashes`, find the first `path` where
+ `NativeBridge.apkEntryDecompressedHash(path, name)` is non-null; compare → `apk_entry_modified`
+ CRITICAL on mismatch, `apk_entry_removed` HIGH if found in none.
+ - Keep the `expectedSourceDirPrefix` (`/data/app/`) check. Keep pushing
+ `dicoreTextSha256ByAbi` / `nativeLibInventoryByAbi` to native (unchanged).
+- **Modify** runtime `internal/Fingerprint.kt` + `internal/FingerprintCodec.kt` — mirror the
+ plugin v3 fields + decoder guard (decode-only side).
+
+## Data flow
+
+```
+BUILD (bundle mode):
+ bundleRelease -> SingleArtifact.BUNDLE (.aab)
+ BundleIntegrityTask:
+ AabHasher: decompressed sha256 of base/dex/classes*.dex + base/lib//*.so (keyed to installed entry names)
+ signerCertSha256 = uploadCert ∪ playSigningCertSha256
+ Fingerprint{bundleMode=true, entries={}, bundleEntryHashes=...} -> encode v3 -> seed‖XOR(...)
+ inject base/assets/.../fingerprint.bin (STORED) ; AabSigner re-signs .aab
+
+RUNTIME (det integrity, bundle blob):
+ decode fingerprint -> bundleMode=true
+ signer: every observed base.apk cert ∈ signerCertSha256 ? else apk_signer_mismatch (CRIT)
+ entries: for name in bundleEntryHashes:
+ h = first non-null over [sourceDir] + splitSourceDirs of apkEntryDecompressedHash(path, name)
+ h == null -> apk_entry_removed (HIGH); h != baked -> apk_entry_modified (CRIT)
+ sourceDir startswith /data/app/ ? else (existing finding)
+```
+
+## Testing / verification
+
+- **Plugin unit tests:** `FingerprintCodec` v3 round-trip (bundleMode + bundleEntryHashes
+ survive encode→decode; a v2 blob still decodes with defaults); `AabHasher` key
+ normalization (`base/dex/classes.dex`→`classes.dex`, `base/lib/arm64-v8a/x.so`→`lib/arm64-v8a/x.so`)
+ and decompressed-hash equals the inflated bytes' SHA-256 on a synthetic zip.
+- **Native test (host, NDK clang):** `hash_entry_decompressed` over a small crafted zip with
+ one STORED and one DEFLATED entry equals the SHA-256 of the decompressed payload; a missing
+ entry → not-found; a truncated/garbage deflate stream → not-found (no crash, bounds-safe).
+- **Device validation (clean device):** build the sample as an `.aab`, `bundletool build-apks
+ --local-testing` (or `--mode=universal`) then `install-apks` to the device (local install
+ uses the **upload key**, which is in the allow-set), launch → integrity must report **no**
+ `fingerprint_asset_missing` / `apk_signer_mismatch` / `apk_entry_modified` (zero false
+ positives). Then a **tamper test**: patch a baked `.so`/dex in a split (or flip one baked
+ hash via a throwaway) → confirm `apk_entry_modified` CRITICAL fires.
+
+## Migration / compatibility
+
+- Schema v3 is **additive**; `MIN_SUPPORTED_FORMAT_VERSION` stays 1. Existing APK consumers
+ (v1/v2 blobs) decode unchanged with `bundleMode=false` → the APK path is **byte-for-byte
+ unchanged**. Bundle mode is **opt-in** (`appBundle.enabled=true`).
+- `fingerprint_asset_missing` remains fail-open (a finding, not a crash), so a developer who
+ enables bundle mode but mis-pins the Play cert gets a visible finding, never a hard failure.
+
+## Residuals / non-goals (v1)
+
+- Resources/manifest not byte-pinned in bundle mode (covered transitively by the signer pin).
+- A kernel-level `/proc`/file MITM is out of scope (as for all of DI).
+- No `apk_entry_added` detection in bundle mode (splits carry legitimate extra entries).
+- bundletool is **not** added as a dependency; AAB re-sign uses the JDK `JarSigner`.
+
+## Reference implementation (mirror, adapt to DI layout)
+
+RASP source to mirror (in `/home/joseph/AndroidStudioProjects/DeviceIntelligenceRASP`):
+`deviceintelligence-gradle/.../internal/AppBundleOptions.kt`, `internal/AabHasher.kt`,
+`internal/AabSigner.kt`, `tasks/BundleFingerprintBuilder.kt`, `tasks/BundleIntegrityTask.kt`,
+and the native bundle branch `deviceintelligence/src/main/cpp/dicore/detectors/apk/apk_verdict.cpp:139-188`
+(adapt: RASP does the decision in native with vendored `tinfl`; **DI does the decision in
+Kotlin and inflates via NDK zlib** per Option A).