Repository Public
1# MacLustr Identity — Android SDK23Native Kotlin SDK for integrating a MacLustr Identity verification into an Android app. Sources: `sdk/kotlin`.45- Package: `ai.spboucher.maclustr.identity` (core) and `ai.spboucher.maclustr.identity.ui` (UI).6- minSdk 26 (Android 8.0), Kotlin + coroutines, Jetpack Compose, CameraX.7- Version 1.1.0. **Nothing is published to a Maven registry**: the SDK is consumed from this repository (see8 [Installation](#installation)).910Status: everything below compiles and the core is unit-tested and integration-tested against a local backend.11**No part of the camera flow has been run on a physical device or an emulator yet**; see12[Not verified on a device](#not-verified-on-a-device).1314## Architecture rule1516A mobile app never holds a secret API key.17181. Your backend creates the session with its secret key: `POST /v1/verification-sessions`.192. It returns to your app either the hosted `url` (`https://identity.spboucher.ai/verify/{id}#{client_secret}`) or20 the pair `{session_id, client_secret}`. The client secret (`vsc_…`) is scoped to that single session.213. The app runs the flow with the SDK.224. The SDK reports an outcome **for user experience only**. Your app must trust only your backend, which learns23 the result from the webhook (`verification.verified`, `verification.completed`, `verification.cancelled`,24 …) or from `GET /v1/verifications/{id}`.2526## Modules2728| Module | Type | Content |29|---|---|---|30| `identity-core` | Kotlin/JVM library | `IdentitySession`, `IdentityClient` (every flow endpoint), models, `IdentityError`, `VerificationFlowModel` (state machine), fr/en strings, capture-guidance logic. No Android dependency. |31| `identity-ui` | Android library | `IdentityVerificationContract`, `IdentityVerificationActivity`, `IdentityVerificationScreen` (Compose), `IdentityWebFlow` (Custom Tabs). Depends on `identity-core`. |32| `demo` | Android app | Paste or fetch a hosted URL, run the native flow or the web flow. |3334Dependencies of the SDK: kotlinx-coroutines, kotlinx-serialization-json (runtime only, used to parse JSON),35Compose (BOM 2026.11.01: ui, foundation, material3), activity-compose, lifecycle, core-ktx, androidx.browser,36CameraX 1.7.0 (core, camera2, lifecycle, view). HTTP uses `HttpURLConnection`. No Google Play services, no ML Kit,37no analytics library.3839## Installation4041Toolchain used to build the SDK: JDK 21, Gradle 9.9.3 (wrapper included), Android Gradle Plugin 9.5.3 (built-in42Kotlin), Kotlin plugins 2.4.21, compileSdk 37.2.4344Clone the repository (or add it as a git submodule), then include the two library modules in your build.45In your app's `settings.gradle.kts`:4647```kotlin48include(":identity-core", ":identity-ui")49project(":identity-core").projectDir = file("path/to/maclustr-identity/sdk/kotlin/identity-core")50project(":identity-ui").projectDir = file("path/to/maclustr-identity/sdk/kotlin/identity-ui")51```5253Your root `build.gradle.kts` must declare the plugins the modules apply (versions as in `sdk/kotlin/build.gradle.kts`):5455```kotlin56plugins {57 id("com.android.library") version "9.5.3" apply false58 id("org.jetbrains.kotlin.jvm") version "2.4.21" apply false59 id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false60}61```6263In your app module:6465```kotlin66dependencies {67 implementation(project(":identity-ui")) // brings identity-core68}69```7071A Gradle composite build (`includeBuild("path/to/maclustr-identity/sdk/kotlin")`) is not set up: the modules do not72declare Maven coordinates for substitution. Use the `include` form above.7374## Manifest and permissions7576Nothing to add to your manifest. The `identity-ui` manifest is merged into your app and declares:7778- `android.permission.CAMERA` (requested at runtime by the SDK, only when a live session reaches a capture step);79- `android.permission.INTERNET`;80- `<uses-feature android:name="android.hardware.camera.any" android:required="false" />`, so that your app stays81 installable on devices without a camera;82- `IdentityVerificationActivity` (`exported="false"`).8384CameraX pulls `androidx.media3:media3-common` transitively, which adds `ACCESS_NETWORK_STATE` to the merged85manifest. The SDK itself does not use it.8687No R8/ProGuard rule is required (the SDK uses no reflection).8889## Quick start9091```kotlin92import ai.spboucher.maclustr.identity.IdentitySession93import ai.spboucher.maclustr.identity.IdentityVerificationResult94import ai.spboucher.maclustr.identity.ui.IdentityVerificationArgs95import ai.spboucher.maclustr.identity.ui.IdentityVerificationContract9697class AccountActivity : ComponentActivity() {98 private val verification = registerForActivityResult(IdentityVerificationContract()) { result ->99 when (result) {100 is IdentityVerificationResult.Completed -> refreshFromBackend() // result.status is a hint only101 IdentityVerificationResult.Canceled -> Unit102 is IdentityVerificationResult.Failed -> showError(result.error)103 }104 }105106 fun startVerification(urlFromMyBackend: String) {107 val session = IdentitySession.fromUrl(urlFromMyBackend) // throws IdentityError.InvalidSessionUrl108 verification.launch(IdentityVerificationArgs(session))109 }110}111```112113With the pair instead of the URL: `IdentitySession.of(sessionId, clientSecret)` (third argument: base URL, by114default `https://identity.spboucher.ai`).115116`IdentitySession` accepts https origins only; plain http is accepted for `localhost`, `127.0.0.1` and `::1`117(local development). Its `toString()` never prints the client secret.118119### In Compose120121```kotlin122val launcher = rememberLauncherForActivityResult(IdentityVerificationContract()) { result -> /* … */ }123Button(onClick = { launcher.launch(IdentityVerificationArgs(session)) }) { Text("Verify my identity") }124```125126To host the flow in your own screen instead of the SDK activity:127128```kotlin129IdentityVerificationScreen(session = session, configuration = IdentityConfiguration(), onFinish = { result -> /* called once */ })130```131132The composable must fill the screen, needs a `ViewModelStoreOwner` (any `ComponentActivity` or navigation entry133provides one) and sets `FLAG_SECURE` on the window while it is displayed.134135### Web flow (no native UI)136137```kotlin138IdentityWebFlow.launch(context, session) // Custom Tab, or the default browser139```140141The browser reports nothing back. Create the session with a `return_url` handled by your app (App Link or custom142scheme) and ask your backend for the result when the app is resumed.143144## Result handling145146`IdentityVerificationResult`:147148| Value | Meaning |149|---|---|150| `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`. |151| `Canceled` | The person left before the end, or withdrew consent (the service then destroyed everything). |152| `Failed(error)` | The flow could not run: invalid session or secret, network failure at start… |153154Create a new session after `Canceled`, `Completed(EXPIRED)` or `Completed(INCONCLUSIVE)` (for example reason155`review_not_completed`: the review by a person was not completed before its deadline). None of these is a refusal.156157`SessionStatus` has one constant per known status (`SessionStatus.VERIFIED`, …); `status.raw` is the wire value,158and a status unknown to this SDK version is preserved (`isKnown == false`).159160`IdentityError` (sealed): `Api(ApiError(status, type, code, message, param, requestId, retryAfterSeconds))`,161`Network`, `InvalidResponse`, `Cancelled`, `InvalidSessionUrl`, `SessionExpired`, `CameraDenied`,162`CameraUnavailable`, `CaptureFailed`. `error.code` gives the API error code; `isRetryable`, `retryAfterSeconds`,163`isSessionStateConflict` and `isAuthenticationFailure` classify it.164API messages are developer-facing and are never shown to the person; the UI shows its own fr/en texts.165166Never unlock anything from `Completed(VERIFIED)` alone: confirm with your backend.167168## What the flow does169170Steps of `VerificationFlowModel` (the same as the iOS SDK): loading → intro → method choice (skipped when the171policy offers a single method) → consent → document front → document back (can be skipped: "My document has no172back") → selfie (method `document_selfie` only) → submitting → processing (polling: 1 s, ×1.5, capped at 8 s,173each delay spread by ±20 %; a `Retry-After` answer is followed, up to 60 s; a "you can close" notice after17490 s) → result.175176- **Consent**: the title, body, points and checkbox label come from the API and are displayed as provided; the177 accept button stays disabled until the box is ticked; `text_version` is the `version` of the text that was178 displayed, as received from the service (the SDK holds no version of its own); `biometric_consent` is sent179 only for biometric methods.180- **Changing method**: while nothing is submitted (document or selfie step) and the session offers more than one181 method, "Change method" returns to the method choice. Accepting the consent of another method makes the182 service destroy the images already uploaded and the capture starts over; "Back" returns to the capture with183 nothing changed.184- **Retry**: when the service returns to `awaiting_document` after an inconclusive capture, the flow goes back to185 the document front with a notice, the number of attempts left and the reasons sent by the service186 (`last_issue`, shown as provided, in the flow's language); the same happens when such a session is resumed.187- **Expiry and external changes**: on `invalid_session_state` the model reloads the state and shows the matching188 result (for example "Session expired").189- **Withdrawal**: "Withdraw my consent" is available from the first capture until the decision, including while190 a person reviews the file (`manual_review`); it calls `POST …/withdraw` and the flow ends with `Canceled`.191- **Nothing is destroyed without a confirmation**: the header button ("Cancel") and the system back gesture192 never withdraw anything; on a step under way they ask "Leave the verification?" (*Leave* keeps the session193 valid and resumable, *Stay*). "Withdraw my consent" always opens an explicit confirmation ("Withdraw and194 destroy everything"); touching outside the dialog or pressing back dismisses it without doing anything.195- **Dispute**: after `rejected` or `inconclusive`, the person can contest the decision (5 to 2000 characters).196- **Sandbox sessions** (`livemode == false`) never open the camera: after the consent, the flow shows the197 simulated scenarios returned by the service and calls `POST …/sandbox`.198- **Resume**: starting the flow on a session already under way positions it on the right step.199200### Document capture201202CameraX back camera, card-shaped framing window, live hint, automatic shutter and a manual shutter button that is203always available.204205- The document is a **full-resolution still photo**, never an analysis frame (a 1080p frame is too small for the206 PDF417 barcode of a licence): `ImageCapture` with `CAPTURE_MODE_MAXIMIZE_QUALITY`, JPEG quality 100 from the207 camera, flash off, and a `ResolutionSelector` asking for the closest size at or above 4000 × 3000, else the208 largest the camera has (`PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE`). A 50–200 MP sensor is therefore not209 asked for an image far larger than what is kept.210- The photo is captured in memory (`takePicture` with `OnImageCapturedCallback`), decoded upright, reduced only211 when its long side exceeds 3600 px (what the service accepts; it is never enlarged) and re-encoded as JPEG at212 quality 92, which also drops EXIF metadata. If the result exceeded 12 MB the quality would be lowered, not213 the resolution. These rules live in `DocumentImagePolicy` (identity-core, unit-tested).214- It is shown on a review screen ("Use this photo" / "Retake"), then uploaded. When its short side is under215 1000 px the review screen warns that the barcode and the fine print may be unreadable; the warning does not216 block the upload. After a failed upload the same in-memory photo stays on the review screen.217- Quality issues returned by the service (`image_blurry`, `image_too_dark`, …) are shown as fr/en messages and218 the capture restarts.219220Honest limits of the guidance: there is **no document detector** on Android yet. The hints come from221`HeuristicDocumentGuide`: brightness, contrast and sharpness (Laplacian variance) measured in the central 70 % of222the analysis frame, and steadiness measured by comparing coarse luminance grids between frames. The guidance223cannot tell whether a document is really in the frame, nor ask to "move closer"; the automatic shutter may fire224on any sharp, steady, well-lit scene, which is why the review screen always follows. Thresholds are approximations225of the server-side checks, not the same computation. Disable the automatic shutter with226`IdentityConfiguration(autoCapture = false)`. No on-device text pre-read (OCR) is performed.227228### Selfie and liveness229230Front camera, oval window, one instruction at a time ("Look straight ahead", "Slowly turn your head to your231left", "Come back to the centre"…), a chevron on the side to turn towards and a progress bar. Frames are taken232from `ImageAnalysis` at the interval given by the challenge (250 ms), rotated upright, **not mirrored** (the233preview is mirrored, the uploaded frames are not), encoded as JPEG (long side at most 960 px) and kept in memory.234At most `frames.max` (24) frames are uploaded, chosen by `FrameSelector`: the last frame of each phase plus an235even spread of the others.236237Honest limits of the guidance: the Android SDK bundles **no face-landmark detector**. ML Kit was deliberately not238added: according to its documentation its SDK sends usage and performance metrics to Google, which would contradict the commitment that nothing leaves the239device except towards MacLustr Identity. Consequently:240241- the head turns are prompted **on a fixed schedule** (`TimedLivenessGuide`: 1.5 s centre, then 2.5 s per turn and242 2 s back to the centre; 10.5 s for two movements); the SDK does not measure the head pose and does not know243 whether the person followed the instructions;244- the platform detector `android.media.FaceDetector` is used only to wait for a frontal face of sufficient size245 before the schedule starts ("Place your face in the oval" / "Move closer"); after 4 s without detection the246 capture starts anyway;247- the server alone decides whether the challenge was performed. A person who moves too late or too little gets248 `liveness_failed`/`manual_review` or a new capture from the server, not from the app.249250`LivenessGuide` (pose-driven guidance with the same yaw index and step order as the server) is implemented and251tested in `identity-core`, ready for a bundled detector (roadmap).252253**Accessible alternative**: "I can't do these movements" requests a challenge with `accessible: true`; no movement254is asked, about 2.5 s of frames are captured (the challenge then asks for 3 frames at least, 8 otherwise: the255SDK always uses the counts it receives), and the service routes the verification to a human reviewer.256257### Permission and interruptions258259- Before the system prompt, a screen explains what the camera is used for. After a refusal the SDK offers to ask260 again, or "Open settings" (application details) when the system no longer prompts. The permission is re-checked261 when the app comes back to the foreground.262- A device without any camera gets an explanatory message instead of the capture.263- CameraX stops the camera when the app goes to the background. A selfie capture interrupted that way is discarded264 and the step restarts with a new challenge; the document guidance restarts from scratch.265- The flow model lives in a `ViewModel`: a configuration change (rotation, dark mode switch) keeps the session266 state, but a capture in progress on the current screen restarts.267268## Theming269270- `IdentityConfiguration(language = IdentityLanguage.FR)` forces the language; by default the flow follows the271 `locale` of the session chosen by your backend (`fr-*` → French, anything else → English). All SDK texts exist272 in French (Québec wording: "égoportrait", "téléverser") and English, in `IdentityString`.273- `IdentityConfiguration(accentColor = 0xFF0B5FFF.toInt())` overrides the accent; otherwise the accent, logo and274 name of the application branding returned by the service are used. An accent too close to the background falls275 back to a neutral tone. The logo is loaded over https only, in memory, 1 MB at most.276- "Verification performed by MacLustr Identity" is always displayed in the footer and cannot be removed: the277 person must know which entity processes the information.278- Light and dark themes follow the system. Flat surfaces, no gradient.279280## Accessibility281282- Every screen is a scrollable column with the actions pinned at the bottom; text uses Material typography in `sp`283 and follows the system font scale.284- Titles are marked as headings; capture hints, errors, the processing text and the result are live regions285 (the selfie instruction is assertive) so that TalkBack announces them; the logo and the camera preview have286 content descriptions; the consent checkbox is a single toggleable row with the checkbox role.287- Touch targets are at least 48 dp. Colour is never the only signal.288- No animation besides the progress indicators.289- The accessible selfie alternative is described above.290291None of this has been checked with TalkBack on a device yet.292293## Privacy behaviour294295- Images exist only in memory: the document JPEG and the selfie frames are byte arrays handed to the upload and296 then released. The SDK creates no file, uses no cache directory, writes nothing to the gallery.297- The SDK logs nothing (no `Log` call) and embeds no analytics or crash reporter.298- `FLAG_SECURE` is set on the verification window: no screenshot, no screen recording, no preview in the recent299 apps list.300- HTTP calls go only to the base URL of the session (and to the https logo URL of the application branding),301 without cache, cookies or redirects. The client secret is sent in the `Authorization` header only and is never302 printed.303- The platform face detector runs on a downscaled copy of the frame, in memory; its output is a "face present"304 flag that is neither kept nor sent.305- The session id and client secret travel in an explicit, non-exported intent inside your own app.306307## Using the core without the UI308309```kotlin310val client = IdentityClient(IdentitySession.fromUrl(url))311val state = client.flowState() // suspend312client.consent(method = "document_review", textVersion = state.methods[0].consentText(IdentityLanguage.EN)!!.version, biometricConsent = false)313client.uploadDocument(DocumentSide.FRONT, jpegBytes)314client.submit()315```316317Or drive the state machine: `VerificationFlowModel(client, scope)` exposes `snapshot: StateFlow<FlowSnapshot>` and318suspend actions (`start`, `acceptConsent`, `uploadDocument`, `requestChallenge`, `uploadSelfie`, `submit`,319`runSandboxScenario`, `withdraw`, `dispute`) plus `changeMethod()` / `resumeCapture()`. It is not thread-safe:320use it from one thread (the main thread).321322`FlowState` carries, besides the status, the methods and their consent texts: `attemptsLeft`, `maxAttempts`,323`lastIssue` (why the previous capture must be redone), `document` (`front`, `back`, `backRequiredFor`,324`accepted`) and `expiresAt` (`isPastExpiry()`).325326### Resilience327328- **Retries.** `IdentityClient` retries a call after a network failure, a 429 `rate_limited` or a 5xx, twice by329 default (`IdentityRetryPolicy`): the delay is a random value in [50 %, 100 %] of `min(8 s, 0.5 s × 2ⁿ)`. A330 `Retry-After` (429, 503 `service_unavailable`) is followed when it is 15 s or less; a longer one is not331 waited for inside the flow: the error is returned with `retryAfterSeconds` and the screen says to try again332 in a moment. Quotas of the session (`too_many_uploads`, `too_many_challenges`) and every other 4xx (400, 401,333 403 `forbidden_network`, 409, 411, 413 `payload_too_large`) are never retried. `IdentityRetryPolicy.NONE`334 makes a single attempt. The policy is a constructor argument of `IdentityClient`; `IdentityConfiguration` does335 not expose it (the UI uses the default).336- **Uploads.** The request is built once: a retried upload sends the same bytes held in memory, nothing is337 captured again. When the answer to a selfie upload was lost and the retry finds its challenge already used,338 the model checks the flow state and continues if the service holds the frames.339- **Deadlines.** Each attempt has its own deadline (`HttpRequest.timeoutMs`), enforced by the client with a340 coroutine timeout whatever the transport does, and applied by the default transport to the connection and341 to each read: 20 s for a JSON call, 120 s for an image upload.342- **Cancellation.** Cancelling the calling coroutine cancels the request and the wait between two attempts343 (`CancellationException` is always rethrown, never turned into an error), and the model's busy flag is reset.344 After `stop()`, an answer still in flight no longer restarts polling.345- **Session ending under the flow.** When the session expires, is cancelled by your backend or is decided346 elsewhere, the next action receives `409 invalid_session_state`: the model reloads the state and shows the347 matching result. If that reload fails too, the error is kept in `lastError` and the step does not move.348- **Tolerant parsing.** Unknown fields are ignored, an unknown status keeps its raw value349 (`SessionStatus.isKnown == false`), an unknown challenge step is `UNKNOWN`, a missing or malformed optional350 field takes a neutral default and a malformed list element is skipped. Only `id` and `status` are required in351 a flow state. A method without a known `biometric` flag is treated as biometric (the express consent is352 asked), and a state without `livemode` is treated as live.353354## Tests355356```bash357cd sdk/kotlin358export JAVA_HOME=$(brew --prefix openjdk@21)359echo "sdk.dir=/opt/homebrew/share/android-commandlinetools" > local.properties360./gradlew :identity-core:test :identity-ui:assembleDebug :demo:assembleDebug361```362363`identity-core` has 91 JUnit tests: 85 unit tests (decoding of real JSON captured from the backend, tolerant364parsing and the new flow fields, hosted-URL parsing, multipart encoding, error mapping, state machine with a365scripted transport, capture-guidance logic, document image rules, and 25 resilience tests: retries with the same366bytes, `Retry-After`, deadlines, cancellation, session expiring at each step, withdrawal during review, change367of method) and 6 integration tests that run only when `MLID_TEST_BASE_URL` and `MLID_TEST_API_KEY` (a sandbox368key) are set; the upload test also needs `MLID_TEST_LIVE_API_KEY` and `MLID_TEST_FIXTURES` (see369`sdk/kotlin/README.md`). The test helper that creates a session with an API key stands in for your backend and370is not part of the SDK. One test reads the Swift string table (`sdk/swift/…/Strings.swift`) and checks that the371two SDKs have the same keys, in the same order, with the same French and English texts. The JSON fixtures are372captured from a local backend by `sdk/capture-fixtures.py` (shared with the Swift SDK).373374`identity-ui` and `demo` have no automated tests: they are compiled and assembled (`assembleDebug`), and375`identity-ui` passes Android lint without errors (`:identity-ui:lintDebug`). The376confirmation dialogs, the low-resolution warning and the "Change method" path of the Android UI are therefore377verified by reading the code only; the same logic is tested in `identity-core` and, for iOS, on a Simulator.378379## Not verified on a device380381Compiled only; never run on a phone or an emulator. The finding of the platform's first real-device trial (a3821080p video frame is too small for a licence barcode) is answered here in code and in unit tests of383`DocumentImagePolicy` only: the full-resolution capture has not itself been tried on a device.384385- the size actually delivered by `ImageCapture` with the resolution selector described above (it depends on the386 sizes each camera advertises), whether the PDF417 barcode of a licence is readable in the resulting 3600 px387 JPEG, and the memory and time taken by decoding a 12 MP (or larger) capture on low-end devices (a failed388 decode, including an out-of-memory error, shows "Capture was interrupted" and lets the person retry);389- the confirmation dialogs (leave, withdraw), the "Change method" path and the low-resolution warning on screen;390- camera preview, capture quality and orientation of the document photo;391- orientation and non-mirroring of the selfie frames on real sensors (the code applies the rotation reported by392 CameraX and no mirroring);393- behaviour of `android.media.FaceDetector` across devices;394- whether the timed head-turn schedule is comfortable and yields sequences the server accepts;395- thresholds of the document guidance against the server-side quality checks;396- permission dialogs, "Open settings" path, background/foreground interruptions;397- TalkBack announcements, large font scales, dark theme rendering;398- Custom Tabs launch;399- the intent round-trip of `IdentityVerificationContract` (no instrumented or Robolectric test).400401## Limits and roadmap402403- No device attestation: Play Integrity is not implemented. The server cannot yet tell a genuine app on a genuine404 device from a script holding a valid client secret. Planned.405- NFC reading of the e-passport chip is not implemented. Planned.406- No on-device document detector, no on-device face landmarks (see the capture sections). Planned: a bundled407 detector without telemetry, which will switch the selfie guidance to `LivenessGuide`.408- No file-picker fallback for the document on Android: a camera is required for live sessions.409- No on-device text pre-read.410- Not published to Maven Central or any registry.411- Strings are bundled in French and English only.412