# Class DeviceIntegrity

java.lang.Object
com.codename1.security.DeviceIntegrity

public final class DeviceIntegrity extends Object

Device-integrity and runtime self-protection (RASP) entry point. Groups three families of security primitives that an app -- a banking app in particular -- can use to react to a hostile runtime environment:

1. Platform attestation -- `requestIntegrityToken(String)` returns a signed Google Play Integrity token (Android) or Apple App Attest assertion (iOS). The token is opaque and must be sent to and verified by your backend; it is the only trustworthy way to gate a high value action (such as a transfer to a newly added beneficiary) on device/app integrity, because a decision made on a compromised device can itself be tampered with.
2. RASP reporting -- `isDeviceCompromised()` / `getCompromiseReasons()` expose a non-exiting aggregate of the root/jailbreak/instrumentation checks so the app can degrade gracefully (warn, disable a feature, require step-up auth) instead of being hard-killed at launch.
3. Accessibility-abuse defense -- `getEnabledAccessibilityServices()` / `hasUntrustedAccessibilityService(String...)` detect malware that abuses Android accessibility services for overlays, remote control and on-screen text extraction, and `setSecureScreen(boolean)` blocks screenshots, screen recording and accessibility screen scraping on sensitive screens.

##### Zero-code build hints

Each capability also has a build hint that wires an automatic launch-time guard, so a project can adopt it without writing code:

- `android.playIntegrity=true` (optionally `android.playIntegrity.verifyUrl=<backend>`) -- bundles the Play Integrity SDK, enables `requestIntegrityToken(String)`, and -- when a verify URL is set -- attests at launch and exits if the backend rejects the token.
- `ios.appAttest=true` -- enables App Attest and `requestIntegrityToken(String)` on iOS.
- `android.rootCheck` / `android.fridaDetection` / `ios.detectJailbreak` -- existing hard launch gates that exit on a compromised device. `isDeviceCompromised()` reports the same signals without exiting.
- `android.accessibilityGuard=true` (optionally `android.accessibilityGuard.allow=<csv packages>` and `android.accessibilityGuard.mode=exit|warn`) -- checks the enabled accessibility services at launch and exits (or logs) when an untrusted one is active.

##### Platform support

- Android -- full support. Attestation via Play Integrity (requires the `android.playIntegrity` build hint to bundle the SDK), RASP via the root/Frida/emulator checks, accessibility enumeration via the system settings, and secure screens via `FLAG_SECURE`.
- iOS -- attestation via App Attest (requires the `ios.appAttest` build hint), RASP via the jailbreak detector. Accessibility-service enumeration and `setSecureScreen(boolean)` are Android-only concepts and are no-ops on iOS.
- JavaSE simulator / other ports -- behave as a clean, unsupported device: attestation completes with an error, `isDeviceCompromised()` returns false and the accessibility list is empty. Application code never needs platform `if` statements.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `static void`
  `confirmAttestation(String keyId)`
  Tells the attestation layer that your backend has recorded the attested key, so later requests can use cheap assertions instead of attesting again.
  `static String[]`
  `getCompromiseReasons()`
  Returns the reason codes behind `isDeviceCompromised()`, e.g.
  `static String[]`
  `getEnabledAccessibilityServices()`
  Returns the component identifiers (`package/.ServiceClass`) of the accessibility services currently enabled on the device.
  `static boolean`
  `hasUntrustedAccessibilityService(String... allowedPackages)`
  Returns true when an accessibility service that is not in the supplied allow-list is currently enabled -- a strong indicator of accessibility-abusing malware on Android.
  `static boolean`
  `isAttestationSupported()`
  Returns true when platform attestation (Play Integrity / App Attest) is available on this device and was bundled into the build via the relevant build hint.
  `static boolean`
  `isDeviceCompromised()`
  Non-exiting RASP check.
  `static AsyncResource<String>`
  `requestIntegrityToken(String serverNonce)`
  Requests a signed platform-attestation token bound to the supplied server nonce.
  `static void`
  `resetAttestation()`
  Discards the cached platform attestation state, so the next `requestIntegrityToken(String)` attests from a fresh hardware key.
  `static void`
  `setSecureScreen(boolean secure)`
  Marks the currently displayed screen as secure, blocking OS screenshots, screen recording and accessibility screen scraping while it is showing (Android `FLAG_SECURE`).

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Method Details

  - ### requestIntegrityToken

    public static AsyncResource<String> requestIntegrityToken(String serverNonce)

    Requests a signed platform-attestation token bound to the supplied server nonce.

    On Android this drives the Google Play Integrity API (bundle it with the `android.playIntegrity` build hint); on iOS it drives Apple App Attest (enable it with the `ios.appAttest` build hint). The resulting token is opaque and must be verified server-side -- POST it to your backend, which decrypts/validates the verdict with Google/Apple and decides whether to permit the action.

        DeviceIntegrity.requestIntegrityToken(serverNonce).onResult((token, err) -> {
            if (err != null) {
                // attestation unavailable -- treat as untrusted / require step-up
                return;
            }
            // POST token to the bank backend; the backend allows or blocks the transfer
        });

    ###### Parameters

    - `serverNonce`: a fresh, server-generated nonce/challenge to bind into the attestation, used by the backend to prevent replay

    ###### Returns

    an `AsyncResource` that completes with the opaque attestation token, or completes with an error when attestation is unsupported or the platform request fails

  - ### isAttestationSupported

    public static boolean isAttestationSupported()
    Returns true when platform attestation (Play Integrity / App Attest) is available on this device and was bundled into the build via the relevant build hint.

  - ### resetAttestation

    public static void resetAttestation()

    Discards the cached platform attestation state, so the next `requestIntegrityToken(String)` attests from a fresh hardware key.

    Only iOS holds client-side attestation state. Apple's model is: generate a hardware key once, attest it once, then produce cheap assertions against it for every subsequent request. Your backend records the key when it accepts the attestation. If the backend later rejects a request because it does not recognise the key -- the app was reinstalled, the device was restored from a backup, or the OS invalidated the key -- call this, then request a token again. That is the only correct recovery; retrying with the same key will keep failing.

    Do not call this on every failure. Attestation is rate limited by Apple, and re-attesting in a loop will get the app throttled. No-op on Android, where Play Integrity keeps no client key, and where attestation is unsupported.

  - ### confirmAttestation

    public static void confirmAttestation(String keyId)

    Tells the attestation layer that your backend has recorded the attested key, so later requests can use cheap assertions instead of attesting again.

    This matters on iOS. The first token of a device's life is an attestation, which carries the public key; every token after it is an assertion, which carries only the key's identifier. An assertion sent before the backend has stored that public key is unresolvable, and the natural reading of that rejection -- the key is invalid -- would throw away a key that was perfectly good and burn one of Apple's rate limited attestations replacing it. So requests made between the attestation and this acknowledgement are refused with a retry hint rather than asserted.

    Call it once, after the response accepting the attestation token, passing the key that response acknowledged. Not calling it is safe but slower: the client assumes registration succeeded after a short grace period. No-op on Android and where attestation is unsupported.

    Parameters:
      `keyId` - the key identifier your backend recorded -- the middle field of the `cn1aa1:attest:<keyId>:<attestation>` token it accepted, base64-decoded. Naming it matters: a response for an earlier attestation can arrive after the key has already been replaced, and acknowledging that would mark a key attested which the backend has never seen.

  - ### isDeviceCompromised

    public static boolean isDeviceCompromised()
    Non-exiting RASP check. Returns true when the device shows signs of being rooted, jailbroken, running under dynamic instrumentation (e.g. Frida) or otherwise tampered. Unlike the `android.rootCheck` / `ios.detectJailbreak` launch gates this never terminates the app, so it is safe to call from runtime logic (for example before authorizing a transfer).

  - ### getCompromiseReasons

    public static String[] getCompromiseReasons()
    Returns the reason codes behind `isDeviceCompromised()`, e.g. `"root"`, `"frida"`, `"emulator"`, `"jailbreak"`. Empty when the device appears clean.

  - ### getEnabledAccessibilityServices

    public static String[] getEnabledAccessibilityServices()
    Returns the component identifiers (`package/.ServiceClass`) of the accessibility services currently enabled on the device. Android only; returns an empty array on iOS and other ports.

  - ### hasUntrustedAccessibilityService

    public static boolean hasUntrustedAccessibilityService(String... allowedPackages)

    Returns true when an accessibility service that is not in the supplied allow-list is currently enabled -- a strong indicator of accessibility-abusing malware on Android. Pass the package names your app explicitly trusts (for example a known screen reader the user relies on); any enabled service whose package is not listed makes this return true. With no arguments, this returns true whenever any accessibility service is enabled.

    ###### Parameters

    - `allowedPackages`: package names of accessibility services considered safe

    ###### Returns

    true if at least one enabled accessibility service is not in `allowedPackages`

  - ### setSecureScreen

    public static void setSecureScreen(boolean secure)

    Marks the currently displayed screen as secure, blocking OS screenshots, screen recording and accessibility screen scraping while it is showing (Android `FLAG_SECURE`). Call with `true` when entering a sensitive screen (PIN entry, transfer confirmation) and `false` when leaving it. No-op on iOS and other ports.

    ###### Parameters

    - `secure`: true to protect the screen, false to clear the protection