package com.aoneahsan.capacitor.biometricauth;

/*
 * BiometricAuthPlugin — 2.3.0 SECURITY OVERHAUL
 * ---------------------------------------------------------------------------
 * This release removes ALL fabricated/placeholder cryptographic output. Every
 * WebAuthn signature, attestation object and authenticatorData is now produced
 * by a real, biometric-bound key in the Android Keystore. Device verification
 * (a successful BiometricPrompt) is REQUIRED before any signing happens — the
 * signing key is unlocked via a BiometricPrompt.CryptoObject and the signature
 * is computed INSIDE onAuthenticationSucceeded. On ANY crypto failure the
 * plugin returns an honest error (call.reject with an UPPER_CASE code) and
 * NEVER emits a placeholder signature/attestation/authenticatorData/success.
 *
 * Other 2.3.0 hardening:
 *  - CryptoObject-bound EC signing key (AND-1)
 *  - No fake fallbacks (AND-2)
 *  - Real CBOR "none" attestation incl. attested-credential-data (AND-3)
 *  - Honest UV flag derived from the authentication type (AND-4)
 *  - Session token encrypted with a Keystore AES-GCM key (AND-5)
 *  - setAllowedAuthenticators instead of deprecated setDeviceCredentialAllowed (AND-6)
 *  - Complete error-code mapping (AND-7)
 *  - Per-invocation prompt state + single-in-flight guard (AND-8)
 *  - App-level lockout enforcement honoring maxAttempts/lockoutDuration (AND-9)
 *  - StrongBox-backed keys with graceful fallback (AND-10)
 *  - Debug-gated logging, no PII/credential/token logging (LOG)
 *
 * NOTE: UNVERIFIED-ON-DEVICE — written without a device build/test. The
 * maintainer must compile and exercise this on real Android hardware.
 */

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.security.keystore.StrongBoxUnavailableException;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;

@CapacitorPlugin(name = "BiometricAuth")
public class BiometricAuthPlugin extends Plugin {

    private static final String TAG = "BiometricAuth";
    private static final String ANDROID_KEYSTORE = "AndroidKeyStore";

    // AES key used to encrypt the session token at rest (Keystore-backed).
    private static final String TOKEN_KEY_ALIAS = "BiometricAuthTokenKey";
    private static final String AES_TRANSFORMATION = "AES/GCM/NoPadding";
    private static final int GCM_TAG_LENGTH = 128;
    private static final int GCM_IV_LENGTH = 12;

    // Shared preferences keys
    private static final String PREFS_NAME = "BiometricAuthPrefs";
    private static final String PREF_SESSION_TOKEN = "sessionTokenEnc"; // encrypted blob
    private static final String PREF_SESSION_EXPIRY = "sessionExpiry";
    private static final String PREF_STORED_CREDENTIALS = "storedCredentials";
    private static final String PREF_FAIL_COUNT = "authFailCount";
    private static final String PREF_LOCKOUT_UNTIL = "authLockoutUntil";

    // EC signing keypair, one per credential.
    private static final String KEY_PAIR_ALIAS_PREFIX = "BiometricAuthKeyPair_";

    // Configuration
    private long sessionDuration = 3600; // 1 hour in seconds
    private boolean allowDeviceCredential = true;
    private int maxAttempts = 3;       // app-level lockout threshold (AND-9)
    private int lockoutDuration = 30;  // seconds blocked after threshold reached

    private KeyStore keyStore;

    // AND-8: only one prompt may be in flight at a time across authenticate/register.
    private final AtomicBoolean promptInFlight = new AtomicBoolean(false);

    @Override
    public void load() {
        try {
            keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
            keyStore.load(null);
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Failed to initialize keystore", e);
            }
        }
    }

    // ---------------------------------------------------------------------
    // Base64URL helpers (WebAuthn compatibility)
    // ---------------------------------------------------------------------
    private String base64UrlEncode(byte[] data) {
        return Base64.encodeToString(data, Base64.NO_WRAP | Base64.URL_SAFE | Base64.NO_PADDING);
    }

    // ---------------------------------------------------------------------
    // isAvailable
    // ---------------------------------------------------------------------
    @PluginMethod
    public void isAvailable(PluginCall call) {
        Context context = getContext();
        BiometricManager biometricManager = BiometricManager.from(context);

        JSObject result = new JSObject();
        int canAuthenticate = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK);

        switch (canAuthenticate) {
            case BiometricManager.BIOMETRIC_SUCCESS:
                result.put("available", true);
                result.put("isAvailable", true);
                break;
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "noHardware");
                result.put("errorMessage", "No biometric hardware detected");
                break;
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "hardwareUnavailable");
                result.put("errorMessage", "Biometric hardware is unavailable");
                break;
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "noEnrolledBiometrics");
                result.put("errorMessage", "No biometric data enrolled");
                break;
            case BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "securityUpdateRequired");
                result.put("errorMessage", "Security update required");
                break;
            case BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "notSupported");
                result.put("errorMessage", "Biometric authentication not supported");
                break;
            default:
                result.put("available", false);
                result.put("isAvailable", false);
                result.put("reason", "unknown");
                result.put("errorMessage", "Unknown error");
                break;
        }

        call.resolve(result);
    }

    // ---------------------------------------------------------------------
    // getSupportedBiometrics
    // ---------------------------------------------------------------------
    @PluginMethod
    public void getSupportedBiometrics(PluginCall call) {
        Context context = getContext();
        BiometricManager biometricManager = BiometricManager.from(context);

        JSONArray biometrics = new JSONArray();

        int canAuthenticate = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG);
        if (canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS) {
            // Android does not expose the concrete modality at the API level.
            biometrics.put("fingerprint");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                biometrics.put("faceAuthentication");
            }
        }

        if (allowDeviceCredential) {
            int deviceCredential = biometricManager.canAuthenticate(BiometricManager.Authenticators.DEVICE_CREDENTIAL);
            if (deviceCredential == BiometricManager.BIOMETRIC_SUCCESS) {
                biometrics.put("passcode");
                biometrics.put("pattern");
                biometrics.put("pin");
            }
        }

        JSObject result = new JSObject();
        result.put("biometrics", biometrics);
        // Keep a key the JS adapter also understands.
        result.put("biometryTypes", biometrics);
        call.resolve(result);
    }

    // ---------------------------------------------------------------------
    // authenticate (assertion / webauthn.get)
    // ---------------------------------------------------------------------
    @PluginMethod
    public void authenticate(final PluginCall call) {
        Activity activity = getActivity();
        if (!(activity instanceof FragmentActivity)) {
            call.reject("Activity must be a FragmentActivity", "NOT_AVAILABLE");
            return;
        }

        // AND-9: enforce app-level lockout before prompting.
        long lockedUntil = getLockoutUntil();
        if (lockedUntil > System.currentTimeMillis()) {
            long secs = (lockedUntil - System.currentTimeMillis() + 999) / 1000;
            call.reject("Too many failed attempts. Locked for " + secs + "s.", "LOCKED_OUT");
            return;
        }

        // AND-8: reject a second concurrent prompt.
        if (!promptInFlight.compareAndSet(false, true)) {
            call.reject("A biometric prompt is already in progress", "AUTHENTICATION_FAILED");
            return;
        }

        final FragmentActivity fragmentActivity = (FragmentActivity) activity;

        // Prompt copy
        final String title = call.getString("title", "Authenticate");
        final String subtitle = call.getString("subtitle", "");
        final String description = call.getString("description", "");
        final String cancelButtonTitle = call.getString("cancelButtonTitle", "Cancel");
        final boolean disableFallback = call.getBoolean("disableFallback", false)
                || call.getBoolean("disableDeviceCredential", false);

        // WebAuthn challenge (assertion)
        String challengeTmp = null;
        final JSObject webAuthnOptions = call.getObject("webAuthnOptions");
        if (webAuthnOptions != null) {
            JSObject getOptions = webAuthnOptions.getJSObject("get");
            if (getOptions != null) {
                challengeTmp = getOptions.getString("challenge");
            }
        }
        final String finalChallenge = challengeTmp;

        // Resolve the credential id + RP id up-front so we can pre-load the
        // signing key and bind it to the prompt via a CryptoObject (AND-1).
        final String credentialId = resolveCredentialId(webAuthnOptions);
        final String rpId = getRpId(webAuthnOptions);
        final String keyAlias = KEY_PAIR_ALIAS_PREFIX + credentialId;

        // Build the Signature now and hand it to the prompt. The private key is
        // user-auth-required, so initSign() arms it but it can only sign after
        // the prompt unlocks it inside onAuthenticationSucceeded. (AND-1/AND-2)
        final Signature signatureForPrompt;
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                throw new IllegalStateException("Biometric signing requires API 23+");
            }
            if (!keyStore.containsAlias(keyAlias)) {
                // No registered credential to assert with.
                promptInFlight.set(false);
                call.reject("No credential registered for this device. Call register() first.", "NO_CREDENTIALS");
                return;
            }
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, null);
            if (privateKey == null) {
                promptInFlight.set(false);
                call.reject("Signing key unavailable", "AUTHENTICATION_FAILED");
                return;
            }
            Signature s = Signature.getInstance("SHA256withECDSA");
            s.initSign(privateKey);
            signatureForPrompt = s;
        } catch (Exception e) {
            // Key may have been invalidated by new biometric enrollment, etc.
            promptInFlight.set(false);
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Failed to initialize signing key for assertion");
            }
            call.reject("Failed to initialize signing key: " + e.getClass().getSimpleName(),
                    "AUTHENTICATION_FAILED");
            return;
        }

        final BiometricPrompt.CryptoObject cryptoObject = new BiometricPrompt.CryptoObject(signatureForPrompt);

        Executor executor = ContextCompat.getMainExecutor(activity);
        final BiometricPrompt biometricPrompt = new BiometricPrompt(fragmentActivity, executor,
                new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                        promptInFlight.set(false);
                        rejectWithMappedError(call, errorCode, errString);
                    }

                    @Override
                    public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult authResult) {
                        super.onAuthenticationSucceeded(authResult);
                        promptInFlight.set(false);
                        resetFailCount();

                        try {
                            // AND-4: derive UV honestly from the authentication type.
                            boolean userVerified = wasUserVerified(authResult);

                            int signCount = getAndIncrementSignCount(credentialId);
                            byte[] authenticatorData = buildAuthenticatorData(rpId, signCount, true, userVerified, null);

                            String challengeToUse = finalChallenge != null
                                    ? finalChallenge
                                    : base64UrlEncode(secureRandomBytes(32));
                            String clientDataJSON = createClientDataJSON("webauthn.get", challengeToUse);
                            byte[] clientDataHash = sha256(clientDataJSON.getBytes(StandardCharsets.UTF_8));

                            // sign( authenticatorData || SHA-256(clientDataJSON) )
                            byte[] signedData = concat(authenticatorData, clientDataHash);

                            // AND-1/AND-2: sign INSIDE the callback using the prompt-unlocked Signature.
                            Signature s = authResult.getCryptoObject() != null
                                    ? authResult.getCryptoObject().getSignature()
                                    : null;
                            if (s == null) {
                                call.reject("CryptoObject signature missing after authentication", "AUTHENTICATION_FAILED");
                                return;
                            }
                            s.update(signedData);
                            byte[] signatureBytes = s.sign();

                            // Assemble the assertion response (all real values).
                            JSObject response = new JSObject();
                            response.put("authenticatorData", base64UrlEncode(authenticatorData));
                            response.put("clientDataJSON", base64UrlEncode(clientDataJSON.getBytes(StandardCharsets.UTF_8)));
                            response.put("signature", base64UrlEncode(signatureBytes));

                            String userId = resolveUserId(webAuthnOptions);
                            response.put("userHandle", userId != null
                                    ? base64UrlEncode(userId.getBytes(StandardCharsets.UTF_8)) : "");

                            JSObject credentialData = new JSObject();
                            credentialData.put("id", credentialId);
                            credentialData.put("rawId", base64UrlEncode(credentialId.getBytes(StandardCharsets.UTF_8)));
                            credentialData.put("response", response);
                            credentialData.put("type", "public-key");
                            credentialData.put("clientExtensionResults", new JSObject());
                            credentialData.put("authenticatorAttachment", "platform");

                            String token = createEnhancedToken(credentialId, "authentication", credentialData);
                            persistSession(token);

                            JSObject result = new JSObject();
                            result.put("success", true);
                            result.put("sessionId", UUID.randomUUID().toString());
                            result.put("token", token);
                            result.put("credential", credentialData);
                            call.resolve(result);
                        } catch (Exception e) {
                            // AND-2: never fabricate output — fail honestly.
                            if (BuildConfig.DEBUG) {
                                Log.e(TAG, "Signing failed during assertion");
                            }
                            call.reject("Failed to produce assertion: " + e.getClass().getSimpleName(),
                                    "AUTHENTICATION_FAILED");
                        }
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                        // A single non-matching attempt — let the user retry. Count it for
                        // app-level lockout (AND-9); the OS handles hard lockout separately.
                        recordFailure();
                    }
                });

        // AND-6: CryptoObject is only compatible with BIOMETRIC_STRONG (never
        // DEVICE_CREDENTIAL). A negative button is required when we do not allow
        // device credential.
        BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle(title)
                .setSubtitle(subtitle)
                .setDescription(description)
                .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
                .setNegativeButtonText(cancelButtonTitle)
                .build();

        activity.runOnUiThread(() -> {
            try {
                biometricPrompt.authenticate(promptInfo, cryptoObject);
            } catch (Exception e) {
                promptInFlight.set(false);
                call.reject("Failed to show biometric prompt: " + e.getClass().getSimpleName(),
                        "AUTHENTICATION_FAILED");
            }
        });
    }

    // ---------------------------------------------------------------------
    // register (attestation / webauthn.create)
    // ---------------------------------------------------------------------
    @PluginMethod
    public void register(final PluginCall call) {
        Activity activity = getActivity();
        if (!(activity instanceof FragmentActivity)) {
            call.reject("Activity must be a FragmentActivity", "NOT_AVAILABLE");
            return;
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            call.reject("Biometric registration requires API 23+", "NOT_AVAILABLE");
            return;
        }

        long lockedUntil = getLockoutUntil();
        if (lockedUntil > System.currentTimeMillis()) {
            long secs = (lockedUntil - System.currentTimeMillis() + 999) / 1000;
            call.reject("Too many failed attempts. Locked for " + secs + "s.", "LOCKED_OUT");
            return;
        }

        if (!promptInFlight.compareAndSet(false, true)) {
            call.reject("A biometric prompt is already in progress", "AUTHENTICATION_FAILED");
            return;
        }

        final FragmentActivity fragmentActivity = (FragmentActivity) activity;

        final String title = call.getString("title", "Register Biometric");
        final String subtitle = call.getString("subtitle", "");
        final String description = call.getString("description", "");
        final String cancelButtonTitle = call.getString("cancelButtonTitle", "Cancel");

        final JSObject webAuthnOpts = call.getObject("webAuthnOptions");
        final String rpId = getRpId(webAuthnOpts);
        final String credentialId = "mobile_" + UUID.randomUUID().toString().replace("-", "");
        final String keyAlias = KEY_PAIR_ALIAS_PREFIX + credentialId;

        // Challenge for webauthn.create
        String challengeTmp = null;
        if (webAuthnOpts != null) {
            JSObject createOptions = webAuthnOpts.getJSObject("create");
            if (createOptions != null) {
                challengeTmp = createOptions.getString("challenge");
            }
        }
        final String challenge = challengeTmp != null ? challengeTmp : base64UrlEncode(secureRandomBytes(32));

        // Create the new biometric-bound EC keypair and arm its Signature so the
        // prompt unlocks it. We sign nothing meaningful for "none" attestation,
        // but binding the key to the prompt proves the user verified. (AND-1/AND-2)
        final Signature signatureForPrompt;
        final byte[] cosePublicKey;
        final byte[] credentialIdBytes = credentialId.getBytes(StandardCharsets.UTF_8);
        try {
            generateSignatureKeyPair(keyAlias);
            PublicKey publicKey = keyStore.getCertificate(keyAlias).getPublicKey();
            cosePublicKey = coseEncodeEcPublicKey((ECPublicKey) publicKey);

            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, null);
            Signature s = Signature.getInstance("SHA256withECDSA");
            s.initSign(privateKey);
            signatureForPrompt = s;
        } catch (Exception e) {
            promptInFlight.set(false);
            // Roll back a half-created key so we don't leave dangling aliases.
            safeDeleteKey(keyAlias);
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Failed to create registration key");
            }
            call.reject("Failed to create signing key: " + e.getClass().getSimpleName(),
                    "AUTHENTICATION_FAILED");
            return;
        }

        final BiometricPrompt.CryptoObject cryptoObject = new BiometricPrompt.CryptoObject(signatureForPrompt);

        Executor executor = ContextCompat.getMainExecutor(activity);
        final BiometricPrompt biometricPrompt = new BiometricPrompt(fragmentActivity, executor,
                new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                        promptInFlight.set(false);
                        safeDeleteKey(keyAlias); // user never completed registration
                        rejectWithMappedError(call, errorCode, errString);
                    }

                    @Override
                    public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult authResult) {
                        super.onAuthenticationSucceeded(authResult);
                        promptInFlight.set(false);
                        resetFailCount();

                        try {
                            boolean userVerified = wasUserVerified(authResult);

                            // Touch the prompt-unlocked signature so the key is provably
                            // unlocked by user verification (defensive; result unused for
                            // "none" attestation).
                            Signature s = authResult.getCryptoObject() != null
                                    ? authResult.getCryptoObject().getSignature()
                                    : null;
                            if (s == null) {
                                safeDeleteKey(keyAlias);
                                call.reject("CryptoObject signature missing after authentication", "AUTHENTICATION_FAILED");
                                return;
                            }

                            int signCount = getAndIncrementSignCount(credentialId);

                            // AT flag set; include attested-credential-data. (AND-3)
                            byte[] attestedCredentialData =
                                    buildAttestedCredentialData(credentialIdBytes, cosePublicKey);
                            byte[] authenticatorData = buildAuthenticatorData(
                                    rpId, signCount, true, userVerified, attestedCredentialData);

                            // AND-3: real CBOR "none" attestation object.
                            byte[] attestationObject = buildNoneAttestationObject(authenticatorData);

                            JSObject response = new JSObject();
                            response.put("attestationObject", base64UrlEncode(attestationObject));
                            response.put("clientDataJSON", base64UrlEncode(
                                    createClientDataJSON("webauthn.create", challenge).getBytes(StandardCharsets.UTF_8)));
                            JSONArray transports = new JSONArray();
                            transports.put("internal");
                            response.put("transports", transports);
                            response.put("publicKey", base64UrlEncode(cosePublicKey));

                            JSObject credentialData = new JSObject();
                            credentialData.put("id", credentialId);
                            credentialData.put("rawId", base64UrlEncode(credentialIdBytes));
                            credentialData.put("response", response);
                            credentialData.put("type", "public-key");
                            credentialData.put("clientExtensionResults", new JSObject());
                            credentialData.put("authenticatorAttachment", "platform");

                            String token = createEnhancedToken(credentialId, "registration", credentialData);
                            persistSession(token);

                            JSObject result = new JSObject();
                            result.put("success", true);
                            result.put("sessionId", UUID.randomUUID().toString());
                            result.put("token", token);
                            result.put("credential", credentialData);
                            call.resolve(result);
                        } catch (Exception e) {
                            // AND-2: honest failure, no fabricated attestation.
                            safeDeleteKey(keyAlias);
                            if (BuildConfig.DEBUG) {
                                Log.e(TAG, "Attestation assembly failed");
                            }
                            call.reject("Failed to produce attestation: " + e.getClass().getSimpleName(),
                                    "AUTHENTICATION_FAILED");
                        }
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                        recordFailure();
                    }
                });

        BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle(title)
                .setSubtitle(subtitle)
                .setDescription(description)
                .setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
                .setNegativeButtonText(cancelButtonTitle)
                .build();

        activity.runOnUiThread(() -> {
            try {
                biometricPrompt.authenticate(promptInfo, cryptoObject);
            } catch (Exception e) {
                promptInFlight.set(false);
                safeDeleteKey(keyAlias);
                call.reject("Failed to show biometric prompt: " + e.getClass().getSimpleName(),
                        "AUTHENTICATION_FAILED");
            }
        });
    }

    // ---------------------------------------------------------------------
    // deleteCredentials
    // ---------------------------------------------------------------------
    @PluginMethod
    public void deleteCredentials(PluginCall call) {
        try {
            SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(PREF_STORED_CREDENTIALS);
            editor.remove(PREF_SESSION_TOKEN);
            editor.remove(PREF_SESSION_EXPIRY);
            editor.remove(PREF_FAIL_COUNT);
            editor.remove(PREF_LOCKOUT_UNTIL);
            editor.apply();

            // Delete every per-credential signing key plus the token-encryption key.
            if (keyStore != null) {
                java.util.Enumeration<String> aliases = keyStore.aliases();
                java.util.List<String> toDelete = new java.util.ArrayList<>();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    if (alias.startsWith(KEY_PAIR_ALIAS_PREFIX) || alias.equals(TOKEN_KEY_ALIAS)) {
                        toDelete.add(alias);
                    }
                }
                for (String alias : toDelete) {
                    safeDeleteKey(alias);
                }
            }

            call.resolve();
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Failed to delete credentials");
            }
            call.reject("Failed to delete credentials", "UNKNOWN");
        }
    }

    // ---------------------------------------------------------------------
    // configure
    // ---------------------------------------------------------------------
    @PluginMethod
    public void configure(PluginCall call) {
        JSObject config = call.getObject("config");

        if (config != null) {
            if (config.has("sessionDuration")) {
                try {
                    sessionDuration = config.getLong("sessionDuration");
                } catch (JSONException e) {
                    // keep default
                }
            }

            JSObject uiConfig = config.getJSObject("uiConfig");
            if (uiConfig != null) {
                // Android BiometricPrompt does not support these UI customizations;
                // ignored intentionally for cross-platform config parity.
            }

            JSONArray fallbackMethods;
            try {
                fallbackMethods = config.getJSONArray("fallbackMethods");
                if (fallbackMethods != null && fallbackMethods.length() > 0) {
                    allowDeviceCredential = false;
                    for (int i = 0; i < fallbackMethods.length(); i++) {
                        String method = fallbackMethods.getString(i);
                        if (method.equals("passcode") || method.equals("pattern") || method.equals("pin")) {
                            allowDeviceCredential = true;
                            break;
                        }
                    }
                }
            } catch (JSONException e) {
                // keep default
            }

            if (config.has("maxAttempts")) {
                try {
                    maxAttempts = config.getInt("maxAttempts");
                } catch (JSONException e) {
                    // keep default
                }
            }
            if (config.has("lockoutDuration")) {
                try {
                    lockoutDuration = config.getInt("lockoutDuration");
                } catch (JSONException e) {
                    // keep default
                }
            }
        }

        call.resolve();
    }

    // =====================================================================
    // Crypto / WebAuthn helpers
    // =====================================================================

    /**
     * Create the biometric-bound EC signing keypair for a credential.
     * AND-1: user-authentication required (must be unlocked by the prompt).
     * AND-10: StrongBox-backed on API 28+ with graceful fallback.
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void generateSignatureKeyPair(String keyAlias) throws Exception {
        try {
            buildAndGenerateKeyPair(keyAlias, true);
        } catch (Exception e) {
            // StrongBox may be unavailable on this device — retry without it.
            boolean strongBoxIssue = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
                    && (e instanceof StrongBoxUnavailableException
                        || (e.getCause() instanceof StrongBoxUnavailableException));
            if (strongBoxIssue) {
                safeDeleteKey(keyAlias);
                buildAndGenerateKeyPair(keyAlias, false);
            } else {
                throw e;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void buildAndGenerateKeyPair(String keyAlias, boolean tryStrongBox)
            throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        java.security.KeyPairGenerator keyPairGenerator = java.security.KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE);

        // setKeySize(256) on the EC AndroidKeyStore provider yields secp256r1
        // (P-256) on all supported API levels (23+). setAlgorithmParameterSpec
        // with ECGenParameterSpec is API 30+ only, so we avoid it for min-SDK 23.
        KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(
                keyAlias,
                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                .setKeySize(256)
                .setDigests(KeyProperties.DIGEST_SHA256)
                .setUserAuthenticationRequired(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            specBuilder.setInvalidatedByBiometricEnrollment(true);
        }

        // Require a strong biometric to unlock the key where supported (API 30+).
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            specBuilder.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG);
        }

        if (tryStrongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            specBuilder.setIsStrongBoxBacked(true);
        }

        keyPairGenerator.initialize(specBuilder.build());
        keyPairGenerator.generateKeyPair();
    }

    private void safeDeleteKey(String keyAlias) {
        try {
            if (keyStore != null && keyStore.containsAlias(keyAlias)) {
                keyStore.deleteEntry(keyAlias);
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.w(TAG, "Failed to delete key alias");
            }
        }
    }

    /**
     * Build WebAuthn authenticatorData.
     * Layout: rpIdHash(32) || flags(1) || signCount(4) [|| attestedCredentialData].
     * Flags: UP=0x01, UV=0x04, AT=0x40.
     */
    private byte[] buildAuthenticatorData(String rpId, int signCount, boolean userPresent,
                                          boolean userVerified, byte[] attestedCredentialData) throws Exception {
        byte[] rpIdHash = sha256(rpId.getBytes(StandardCharsets.UTF_8));

        byte flags = 0;
        if (userPresent) flags |= 0x01;
        if (userVerified) flags |= 0x04;
        if (attestedCredentialData != null) flags |= 0x40; // AT

        byte[] signCountBytes = new byte[]{
                (byte) ((signCount >> 24) & 0xFF),
                (byte) ((signCount >> 16) & 0xFF),
                (byte) ((signCount >> 8) & 0xFF),
                (byte) (signCount & 0xFF)
        };

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(rpIdHash);
        out.write(flags);
        out.write(signCountBytes);
        if (attestedCredentialData != null) {
            out.write(attestedCredentialData);
        }
        return out.toByteArray();
    }

    /**
     * attestedCredentialData = AAGUID(16) || credIdLen(2, big-endian) || credId || COSEKey.
     * AAGUID is all-zero for "none" attestation. (AND-3)
     */
    private byte[] buildAttestedCredentialData(byte[] credentialId, byte[] cosePublicKey) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(new byte[16]); // AAGUID = 16 zero bytes
        int len = credentialId.length;
        out.write((byte) ((len >> 8) & 0xFF));
        out.write((byte) (len & 0xFF));
        out.write(credentialId);
        out.write(cosePublicKey);
        return out.toByteArray();
    }

    /**
     * Minimal CBOR encoder for the "none" attestation object:
     *   { "fmt": "none", "attStmt": {}, "authData": <bytes> }
     * Encoded as a definite-length map of 3 pairs. (AND-3)
     */
    private byte[] buildNoneAttestationObject(byte[] authData) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        cborWriteMapHeader(out, 3);

        cborWriteTextString(out, "fmt");
        cborWriteTextString(out, "none");

        cborWriteTextString(out, "attStmt");
        cborWriteMapHeader(out, 0); // empty map

        cborWriteTextString(out, "authData");
        cborWriteByteString(out, authData);

        return out.toByteArray();
    }

    /**
     * COSE_Key for a P-256 EC2 public key (RFC 8152 / WebAuthn):
     *   { 1: 2 (kty EC2), 3: -7 (alg ES256), -1: 1 (crv P-256), -2: x(32), -3: y(32) }
     * Encoded as a definite-length CBOR map of 5 pairs. (AND-3)
     */
    private byte[] coseEncodeEcPublicKey(ECPublicKey publicKey) throws Exception {
        ECPoint point = publicKey.getW();
        byte[] x = toFixedLength(point.getAffineX().toByteArray(), 32);
        byte[] y = toFixedLength(point.getAffineY().toByteArray(), 32);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        cborWriteMapHeader(out, 5);

        cborWriteInt(out, 1);   // kty
        cborWriteInt(out, 2);   // EC2
        cborWriteInt(out, 3);   // alg
        cborWriteInt(out, -7);  // ES256
        cborWriteInt(out, -1);  // crv
        cborWriteInt(out, 1);   // P-256
        cborWriteInt(out, -2);  // x
        cborWriteByteString(out, x);
        cborWriteInt(out, -3);  // y
        cborWriteByteString(out, y);

        return out.toByteArray();
    }

    /**
     * Normalize a BigInteger.toByteArray() result to an exact unsigned length:
     * strip a leading sign byte, or left-pad with zeros.
     */
    private byte[] toFixedLength(byte[] src, int length) {
        if (src.length == length) {
            return src;
        }
        if (src.length == length + 1 && src[0] == 0) {
            byte[] out = new byte[length];
            System.arraycopy(src, 1, out, 0, length);
            return out;
        }
        byte[] out = new byte[length];
        if (src.length < length) {
            System.arraycopy(src, 0, out, length - src.length, src.length);
        } else {
            // Larger than expected (shouldn't happen for P-256): keep low-order bytes.
            System.arraycopy(src, src.length - length, out, 0, length);
        }
        return out;
    }

    // ----- Minimal CBOR primitives (definite-length only; no dependency) -----

    private void cborWriteTypeAndLength(ByteArrayOutputStream out, int majorType, long value) {
        int mt = majorType << 5;
        if (value < 24) {
            out.write(mt | (int) value);
        } else if (value < 0x100L) {
            out.write(mt | 24);
            out.write((int) (value & 0xFF));
        } else if (value < 0x10000L) {
            out.write(mt | 25);
            out.write((int) ((value >> 8) & 0xFF));
            out.write((int) (value & 0xFF));
        } else if (value < 0x100000000L) {
            out.write(mt | 26);
            out.write((int) ((value >> 24) & 0xFF));
            out.write((int) ((value >> 16) & 0xFF));
            out.write((int) ((value >> 8) & 0xFF));
            out.write((int) (value & 0xFF));
        } else {
            out.write(mt | 27);
            for (int i = 7; i >= 0; i--) {
                out.write((int) ((value >> (8 * i)) & 0xFF));
            }
        }
    }

    private void cborWriteMapHeader(ByteArrayOutputStream out, int pairs) {
        cborWriteTypeAndLength(out, 5, pairs); // major type 5 = map
    }

    private void cborWriteTextString(ByteArrayOutputStream out, String s) throws java.io.IOException {
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        cborWriteTypeAndLength(out, 3, bytes.length); // major type 3 = text string
        out.write(bytes);
    }

    private void cborWriteByteString(ByteArrayOutputStream out, byte[] bytes) throws java.io.IOException {
        cborWriteTypeAndLength(out, 2, bytes.length); // major type 2 = byte string
        out.write(bytes);
    }

    /** Encodes a CBOR integer, including negative values per RFC 8949. */
    private void cborWriteInt(ByteArrayOutputStream out, int value) {
        if (value >= 0) {
            cborWriteTypeAndLength(out, 0, value); // major type 0 = unsigned int
        } else {
            cborWriteTypeAndLength(out, 1, -1L - value); // major type 1 = negative int
        }
    }

    // ----- Misc crypto helpers -----

    private byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        return digest.digest(data);
    }

    private byte[] concat(byte[] a, byte[] b) {
        byte[] out = new byte[a.length + b.length];
        System.arraycopy(a, 0, out, 0, a.length);
        System.arraycopy(b, 0, out, a.length, b.length);
        return out;
    }

    private byte[] secureRandomBytes(int length) {
        byte[] bytes = new byte[length];
        new java.security.SecureRandom().nextBytes(bytes);
        return bytes;
    }

    /**
     * AND-4: report UV only when biometric/credential verification actually
     * occurred. On API 30+ we read the concrete authentication type; on older
     * APIs a successful BIOMETRIC_STRONG prompt with a CryptoObject implies UV.
     */
    private boolean wasUserVerified(BiometricPrompt.AuthenticationResult result) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            int type = result.getAuthenticationType();
            return type == BiometricPrompt.AUTHENTICATION_RESULT_TYPE_BIOMETRIC
                    || type == BiometricPrompt.AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL;
        }
        // Pre-R: the prompt only succeeds with a CryptoObject after strong
        // biometric verification, so UV is true here.
        return result.getCryptoObject() != null;
    }

    // =====================================================================
    // Session token storage (AND-5: encrypted at rest with a Keystore AES key)
    // =====================================================================

    private void persistSession(String token) {
        try {
            String encrypted = encryptToken(token);
            SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            prefs.edit()
                    .putString(PREF_SESSION_TOKEN, encrypted)
                    .putLong(PREF_SESSION_EXPIRY, System.currentTimeMillis() + (sessionDuration * 1000))
                    .apply();
        } catch (Exception e) {
            // Never persist an unencrypted token. If encryption fails, drop the
            // at-rest copy — the token is still returned to the caller in-memory.
            if (BuildConfig.DEBUG) {
                Log.w(TAG, "Failed to encrypt session token; not persisting at rest");
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private SecretKey getOrCreateTokenKey() throws Exception {
        if (keyStore.containsAlias(TOKEN_KEY_ALIAS)) {
            return (SecretKey) keyStore.getKey(TOKEN_KEY_ALIAS, null);
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE);
        KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(TOKEN_KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                // Token must be readable without a prompt (e.g. to check session
                // validity); the key never leaves the Keystore.
                .setUserAuthenticationRequired(false)
                .setKeySize(256)
                .build();
        keyGenerator.init(spec);
        return keyGenerator.generateKey();
    }

    private String encryptToken(String token) throws Exception {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            throw new IllegalStateException("Keystore AES requires API 23+");
        }
        SecretKey key = getOrCreateTokenKey();
        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] iv = cipher.getIV();
        byte[] encrypted = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8));
        byte[] combined = concat(iv, encrypted);
        return Base64.encodeToString(combined, Base64.NO_WRAP);
    }

    @SuppressWarnings("unused") // available for future session-read APIs
    private String decryptToken(String encrypted) throws Exception {
        SecretKey key = (SecretKey) keyStore.getKey(TOKEN_KEY_ALIAS, null);
        byte[] combined = Base64.decode(encrypted, Base64.NO_WRAP);
        byte[] iv = new byte[GCM_IV_LENGTH];
        byte[] cipherBytes = new byte[combined.length - GCM_IV_LENGTH];
        System.arraycopy(combined, 0, iv, 0, GCM_IV_LENGTH);
        System.arraycopy(combined, GCM_IV_LENGTH, cipherBytes, 0, cipherBytes.length);

        Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH, iv));
        return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
    }

    // =====================================================================
    // App-level lockout (AND-9)
    // =====================================================================

    private long getLockoutUntil() {
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        return prefs.getLong(PREF_LOCKOUT_UNTIL, 0L);
    }

    private void recordFailure() {
        if (maxAttempts <= 0) {
            return; // 0/negative disables app-level lockout; rely on the OS.
        }
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        int count = prefs.getInt(PREF_FAIL_COUNT, 0) + 1;
        SharedPreferences.Editor editor = prefs.edit();
        if (count >= maxAttempts) {
            editor.putInt(PREF_FAIL_COUNT, 0);
            editor.putLong(PREF_LOCKOUT_UNTIL, System.currentTimeMillis() + (lockoutDuration * 1000L));
        } else {
            editor.putInt(PREF_FAIL_COUNT, count);
        }
        editor.apply();
    }

    private void resetFailCount() {
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().putInt(PREF_FAIL_COUNT, 0).putLong(PREF_LOCKOUT_UNTIL, 0L).apply();
    }

    // =====================================================================
    // Token payload + client data + identifiers
    // =====================================================================

    private String createEnhancedToken(String credentialId, String type, JSObject credentialData) {
        try {
            JSONObject tokenPayload = new JSONObject();
            tokenPayload.put("credentialId", credentialId);
            tokenPayload.put("timestamp", System.currentTimeMillis());
            tokenPayload.put("sessionId", UUID.randomUUID().toString());
            tokenPayload.put("type", type);
            if (credentialData != null) {
                tokenPayload.put("credentialData", new JSONObject(credentialData.toString()));
            }
            String tokenJson = tokenPayload.toString();
            return Base64.encodeToString(tokenJson.getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP);
        } catch (JSONException e) {
            // Opaque session token fallback — NOT a credential/signature, safe.
            return UUID.randomUUID().toString();
        }
    }

    private String createClientDataJSON(String type, String challenge) {
        try {
            JSONObject clientData = new JSONObject();
            clientData.put("type", type);
            // The challenge from a server is already base64url; pass it through.
            clientData.put("challenge", challenge);
            clientData.put("origin", "android:apk-key-hash:" + getApkKeyHash());
            clientData.put("androidPackageName", getContext().getPackageName());
            clientData.put("crossOrigin", false);
            return clientData.toString();
        } catch (JSONException e) {
            return "{}";
        }
    }

    private String getApkKeyHash() {
        try {
            Context context = getContext();
            android.content.pm.PackageInfo packageInfo;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo = context.getPackageManager().getPackageInfo(
                        context.getPackageName(),
                        android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES);
                android.content.pm.Signature[] signatures = packageInfo.signingInfo.getApkContentsSigners();
                if (signatures.length > 0) {
                    return base64UrlEncode(sha256(signatures[0].toByteArray()));
                }
            } else {
                packageInfo = context.getPackageManager().getPackageInfo(
                        context.getPackageName(),
                        android.content.pm.PackageManager.GET_SIGNATURES);
                if (packageInfo.signatures != null && packageInfo.signatures.length > 0) {
                    return base64UrlEncode(sha256(packageInfo.signatures[0].toByteArray()));
                }
            }
        } catch (Exception e) {
            if (BuildConfig.DEBUG) {
                Log.w(TAG, "Failed to get APK key hash");
            }
        }
        return "unknown";
    }

    private int getAndIncrementSignCount(String credentialId) {
        SharedPreferences prefs = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String key = "signCount_" + credentialId;
        int signCount = prefs.getInt(key, 0);
        prefs.edit().putInt(key, signCount + 1).apply();
        return signCount;
    }

    private String resolveCredentialId(JSObject webAuthnOptions) {
        if (webAuthnOptions != null) {
            JSObject getOptions = webAuthnOptions.getJSObject("get");
            if (getOptions != null) {
                String stored = getOptions.getString("storedCredentialId");
                if (stored != null && !stored.isEmpty()) {
                    return stored;
                }
            }
        }
        // Fall back to a stable per-device alias so an assertion can find its key
        // even if the caller did not echo back a stored id.
        return "device_default";
    }

    private String resolveUserId(JSObject webAuthnOptions) {
        if (webAuthnOptions != null) {
            JSObject getOptions = webAuthnOptions.getJSObject("get");
            if (getOptions != null) {
                String userId = getOptions.getString("storedUserId");
                if (userId != null && !userId.isEmpty()) {
                    return userId;
                }
            }
        }
        return null;
    }

    private String getRpId(JSObject webAuthnOptions) {
        if (webAuthnOptions != null) {
            JSObject getOptions = webAuthnOptions.getJSObject("get");
            if (getOptions != null) {
                String rpId = getOptions.getString("rpId");
                if (rpId != null && !rpId.isEmpty()) {
                    return rpId;
                }
            }
            JSObject createOptions = webAuthnOptions.getJSObject("create");
            if (createOptions != null) {
                JSObject rp = createOptions.getJSObject("rp");
                if (rp != null) {
                    String rpId = rp.getString("id");
                    if (rpId != null && !rpId.isEmpty()) {
                        return rpId;
                    }
                }
            }
        }
        return getContext().getPackageName();
    }

    // =====================================================================
    // Error mapping (AND-7) — UPPER_CASE codes consistent with the JS layer.
    // =====================================================================

    private void rejectWithMappedError(PluginCall call, int errorCode, CharSequence errString) {
        String code;
        switch (errorCode) {
            case BiometricPrompt.ERROR_NEGATIVE_BUTTON:
            case BiometricPrompt.ERROR_USER_CANCELED:
            case BiometricPrompt.ERROR_CANCELED:
                code = "USER_CANCELLED";
                break;
            case BiometricPrompt.ERROR_LOCKOUT:
                code = "LOCKED_OUT";
                break;
            case BiometricPrompt.ERROR_LOCKOUT_PERMANENT:
                // Distinct subtype; JS maps any LOCKED_OUT variant to LOCKED_OUT.
                code = "LOCKED_OUT";
                break;
            case BiometricPrompt.ERROR_NO_BIOMETRICS:
            case BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL:
                code = "NOT_ENROLLED";
                break;
            case BiometricPrompt.ERROR_HW_NOT_PRESENT:
            case BiometricPrompt.ERROR_HW_UNAVAILABLE:
                code = "NOT_AVAILABLE";
                break;
            case BiometricPrompt.ERROR_TIMEOUT:
                code = "TIMEOUT";
                break;
            default:
                code = "AUTHENTICATION_FAILED";
                break;
        }
        call.reject(errString != null ? errString.toString() : code, code);
    }
}
