@onetokenfe/react-native-nfc-wallet-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/NfcWalletSdk.podspec +22 -0
  2. package/README.md +81 -0
  3. package/android/build.gradle +59 -0
  4. package/android/src/main/AndroidManifest.xml +4 -0
  5. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/NfcWalletEngine.kt +486 -0
  6. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/NfcWalletSdkModule.kt +268 -0
  7. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/NfcWalletSdkPackage.kt +14 -0
  8. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/nfc/NfcUtils.kt +24 -0
  9. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/utils/HexUtils.kt +24 -0
  10. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/wallet/WalletApduClient.kt +495 -0
  11. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/wallet/WalletConstants.kt +105 -0
  12. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/wallet/WalletNfcController.kt +262 -0
  13. package/android/src/main/java/com/ziancube/reactnativenfcwalletsdk/wallet/WalletNfcTagHolder.kt +74 -0
  14. package/ios/Classes/NfcWalletHexUtils.h +8 -0
  15. package/ios/Classes/NfcWalletHexUtils.m +31 -0
  16. package/ios/Classes/NfcWalletNFCManager.h +58 -0
  17. package/ios/Classes/NfcWalletNFCManager.m +244 -0
  18. package/ios/Classes/NfcWalletSession.h +52 -0
  19. package/ios/Classes/NfcWalletSession.m +1109 -0
  20. package/ios/NfcWalletSdk.h +5 -0
  21. package/ios/NfcWalletSdk.mm +369 -0
  22. package/lib/module/NativeNfcWalletSdk.js +8 -0
  23. package/lib/module/NativeNfcWalletSdk.js.map +1 -0
  24. package/lib/module/constants.js +5 -0
  25. package/lib/module/constants.js.map +1 -0
  26. package/lib/module/index.js +8 -0
  27. package/lib/module/index.js.map +1 -0
  28. package/lib/module/nfc.js +81 -0
  29. package/lib/module/nfc.js.map +1 -0
  30. package/lib/module/package.json +1 -0
  31. package/lib/module/walletOperations.js +68 -0
  32. package/lib/module/walletOperations.js.map +1 -0
  33. package/lib/typescript/package.json +1 -0
  34. package/lib/typescript/src/NativeNfcWalletSdk.d.ts +166 -0
  35. package/lib/typescript/src/NativeNfcWalletSdk.d.ts.map +1 -0
  36. package/lib/typescript/src/constants.d.ts +3 -0
  37. package/lib/typescript/src/constants.d.ts.map +1 -0
  38. package/lib/typescript/src/index.d.ts +7 -0
  39. package/lib/typescript/src/index.d.ts.map +1 -0
  40. package/lib/typescript/src/nfc.d.ts +43 -0
  41. package/lib/typescript/src/nfc.d.ts.map +1 -0
  42. package/lib/typescript/src/walletOperations.d.ts +22 -0
  43. package/lib/typescript/src/walletOperations.d.ts.map +1 -0
  44. package/package.json +90 -0
  45. package/react-native.config.js +10 -0
  46. package/src/NativeNfcWalletSdk.ts +205 -0
  47. package/src/constants.ts +2 -0
  48. package/src/index.tsx +33 -0
  49. package/src/nfc.ts +80 -0
  50. package/src/walletOperations.ts +152 -0
@@ -0,0 +1,22 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "NfcWalletSdk"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = "https://github.com/qiaomc/NFC-Wallet"
10
+ s.license = package["license"]
11
+ s.authors = package["author"]
12
+ s.platforms = { :ios => "13.0" }
13
+ s.source = { :git => "https://github.com/qiaomc/onetoken_NFC_wallet_sdk.git", :tag => "#{s.version}" }
14
+
15
+ s.source_files = "ios/**/*.{h,m,mm}"
16
+ s.frameworks = "CoreNFC"
17
+ s.pod_target_xcconfig = {
18
+ "OTHER_LDFLAGS" => "$(inherited) -ObjC"
19
+ }
20
+
21
+ install_modules_dependencies(s)
22
+ end
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # OneToken NFC Wallet SDK (React Native)
2
+
3
+ React Native TurboModule for **NFC-Wallet** Java Card applet (`6F6E65746F6B656E02`).
4
+ Lightweight APDU session — no SCP11/SCP03, no GPChannel native libs.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ yarn add file:../onetoken_NFC_wallet_sdk
10
+ # or after publish:
11
+ # yarn add @onetokenfe/react-native-nfc-wallet-sdk
12
+ ```
13
+
14
+ ### iOS (`ds_dev` / mobile app)
15
+
16
+ 1. `pod install` in `apps/mobile/ios`
17
+ 2. Enable **Near Field Communication Tag Reading** capability
18
+ 3. Add to `Info.plist`:
19
+
20
+ ```xml
21
+ <key>NFCReaderUsageDescription</key>
22
+ <string>Scan NFC wallet card to sign transactions</string>
23
+ <key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
24
+ <array>
25
+ <string>6F6E65746F6B656E02</string>
26
+ </array>
27
+ ```
28
+
29
+ ### Android
30
+
31
+ `AndroidManifest.xml` of host app should include NFC permission (library manifest merges `NFC` permission).
32
+
33
+ Handle NFC intent in `MainActivity` (same as backup card SDK):
34
+
35
+ ```kotlin
36
+ override fun onNewIntent(intent: Intent) {
37
+ super.onNewIntent(intent)
38
+ setIntent(intent)
39
+ }
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```typescript
45
+ import {
46
+ getWalletInfo,
47
+ initializeWallet,
48
+ unlockAndSign,
49
+ checkNFCPermission,
50
+ } from '@onetokenfe/react-native-nfc-wallet-sdk';
51
+
52
+ const perm = await checkNFCPermission();
53
+ const info = await getWalletInfo(); // one tap
54
+ const setup = await initializeWallet('1234'); // set PIN + create key, one tap
55
+ const sig = await unlockAndSign('1234', hashHex); // verify + sign, one tap
56
+ ```
57
+
58
+ ## API
59
+
60
+ | Method | Description |
61
+ |--------|-------------|
62
+ | `getWalletInfo()` | Serial, status, PIN retries |
63
+ | `setPin(pin)` | First-time access code |
64
+ | `verifyPin(pin, expectedSerial?)` | Open session; optional on-card serial check (applet >= 1.0.17) |
65
+ | `createWallet(expectedSerial?)` | Card-generated master seed; optional on-card serial (applet >= 1.0.18) |
66
+ | `createWalletWithSeed(seedHex, expectedSerial?)` | Import 64-byte BIP39 seed; optional on-card serial |
67
+ | `getPublicKey()` | 65-byte uncompressed hex |
68
+ | `signHash(hashHex)` | 32-byte hash → ECDSA sig hex |
69
+ | `initializeWallet(pin)` | Composite: setup + create |
70
+ | `initializeWalletWithPubkeys(pin, pathsJson, seedHex?, expectedSerial?)` | Init + multi-path pubkeys; optional serial bind |
71
+ | `unlockAndSign(pin, hashHex)` | Composite: verify + sign |
72
+ | `wipeWallet()` | Factory reset |
73
+
74
+ ## ds_dev integration
75
+
76
+ Add package dependency in `apps/mobile/package.json`, then implement a hardware signer provider that calls `unlockAndSign` for transaction hashes.
77
+
78
+ ## Related
79
+
80
+ - Applet: [NFC-Wallet](https://github.com/qiaomc/NFC-Wallet)
81
+ - Backup SDK: `@digitalshieldfe/react-native-backup-card-sdk`
@@ -0,0 +1,59 @@
1
+ buildscript {
2
+ ext.NfcWalletSdk = [
3
+ kotlinVersion: "2.0.21",
4
+ minSdkVersion: 24,
5
+ compileSdkVersion: 36,
6
+ targetSdkVersion: 36
7
+ ]
8
+
9
+ ext.getExtOrDefault = { prop ->
10
+ if (rootProject.ext.has(prop)) {
11
+ return rootProject.ext.get(prop)
12
+ }
13
+ return NfcWalletSdk[prop]
14
+ }
15
+
16
+ repositories {
17
+ google()
18
+ mavenCentral()
19
+ }
20
+
21
+ dependencies {
22
+ classpath "com.android.tools.build:gradle:8.7.2"
23
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
24
+ }
25
+ }
26
+
27
+ apply plugin: "com.android.library"
28
+ apply plugin: "kotlin-android"
29
+ apply plugin: "com.facebook.react"
30
+
31
+ react {
32
+ jsRootDir = file("../src/")
33
+ libraryName = "NfcWalletSdkSpec"
34
+ codegenJavaPackageName = "com.ziancube.reactnativenfcwalletsdk"
35
+ }
36
+
37
+ android {
38
+ namespace "com.ziancube.reactnativenfcwalletsdk"
39
+ compileSdkVersion getExtOrDefault("compileSdkVersion")
40
+
41
+ defaultConfig {
42
+ minSdkVersion getExtOrDefault("minSdkVersion")
43
+ targetSdkVersion getExtOrDefault("targetSdkVersion")
44
+ }
45
+
46
+ compileOptions {
47
+ sourceCompatibility JavaVersion.VERSION_17
48
+ targetCompatibility JavaVersion.VERSION_17
49
+ }
50
+
51
+ kotlinOptions {
52
+ jvmTarget = "17"
53
+ }
54
+ }
55
+
56
+ dependencies {
57
+ implementation "com.facebook.react:react-android"
58
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"
59
+ }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.NFC" />
3
+ <uses-feature android:name="android.hardware.nfc" android:required="false" />
4
+ </manifest>
@@ -0,0 +1,486 @@
1
+ package com.ziancube.reactnativenfcwalletsdk
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import com.ziancube.reactnativenfcwalletsdk.wallet.WalletApduException
6
+ import com.ziancube.reactnativenfcwalletsdk.wallet.WalletConstants
7
+ import com.ziancube.reactnativenfcwalletsdk.wallet.WalletInfoData
8
+ import com.ziancube.reactnativenfcwalletsdk.wallet.WalletNfcController
9
+ import com.ziancube.reactnativenfcwalletsdk.utils.HexUtils
10
+
11
+ class NfcWalletEngine(private val controller: WalletNfcController) {
12
+ fun getWalletInfo(): WalletInfoData = controller.withWalletSession { it.readWalletInfo() }
13
+
14
+ fun setPin(pin: String) {
15
+ controller.withWalletSession { it.setPin(pin.toByteArray(Charsets.UTF_8)) }
16
+ }
17
+
18
+ /**
19
+ * Change access code on the tapped card only (applet >= 1.0.25).
20
+ * Single NFC session: read serial → reject mismatch → CHANGE_PIN.
21
+ * expectedSerial is required so a different card cannot be updated by accident.
22
+ */
23
+ fun changePin(oldPin: String, newPin: String, expectedSerial: String? = null): WalletInfoData {
24
+ return controller.withWalletSession { client ->
25
+ val info = client.readWalletInfo()
26
+ val expected =
27
+ expectedSerial?.takeIf { it.isNotEmpty() }
28
+ ?: throw IllegalArgumentException("expectedSerial is required for changePin")
29
+ if (!info.serialNumber.equals(expected, ignoreCase = true)) {
30
+ throw WalletApduException(
31
+ WalletConstants.SW_SERIAL_MISMATCH,
32
+ "Wrong card: expected $expected, got ${info.serialNumber}",
33
+ )
34
+ }
35
+ val versionHex = info.version?.replace(" ", "")?.lowercase().orEmpty()
36
+ // 1.0.25 = 010019
37
+ if (versionHex.length >= 6) {
38
+ val ver = versionHex.substring(0, 6)
39
+ if (ver < "010019") {
40
+ throw IllegalArgumentException(
41
+ "CHANGE_PIN requires applet >= 1.0.25 (got ${info.version})",
42
+ )
43
+ }
44
+ }
45
+ client.changePin(
46
+ oldPin.toByteArray(Charsets.UTF_8),
47
+ newPin.toByteArray(Charsets.UTF_8),
48
+ expected,
49
+ )
50
+ info
51
+ }
52
+ }
53
+
54
+ fun verifyPin(pin: String, expectedSerial: String? = null) {
55
+ controller.withWalletSession {
56
+ it.verifyPin(pin.toByteArray(Charsets.UTF_8), expectedSerial)
57
+ }
58
+ }
59
+
60
+ fun logout() {
61
+ controller.withWalletSession { it.logout() }
62
+ }
63
+
64
+ fun createWallet(expectedSerial: String? = null): WalletInfoData =
65
+ controller.withWalletSession { client ->
66
+ // On-card serial check when expected is set (applet >= 1.0.18, SW=6A20).
67
+ client.createWallet(expectedSerial)
68
+ client.readWalletInfo()
69
+ }
70
+
71
+ fun createWalletWithSeed(seedHex: String, expectedSerial: String? = null): WalletInfoData {
72
+ val seed = HexUtils.decode(seedHex)
73
+ require(seed.size == WalletConstants.MASTER_SEED_LEN) {
74
+ "seed must be ${WalletConstants.MASTER_SEED_LEN} bytes"
75
+ }
76
+ return controller.withWalletSession { client ->
77
+ client.createWalletWithSeed(seed, expectedSerial)
78
+ client.readWalletInfo()
79
+ }
80
+ }
81
+
82
+ fun getPublicKeyHex(path: String? = null, curve: String? = null): String =
83
+ controller.withWalletSession {
84
+ val curveP1 =
85
+ if (curve == "ed25519") {
86
+ WalletConstants.P1_PUBKEY_ED25519
87
+ } else {
88
+ WalletConstants.P1_PUBKEY_SECP256K1
89
+ }
90
+ HexUtils.encode(it.getPublicKey(path, curveP1))
91
+ }
92
+
93
+ data class InitializeWalletWithPubkeysResult(
94
+ val pubkeysJson: String,
95
+ val walletInfo: WalletInfoData,
96
+ )
97
+
98
+ fun initializeWalletWithPubkeys(
99
+ pin: String,
100
+ seedHex: String? = null,
101
+ pathsJson: String,
102
+ expectedSerial: String? = null,
103
+ ): InitializeWalletWithPubkeysResult {
104
+ return controller.withWalletSession { client ->
105
+ val info = client.readWalletInfo()
106
+ val expected = expectedSerial?.takeIf { it.isNotEmpty() }
107
+ if (expected != null &&
108
+ !info.serialNumber.equals(expected, ignoreCase = true)
109
+ ) {
110
+ throw WalletApduException(
111
+ WalletConstants.SW_SERIAL_MISMATCH,
112
+ "Wrong card: expected $expected, got ${info.serialNumber}",
113
+ )
114
+ }
115
+ // 0=NEW, 3=WALLET_NO_PIN (Tangem: seed before access code)
116
+ if (needsSetPin(info.cardStatus)) {
117
+ client.setPin(pin.toByteArray(Charsets.UTF_8))
118
+ } else {
119
+ // On-card serial check when expected is set (applet >= 1.0.17).
120
+ client.verifyPin(pin.toByteArray(Charsets.UTF_8), expected)
121
+ }
122
+ if (!info.hasKey) {
123
+ if (seedHex.isNullOrBlank()) {
124
+ // On-card serial check when expected is set (applet >= 1.0.18).
125
+ client.createWallet(expected)
126
+ } else {
127
+ val seed = HexUtils.decode(seedHex)
128
+ require(seed.size == WalletConstants.MASTER_SEED_LEN) {
129
+ "seed must be ${WalletConstants.MASTER_SEED_LEN} bytes"
130
+ }
131
+ client.createWalletWithSeed(seed, expected)
132
+ }
133
+ }
134
+ val paths = org.json.JSONArray(pathsJson)
135
+ val result = org.json.JSONObject()
136
+ for (i in 0 until paths.length()) {
137
+ val item = paths.getJSONObject(i)
138
+ val path = item.getString("path")
139
+ val curve = item.optString("curve", "secp256k1")
140
+ val keyType = item.optString("keyType", WalletConstants.KEY_TYPE_PUBKEY)
141
+ val curveP1 =
142
+ if (curve == "ed25519") {
143
+ WalletConstants.P1_PUBKEY_ED25519
144
+ } else {
145
+ WalletConstants.P1_PUBKEY_SECP256K1
146
+ }
147
+ try {
148
+ val payloadHex =
149
+ if (keyType == WalletConstants.KEY_TYPE_XPUB) {
150
+ HexUtils.encode(client.getXpubMaterial(path))
151
+ } else {
152
+ HexUtils.encode(client.getPublicKey(path, curveP1))
153
+ }
154
+ if (payloadHex.isEmpty()) {
155
+ throw WalletApduException(
156
+ -1,
157
+ "$keyType returned empty data for path $path",
158
+ )
159
+ }
160
+ result.put(path, payloadHex)
161
+ } catch (e: WalletApduException) {
162
+ throw WalletApduException(
163
+ e.statusWord,
164
+ "$keyType failed for path $path (SW=${String.format("%04X", e.statusWord)})",
165
+ )
166
+ }
167
+ }
168
+ InitializeWalletWithPubkeysResult(
169
+ pubkeysJson = result.toString(),
170
+ walletInfo = client.readWalletInfo(),
171
+ )
172
+ }
173
+ }
174
+
175
+ fun signHashHex(hashHex: String, path: String? = null): String =
176
+ controller.withWalletSession {
177
+ HexUtils.encode(it.signHash(HexUtils.decode(hashHex), path))
178
+ }
179
+
180
+ fun wipeWallet() {
181
+ controller.withWalletSession { it.wipe() }
182
+ }
183
+
184
+ /**
185
+ * Single session: bind expectedSerial → VERIFY_PIN → WIPE.
186
+ * Caller must ensure the card still has a wallet (probe first).
187
+ */
188
+ fun wipeWalletWithPin(pin: String, expectedSerial: String): WalletInfoData {
189
+ return controller.withWalletSession { client ->
190
+ val expected =
191
+ expectedSerial.takeIf { it.isNotEmpty() }
192
+ ?: throw IllegalArgumentException("expectedSerial is required for wipe")
193
+ val info = client.readWalletInfo()
194
+ if (!info.serialNumber.equals(expected, ignoreCase = true)) {
195
+ throw WalletApduException(
196
+ WalletConstants.SW_SERIAL_MISMATCH,
197
+ "Wrong card: expected $expected, got ${info.serialNumber}",
198
+ )
199
+ }
200
+ if (!info.hasKey) {
201
+ return@withWalletSession info
202
+ }
203
+ client.verifyPin(pin.toByteArray(Charsets.UTF_8), expected)
204
+ client.wipe()
205
+ client.readWalletInfo()
206
+ }
207
+ }
208
+
209
+ fun initializeWallet(pin: String, seedHex: String? = null): String {
210
+ return controller.withWalletSession { client ->
211
+ val info = client.readWalletInfo()
212
+ if (needsSetPin(info.cardStatus)) {
213
+ client.setPin(pin.toByteArray(Charsets.UTF_8))
214
+ } else {
215
+ client.verifyPin(pin.toByteArray(Charsets.UTF_8))
216
+ }
217
+ if (!info.hasKey) {
218
+ if (seedHex.isNullOrBlank()) {
219
+ client.createWallet()
220
+ } else {
221
+ val seed = HexUtils.decode(seedHex)
222
+ require(seed.size == WalletConstants.MASTER_SEED_LEN) {
223
+ "seed must be ${WalletConstants.MASTER_SEED_LEN} bytes"
224
+ }
225
+ client.createWalletWithSeed(seed)
226
+ }
227
+ }
228
+ HexUtils.encode(client.getPublicKey(WalletConstants.DEFAULT_EVM_PATH))
229
+ }
230
+ }
231
+
232
+ fun unlockAndSign(pin: String, hashHex: String, path: String? = null): String {
233
+ return controller.withWalletSession { client ->
234
+ client.verifyPin(pin.toByteArray(Charsets.UTF_8))
235
+ HexUtils.encode(client.signHash(HexUtils.decode(hashHex), path))
236
+ }
237
+ }
238
+
239
+ data class AttestCardResult(
240
+ val json: String,
241
+ val walletInfo: WalletInfoData,
242
+ )
243
+
244
+ /**
245
+ * One NFC session: GET_INFO serial + GET_CERT + ATTEST_SIGN(challenge).
246
+ * Returns JSON: { serialNumber, certHex, signatureHex }.
247
+ */
248
+ fun attestCard(challengeHex: String): AttestCardResult {
249
+ val challenge = HexUtils.decode(challengeHex)
250
+ require(challenge.size in WalletConstants.ATTEST_CHALLENGE_MIN..WalletConstants.ATTEST_CHALLENGE_MAX) {
251
+ "challenge must be ${WalletConstants.ATTEST_CHALLENGE_MIN}..${WalletConstants.ATTEST_CHALLENGE_MAX} bytes"
252
+ }
253
+ return controller.withWalletSession { client ->
254
+ val info = client.readWalletInfo()
255
+ val cert = client.getAttestCert()
256
+ val signature = client.attestSign(challenge)
257
+ val json =
258
+ org.json.JSONObject()
259
+ .put("serialNumber", info.serialNumber)
260
+ .put("certHex", HexUtils.encode(cert))
261
+ .put("signatureHex", HexUtils.encode(signature))
262
+ .toString()
263
+ AttestCardResult(json, info)
264
+ }
265
+ }
266
+
267
+ /**
268
+ * One NFC tap for Tangem-style backup shuttle.
269
+ * step: begin | accept | export | import | confirm
270
+ * Returns response payload hex (handshake / enc blob / status).
271
+ */
272
+ fun runBackupStep(
273
+ step: String,
274
+ pin: String?,
275
+ payloadHex: String?,
276
+ backupCount: Int = 2,
277
+ ): String {
278
+ val pinBytes = pin?.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
279
+ val payload = payloadHex?.takeIf { it.isNotEmpty() }?.let { HexUtils.decode(it) }
280
+ return controller.withWalletSession { client ->
281
+ when (step.lowercase()) {
282
+ "begin" -> {
283
+ require(pinBytes != null) { "PIN required for backup begin" }
284
+ HexUtils.encode(client.backupBegin(pinBytes, backupCount))
285
+ }
286
+ "accept" -> {
287
+ require(payload != null) { "handshakeA required for backup accept" }
288
+ HexUtils.encode(client.backupAccept(payload, pinBytes))
289
+ }
290
+ "export" -> {
291
+ require(pinBytes != null) { "PIN required for backup export" }
292
+ require(payload != null) { "handshakeB required for backup export" }
293
+ HexUtils.encode(client.backupFinishExport(pinBytes, payload))
294
+ }
295
+ "import" -> {
296
+ // Empty backup: do not VERIFY_PIN before IMPORT (6A15).
297
+ require(payload != null) { "encBlob required for backup import" }
298
+ HexUtils.encode(client.backupImport(payload, null))
299
+ }
300
+ "importwithcardset" -> {
301
+ // UTF-8 JSON hex: {"peerBlob":"...","memberSerials":["S1","S2"]}
302
+ // One APDU: IMPORT blob||cardSet (applet >= 1.0.23). No pre-VERIFY.
303
+ require(payload != null) { "importWithCardSet JSON required" }
304
+ val asText = String(payload, Charsets.UTF_8).trim()
305
+ require(asText.startsWith("{")) {
306
+ "importWithCardSet requires JSON payload"
307
+ }
308
+ val root = org.json.JSONObject(asText)
309
+ val encBlob = HexUtils.decode(root.getString("peerBlob"))
310
+ val memberSerials =
311
+ root.getJSONArray("memberSerials").let { arr ->
312
+ (0 until arr.length()).map { arr.getString(it) }
313
+ }
314
+ require(memberSerials.isNotEmpty()) { "memberSerials required" }
315
+ val cardSet = client.encodeCardSet(memberSerials)
316
+ HexUtils.encode(client.backupImport(encBlob, null, cardSet))
317
+ }
318
+ "enroll" -> {
319
+ HexUtils.encode(client.backupEnroll())
320
+ }
321
+ "exportpeer" -> {
322
+ require(pinBytes != null) { "PIN required for backup exportPeer" }
323
+ require(payload != null) { "linkPubB required for backup exportPeer" }
324
+ HexUtils.encode(client.backupExportToPeer(pinBytes, payload, backupCount))
325
+ }
326
+ "completeprimary" -> {
327
+ // Tangem Complete Backup — primary export hold (NO confirm):
328
+ // SET/VERIFY PIN + exportPeer×N. App must persist peerBlobs, then call confirm.
329
+ // (Confirm used to run here; early card removal after latch lost blobs forever.)
330
+ // payloadHex = UTF-8 JSON hex:
331
+ // {"primarySerial":"...","memberSerials":["S1","S2"],"peers":[{"serialNumber":"...","linkPubB":"..."}]}
332
+ require(pinBytes != null) { "PIN required for completePrimary" }
333
+ require(payload != null) { "peersJson hex required for completePrimary" }
334
+ val peersJson = String(payload, Charsets.UTF_8)
335
+ val trimmed = peersJson.trim()
336
+ require(trimmed.startsWith("{")) {
337
+ "completePrimary requires {primarySerial,peers} JSON"
338
+ }
339
+ val root = org.json.JSONObject(trimmed)
340
+ val expectedPrimary = root.getString("primarySerial")
341
+ require(expectedPrimary.isNotEmpty()) { "primarySerial required" }
342
+ val peers = root.getJSONArray("peers")
343
+ require(peers.length() in 1..2) { "completePrimary requires 1 or 2 peers" }
344
+ try {
345
+ client.verifyPin(pinBytes, expectedPrimary)
346
+ } catch (e: WalletApduException) {
347
+ when (e.statusWord) {
348
+ WalletConstants.SW_PIN_NOT_SET -> {
349
+ try {
350
+ client.setPin(pinBytes, expectedPrimary)
351
+ } catch (e2: WalletApduException) {
352
+ throw remapCompletePrimaryCardError(e2)
353
+ }
354
+ }
355
+ else -> throw remapCompletePrimaryCardError(e)
356
+ }
357
+ }
358
+ val out = org.json.JSONArray()
359
+ for (i in 0 until peers.length()) {
360
+ val peer = peers.getJSONObject(i)
361
+ val serial = peer.getString("serialNumber")
362
+ val linkPubB = HexUtils.decode(peer.getString("linkPubB"))
363
+ val blob = client.backupExportToPeer(pinBytes, linkPubB, backupCount)
364
+ out.put(
365
+ org.json.JSONObject()
366
+ .put("serialNumber", serial)
367
+ .put("peerBlob", HexUtils.encode(blob)),
368
+ )
369
+ }
370
+ out.toString()
371
+ }
372
+ "confirm" -> {
373
+ require(pinBytes != null) { "PIN required for backup confirm" }
374
+ // Optional payload: UTF-8 JSON {"memberSerials":["..."]} for atomic card-set.
375
+ val cardSet =
376
+ payload?.let { raw ->
377
+ val text = String(raw, Charsets.UTF_8).trim()
378
+ if (text.startsWith("{")) {
379
+ val root = org.json.JSONObject(text)
380
+ val arr = root.getJSONArray("memberSerials")
381
+ val members =
382
+ (0 until arr.length()).map { arr.getString(it) }
383
+ require(members.isNotEmpty()) { "memberSerials required" }
384
+ client.encodeCardSet(members)
385
+ } else {
386
+ raw
387
+ }
388
+ }
389
+ HexUtils.encode(client.backupConfirmDone(pinBytes, cardSet))
390
+ }
391
+ else -> throw IllegalArgumentException("Unknown backup step: $step")
392
+ }
393
+ }
394
+ }
395
+
396
+ companion object {
397
+ /** Applet cardStatus: NEW(0) or WALLET_NO_PIN(3) → SET_PIN; else VERIFY_PIN. */
398
+ fun needsSetPin(cardStatus: Int): Boolean = cardStatus == 0 || cardStatus == 3
399
+
400
+ /** App WalletErrors.WrongCard — Complete Backup step card mismatch. */
401
+ const val APP_WRONG_CARD = 2015
402
+
403
+ /**
404
+ * Map serial/seed mismatch during completePrimary to WrongCard (2015),
405
+ * not NotSameNFCLite (2002) — different user-facing copy.
406
+ */
407
+ fun remapCompletePrimaryCardError(e: WalletApduException): Throwable =
408
+ when (e.statusWord) {
409
+ WalletConstants.SW_SERIAL_MISMATCH,
410
+ WalletConstants.SW_NO_KEY,
411
+ ->
412
+ WalletAppException(
413
+ APP_WRONG_CARD,
414
+ "Wrong card. Scan the card shown for this backup step.",
415
+ e,
416
+ )
417
+ else -> e
418
+ }
419
+
420
+ fun mapErrorCode(t: Throwable): Int {
421
+ if (t is WalletAppException) {
422
+ return t.appCode
423
+ }
424
+ if (t is WalletApduException) {
425
+ return when (t.statusWord) {
426
+ WalletConstants.SW_SECURITY -> 2005
427
+ WalletConstants.SW_NO_KEY -> 2010
428
+ WalletConstants.SW_KEY_EXISTS -> 2011
429
+ WalletConstants.SW_PIN_NOT_SET -> 2006
430
+ WalletConstants.SW_BACKUP_DONE -> 2012
431
+ WalletConstants.SW_BACKUP_STATE -> 2013
432
+ WalletConstants.SW_BACKUP_CRYPTO -> 2014
433
+ WalletConstants.SW_SERIAL_MISMATCH -> 2002 // NotSameNFCLite (create/onboarding)
434
+ WalletConstants.SW_ATTEST_NOT_READY -> 2016
435
+ WalletConstants.SW_ATTEST_LOCKED -> 2017
436
+ WalletConstants.SW_ATTEST_INVALID -> 2018
437
+ else -> t.statusWord
438
+ }
439
+ }
440
+ if (t is java.util.concurrent.CancellationException) {
441
+ return 2008 // UserCancel
442
+ }
443
+ return 2001
444
+ }
445
+ }
446
+ }
447
+
448
+ /** App-level error code (not raw applet SW), e.g. WrongCard for backup UX. */
449
+ class WalletAppException(
450
+ val appCode: Int,
451
+ message: String,
452
+ cause: Throwable? = null,
453
+ ) : Exception(message, cause)
454
+
455
+ object ActivityHolder {
456
+ private var app: Application? = null
457
+ @Volatile private var topActivity: Activity? = null
458
+
459
+ fun init(application: Application) {
460
+ app = application
461
+ application.registerActivityLifecycleCallbacks(
462
+ object : Application.ActivityLifecycleCallbacks {
463
+ override fun onActivityResumed(activity: Activity) {
464
+ topActivity = activity
465
+ }
466
+
467
+ override fun onActivityPaused(activity: Activity) {
468
+ // Keep last activity — clearing here broke NFC engine reuse
469
+ // when a dialog / brief pause happened between APDU calls.
470
+ }
471
+
472
+ override fun onActivityCreated(activity: Activity, savedInstanceState: android.os.Bundle?) {}
473
+ override fun onActivityStarted(activity: Activity) {}
474
+ override fun onActivityStopped(activity: Activity) {}
475
+ override fun onActivitySaveInstanceState(activity: Activity, outState: android.os.Bundle) {}
476
+ override fun onActivityDestroyed(activity: Activity) {
477
+ if (topActivity === activity) {
478
+ topActivity = null
479
+ }
480
+ }
481
+ },
482
+ )
483
+ }
484
+
485
+ fun getTopActivity(): Activity? = topActivity
486
+ }