Release v0.3.1, 21-Nov-2026 · all releases
Middleware: onboarding a device
10-Nov-2026.
This is the walk for a vendor writing an Android app for a SUNMI device: a payment terminal,
or a register, which is a POS app on a device. It goes from registering the app with the middleware
to a certificate the app renews by itself, with Kotlin to paste at each step on the device,
and says what the app’s enrolment screen must be and how a person reaches it (The enrolment
screen). You can build the device’s side from this document alone. An agent reads the same bytes
through llms.txt, and through the sandbox’s MCP server as mw://onboarding/device.
A live device proves who it is with a client certificate from the middleware’s own CA. Its key is made in the Android keystore and never leaves it. The middleware issues the certificate once the device shows three things: a pairing code an installer typed or scanned, which proves an authorised person is at the device now; the serial its listing holds; and an Android Key Attestation chain, which proves the key is in hardware, on an unmodified device of an allowed model, held by the app its vendor registered. Nothing is given to a vendor to embed in an app. The certificate lasts 30 days and renews from day 15 with a new key. FUNDiMO’s staging middleware can be set to issue it though some checks of the attestation fail, for testing, and to mark the device so (step 3, Which devices the middleware admits).
Read it beside docs/api/terminal.md, the terminal’s contract, and the operations of
docs/api/openapi.yaml tagged operator, the back office’s routes. A vendor with a server
reads docs/api/onboarding-server.md instead, and linking a register to a terminal at the
counter is docs/api/linking.md. docs/api/openapi.yaml holds the schema of every route named
here. The middleware publishes no Android library: the code here is for you to paste and own.
What is proven on a device, and what is not yet
Every step here was written from documents. Two runs have since tried parts of it on one SUNMI P2 Lite SE, Android 11 (API 30), whose keystore is software: AOSP’s software keymaster keeps its keys, and no trusted environment was found behind Android’s keystore. FUNDiMO’s bench, run from 12-Nov-2026, ran on the device alone, with no network and no middleware. A terminal vendor’s trial on 13-Nov-2026 enrolled in the sandbox on its first attempt and connected on its certificate. The sandbox requires no attestation, so neither run proves a live enrolment. Each step that rests on something only a device can confirm says so, by the bench item it rests on: proven on a device, and on which, or not yet proven on a device. Each item not yet proven is checked on a SUNMI device before the first live enrolment, and this walk is not final until BENCH-2 is.
| Item | What is assumed | The step | What the runs showed |
|---|---|---|---|
| BENCH-1 | SUNMI’s models chain to Google’s attestation root | 3, the key | Not on that unit: its chain ends at Android’s software attestation root |
| BENCH-2 | An app can read its device’s serial through SUNMI’s SDK | 5, the serial | The serial read from SUNMI’s system property ro.sunmi.serial, not yet compared with a listing’s |
| BENCH-3 | The attestation holds attestationIdModel on API 31 and later, and verifiedBootKey names SUNMI’s firmware signer on older releases | 3, the key | Not on that unit: on API 30 it attests no model, and its software keymaster attests a boot key of 32 zero bytes, which names no signer |
| BENCH-4 | A keystore key can drive client TLS through OkHttp and an X509ExtendedKeyManager, on a WebSocket as on REST | 8, the key manager | Proven on that unit, by both runs |
| BENCH-5 | A SUNMI device’s clock is near enough to validate a public server certificate | 6, enrolment | Not measured. The device’s calls over HTTPS to the sandbox in the trial succeeded |
| BENCH-6 | A real attestation chain parses as the middleware parses one | 3, the key | That unit’s software chain parses |
In short
- The vendor registers the app’s package and signing digest for its role (step 1).
- The terminal’s fleet owner, or the POS vendor for a register, lists the device by its serial, and gives the installer the pairing code the middleware answers with (step 2).
- On the device, the app takes the code’s five words, as the installer types them or scans
them from a QR code (step 2), reads the serial (step 5), makes a P-256 key in the Android
keystore with the enrolment challenge (step 3), builds a CSR for it (step 4), and sends all
of it to
POST /v1/enrol(step 6). - It keeps the
CertificateChainthe middleware answers with against the key’s alias (step 7), and presents the key and the chain at the TLS handshake of every call after, REST and WebSocket alike (step 8). - Once a day it asks
GET /v1/certificates/self(step 9). WhenRenewNowistrue, it renews with a new key under a new alias, and deletes the old key only after a call on the new one has been answered (step 10). - After a refusal it does what the holder’s table says, and never deletes its key (What a holder of a dead certificate does). A device off longer than its certificate re-enrols with a new code (step 11).
- A person enrols the device on the app’s enrolment screen, which an entry of the app’s own menu or settings opens, with the device alone, and again after the first enrolment (The enrolment screen).
In the sandbox
The same file is served in the sandbox, where three things differ.
- The sandbox’s gate answers
404to the operator’s routes. In their place the sandbox has two routes of its own, served by its own process,mw-sandbox(the middleware’s003b-sandbox), under your tester’s sandbox key, and alivemiddleware has neither:POST /sandbox/v1/app-identitiesregisters the app (step 1), andPOST /sandbox/v1/codesgives the code (step 2). - No attestation is required, so an emulator or a debug build can enrol. A chain sent is checked all the same, for its key, its challenge and its app, against app identities where a debug build counts, so you can prove your package and signing digest before you have a device. The first live enrolment is where the rest is proven.
- Enrolment needs a sandbox with an issuing certificate. A sandbox run without one answers
POST /v1/enrolwith503 ca_unavailable.
What you need
- An Android app on the device.
setAttestationChallengeneeds API 24, andsetDevicePropertiesAttestationIncluded, which puts the device’s brand and model in the attestation, needs API 31. - OkHttp,
com.squareup.okhttp3:okhttp, for every call. - Bouncy Castle’s PKIX library,
org.bouncycastle:bcpkix-jdk18on, to build the CSR. Only its CSR classes are used, and it is not installed as a security provider. It bringsbcprov-jdk18on, which holds class files for Java 9 and later. A toolchain that cannot read them fails withUnsupported class file major version 59, as Android Gradle Plugin 4.2 with Jetifier does: there, takeorg.bouncycastle:bcpkix-jdk15to18, the same classes built for Java 5 to 8. - WorkManager,
androidx.work:work-runtime-ktx, for the daily check, or any scheduler the app already has. - Android’s own
org.json, for bodies. - The middleware’s word list,
docs/api/words.txt, in the app’s resources, to read a code (step 2). - The middleware’s base URL, one of those
/docs/api/environments.mdnames, kept in a setting, which the helpers below read asMW.
Take a current release of each library. The snippets below share these helpers. Make every call off the main thread.
import android.util.Base64
import java.io.IOException
import kotlin.random.Random
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
/**
* The base URL the app chose, set from its data when the app starts, in `Application.onCreate`,
* so every call here, the daily check's worker among them, has it. Null until one is chosen.
*/
var chosenBaseUrl: String? = null
/**
* The middleware's base URL, one of those `/docs/api/environments.md` names. The app chooses it
* once, before its first enrolment, from a list its configuration holds, never an address an
* installer types, and keeps the choice in its data beside its identities (step 7), so clearing
* the app's data clears both.
*/
val MW: String
get() = checkNotNull(chosenBaseUrl) {
"No base URL chosen: choose one of those /docs/api/environments.md names before enrolling"
}
val JSON = "application/json".toMediaType()
/** A client presenting no certificate: for `POST /v1/enrol` alone. */
val plain = OkHttpClient()
/** What the middleware answered: a 2xx and its body, or a refusal and its `Error.Code`. */
sealed interface Answer {
data class Ok(val status: Int, val body: JSONObject) : Answer
data class Refused(val status: Int, val code: String?) : Answer
}
/**
* Sends [request] and reads the answer. Throws `IOException` where no answer came: a close, a
* reset, a timeout, or a handshake that failed.
*/
fun call(client: OkHttpClient, request: Request): Answer =
client.newCall(request).execute().use { response ->
val text = response.body?.string().orEmpty()
if (response.isSuccessful) {
Answer.Ok(response.code, JSONObject(text.ifEmpty { "{}" }))
} else {
val code = runCatching { JSONObject(text).getJSONObject("Error").getString("Code") }
Answer.Refused(response.code, code.getOrNull())
}
}
/**
* Sends [request] until an answer comes, waiting 1 second, then twice as long each time up to
* 30 seconds, with a little randomness. Only for a body that is safe to send again: enrolment
* and renewal answer a repeat with what they already issued.
*/
fun sendUntilAnswered(client: OkHttpClient, request: Request, tries: Int = 5): Answer {
var wait = 1_000L
repeat(tries - 1) {
try {
return call(client, request)
} catch (noAnswer: IOException) {
Thread.sleep(wait + Random.nextLong(wait / 2))
wait = minOf(wait * 2, 30_000L)
}
}
return call(client, request)
}
/** DER bytes as PEM, 64 characters a line. */
fun pem(label: String, der: ByteArray): String {
val body = Base64.encodeToString(der, Base64.NO_WRAP).chunked(64).joinToString("\n")
return "-----BEGIN $label-----\n$body\n-----END $label-----\n"
}
/** Bytes as lowercase hex. */
fun ByteArray.hex(): String =
joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
/** 64 lowercase hex characters as 32 bytes, or null. */
fun bytesOfHex(text: String): ByteArray? {
if (text.length != 64 || !text.all { it in '0'..'9' || it in 'a'..'f' }) return null
return ByteArray(32) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
}
1. Register the app identity
A device enrols only if the app holding its key is one its vendor registered. The middleware learns
which app holds the key from the attestation, which states the app’s Android package and the
SHA-256 of each certificate the app is signed with, so nothing secret is put in the app.
Register each app once for its role: terminal for a payment terminal’s app, register for a
POS app on a device.
On live, the operator or the vendor’s own admin sends
POST /v1/vendors/{VendorIdentification}/app-identities (in docs/api/openapi.yaml, tagged
operator), with this body:
{ "Role": "terminal", "AppPackage": "au.com.example.terminal", "SigningDigest": "..." }
In the sandbox, POST /sandbox/v1/app-identities takes the same body under your tester’s
key, with $SANDBOX the sandbox’s address:
curl -s -X POST "$SANDBOX/sandbox/v1/app-identities" \
-H 'Authorization: Bearer sbx_...' \
-H 'Content-Type: application/json' \
-d '{"Role":"terminal","AppPackage":"au.com.example.terminal","SigningDigest":"..."}'
The answer is 201:
{ "AppIdentification": "app_...", "Role": "terminal", "AppPackage": "au.com.example.terminal", "SigningDigest": "...", "Debug": true, "State": "active" }
| Field | Rule |
|---|---|
Role | terminal or register |
AppPackage | The app’s Android package, as the attestation names it: two or more segments joined by ., each a letter then letters, digits and _, at most 128 characters and 8 digits |
SigningDigest | The SHA-256 of a certificate the app is signed with, 64 lowercase hex characters |
Debug | true for a debug build, which a sandbox takes and a live middleware refuses, unless it is set to mark (step 3, Which devices the middleware admits). The sandbox’s route registers every app as a debug build, whatever this says |
The digest is of the certificate that signed the app as it is installed on the device. If a store re-signs your app, it is the store’s certificate, not your upload key’s. Register a debug build’s digest apart, as a debug build. To read the digests from the app itself:
import android.content.Context
import android.content.pm.PackageManager
import java.security.MessageDigest
/** The SHA-256 of each certificate this app, as installed, is signed with. API 28 and later. */
fun signingDigests(context: Context): List<String> {
val info = context.packageManager
.getPackageInfo(context.packageName, PackageManager.GET_SIGNING_CERTIFICATES)
val signers = info.signingInfo?.apkContentsSigners ?: return emptyList()
return signers.map { MessageDigest.getInstance("SHA-256").digest(it.toByteArray()).hex() }
}
Two rules of the attestation follow from this step. The app must be the only package holding
the key: an app sharing its user id with another package, by android:sharedUserId, shares
its keys with it, the attestation then names more than one package, and that is refused. And
every digest the attestation states must be registered, so an app signed with two
certificates registers each. A device whose app is not registered is refused
403 app_identity_unknown at enrolment and at renewal.
2. The listing and the code
Every device starts with one human act. On live, the terminal’s fleet owner lists it at a
store by its serial, POST /v1/merchant-stores/{StoreIdentification}/terminals, and the POS
vendor’s admin lists a register by its serial, POST /v1/registers (both in
docs/api/openapi.yaml, tagged operator). The 201 holds the
device’s id, POIIdentification or RegisterIdentification, and its PairingCode:
{ "POIIdentification": "poi_...", "SerialNumber": "SN-0001", "State": "listed", "PairingCode": "bronze.farm.loop.prism.tempo" }
The code is five different words of the middleware’s word list, in lower case and joined by
dots, valid 15 minutes and for one use, and shown this once. It is a secret: the listing party
gives it to the installer, read aloud, sent, or shown as a QR code (The QR code, below), and the
installer types or scans it into your app’s enrolment screen at the device (The enrolment
screen). It is kept out of every log, the app’s
own among them. A fresh one comes from POST /v1/terminals/{POIIdentification}/pairing-code,
which also re-pairs a paired terminal, or for a register from
POST /v1/registers/{RegisterIdentification}/pairing-code.
In the sandbox the listing is done for you: your tester’s world holds a terminal of your own,
-yours, listed with the serial <tester>-yours. POST /sandbox/v1/codes gives its code,
under your tester’s key:
curl -s -X POST "$SANDBOX/sandbox/v1/codes" \
-H 'Authorization: Bearer sbx_...' \
-H 'Content-Type: application/json' \
-d '{"Role":"terminal"}'
The answer is 201:
{ "Role": "terminal", "PairingCode": "bronze.farm.loop.prism.tempo", "SerialNumber": "sbx-...-yours", "Next": "..." }
Enrol with that code and that SerialNumber within 15 minutes. A new code re-pairs -yours,
so its sandbox key is refused on its upgrade until it enrols. Past 6 codes an hour the route
answers 429 sandbox_rate. Role: register is not built yet, and answers
400 invalid_field: until it is, a POS app on a device runs the sandbox on a server’s code,
as docs/api/onboarding-server.md walks.
The word list
The list is docs/api/words.txt: 1,024 words, one a line, each 3 to 6 letters a to z. The
sandbox serves it as /docs/api/words.txt, and its MCP server as mw://docs/words.txt. Each
word is named by its first four letters: no two words share them, and none begins another, so
an app can complete a word from its first letters, by the fourth at the latest, and a word of
three letters at its third. No word is one said for a separator, as dot or dash would be,
so a code read aloud is five words and nothing between them.
Put the list in the app as src/main/resources/words.txt, so the app and its unit tests read
the same bytes. The SHA-256 of the list as published is
e6104a521cec9b0224c1dfa51e6fceefcb7f5e0e4cd36adb168e15fa92686d5a: check your copy against it.
Typing the code
The middleware reads a device’s code one way, and the app reads it the same way before it sends, so a code the middleware would refuse never leaves the device. The middleware takes:
- at most 64 characters;
- spaces, tabs and line ends before the first word and after the last, which it drops, since a scanner often ends its text with a line end;
- one or more dots, spaces or hyphens between two words, mixed as typed;
- the letters
atozin either case, read as lower case, and no other letter; - and then five words of the list, all different.
Anything else is 400 invalid_field naming PairingCode, before any code is looked up, so it
costs no attempt. The middleware completes no word: bron is not bronze. Completing a word
is the app’s, so the app sends the whole words, and computes the challenge from them.
What the app does:
- Its field turns off the keyboard’s own corrections and suggestions, with
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD, so the keyboard does not change one word into another. - Once the letters typed begin one word of the list alone, it completes the word and its dot, and the fifth word without its dot: a dot or a hyphen after the last word is refused.
- A letter that begins no word is shown at once, so a misheard word costs a retype, not an attempt.
- It lowers case with
lowercase(Locale.ROOT). On a device set to Turkish, the device’s own locale lowersIto a dotlessı, andPRISMwould read as no word. - It sends the code as the middleware shows it,
bronze.farm.loop.prism.tempo, asdeviceCodereturns it, and computes the challenge from the same text (step 3).
import android.text.InputType
import android.widget.EditText
import java.util.Locale
/** The list, the app's `src/main/resources/words.txt`, one word a line, read once. */
val WORDS: Set<String> by lazy {
val list = checkNotNull(WordList::class.java.getResourceAsStream("/words.txt")) {
"words.txt is not in the app's resources"
}
list.bufferedReader(Charsets.US_ASCII).useLines { lines ->
lines.filter { it.isNotEmpty() }.toSet()
}
}
private object WordList
/** What may stand between two words: one or more of them, mixed. */
private val SEPARATORS = charArrayOf('.', ' ', '-')
/** What is dropped before the first word and after the last. */
private val ENDS = charArrayOf(' ', '\t', '\r', '\n')
/**
* The code as the installer typed it, or a scanner read it, read as the middleware reads it.
* Returns the code as the middleware shows it, five words in lower case joined by dots, or null
* for anything else. Never send a null: ask the installer to type the code again.
*/
fun deviceCode(typed: String, words: Set<String>): String? {
// At most 64 characters, each of them ASCII: the middleware counts 64 bytes, and reads no
// letter outside `a` to `z` as part of a word.
if (typed.length > 64 || typed.any { it.code > 0x7f }) return null
val text = typed.trim(*ENDS).lowercase(Locale.ROOT)
if (text.isEmpty() || text.first() in SEPARATORS || text.last() in SEPARATORS) return null
val tokens = text.split(*SEPARATORS).filter { it.isNotEmpty() }
if (tokens.size != 5 || tokens.toSet().size != 5 || !words.containsAll(tokens)) return null
return tokens.joinToString(".")
}
/** What the letters of the word being typed begin, on the list. */
sealed interface Begun {
/** One word alone: complete it, and its dot, unless it is the fifth word. */
data class Word(val word: String) : Begun
/** More than one: wait for the next letter. By the fourth there is one or none. */
object Several : Begun
/** None: show it at once, so the installer retypes the word and spends no attempt. */
object NoWord : Begun
}
/** What [letters], the letters typed of one word, begin in [words]. */
fun begun(letters: String, words: Set<String>): Begun {
val typed = letters.lowercase(Locale.ROOT)
val begins = words.filter { it.startsWith(typed) }
return when (begins.size) {
0 -> Begun.NoWord
1 -> Begun.Word(begins.single())
else -> Begun.Several
}
}
/** The code's field: none of the keyboard's own corrections or suggestions. */
fun EditText.forDeviceCode() {
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
}
Check your build against these examples, which the middleware reads as deviceCode does. The
test runs as a device set to Turkish would:
| Typed, as Kotlin writes it | deviceCode gives | Why |
|---|---|---|
Bronze Farm-loop PRISM tempo | bronze.farm.loop.prism.tempo | Either case, and one or more separators, mixed |
bronze.farm.loop.prism.tempo\r\n | bronze.farm.loop.prism.tempo | A scanner’s line end, dropped |
BRONZE FARM LOOP PRISM TEMPO | bronze.farm.loop.prism.tempo | A capital I, which a Turkish locale lowers to a dotless ı and Locale.ROOT to i |
BRONZE FARM LOOP PRİSM TEMPO | null | A dotted capital İ, not a letter A to Z |
bronze.farm.loop.prism.temp | null | A word begun and not finished: completing it is the app’s |
bronze.farm.loop.prison.tempo | null | A word not on the list |
bronze.farm.loop.prism.bronze | null | A word twice |
bronze.farm.loop.prism.tempo.kite | null | Six words |
.bronze.farm.loop.prism.tempo | null | A separator before the first word |
bronze.farm.loop.prism.tempo. | null | A dot after the last word: completion adds none after the fifth |
bronze\tfarm.loop.prism.tempo | null | A tab between two words |
import java.util.Locale
import org.junit.Assert.assertEquals
import org.junit.Test
class DeviceCodeTest {
@Test
fun readsACodeAsTheMiddlewareDoes() {
val before = Locale.getDefault()
// A device set to Turkish, whose own locale lowers `I` to a dotless `ı`.
Locale.setDefault(Locale.forLanguageTag("tr-TR"))
try {
val examples = listOf(
"Bronze Farm-loop PRISM tempo" to "bronze.farm.loop.prism.tempo",
"bronze.farm.loop.prism.tempo\r\n" to "bronze.farm.loop.prism.tempo",
"BRONZE FARM LOOP PRISM TEMPO" to "bronze.farm.loop.prism.tempo",
"BRONZE FARM LOOP PRİSM TEMPO" to null,
"bronze.farm.loop.prism.temp" to null,
"bronze.farm.loop.prison.tempo" to null,
"bronze.farm.loop.prism.bronze" to null,
"bronze.farm.loop.prism.tempo.kite" to null,
".bronze.farm.loop.prism.tempo" to null,
"bronze.farm.loop.prism.tempo." to null,
"bronze\tfarm.loop.prism.tempo" to null,
)
for ((typed, shown) in examples) {
assertEquals(typed, shown, deviceCode(typed, WORDS))
}
} finally {
Locale.setDefault(before)
}
}
@Test
fun completesAWordByItsFourthLetter() {
assertEquals(Begun.Several, begun("pri", WORDS))
assertEquals(Begun.Word("prism"), begun("PRIS", WORDS))
assertEquals(Begun.NoWord, begun("priso", WORDS))
}
}
The QR code
Whoever shows the code may show a QR code of it beside the words, for the app to scan. A QR
code of a device’s code holds the code as the middleware shows it and nothing else,
bronze.farm.loop.prism.tempo, in byte mode at error correction M. A code is at most 34
bytes, five words of six letters and four dots, so every code fits a version 3 symbol, 29
modules a side, which holds 42 bytes at M. The middleware answers the code as text and draws
no image: whoever shows the code draws the QR from the PairingCode it was given. A server’s
code has no QR.
The app reads the symbol’s text with its camera or the device’s scanner, by the rule a typed
code is read by, deviceCode, so the line end a scanner leaves is dropped; shows the five
words; and enrols when the installer taps to. It never follows the text as a link, and never
reads a host from it: the middleware’s address is the app’s own. A text that is not a code is
refused, as a typed one is. A photograph of the QR is a photograph of the words: good for 15
minutes, once, and of no use without the listed serial and, on live, a device that passes
attestation.
3. The key, in the Android keystore
The device’s key is P-256, made in the Android keystore under an alias of your choosing, and
it never leaves the keystore. It is made with an attestation challenge, so the attestation
the keystore writes for it carries that challenge, and the middleware can tell the key was made for
this enrolment and no other. Ask for the device’s brand and model in the attestation with
setDevicePropertiesAttestationIncluded where the API has it, API 31 and later: the
operator’s allowed list admits a device by them.
The challenge is fixed before the key exists. At enrolment it is the SHA-256 of
mw-enrol-v1, the code as the middleware shows it, its five words in lower case joined by
dots as deviceCode returns them (step 2), and the device’s serial as step 5 reads it, so read
the serial before you make the key. At renewal it is the Challenge the middleware answers
(step 10).
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.ProviderException
import java.security.spec.ECGenParameterSpec
/**
* Makes a P-256 key in the Android keystore under [alias], attested with [challenge], with the
* device's brand and model in the attestation where the platform can put them there. Returns
* whether it did.
*/
fun makeKey(alias: String, challenge: ByteArray): Boolean {
fun spec(deviceProperties: Boolean): KeyGenParameterSpec {
val builder = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
.setDigests(
KeyProperties.DIGEST_NONE,
KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA384,
KeyProperties.DIGEST_SHA512,
)
.setAttestationChallenge(challenge)
if (deviceProperties && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setDevicePropertiesAttestationIncluded(true)
}
return builder.build()
}
val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
try {
generator.initialize(spec(deviceProperties = true))
generator.generateKeyPair()
return true
} catch (unsupported: ProviderException) {
// This device cannot attest its brand and model: made again without them.
}
}
generator.initialize(spec(deviceProperties = false))
generator.generateKeyPair()
return false
}
/** What `KeyStore.getCertificateChain` gives for [alias], leaf first, as one PEM text. */
fun attestationChainOf(alias: String): String {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val chain = checkNotNull(keyStore.getCertificateChain(alias)) { "no key under $alias" }
return chain.joinToString("") { pem("CERTIFICATE", it.encoded) }
}
KeyStore.getCertificateChain gives the attestation: the key’s own certificate first, then
the certificates the keystore’s attestation key chains through, to Google’s root. Send all of
it, as it comes, in AttestationChain. Do not check it on the device: the middleware checks it, on
the server, as Google’s guidance says. The key allows signing with no digest of its own,
DIGEST_NONE, beside SHA-256 to SHA-512, for the handshake of step 8: Google’s reference for
setDigests, read on 10-Nov-2026, says a key used for TLS client authentication usually needs
it, “because TLS/SSL stacks typically generate the necessary digest(s) themselves”.
Where setDevicePropertiesAttestationIncluded is not supported, key generation throws
ProviderException, and makeKey makes the key without them. Such a key’s attestation names
no brand and no model, so only an allowed-list row naming the firmware’s VerifiedBootKey
alone can admit the device: tell the operator which of your devices this is.
Which devices the middleware admits
On live every enrolment and renewal of a device is attested, and the middleware refuses a chain
unless: it chains to one of Google’s two attestation roots, and no certificate in it is
revoked or suspended; the key is the CSR’s, P-256, made in the keystore’s trusted environment
or StrongBox, for signing; the challenge is this call’s; the bootloader is locked and the boot
verified; the app is the one registered (step 1); and the device is on the operator’s allowed
list, by its attested brand and model, its firmware’s boot key, or both. The allowed list
starts empty, so ask the operator to allow your models before the first live enrolment. A
middleware set to mark is the one exception, below.
- BENCH-1, not yet proven on a device. That SUNMI’s models chain to Google’s attestation root. A device certified for Google’s apps should. A device that is not may use its maker’s own root, which the middleware does not take, and such a model is refused at enrolment until the operator decides what a device of it may do. On the unit of the runs above, the chain ended at Android’s software attestation root, which a live middleware refuses.
- BENCH-3, not yet proven on a device. That the attestation holds
attestationIdModelon API 31 and later, and thatverifiedBootKeynames SUNMI’s firmware signer on older releases. The allowed list cannot tell a model with neither from any other, and treats it as a model with no attestation. On the unit of the runs above, on API 30, the attestation named no model, and its root of trust was the software keymaster’s: a boot key of 32 zero bytes,Unverifiedand unlocked, which AOSP’s software keymaster on Android 11 attests whatever the boot properties say, though the device’s own properties read verified bootgreenand a locked bootloader. A live middleware refuses a root of trust the keystore’s secure hardware did not attest. - BENCH-6, not yet proven on a device. That a real attestation chain parses as the middleware parses one, on each firmware. The software chain of the unit of the runs above did; no device run has yet tried a chain from secure hardware, a trusted environment or StrongBox.
FUNDiMO’s staging middleware alone can be set to mark a device whose attestation fails rather
than refuse it, so that everything but the attestation can be tried on a device that cannot pass
it. Set so, at enrolment and at renewal, it admits a device whose chain fails only the checks
that are the device’s and its maker’s: a chain not ending at one of Google’s roots or not one
the middleware can follow, a certificate in it out of its dates or on Google’s status list, a
key not in the trusted environment or StrongBox, a bootloader not locked or a boot not verified,
and a device the allowed list does not hold. It also admits one whose app is registered as a
debug build alone, and one that sends no chain. It issues the certificate and records on it
which checks failed, which the device’s listings show, and the device then works as any other.
It refuses as written above everything else: a chain that does not parse, an attestation
extension not on the key’s own certificate alone, a key not the CSR’s, a challenge not the
call’s, a serial attested in secure hardware that is not the listed one, and an app its vendor
has not registered. A SUNMI terminal as FUNDiMO’s bench measured one, its attestation at
software level under AOSP’s software attestation root, not Google’s, every tag in
softwareEnforced, a boot key of 32 zero bytes and its boot Unverified, is admitted there,
marked as failing the root, the hardware, the boot and the model. Production refuses as
written, and the sandbox requires no attestation, so it marks nothing. Build the app for the
rules above: a device staging marks, a middleware that does not mark refuses.
The challenge, worked
With the code the installer typed as Bronze Farm-loop PRISM tempo, and the serial S-1:
| What | Value |
|---|---|
| The code, as typed | Bronze Farm-loop PRISM tempo |
| The code, as the middleware shows it | bronze.farm.loop.prism.tempo |
| The serial | S-1 |
| The input, 42 bytes of ASCII | mw-enrol-v1bronze.farm.loop.prism.tempoS-1 |
| The input, in hex | 6d772d656e726f6c2d7631 62726f6e7a652e6661726d2e6c6f6f702e707269736d2e74656d706f 532d31 |
| The challenge, the SHA-256 of the input | a41058ea920e1fd50a28a67617444d4b99a1ca8f0a0b21b81832247fc6580b76 |
The prefix, mw-enrol-v1, the code and the serial are joined with nothing between. The code is
its five words as the middleware shows them, never as the installer typed them: a challenge over
Bronze Farm-loop PRISM tempo is another, and is refused. The serial is the one
the device sends in SerialNumber, exactly as its listing holds it, case and all. The
challenge is the 32 bytes of the digest, not its hex: pass the bytes to
setAttestationChallenge. A challenge one byte different from the middleware’s is refused
attestation_failed. Check your build against these values:
import java.security.MessageDigest
import org.junit.Assert.assertEquals
import org.junit.Test
/** The attestation challenge of an enrolment: the SHA-256 of the prefix, the code and the serial. */
fun enrolmentChallenge(code: String, serial: String): ByteArray =
MessageDigest.getInstance("SHA-256")
.digest("mw-enrol-v1$code$serial".toByteArray(Charsets.US_ASCII))
class WorkedChallengeTest {
@Test
fun theWorkedChallenge() {
val code = requireNotNull(deviceCode("Bronze Farm-loop PRISM tempo", WORDS))
assertEquals("bronze.farm.loop.prism.tempo", code)
assertEquals(
"a41058ea920e1fd50a28a67617444d4b99a1ca8f0a0b21b81832247fc6580b76",
enrolmentChallenge(code, "S-1").hex(),
)
}
}
4. The CSR
The middleware reads one thing from the CSR: its public key. It checks the CSR’s own signature and
that the key is P-256, and writes every name in the certificate itself, so the subject says
nothing, and holds nothing about the device. The CSR is signed by the keystore key, through a
Bouncy Castle ContentSigner that hands the bytes to the keystore, so the key never leaves
it.
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.security.KeyStore
import java.security.PrivateKey
import java.security.Signature
import org.bouncycastle.asn1.x500.X500Name
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers
import org.bouncycastle.operator.ContentSigner
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder
/** Signs with a keystore key, which signs inside the keystore. */
class KeystoreSigner(key: PrivateKey) : ContentSigner {
private val signature = Signature.getInstance("SHA256withECDSA").apply { initSign(key) }
private val written = ByteArrayOutputStream()
override fun getAlgorithmIdentifier() = AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA256)
override fun getOutputStream(): OutputStream = written
override fun getSignature(): ByteArray {
signature.update(written.toByteArray())
return signature.sign()
}
}
/** A CSR for the key under [alias], PEM. The middleware reads its key alone. */
fun csrFor(alias: String): String {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val key = keyStore.getKey(alias, null) as PrivateKey
val publicKey = keyStore.getCertificate(alias).publicKey
val csr = JcaPKCS10CertificationRequestBuilder(X500Name("CN=device"), publicKey)
.build(KeystoreSigner(key))
return pem("CERTIFICATE REQUEST", csr.encoded)
}
A CSR whose signature does not verify, or whose key is not P-256, is refused
400 invalid_field, with Fields naming CertificateSigningRequest.
5. The serial, through SUNMI’s SDK
The middleware compares the serial the device sends with the one its listing holds, and the
enrolment challenge is computed over it, so the app needs the serial as printed on the
device. On Android 10 and later the platform’s own Build.getSerial() needs
READ_PRIVILEGED_PHONE_STATE, which a third-party app cannot hold, so the serial comes from
SUNMI’s SDK.
- BENCH-2, not yet proven on a device. That an app can read its serial through SUNMI’s
SDK. SUNMI’s pages read on 07-Nov-2026 name no such call, and a third party’s wrapper
suggests a system parameter named
SN. On the unit of the runs above, an app holdingREAD_PHONE_STATEread the serial from SUNMI’s system propertyro.sunmi.serialon FUNDiMO’s bench, not yet compared with the serial a listing holds. The code below is the shape: put that read, or the SDK’s own call, in it once the bench confirms one.
/** A serial as the middleware holds one: `^[A-Za-z0-9._-]{1,64}$`. */
val SERIAL = Regex("^[A-Za-z0-9._-]{1,64}$")
/**
* The device's serial, read through SUNMI's SDK by [readSunmiSerial], the SDK's call, or null
* where it gives none, or gives something no listing could hold.
*/
fun serialOf(readSunmiSerial: () -> String?): String? =
readSunmiSerial()?.trim()?.takeIf { SERIAL.matches(it) }
If the SDK gives no serial, ask the installer to type the serial printed on the device,
beside the code: the middleware takes a string either way, and compares it with the listing’s. Send
it exactly as the listing holds it. One that differs is refused with the same
403 code_not_valid as a wrong code. In the sandbox, send the SerialNumber that
POST /sandbox/v1/codes answered. The enrolment screen says how the serial is shown, and when
it is typed (SCREEN-10 and SCREEN-11).
6. Enrol: POST /v1/enrol
With the code, the serial, the key and its CSR, the app enrols. The call carries no credential, because the code is the credential, so the client presents no certificate.
| Field | Holds |
|---|---|
PairingCode | The code as the middleware shows it, five words joined by dots, as deviceCode returns it (step 2) |
CertificateSigningRequest | The CSR, PEM (step 4) |
SerialNumber | The serial (step 5) |
AttestationChain | What KeyStore.getCertificateChain gave, PEM, leaf first (step 3) |
import java.util.UUID
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
/**
* An enrolment built and not yet answered: the keystore alias of its key, and its request. Keep
* it while the code's screen is open, and send this same one again after no answer, a `429` or
* a `5xx`: it may have spent the code, and a spent code refuses any key but the one it was
* spent with, which inside the code's 15 minutes it answers `200`.
*/
class Enrolment(val alias: String, val request: Request)
/**
* Builds the enrolment of this device with the code the installer typed and its serial: a new
* keystore key under a new alias, its CSR and its attestation. Build a new one for a new code,
* or after a `400` or a `403` of the table below, a verdict on this very enrolment. Never after
* no answer, a `429` or a `5xx`, which may follow an enrolment that spent the code.
*/
fun enrolment(typedCode: String, serial: String): Enrolment {
val code = requireNotNull(deviceCode(typedCode, WORDS)) { "not five words of the list: type it again" }
require(SERIAL.matches(serial)) { "not a serial a listing holds" }
val alias = "mw-" + UUID.randomUUID()
makeKey(alias, enrolmentChallenge(code, serial))
val body = JSONObject()
.put("PairingCode", code)
.put("CertificateSigningRequest", csrFor(alias))
.put("SerialNumber", serial)
.put("AttestationChain", attestationChainOf(alias))
.toString()
.toRequestBody(JSON)
// No certificate yet: the code is the credential.
return Enrolment(alias, Request.Builder().url("$MW/v1/enrol").post(body).build())
}
/**
* Sends [enrolment] until an answer comes. Throws `IOException` where none came, and
* `JSONException` where a `2xx`'s body was not JSON: send the same [enrolment] again on the
* person's next tap, never a new one.
*/
fun enrolDevice(enrolment: Enrolment): Answer = sendUntilAnswered(plain, enrolment.request)
The answer is 201:
{ "CertificateChain": "-----BEGIN CERTIFICATE-----\n...", "POIIdentification": "poi_...", "SpiffeId": "spiffe://.../live/terminal/poi_...", "NotAfter": "...", "RenewFrom": "..." }
SpiffeId is the certificate’s URI. Its host is the trust domain of the deployment that issued
it, which need not be the address you call, and its first segment is the environment, live or
sandbox.
A register’s answer names RegisterIdentification where a terminal’s names
POIIdentification. NotAfter is when the certificate ends, 30 days on, and RenewFrom is
day 15. If an answer is lost, send the same body again inside the code’s 15 minutes, as
sendUntilAnswered does: the same code and the same key answer 200 with the certificate
already issued. The same code with another key is 403 code_not_valid, so never make a new
key to repeat a call that got no answer: keep the Enrolment until it is answered, and send it
again.
- BENCH-5, not yet proven on a device. That a SUNMI device’s clock is near enough to validate the middleware’s public server certificate. Enrolment is the device’s first call over HTTPS. A clock far enough out fails the handshake on the server’s certificate before the middleware sees the call, as it would for any HTTPS client: set the device’s date and time, and try again. Nothing the middleware decides rests on the device’s clock.
When enrolment is refused
Each refusal from the middleware has the body
{ "Error": { "Code": "...", "Message": "...", "Fields": [] } }. The edge’s 429 is the one
that differs: the edge in front of a hosted middleware sends it, and its body is the edge’s own.
A refusal once the code is found counts an attempt against it, unless the code is already spent
or burned, and five attempts burn it, so fix what a refusal names before you try again. A 503
counts nothing and leaves the code unspent, and the edge’s 429 never reaches the middleware, so
it counts nothing either.
Of invalid_json, unknown_field, missing_field and invalid_field, the first class that
fails answers alone, with Fields naming every field of it, sorted.
| Status | Error.Code | When | What to do |
|---|---|---|---|
400 | invalid_json, unknown_field, missing_field | The body is not a JSON object, holds a field the route does not name, or lacks one, and Fields names each | A bug in the app: fix it. Retrying will not help |
400 | invalid_field | A field breaks its rule, and Fields names it. For CertificateSigningRequest: its signature does not verify, or its key is not P-256 | Fix the field. For the CSR, make a new P-256 key under a new alias, with the same challenge, and a CSR from it |
403 | code_not_valid | The code is wrong, unknown, expired, spent or burned, the serial is not the listing’s, the device is not listed, or its vendor is suspended. One answer for every reason, so the route tells a stranger nothing | Check the serial against the listing, then ask the listing party for a new code |
403 | attestation_failed | The chain fails a check of Which devices the middleware admits (step 3), other than the app’s and the model’s, or does not parse | Fix the cause and try again: the code stays live for its 15 minutes. Check the challenge against the worked one, and that the key was made in the keystore with it. A device rooted, unlocked or revoked does not pass |
403 | app_identity_unknown | The attestation names a package or a signing digest not registered for this vendor and role, or more than one package | Register the app’s package and signing digest (step 1), then try again inside the 15 minutes |
403 | model_not_allowed | No row of the allowed list admits what the device attested | Ask the operator to allow the model, then try again inside the 15 minutes, or later with a new code |
429 | None: the body is the edge’s own, not an Error | Sent by the edge in front of a hosted middleware, never by the middleware itself: more enrolments came from this address in a minute than the edge allows. The code was not read, and no attempt is counted against it | Wait a minute, then try again with the same body. Do not read the body as an Error |
503 | ca_unavailable, attestation_status_unavailable | The middleware could not sign, or holds no fresh copy of Google’s attestation status list | Back off and try again with the same body. The code is not spent |
503 | store_unavailable | The middleware’s store did not answer | Back off and try again with the same body |
7. Store the chain against the alias
The 201’s CertificateChain is two certificates, PEM: the device’s own, then the issuing
certificate. The device presents both at the handshake of every call from now on (step 8). A
certificate is public, so the chain needs no protecting, but it belongs to the key under one
alias, and is kept against that alias. The app keeps the alias of the key it connects with,
current, and while a new certificate waits for its first use, that one’s, next.
import android.content.Context
import java.io.File
import java.io.IOException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
/** The chains the middleware issued, each against the keystore alias of its key, and which is in use. */
class Identities(context: Context) {
private val prefs = context.getSharedPreferences("mw-identity", Context.MODE_PRIVATE)
private val dir = File(context.noBackupFilesDir, "mw").apply { mkdirs() }
/** The alias of the key the device connects with. */
var current: String?
get() = prefs.getString("current", null)
set(alias) {
prefs.edit().putString("current", alias).commit()
}
/** The alias of a certificate issued and not yet used: a renewal's or a re-enrolment's. */
var next: String?
get() = prefs.getString("next", null)
set(alias) {
prefs.edit().putString("next", alias).commit()
}
/** Keeps a `201`'s `CertificateChain` against [alias], whole or not at all. */
fun storeChain(alias: String, certificateChain: String) {
val partial = File(dir, "$alias.pem.partial")
partial.writeText(certificateChain)
if (!partial.renameTo(File(dir, "$alias.pem"))) {
throw IOException("cannot keep the chain of $alias")
}
}
/** The chain kept against [alias], leaf first, or null. */
fun chain(alias: String): Array<X509Certificate>? {
val file = File(dir, "$alias.pem")
if (!file.exists()) return null
return file.inputStream().use { stream ->
CertificateFactory.getInstance("X.509")
.generateCertificates(stream)
.map { it as X509Certificate }
.toTypedArray()
}
}
/** Forgets the chain of a key that was deleted. */
fun forget(alias: String) {
File(dir, "$alias.pem").delete()
}
}
/** After the first enrolment: the chain kept against the new alias, which is now current. */
fun enrolled(identities: Identities, enrolment: Enrolment): Answer {
val answer = enrolDevice(enrolment)
if (answer is Answer.Ok) {
identities.storeChain(enrolment.alias, answer.body.getString("CertificateChain"))
identities.current = enrolment.alias
}
// A refusal: the table of step 6 says what to tell the installer.
return answer
}
A 201 ends any wait a refusal set: connect at once on the new certificate. A new code re-pairs
the device, so the credential it held, a certificate or in the sandbox its key, is refused
403 not_permitted, which the holder’s table backs off an hour. That hour is for the credential
refused, and the middleware takes the new certificate at once.
The chain is kept in the app’s no-backup storage, because a backup restored to another device would hold a chain whose key is not there. A certificate’s key is kept nowhere but the keystore.
8. Give OkHttp the key: an X509ExtendedKeyManager
Every call after enrolment presents the certificate at the TLS handshake. The key stays in the
keystore, so OkHttp is given a key manager that names the keystore alias, hands over the kept
chain, and gives the TLS stack the keystore’s handle to the key, which signs inside the
keystore. One OkHttp client built on it serves REST and the WebSocket alike: a register’s
sales and links, a terminal’s connection (docs/api/terminal.md, Connect), the daily check
and renewal.
import java.net.Socket
import java.security.KeyStore
import java.security.Principal
import java.security.PrivateKey
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLEngine
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509ExtendedKeyManager
import javax.net.ssl.X509TrustManager
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener
/** Presents the keystore key under [alias], with the chain the middleware issued for it, and no other. */
class KeystoreKeyManager(
private val alias: String,
private val chain: Array<X509Certificate>,
) : X509ExtendedKeyManager() {
private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
override fun chooseClientAlias(
keyType: Array<out String>?,
issuers: Array<out Principal>?,
socket: Socket?,
): String = alias
override fun chooseEngineClientAlias(
keyType: Array<out String>?,
issuers: Array<out Principal>?,
engine: SSLEngine?,
): String = alias
override fun getClientAliases(keyType: String?, issuers: Array<out Principal>?): Array<String> =
arrayOf(alias)
override fun getCertificateChain(alias: String?): Array<X509Certificate>? =
if (alias == this.alias) chain else null
override fun getPrivateKey(alias: String?): PrivateKey? =
if (alias == this.alias) keyStore.getKey(this.alias, null) as? PrivateKey else null
override fun chooseServerAlias(
keyType: String?,
issuers: Array<out Principal>?,
socket: Socket?,
): String? = null
override fun getServerAliases(keyType: String?, issuers: Array<out Principal>?): Array<String>? =
null
}
/** A client presenting the key under [alias], for REST and the WebSocket alike. */
fun clientFor(alias: String, chain: Array<X509Certificate>): OkHttpClient {
val trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustFactory.init(null as KeyStore?)
val trust = trustFactory.trustManagers.filterIsInstance<X509TrustManager>().first()
val tls = SSLContext.getInstance("TLS")
tls.init(arrayOf(KeystoreKeyManager(alias, chain)), arrayOf(trust), null)
return OkHttpClient.Builder()
.sslSocketFactory(tls.socketFactory, trust)
// OkHttp answers the middleware's Pings itself and never shows them: send its own.
.pingInterval(30, TimeUnit.SECONDS)
.build()
}
/**
* A terminal's connection, `docs/api/terminal.md`, Connect, on [client]. OkHttp opens a
* WebSocket from an https address, and presents the key at its handshake as for REST.
*/
fun connect(client: OkHttpClient, poiIdentification: String, listener: WebSocketListener): WebSocket {
val request = Request.Builder().url("$MW/v1/terminals/$poiIdentification/connect").build()
return client.newWebSocket(request, listener)
}
Build the client once for each alias, and use it for every call while that alias is in use.
Never change which key one client presents: a client’s TLS context keeps its sessions, and a
resumed session stands on the certificate of the handshake it resumes, so a new certificate
goes with a new client (step 10). Send no Authorization header on a client that presents a
certificate: the two together are refused 401 certificate_invalid. The client’s
pingInterval is what keeps the terminal’s WebSocket to the contract’s Hold
(docs/api/terminal.md, Hold), since OkHttp shows the app none of the middleware’s Pings.
- BENCH-4, proven on a SUNMI P2 Lite SE, Android 11, the unit of the runs above, on its
software keystore. A keystore key drove client TLS through OkHttp and an
X509ExtendedKeyManager, TLS 1.3 and 1.2, on REST and on a WebSocket, on FUNDiMO’s bench of 12-Nov-2026, and a terminal vendor’s app connected to the sandbox on its certificate this way on 13-Nov-2026. A key in secure hardware is not yet tried.
9. The daily check: GET /v1/certificates/self
Once a day the device sends GET /v1/certificates/self, on its own certificate. The middleware
answers when the certificate ends, and whether to renew:
{ "NotAfter": "...", "RenewFrom": "...", "RenewNow": true }
Renew when RenewNow is true, and not before. The middleware decides, so the device’s clock does
not matter. RenewNow reads true only on the newest certificate in use, from RenewFrom
on, and false on a certificate that is retired.
import android.content.Context
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.io.IOException
import java.util.concurrent.TimeUnit
import okhttp3.Request
/** Once a day: a certificate waiting for its first use, then the daily check, then any renewal. */
class DailyCheck(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result = try {
val identities = Identities(applicationContext)
firstUse(identities)
val alias = identities.current
val chain = alias?.let { identities.chain(it) }
if (alias != null && chain != null) {
val client = clientFor(alias, chain)
val self = Request.Builder().url("$MW/v1/certificates/self").build()
val answer = call(client, self)
if (answer is Answer.Ok && answer.body.getBoolean("RenewNow")) {
if (renew(client, identities) is Answer.Ok) firstUse(identities)
}
// A refusal: the holder's table, below.
}
Result.success()
} catch (noAnswer: IOException) {
Result.retry()
}
}
/** One daily check, however often this is called. */
fun scheduleDailyCheck(context: Context) {
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
"mw-daily-check",
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<DailyCheck>(1, TimeUnit.DAYS).build(),
)
}
A refusal of the daily check is read by the holder’s table (What a holder of a dead certificate does, below). A call that gets no answer is tried again later.
10. Renew: a new key under a new alias
A certificate renews from day 15, always with a new key. So a device proves its state again every 15 days, and a device rooted after it enrolled loses its identity within one lifetime of a certificate, but on a middleware set to mark (step 3), which marks it instead.
- Send
POST /v1/certificates/challengeon the current certificate, with no body and withContent-Length: 0: over HTTP/1.1, the edge in front of a hosted middleware refuses it without that header, with a411of its own. The201holdsChallenge, 32 bytes as 64 hex characters, andExpiresInSeconds, 600. - Make a new key under a new alias with those 32 bytes as its attestation challenge (step 3), and a CSR for it (step 4).
- Send
POST /v1/certificates/renewwithCertificateSigningRequestandAttestationChain, on the current certificate, inside the challenge’s 10 minutes. The201is enrolment’s. If an answer is lost, send the same body again: a CSR of the key the middleware issued for last answers200with that certificate. - Keep the new chain against the new alias, as the next certificate (step 7), and use it from the next connection, on a new client of its own (step 8).
- Once a call on the new certificate has been answered, it is current. Only then delete the old key.
import java.security.KeyStore
import java.util.UUID
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
/**
* Renews on [client], the current certificate's: a challenge, a new key under a new alias made
* with it, and the renewal. A certificate issued is kept as the next one.
*/
fun renew(client: OkHttpClient, identities: Identities): Answer {
val ask = Request.Builder()
.url("$MW/v1/certificates/challenge")
.post(ByteArray(0).toRequestBody())
.build()
val issued = call(client, ask)
if (issued !is Answer.Ok) return issued
val challenge = requireNotNull(bytesOfHex(issued.body.getString("Challenge"))) {
"a challenge is 64 hex characters"
}
val alias = "mw-" + UUID.randomUUID()
makeKey(alias, challenge)
val body = JSONObject()
.put("CertificateSigningRequest", csrFor(alias))
.put("AttestationChain", attestationChainOf(alias))
.toString()
.toRequestBody(JSON)
val request = Request.Builder().url("$MW/v1/certificates/renew").post(body).build()
val renewed = sendUntilAnswered(client, request)
if (renewed is Answer.Ok) {
identities.storeChain(alias, renewed.body.getString("CertificateChain"))
identities.next = alias
}
return renewed
}
/**
* The first use of the next certificate, on a client of its own. Once the middleware has answered on
* it, it is current, and only then are the old key, and any key a refused renewal left, deleted.
* Returns whether it moved.
*/
fun firstUse(identities: Identities): Boolean {
val next = identities.next ?: return false
val chain = identities.chain(next) ?: return false
val self = Request.Builder().url("$MW/v1/certificates/self").build()
if (call(clientFor(next, chain), self) !is Answer.Ok) return false
identities.current = next
identities.next = null
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
for (alias in keyStore.aliases().toList()) {
if (alias.startsWith("mw-") && alias != next) {
keyStore.deleteEntry(alias)
identities.forget(alias)
}
}
return true
}
The old certificate stays good until the new one is first used, and for an hour after,
MW_CERT_OVERLAP_SECS. Move every connection to the new client inside that hour: a
terminal moves its WebSocket between sales. Past the hour, a call on the old certificate is
refused 403 certificate_retired, and a terminal’s WebSocket still open on it is closed. If
the first call on the new certificate gets no answer, go on with the old one, which is good
until then, and try the new one again later.
Run the daily check, a renewal and a first use one at a time. A second renewal retires a certificate the first issued that is not yet used, and the middleware warns the operator of it, as the sign of an identity copied.
When renewal is refused
A refusal of a renewal leaves the current certificate as it was.
Of invalid_json, unknown_field, missing_field and invalid_field, the first class that
fails answers alone, with Fields naming every field of it, sorted.
| Status | Error.Code | When | What to do |
|---|---|---|---|
409 | renewal_not_due | Before RenewFrom | Wait: renew when the daily check’s RenewNow is true |
403 | challenge_not_valid | The key was made with no live challenge of this certificate’s: none asked, one past its 10 minutes, or one spent | Ask a new challenge, and make a new key with it under another new alias |
400 | invalid_field | The CSR’s signature does not verify, its key is not P-256, or its key was used before | Make a new P-256 key under a new alias, with a new challenge |
403 | attestation_failed, app_identity_unknown, model_not_allowed | The new key’s attestation fails, as at enrolment (step 6) | The current certificate is good until its NotAfter, and the operator is warned. Fix the cause, and try again with a new challenge at the next daily check |
429 | renewal_rate | 5 certificates for this identity in 24 hours | Back off, and try again tomorrow |
403 | not_permitted | The device or its vendor is not in good standing: removed, suspended or re-paired | Back off to one hour. The certificate was good and the row refused it |
403 | certificate_retired | The certificate presented is retired | Renew on the newer certificate if the device holds one. On its newest, stop and tell a person: something else holds a newer certificate of this identity |
401 | certificate_expired | The certificate is past its NotAfter | Re-enrol with a new code (step 11) |
503 | ca_unavailable, attestation_status_unavailable, store_unavailable | The middleware could not sign, holds no fresh status list, or its store did not answer | Back off and try again with the same body inside the challenge’s 10 minutes, or later with a new challenge and a new key |
What a holder of a dead certificate does
A device holding a certificate is its holder. A refusal at the TLS handshake, or of a call, is
read by this table, which is docs/api/terminal.md’s.
| What the device sees | What it does next |
|---|---|
| A close, a reset, a timeout, or any failure with no TLS alert | The normal backoff (docs/api/terminal.md, Reconnect), which resets only once a connection has stayed open 10 seconds. It says nothing about a certificate |
A TLS alert naming the certificate: certificate_expired, bad_certificate, certificate_unknown, unknown_ca or decrypt_error. Only where the middleware ends TLS itself | Back off an hour. After three, an hour apart, tell the installer the device needs a new code, and keep trying hourly |
401 certificate_expired or 401 certificate_invalid | Back off an hour. After three, an hour apart, tell the installer the device needs a new code, and keep trying hourly |
401 certificate_required | A client’s own bug, or a route it has no certificate for: enrol first |
403 certificate_retired, holding a newer certificate than the one presented | Drop that connection and retry on the newer one, with the same idempotency key where the request carried one |
403 certificate_retired on its newest certificate | Stop, keep any outcome, and tell a person: something else holds a newer certificate of this identity |
403 not_permitted | Back off to one hour, keeping any outcome. The certificate was good and the row refused it, which is what a removal or a re-pair reads as |
403 challenge_not_valid | Ask a new challenge, with a new key |
429, 503, edge_not_trusted among them | The normal backoff. 503 edge_not_trusted is an edge fault, and the device’s certificate is not in question |
OkHttp reports a TLS alert as an SSLException. On the unit of the runs above, a
certificate_unknown alert came as an SSLProtocolException whose message names
SSLV3_ALERT_CERTIFICATE_UNKNOWN; how a SUNMI device words the other alerts is not yet proven
on a device. Behind the middleware’s load balancer no handshake fails on a client certificate,
and the refusal comes as a 401 or a 403 instead.
A device never deletes its key or its certificate on a refusal, any of those above. A device can recover from a mistake of the middleware’s by a fix on the middleware’s side, and a key deleted cannot be recovered. A device holding a certificate makes a new key only to renew, or when a person brings a new code, and deletes an old key only once a call on the certificate that follows it has been answered. A device decides none of this by its own clock.
11. Re-enrol with a new code
A device off longer than its certificate, past its NotAfter, re-enrols with a new code. So
does a device told after three hourly tries that it needs one, and a device its listing party
re-paired, which is refused 403 not_permitted until a person brings it the new code. This is
the one case after the first enrolment in which a person is needed.
- The installer asks the listing party for a new code:
POST /v1/terminals/{POIIdentification}/pairing-codefor a terminal,POST /v1/registers/{RegisterIdentification}/pairing-codefor a register, or in the sandboxPOST /sandbox/v1/codes. A new code re-pairs the device, which retires its certificates. - The installer opens the app’s enrolment screen from its menu or settings, on the device as it is, and types the new code’s words, or scans its QR code (step 2, and The enrolment screen).
- The app enrols as it did the first time (step 6), with a new key under a new alias, and the challenge of the new code.
- It keeps the chain as the next certificate, and deletes the old key once a call on the new one has been answered, as a renewal does (step 10).
- A
201ends any wait a refusal set: it connects at once on the new certificate, though the old one’s403 not_permittedset an hour (step 7).
import java.io.IOException
/**
* Re-enrolment with the new code the installer typed, built by `enrolment`. The new certificate
* is kept as the next one, and the old key stays until a call on it has been answered. A first
* use that gets no answer leaves it next: the screen says the device is enrolled and not yet
* connected, and tries `firstUse` again, which needs no code, and never the enrolment, which
* the code refuses once its 15 minutes end.
*/
fun reEnrol(identities: Identities, enrolment: Enrolment): Answer {
val answer = enrolDevice(enrolment)
if (answer is Answer.Ok) {
identities.storeChain(enrolment.alias, answer.body.getString("CertificateChain"))
identities.next = enrolment.alias
try {
firstUse(identities)
} catch (noAnswer: IOException) {
// Still next: the screen tries the first use again (SCREEN-24).
}
}
// A refusal: the table of step 6.
return answer
}
The device keeps its id, POIIdentification or RegisterIdentification, and a register’s
links to terminals stand: a re-pair ends none.
The enrolment screen
The enrolment screen is the screen of your app on which a person enrols the device: it takes the code (step 2), shows the serial (step 5), sends the enrolment (step 6) and says what came of it. An installer or a store’s staff uses it at the first enrolment and at each re-enrolment (step 11), at the device, with nothing else to hand. So each requirement here has a check a person can make at the device: most with the device alone, and the few that need more, a sale sent to the device, or the app’s own log or tests, say so. A Must is one an app is not ready for a store without. A Should is one an app meets unless its vendor can say why it does not. A register’s app enrols on a server’s code in the sandbox (step 2), so its screen is first tried at staging.
A conformance run does not check this screen. It judges what a terminal sends on its connection,
and sees no screen (docs/api/sandbox.md, What a green run does not check).
How a person reaches it
| Id | Requirement | Strength | How a person at the device checks it |
|---|---|---|---|
| SCREEN-1 | An entry in the app’s own menu or settings opens the screen, and its name says what it does, such as Enrol this device | Must | Open the app, and find the entry by its name |
| SCREEN-2 | The device alone reaches it: no cable, no developer option, no command, no launcher of another app, and no second device. A store or an installer has none of those, so a screen that only a developer’s command over USB opens cannot be reached at a store | Must | With USB debugging off and nothing plugged in, go from the app’s home screen to the enrolment screen |
| SCREEN-3 | It stays reachable after the first enrolment, and opens on a device that holds a certificate, so a person re-enrols the device with a new code without reinstalling the app or clearing its data: for a certificate replaced (step 11), at a new store, or in a new sandbox world. The device enrols as the id the 201 names, which a new store or a new world changes, so the app takes its id from the 201 and keeps no earlier one | Must | On a device already enrolled, with nothing reinstalled, open the screen again, enrol it with a new code, and read the state it shows: the id the new code’s 201 named (SCREEN-14) |
| SCREEN-4 | It is at most two taps from the app’s home screen, such as a menu, then the entry | Should | Count the taps from the app’s home screen to the enrolment screen |
| SCREEN-5 | Where the device holds no certificate, or the holder’s table has the app tell the installer the device needs a new code (What a holder of a dead certificate does), the app says so where its staff look, and leads to the screen in one tap | Should | Open the app on a device not enrolled, and see it say so and lead to the screen |
| SCREEN-6 | On a device that holds a certificate, the screen takes a code only after the app’s own supervisor or merchant sign-in, or its own PIN, which store staff or an installer holds, and a choice of environment before the first enrolment asks the same. Nothing else guards the screen: never a cable, a developer option, a command, a second device, a gesture with no name on the screen, or a password only the app’s developer holds | Must | On a device enrolled, open the screen, and see it ask for the sign-in or the PIN before it takes a code. On a device not yet enrolled whose app offers more than one environment, see the choice ask the same. Reach the screen with what the store’s staff hold, and nothing else |
The code is the credential (step 6), but a code for another listing, or a sandbox code anyone can take, would enrol a device in service as something else. So the screen of a device that holds a certificate takes a code only behind what the store’s staff hold (SCREEN-6), and never moves the device to another environment (SCREEN-13).
What it shows and takes
| Id | Requirement | Strength | How a person at the device checks it |
|---|---|---|---|
| SCREEN-7 | A field for the code’s five words, which completes each word from the word list the app bundles, marks at once a letter that begins no word, and has the keyboard’s own corrections turned off (step 2, Typing the code) | Must | Type a word’s first four letters, and see the word completed. Type a letter that begins no word, and see it marked before you type another |
| SCREEN-8 | Where the device has a camera or a scanner, a way to scan the code’s QR code into the same field (step 2, The QR code) | Should | Scan a QR code of a code, and see its five words in the field |
| SCREEN-9 | The five words, as the app read them, are shown before the person taps to enrol, and the enrolment is sent on that tap alone, never on a scan or on the fifth word typed | Must | Type or scan a code, and see that nothing is sent until you tap |
| SCREEN-10 | Where the serial to send is the device’s own, as it is outside the sandbox, and the device reports it (step 5), the screen shows that serial, read each time the screen opens, not typed and not editable. A serial kept from an earlier enrolment is never shown in its place | Must | Outside the sandbox, compare the serial on the screen with the one printed on the device |
| SCREEN-11 | Where the serial to send is not one the device reports, the screen takes it typed, in a field that is empty each time the screen opens and never filled from an earlier enrolment, and says which serial it asks for. In the sandbox a world names its own, <tester>-yours, the SerialNumber that POST /sandbox/v1/codes answered beside the code, and the screen asks for that one. On a device whose SDK gives no serial (step 5), it asks for the one printed on the device | Must | Enrol in the sandbox, open the screen again, and see the serial’s field empty |
| SCREEN-12 | The environment it will enrol into, by the name docs/api/environments.md gives it, the sandbox or staging, and its base URL’s host, taken from the list the app holds and never from an address typed (What you need) | Must | Read the environment on the screen before you tap to enrol |
| SCREEN-13 | On a device that holds a certificate, the screen offers no other environment. Moving a device to another environment is clearing the app’s data, a deliberate act, as docs/api/environments.md says, and never a choice on this screen, so no code from another environment, a sandbox code anyone can take among them, moves a device in service | Must | On a device enrolled, open the screen, and find no way to choose another environment |
| SCREEN-14 | The state the device is in: not enrolled; or enrolled, as which terminal by its POIIdentification, or which register by its RegisterIdentification, in which environment, and its certificate’s dates, NotAfter and RenewFrom, as the last 201 or daily check answered them | Must | Read the state on a device not enrolled, and on one enrolled |
| SCREEN-15 | The store the device is enrolled at, by the name its staff know, where the app has it from its fleet’s own records. The middleware’s answers name the terminal, not its store | Should | Read the store’s name on a device enrolled |
| SCREEN-16 | Each refusal is shown in words a person can act on, saying what to do next, as What it says to each refusal gives them: never a status number alone, nor the middleware’s Message alone | Must | Enrol with five words of the list that are not the code you were given, and read what the screen says |
| SCREEN-17 | Beside those words, the refusal’s Error.Code, in small type, for whoever supports the app | Should | Read the code under the words of a refusal |
| SCREEN-18 | One tap sends one enrolment, and while it waits the screen says so and takes no second tap. The app keeps the enrolment it built, enrolment (step 6), while the screen is open, and while it keeps one the words and the serial cannot be edited: the screen offers to send it again, or to start over. It sends the same enrolment again, with the same key, after no answer, a 429, a 5xx or an answer it cannot read, any of which may follow an enrolment that spent the code: a spent code refuses any key but the one it was spent with, and inside the code’s 15 minutes answers that one 200 (step 6). A 201 or its 200, a 400 or a 403 of step 6’s table, starting over, or the screen closing ends it, and after a 400 or a 403, a verdict on this very enrolment, the next tap builds a new one from the words shown | Must | Tap to enrol twice, quickly, and see one enrolment answered. That a tap after no answer sends the same key, the vendor shows with a test of its own that loses the answer |
What it says to each refusal
Each refusal of step 6, in words a person at the device can act on. Put them in your own words,
saying the same. As step 6 says, a refusal of a code the middleware found uses one of its five
tries, unless the code was already spent or burned. The edge’s 429, 503 ca_unavailable and
503 attestation_status_unavailable use none, and a 503 store_unavailable whose commit landed
may have used one, or spent the code.
| What comes back | What the screen says |
|---|---|
403 code_not_valid | The code or the serial was not taken. Check that the serial on the screen is the one the code was given for, then ask whoever gave you the code for a new one |
403 attestation_failed | This device did not pass the middleware’s check of its hardware and software. Tell the app’s support. The code stays good for its 15 minutes, less this try |
403 app_identity_unknown | This build of the app is not registered in this environment. Tell the app’s support. The code stays good for its 15 minutes, less this try |
403 model_not_allowed | This model of device is not yet allowed. Ask whoever gave you the code to have it allowed, then try again within the code’s 15 minutes, or later with a new code |
400 invalid_json, unknown_field, missing_field or invalid_field | The app could not make its request. Tell the app’s support |
429 from the edge, whose body is not an Error | Too many enrolments came from this network just now. Wait a minute, then tap to enrol again: the app sends the same enrolment (SCREEN-18). The code was not read |
503 ca_unavailable, attestation_status_unavailable or store_unavailable | The middleware cannot enrol a device just now. Wait, then tap to enrol again: the app sends the same enrolment, with the same key (SCREEN-18) |
| No answer, or a handshake that failed | The middleware did not answer. Check the network, and the device’s date and time, then tap to enrol again: the app sends the same enrolment, with the same key (SCREEN-18) |
Any other answer, such as a 502 or a 504 from in front of the middleware | The middleware’s answer could not be read. Wait, then tap to enrol again: the app sends the same enrolment, with the same key (SCREEN-18). If it comes again, tell the app’s support |
What it never shows or keeps
| Id | Requirement | Strength | How a person at the device checks it |
|---|---|---|---|
| SCREEN-19 | The code’s words are cleared from the screen on a 201, or a 200 repeating it, and when the screen closes. They are held only in the enrolment the screen keeps for a resend (SCREEN-18), never written to the device’s storage or to a log, the app’s own among them, and never put back in the field when the screen next opens | Must | Enrol, leave the screen, open it again, and see the code’s field empty. The app’s own log, which its vendor reads, holds no code’s words |
| SCREEN-20 | No key: not the device’s key, which never leaves the keystore (step 3), not a sandbox key, and no certificate’s private part. A certificate is public, and the screen may show its dates | Must | Go through the screen and each screen it opens, and see no key |
| SCREEN-21 | The screen sets Android’s FLAG_SECURE, so the code’s words reach no screenshot and no picture in the list of recent apps | Should | With words in the field, open the list of recent apps, and see the screen blank |
After a success
| Id | Requirement | Strength | How a person at the device checks it |
|---|---|---|---|
| SCREEN-22 | On a 201, or a 200 repeating it, the screen says the device is enrolled: as which terminal or register, in which environment, and until when, as SCREEN-14 shows them, with the code’s words gone | Must | Enrol, and read the screen |
| SCREEN-23 | The app uses the new certificate at once, with no restart of the app or the device and nothing more for the person to do: a 201, or a 200 repeating it, ends any wait a refusal set (step 7) | Must | Enrol, then, restarting nothing, send a sale: to a terminal from the store’s POS or the sandbox’s send_sale, from a register at its till. See it go through |
| SCREEN-24 | The screen says when the device has connected on its new certificate, so the person knows before leaving the device. While a re-enrolment’s certificate waits for its first use (step 11), the screen says the device is enrolled and not yet connected, and each tap tries the first use again, firstUse (step 10), which needs no code: never the enrolment, which the code refuses once its 15 minutes end | Must | Enrol, and see the screen say the device is connected |