# Authentication

Ask the OS to confirm the device owner is present, with Touch ID, Face ID, Windows Hello, Android BiometricPrompt or polkit, from Kotlin Multiplatform code.

`authentication` asks the operating system to confirm that the device owner is present, through
the system's own prompt. Your app only learns whether it succeeded: it never sees a password or a
biometric. It is a Kotlin Multiplatform module: the same calls work on desktop, Android and iOS.

| Platform | Prompt | `Biometrics` policy |
| --- | --- | --- |
| Windows | Windows Hello (face, fingerprint, PIN). The account password through CredUI when Hello is not set up | No |
| macOS | LocalAuthentication `LAContext`: Touch ID, Apple Watch or the login password | Yes |
| Linux | polkit: the desktop's polkit agent asks for the password of an action your app declares | No |
| Android 9+ (API 28) | Framework `BiometricPrompt`, with the screen lock as fallback from API 29 | Yes |
| iOS | `LAContext`: Face ID or Touch ID, with the passcode as fallback | Yes |

This is a gate, not a key. Success releases nothing cryptographic, so a process that can patch
your app can skip the check. Use it for "confirm before showing the API key", not to protect a
secret at rest: keep secrets in a store that releases them only after the same check, such as
Keychain access control or the Android Keystore.

## Add the dependency

```kotlin title="build.gradle.kts"
// commonMain in a KMP project, dependencies { } in a JVM desktop app
implementation("dev.nucleusframework:nucleus.authentication:3.0.0")
```

`nucleus-application` does not bring it: add it yourself to call `NucleusWindow.authenticate`.

## Check availability

`Authenticator.availability(policy)` tells you, without showing anything, whether a prompt can
appear and which sensor the device has. Ask before you offer an "Unlock with Touch ID" button,
not after a failed attempt:

```kotlin
import dev.nucleusframework.authentication.Authenticator

val availability = Authenticator.availability(AuthenticationPolicy.Biometrics)
if (availability.isAvailable) {
    showUnlockButton(availability.biometry) // Fingerprint, Face, Iris, Unknown or None
} else {
    println("${availability.error}: ${availability.message}")
}
```

- `isAvailable` is `true` when `error` is `null`. `message` carries the platform's own words about
  the error.
- `biometry` names the sensor the device offers, enrolled or not. Windows Hello and Android
  devices with several sensors report `Unknown`. Linux always reports `None`.
- `Authenticator.isSupported` is `false` when the platform has no backend: on desktop, when the
  native library did not load, and on Android below API 28. `availability()` then returns
  `Unsupported`.
- On Linux, `availability()` checks that polkit answers on the system bus. It does not check your
  action id: an undeclared action fails only when you authenticate.

## Authenticate

```kotlin
scope.launch {
    try {
        Authenticator.authenticate(
            AuthenticationPrompt(
                reason = "unlock your vault",
                linuxActionId = "com.example.app.unlock", // required on Linux, see below
            ),
        )
        showVault()
    } catch (e: AuthenticationException) {
        if (e.error != AuthenticationError.UserCanceled) showError(e.error)
    }
}
```

- `authenticate` suspends until the user answers. It returns when the owner authenticated and
  throws `AuthenticationException` otherwise. Call it from any dispatcher: each platform moves to
  its own UI thread.
- Cancelling the calling coroutine dismisses the prompt and resumes the caller at once with a
  `CancellationException`. A late answer is dropped. Windows Hello is the exception: see
  [Limitations](#limitations).
- A blank `reason` fails with `InvalidPrompt` before anything is shown.

`AuthenticationPrompt` holds the text. Each platform shows what it has room for:

| Property | Shown |
| --- | --- |
| `reason` | Required. The `localizedReason` on Apple platforms ("*App* is trying to *reason*" on macOS), the message of Windows Hello and of the password prompt, the subtitle on Android. Not shown on Linux |
| `title` | Android's prompt title (the app's label when `null`) and the caption of the Windows password prompt |
| `cancelLabel` | The cancel button on Apple platforms and in Android's biometrics-only prompt. The platform's localized default when `null` |
| `linuxActionId` | The polkit action to check on Linux, required there. polkit shows the action's message, not `reason` |

### Choose a policy

`AuthenticationPolicy` says what counts as proof:

- `DeviceOwner` (default): a biometric, or whatever unlocks the device instead. That is the
  passcode or screen lock, the macOS login password or an Apple Watch, the Windows Hello PIN or
  the account password, or the password the polkit agent asks for.
- `Biometrics`: a biometric only. Windows cannot enforce it, because Hello always accepts its PIN,
  and neither can Linux, where PAM decides how polkit authenticates. There `authenticate` fails
  with `UnsupportedPolicy` rather than accept less, and `availability()` reports the same error.

On macOS and iOS, `Biometrics` hides the "Enter Password" fallback. On Android it allows strong
biometrics only and adds a cancel button.

## Choose the parent window

On Windows, the Hello dialog and the password prompt are modal to a window. From
`nucleus-application`, call `authenticate` on the window that asks:

```kotlin
val window = LocalNucleusWindow.current
scope.launch {
    window.authenticate(AuthenticationPrompt(reason = "unlock your vault"))
}
```

Without `nucleus-application`, pass an `AuthenticationParent` on the JVM:

```kotlin
Authenticator.authenticate(
    prompt,
    parent = AuthenticationParent.Windows(taoWindow.nativeHandle), // the Tao window's HWND
)
```

`AuthenticationParent.Auto`, the default, uses the app's frontmost window. A child window resolves
to its top-level window. Only Windows uses the parent: the macOS panel and the polkit agent's
dialog belong to the system.

On Android, the prompt is shown from the resumed activity. The overload
`Authenticator.authenticate(prompt, policy, activity)` names one explicitly.

## Set up each platform

### macOS

No entitlement or `Info.plist` key is needed. The Touch ID panel is system-modal and shows your
app's name before `reason`.

### iOS

Declare `NSFaceIDUsageDescription` in the app's `Info.plist` to use Face ID:

```xml title="Info.plist"
<key>NSFaceIDUsageDescription</key>
<string>Unlocks your vault with Face ID.</string>
```

An unanswered prompt times out by itself after about five minutes, with `SystemCanceled`.

### Windows

No manifest capability. When Windows Hello is set up, its dialog accepts face, fingerprint or
PIN. When it is not, a CredUI prompt asks for the current account's password; credentials of
another account fail with `Failed`. A group policy that disables Hello ends with
`DisabledByPolicy`.

### Linux

polkit only prompts for an action that an installed `.policy` file declares, and its dialog shows
that file's message. Declare the action in the Nucleus plugin: the Deb, RPM and Pacman packages
install it under `/usr/share/polkit-1/actions/` and remove it on uninstall.

```kotlin title="build.gradle.kts"
nucleus.application {
    nativeDistributions {
        linux {
            polkitActions {
                action("com.example.app.unlock") {
                    message = "Authentication is required to unlock Example"
                    // allowActive = PolkitAuthorization.AuthSelf (default): the user's own password
                }
            }
        }
    }
}
```

- `message` is required and must fit on one line. `description` is what `pkaction` lists, the
  message by default.
- `allowActive`, `allowInactive` and `allowAny` take a `PolkitAuthorization`: `No`, `Yes`,
  `AuthSelf`, `AuthSelfKeep`, `AuthAdmin` or `AuthAdminKeep`. `AuthSelf` asks for the user's own
  password, `AuthAdmin` for an administrator's, and the `*Keep` variants remember the answer for a
  few minutes. The defaults are `AuthSelf` for the active session and `No` for the others.
- An action the user may never perform (`No`) fails with `DisabledByPolicy`, without a prompt. A
  missing `linuxActionId`, or an action no `.policy` file declares, fails with `InvalidPrompt`.

Packaging without the plugin, install the equivalent file yourself:

```xml title="/usr/share/polkit-1/actions/com.example.app.unlock.policy"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
  "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<policyconfig>
  <action id="com.example.app.unlock">
    <description>Unlock Example</description>
    <message>Authentication is required to unlock Example</message>
    <defaults>
      <allow_any>no</allow_any>
      <allow_inactive>no</allow_inactive>
      <allow_active>auth_self</allow_active>
    </defaults>
  </action>
</policyconfig>
```

Flatpak, Snap and AppImage cannot install system files, so the plugin does not ship the action
there: it must already be declared on the host. In a Flatpak, also add
`--system-talk-name=org.freedesktop.PolicyKit1` to the [finish args](/docs/packaging/linux#build-a-flatpak-bundle).
Without it, every call fails with `Unavailable`.

### Android

The library manifest declares `USE_BIOMETRIC`, a normal permission granted at install, and a
`ContentProvider` that tracks the resumed activity. Removing that provider disables the library.
The module runs from API 21, but the prompt needs API 28: below it, `isSupported` is `false`.

## Handle errors

`AuthenticationException.error` is an `AuthenticationError`. The exception's message comes from
the platform when it gave one.

| Value | Meaning |
| --- | --- |
| `UserCanceled` | The user dismissed the prompt |
| `AppCanceled` | The app dismissed the prompt from outside the calling coroutine |
| `SystemCanceled` | The system dismissed it: another app came forward, the screen locked, the activity went away, or nobody answered for minutes |
| `Failed` | The user could not prove who they are |
| `Lockout` | Too many failed attempts: biometrics are locked until the device credential is entered again |
| `NotEnrolled` | The device has the sensor, but no fingerprint or face is enrolled |
| `NoCredential` | No passcode, screen lock or Windows Hello is set up |
| `Unavailable` | No usable sensor, no polkit agent, or an Android version without the prompt |
| `DisabledByPolicy` | Disabled by an administrator: a Windows group policy, or a polkit action denied to the user |
| `Busy` | The sensor is in use by another request |
| `NotInteractive` | The process cannot show UI right now (Apple platforms) |
| `UnsupportedPolicy` | This platform cannot enforce the policy: `Biometrics` on Windows and Linux |
| `InvalidPrompt` | A blank `reason`, no `linuxActionId` on Linux, or an action no `.policy` file declares |
| `Unsupported` | No backend on this platform, or the native library did not load |
| `Platform` | The platform API failed; read the message |

Cancelling the calling coroutine never produces `AppCanceled`: it throws `CancellationException`.

## Limitations

- **Windows Hello may outlive a cancel.** The caller always resumes at once, but the Hello dialog
  belongs to the system, which may leave it on screen until the user dismisses it. Answering it
  then changes nothing. Windows shows one Hello request at a time, so a new request first waits up
  to 15 seconds for a cancelled dialog to close. The CredUI password prompt does close on cancel.
- **No biometrics-only check on Windows and Linux.** `Biometrics` fails with `UnsupportedPolicy`
  there. A fingerprint reader on Linux works only if the system's PAM stack offers it to the
  polkit agent, which your app cannot control.
- **Linux shows the action's message**, not `reason`, and the dialog has no parent window.
- **polkit in a Flatpak.** The app identifies itself to polkit by its D-Bus name, so the check
  works inside a sandbox's own pid namespace. The action must still be declared on the host.

- Desktop goes through a Rust JNI library, `nucleus_authentication`, derived from
  `robius-authentication`. Android and iOS are pure Kotlin.
- macOS and iOS call `LAContext.evaluatePolicy` with a fresh context per request, and cancel with
  `LAContext.invalidate()`.
- Windows calls `UserConsentVerifier` through its window interop, and checks the CredUI password
  with `LogonUserW`.
- Linux calls polkit's `CheckAuthorization` over D-Bus with user interaction allowed, as the
  connection's unique bus name, and cancels with `CancelCheckAuthorization`.
- Android uses the framework `BiometricPrompt`, not `androidx.biometric`: no AndroidX dependency
  and no `FragmentActivity` requirement.
- The JVM artifact carries GraalVM reachability metadata.

## API reference

| Symbol | Notes |
| --- | --- |
| `Authenticator.isSupported` | Whether this platform has a backend |
| `Authenticator.availability(policy = DeviceOwner)` | `suspend`, returns `AuthenticationAvailability(biometry, error, message)` without showing anything |
| `Authenticator.authenticate(prompt, policy = DeviceOwner)` | `suspend`, throws `AuthenticationException` |
| `Authenticator.authenticate(prompt, policy, parent)` | JVM: owned by an `AuthenticationParent` (`Auto` or `Windows(hwnd)`) |
| `Authenticator.authenticate(prompt, policy, activity)` | Android: shown from this `Activity` |
| `NucleusWindow.authenticate(prompt, policy = DeviceOwner)` | In `nucleus-application`: parents the prompt to the window on Windows |
| `AuthenticationPrompt(reason, title, cancelLabel, linuxActionId)` | The prompt's text |
| `AuthenticationPolicy` | `DeviceOwner`, `Biometrics` |
| `BiometryType` | `None`, `Fingerprint`, `Face`, `Iris`, `Unknown` |

## What's next

- [Location](/docs/os/location): another Kotlin Multiplatform module.
- [Building for Linux](/docs/packaging/linux): the Deb, RPM, Pacman and Flatpak formats.
- [Sandboxing](/docs/packaging/sandboxing): the Flatpak sandbox.
