MacLustr Identity — Android SDK
Native Kotlin SDK for integrating a MacLustr Identity verification into an Android app. Sources: sdk/kotlin.
- Package:
ai.spboucher.maclustr.identity(core) andai.spboucher.maclustr.identity.ui(UI). - minSdk 26 (Android 8.0), Kotlin + coroutines, Jetpack Compose, CameraX.
- Version 1.1.0. Nothing is published to a Maven registry: the SDK is consumed from this repository (see Installation).
Status: everything below compiles and the core is unit-tested and integration-tested against a local backend. No part of the camera flow has been run on a physical device or an emulator yet; see Not verified on a device.
Architecture rule
A mobile app never holds a secret API key.
- Your backend creates the session with its secret key:
POST /v1/verification-sessions. - It returns to your app either the hosted
url(https://identity.spboucher.ai/verify/{id}#{client_secret}) or the pair{session_id, client_secret}. The client secret (vsc_…) is scoped to that single session. - The app runs the flow with the SDK.
- The SDK reports an outcome for user experience only. Your app must trust only your backend, which learns
the result from the webhook (
verification.verified,verification.completed,verification.cancelled, …) or fromGET /v1/verifications/{id}.
Modules
| Module | Type | Content |
|---|---|---|
identity-core |
Kotlin/JVM library | IdentitySession, IdentityClient (every flow endpoint), models, IdentityError, VerificationFlowModel (state machine), fr/en strings, capture-guidance logic. No Android dependency. |
identity-ui |
Android library | IdentityVerificationContract, IdentityVerificationActivity, IdentityVerificationScreen (Compose), IdentityWebFlow (Custom Tabs). Depends on identity-core. |
demo |
Android app | Paste or fetch a hosted URL, run the native flow or the web flow. |
Dependencies of the SDK: kotlinx-coroutines, kotlinx-serialization-json (runtime only, used to parse JSON),
Compose (BOM 2026.11.01: ui, foundation, material3), activity-compose, lifecycle, core-ktx, androidx.browser,
CameraX 1.7.0 (core, camera2, lifecycle, view). HTTP uses HttpURLConnection. No Google Play services, no ML Kit,
no analytics library.
Installation
Toolchain used to build the SDK: JDK 21, Gradle 9.9.3 (wrapper included), Android Gradle Plugin 9.5.3 (built-in Kotlin), Kotlin plugins 2.4.21, compileSdk 37.2.
Clone the repository (or add it as a git submodule), then include the two library modules in your build.
In your app's settings.gradle.kts:
include(":identity-core", ":identity-ui")
project(":identity-core").projectDir = file("path/to/maclustr-identity/sdk/kotlin/identity-core")
project(":identity-ui").projectDir = file("path/to/maclustr-identity/sdk/kotlin/identity-ui")Your root build.gradle.kts must declare the plugins the modules apply (versions as in sdk/kotlin/build.gradle.kts):
plugins {
id("com.android.library") version "9.5.3" apply false
id("org.jetbrains.kotlin.jvm") version "2.4.21" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false
}In your app module:
dependencies {
implementation(project(":identity-ui")) // brings identity-core
}A Gradle composite build (includeBuild("path/to/maclustr-identity/sdk/kotlin")) is not set up: the modules do not
declare Maven coordinates for substitution. Use the include form above.
Manifest and permissions
Nothing to add to your manifest. The identity-ui manifest is merged into your app and declares:
android.permission.CAMERA(requested at runtime by the SDK, only when a live session reaches a capture step);android.permission.INTERNET;<uses-feature android:name="android.hardware.camera.any" android:required="false" />, so that your app stays installable on devices without a camera;IdentityVerificationActivity(exported="false").
CameraX pulls androidx.media3:media3-common transitively, which adds ACCESS_NETWORK_STATE to the merged
manifest. The SDK itself does not use it.
No R8/ProGuard rule is required (the SDK uses no reflection).
Quick start
import ai.spboucher.maclustr.identity.IdentitySession
import ai.spboucher.maclustr.identity.IdentityVerificationResult
import ai.spboucher.maclustr.identity.ui.IdentityVerificationArgs
import ai.spboucher.maclustr.identity.ui.IdentityVerificationContract
class AccountActivity : ComponentActivity() {
private val verification = registerForActivityResult(IdentityVerificationContract()) { result ->
when (result) {
is IdentityVerificationResult.Completed -> refreshFromBackend() // result.status is a hint only
IdentityVerificationResult.Canceled -> Unit
is IdentityVerificationResult.Failed -> showError(result.error)
}
}
fun startVerification(urlFromMyBackend: String) {
val session = IdentitySession.fromUrl(urlFromMyBackend) // throws IdentityError.InvalidSessionUrl
verification.launch(IdentityVerificationArgs(session))
}
}With the pair instead of the URL: IdentitySession.of(sessionId, clientSecret) (third argument: base URL, by
default https://identity.spboucher.ai).
IdentitySession accepts https origins only; plain http is accepted for localhost, 127.0.0.1 and ::1
(local development). Its toString() never prints the client secret.
In Compose
val launcher = rememberLauncherForActivityResult(IdentityVerificationContract()) { result -> /* … */ }
Button(onClick = { launcher.launch(IdentityVerificationArgs(session)) }) { Text("Verify my identity") }To host the flow in your own screen instead of the SDK activity:
IdentityVerificationScreen(session = session, configuration = IdentityConfiguration(), onFinish = { result -> /* called once */ })The composable must fill the screen, needs a ViewModelStoreOwner (any ComponentActivity or navigation entry
provides one) and sets FLAG_SECURE on the window while it is displayed.
Web flow (no native UI)
IdentityWebFlow.launch(context, session) // Custom Tab, or the default browserThe browser reports nothing back. Create the session with a return_url handled by your app (App Link or custom
scheme) and ask your backend for the result when the app is resumed.
Result handling
IdentityVerificationResult:
| Value | Meaning |
|---|---|
Completed(status) |
The flow reached its end. status is the session status last seen by the SDK: usually verified, manual_review, processing (the person closed while the analysis was still running), inconclusive, rejected, expired or revoked. |
Canceled |
The person left before the end, or withdrew consent (the service then destroyed everything). |
Failed(error) |
The flow could not run: invalid session or secret, network failure at start… |
Create a new session after Canceled, Completed(EXPIRED) or Completed(INCONCLUSIVE) (for example reason
review_not_completed: the review by a person was not completed before its deadline). None of these is a refusal.
SessionStatus has one constant per known status (SessionStatus.VERIFIED, …); status.raw is the wire value,
and a status unknown to this SDK version is preserved (isKnown == false).
IdentityError (sealed): Api(ApiError(status, type, code, message, param, requestId, retryAfterSeconds)),
Network, InvalidResponse, Cancelled, InvalidSessionUrl, SessionExpired, CameraDenied,
CameraUnavailable, CaptureFailed. error.code gives the API error code; isRetryable, retryAfterSeconds,
isSessionStateConflict and isAuthenticationFailure classify it.
API messages are developer-facing and are never shown to the person; the UI shows its own fr/en texts.
Never unlock anything from Completed(VERIFIED) alone: confirm with your backend.
What the flow does
Steps of VerificationFlowModel (the same as the iOS SDK): loading → intro → method choice (skipped when the
policy offers a single method) → consent → document front → document back (can be skipped: "My document has no
back") → selfie (method document_selfie only) → submitting → processing (polling: 1 s, ×1.5, capped at 8 s,
each delay spread by ±20 %; a Retry-After answer is followed, up to 60 s; a "you can close" notice after
90 s) → result.
- Consent: the title, body, points and checkbox label come from the API and are displayed as provided; the
accept button stays disabled until the box is ticked;
text_versionis theversionof the text that was displayed, as received from the service (the SDK holds no version of its own);biometric_consentis sent only for biometric methods. - Changing method: while nothing is submitted (document or selfie step) and the session offers more than one method, "Change method" returns to the method choice. Accepting the consent of another method makes the service destroy the images already uploaded and the capture starts over; "Back" returns to the capture with nothing changed.
- Retry: when the service returns to
awaiting_documentafter an inconclusive capture, the flow goes back to the document front with a notice, the number of attempts left and the reasons sent by the service (last_issue, shown as provided, in the flow's language); the same happens when such a session is resumed. - Expiry and external changes: on
invalid_session_statethe model reloads the state and shows the matching result (for example "Session expired"). - Withdrawal: "Withdraw my consent" is available from the first capture until the decision, including while
a person reviews the file (
manual_review); it callsPOST …/withdrawand the flow ends withCanceled. - Nothing is destroyed without a confirmation: the header button ("Cancel") and the system back gesture never withdraw anything; on a step under way they ask "Leave the verification?" (Leave keeps the session valid and resumable, Stay). "Withdraw my consent" always opens an explicit confirmation ("Withdraw and destroy everything"); touching outside the dialog or pressing back dismisses it without doing anything.
- Dispute: after
rejectedorinconclusive, the person can contest the decision (5 to 2000 characters). - Sandbox sessions (
livemode == false) never open the camera: after the consent, the flow shows the simulated scenarios returned by the service and callsPOST …/sandbox. - Resume: starting the flow on a session already under way positions it on the right step.
Document capture
CameraX back camera, card-shaped framing window, live hint, automatic shutter and a manual shutter button that is always available.
- The document is a full-resolution still photo, never an analysis frame (a 1080p frame is too small for the
PDF417 barcode of a licence):
ImageCapturewithCAPTURE_MODE_MAXIMIZE_QUALITY, JPEG quality 100 from the camera, flash off, and aResolutionSelectorasking for the closest size at or above 4000 × 3000, else the largest the camera has (PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE). A 50–200 MP sensor is therefore not asked for an image far larger than what is kept. - The photo is captured in memory (
takePicturewithOnImageCapturedCallback), decoded upright, reduced only when its long side exceeds 3600 px (what the service accepts; it is never enlarged) and re-encoded as JPEG at quality 92, which also drops EXIF metadata. If the result exceeded 12 MB the quality would be lowered, not the resolution. These rules live inDocumentImagePolicy(identity-core, unit-tested). - It is shown on a review screen ("Use this photo" / "Retake"), then uploaded. When its short side is under 1000 px the review screen warns that the barcode and the fine print may be unreadable; the warning does not block the upload. After a failed upload the same in-memory photo stays on the review screen.
- Quality issues returned by the service (
image_blurry,image_too_dark, …) are shown as fr/en messages and the capture restarts.
Honest limits of the guidance: there is no document detector on Android yet. The hints come from
HeuristicDocumentGuide: brightness, contrast and sharpness (Laplacian variance) measured in the central 70 % of
the analysis frame, and steadiness measured by comparing coarse luminance grids between frames. The guidance
cannot tell whether a document is really in the frame, nor ask to "move closer"; the automatic shutter may fire
on any sharp, steady, well-lit scene, which is why the review screen always follows. Thresholds are approximations
of the server-side checks, not the same computation. Disable the automatic shutter with
IdentityConfiguration(autoCapture = false). No on-device text pre-read (OCR) is performed.
Selfie and liveness
Front camera, oval window, one instruction at a time ("Look straight ahead", "Slowly turn your head to your
left", "Come back to the centre"…), a chevron on the side to turn towards and a progress bar. Frames are taken
from ImageAnalysis at the interval given by the challenge (250 ms), rotated upright, not mirrored (the
preview is mirrored, the uploaded frames are not), encoded as JPEG (long side at most 960 px) and kept in memory.
At most frames.max (24) frames are uploaded, chosen by FrameSelector: the last frame of each phase plus an
even spread of the others.
Honest limits of the guidance: the Android SDK bundles no face-landmark detector. ML Kit was deliberately not added: according to its documentation its SDK sends usage and performance metrics to Google, which would contradict the commitment that nothing leaves the device except towards MacLustr Identity. Consequently:
- the head turns are prompted on a fixed schedule (
TimedLivenessGuide: 1.5 s centre, then 2.5 s per turn and 2 s back to the centre; 10.5 s for two movements); the SDK does not measure the head pose and does not know whether the person followed the instructions; - the platform detector
android.media.FaceDetectoris used only to wait for a frontal face of sufficient size before the schedule starts ("Place your face in the oval" / "Move closer"); after 4 s without detection the capture starts anyway; - the server alone decides whether the challenge was performed. A person who moves too late or too little gets
liveness_failed/manual_reviewor a new capture from the server, not from the app.
LivenessGuide (pose-driven guidance with the same yaw index and step order as the server) is implemented and
tested in identity-core, ready for a bundled detector (roadmap).
Accessible alternative: "I can't do these movements" requests a challenge with accessible: true; no movement
is asked, about 2.5 s of frames are captured (the challenge then asks for 3 frames at least, 8 otherwise: the
SDK always uses the counts it receives), and the service routes the verification to a human reviewer.
Permission and interruptions
- Before the system prompt, a screen explains what the camera is used for. After a refusal the SDK offers to ask again, or "Open settings" (application details) when the system no longer prompts. The permission is re-checked when the app comes back to the foreground.
- A device without any camera gets an explanatory message instead of the capture.
- CameraX stops the camera when the app goes to the background. A selfie capture interrupted that way is discarded and the step restarts with a new challenge; the document guidance restarts from scratch.
- The flow model lives in a
ViewModel: a configuration change (rotation, dark mode switch) keeps the session state, but a capture in progress on the current screen restarts.
Theming
IdentityConfiguration(language = IdentityLanguage.FR)forces the language; by default the flow follows thelocaleof the session chosen by your backend (fr-*→ French, anything else → English). All SDK texts exist in French (Québec wording: "égoportrait", "téléverser") and English, inIdentityString.IdentityConfiguration(accentColor = 0xFF0B5FFF.toInt())overrides the accent; otherwise the accent, logo and name of the application branding returned by the service are used. An accent too close to the background falls back to a neutral tone. The logo is loaded over https only, in memory, 1 MB at most.- "Verification performed by MacLustr Identity" is always displayed in the footer and cannot be removed: the person must know which entity processes the information.
- Light and dark themes follow the system. Flat surfaces, no gradient.
Accessibility
- Every screen is a scrollable column with the actions pinned at the bottom; text uses Material typography in
spand follows the system font scale. - Titles are marked as headings; capture hints, errors, the processing text and the result are live regions (the selfie instruction is assertive) so that TalkBack announces them; the logo and the camera preview have content descriptions; the consent checkbox is a single toggleable row with the checkbox role.
- Touch targets are at least 48 dp. Colour is never the only signal.
- No animation besides the progress indicators.
- The accessible selfie alternative is described above.
None of this has been checked with TalkBack on a device yet.
Privacy behaviour
- Images exist only in memory: the document JPEG and the selfie frames are byte arrays handed to the upload and then released. The SDK creates no file, uses no cache directory, writes nothing to the gallery.
- The SDK logs nothing (no
Logcall) and embeds no analytics or crash reporter. FLAG_SECUREis set on the verification window: no screenshot, no screen recording, no preview in the recent apps list.- HTTP calls go only to the base URL of the session (and to the https logo URL of the application branding),
without cache, cookies or redirects. The client secret is sent in the
Authorizationheader only and is never printed. - The platform face detector runs on a downscaled copy of the frame, in memory; its output is a "face present" flag that is neither kept nor sent.
- The session id and client secret travel in an explicit, non-exported intent inside your own app.
Using the core without the UI
val client = IdentityClient(IdentitySession.fromUrl(url))
val state = client.flowState() // suspend
client.consent(method = "document_review", textVersion = state.methods[0].consentText(IdentityLanguage.EN)!!.version, biometricConsent = false)
client.uploadDocument(DocumentSide.FRONT, jpegBytes)
client.submit()Or drive the state machine: VerificationFlowModel(client, scope) exposes snapshot: StateFlow<FlowSnapshot> and
suspend actions (start, acceptConsent, uploadDocument, requestChallenge, uploadSelfie, submit,
runSandboxScenario, withdraw, dispute) plus changeMethod() / resumeCapture(). It is not thread-safe:
use it from one thread (the main thread).
FlowState carries, besides the status, the methods and their consent texts: attemptsLeft, maxAttempts,
lastIssue (why the previous capture must be redone), document (front, back, backRequiredFor,
accepted) and expiresAt (isPastExpiry()).
Resilience
- Retries.
IdentityClientretries a call after a network failure, a 429rate_limitedor a 5xx, twice by default (IdentityRetryPolicy): the delay is a random value in [50 %, 100 %] ofmin(8 s, 0.5 s × 2ⁿ). ARetry-After(429, 503service_unavailable) is followed when it is 15 s or less; a longer one is not waited for inside the flow: the error is returned withretryAfterSecondsand the screen says to try again in a moment. Quotas of the session (too_many_uploads,too_many_challenges) and every other 4xx (400, 401, 403forbidden_network, 409, 411, 413payload_too_large) are never retried.IdentityRetryPolicy.NONEmakes a single attempt. The policy is a constructor argument ofIdentityClient;IdentityConfigurationdoes not expose it (the UI uses the default). - Uploads. The request is built once: a retried upload sends the same bytes held in memory, nothing is captured again. When the answer to a selfie upload was lost and the retry finds its challenge already used, the model checks the flow state and continues if the service holds the frames.
- Deadlines. Each attempt has its own deadline (
HttpRequest.timeoutMs), enforced by the client with a coroutine timeout whatever the transport does, and applied by the default transport to the connection and to each read: 20 s for a JSON call, 120 s for an image upload. - Cancellation. Cancelling the calling coroutine cancels the request and the wait between two attempts
(
CancellationExceptionis always rethrown, never turned into an error), and the model's busy flag is reset. Afterstop(), an answer still in flight no longer restarts polling. - Session ending under the flow. When the session expires, is cancelled by your backend or is decided
elsewhere, the next action receives
409 invalid_session_state: the model reloads the state and shows the matching result. If that reload fails too, the error is kept inlastErrorand the step does not move. - Tolerant parsing. Unknown fields are ignored, an unknown status keeps its raw value
(
SessionStatus.isKnown == false), an unknown challenge step isUNKNOWN, a missing or malformed optional field takes a neutral default and a malformed list element is skipped. Onlyidandstatusare required in a flow state. A method without a knownbiometricflag is treated as biometric (the express consent is asked), and a state withoutlivemodeis treated as live.
Tests
cd sdk/kotlin
export JAVA_HOME=$(brew --prefix openjdk@21)
echo "sdk.dir=/opt/homebrew/share/android-commandlinetools" > local.properties
./gradlew :identity-core:test :identity-ui:assembleDebug :demo:assembleDebugidentity-core has 91 JUnit tests: 85 unit tests (decoding of real JSON captured from the backend, tolerant
parsing and the new flow fields, hosted-URL parsing, multipart encoding, error mapping, state machine with a
scripted transport, capture-guidance logic, document image rules, and 25 resilience tests: retries with the same
bytes, Retry-After, deadlines, cancellation, session expiring at each step, withdrawal during review, change
of method) and 6 integration tests that run only when MLID_TEST_BASE_URL and MLID_TEST_API_KEY (a sandbox
key) are set; the upload test also needs MLID_TEST_LIVE_API_KEY and MLID_TEST_FIXTURES (see
sdk/kotlin/README.md). The test helper that creates a session with an API key stands in for your backend and
is not part of the SDK. One test reads the Swift string table (sdk/swift/…/Strings.swift) and checks that the
two SDKs have the same keys, in the same order, with the same French and English texts. The JSON fixtures are
captured from a local backend by sdk/capture-fixtures.py (shared with the Swift SDK).
identity-ui and demo have no automated tests: they are compiled and assembled (assembleDebug), and
identity-ui passes Android lint without errors (:identity-ui:lintDebug). The
confirmation dialogs, the low-resolution warning and the "Change method" path of the Android UI are therefore
verified by reading the code only; the same logic is tested in identity-core and, for iOS, on a Simulator.
Not verified on a device
Compiled only; never run on a phone or an emulator. The finding of the platform's first real-device trial (a
1080p video frame is too small for a licence barcode) is answered here in code and in unit tests of
DocumentImagePolicy only: the full-resolution capture has not itself been tried on a device.
- the size actually delivered by
ImageCapturewith the resolution selector described above (it depends on the sizes each camera advertises), whether the PDF417 barcode of a licence is readable in the resulting 3600 px JPEG, and the memory and time taken by decoding a 12 MP (or larger) capture on low-end devices (a failed decode, including an out-of-memory error, shows "Capture was interrupted" and lets the person retry); - the confirmation dialogs (leave, withdraw), the "Change method" path and the low-resolution warning on screen;
- camera preview, capture quality and orientation of the document photo;
- orientation and non-mirroring of the selfie frames on real sensors (the code applies the rotation reported by CameraX and no mirroring);
- behaviour of
android.media.FaceDetectoracross devices; - whether the timed head-turn schedule is comfortable and yields sequences the server accepts;
- thresholds of the document guidance against the server-side quality checks;
- permission dialogs, "Open settings" path, background/foreground interruptions;
- TalkBack announcements, large font scales, dark theme rendering;
- Custom Tabs launch;
- the intent round-trip of
IdentityVerificationContract(no instrumented or Robolectric test).
Limits and roadmap
- No device attestation: Play Integrity is not implemented. The server cannot yet tell a genuine app on a genuine device from a script holding a valid client secret. Planned.
- NFC reading of the e-passport chip is not implemented. Planned.
- No on-device document detector, no on-device face landmarks (see the capture sections). Planned: a bundled
detector without telemetry, which will switch the selfie guidance to
LivenessGuide. - No file-picker fallback for the document on Android: a camera is required for live sessions.
- No on-device text pre-read.
- Not published to Maven Central or any registry.
- Strings are bundled in French and English only.