@onekeyfe/react-native-lite-card 6.7.0-24 → 6.7.0-26

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.
package/README.md CHANGED
@@ -41,7 +41,9 @@ if (result.error) {
41
41
  state, new-card status and remaining PIN retries.
42
42
  - `setMnemonic(mnemonic, pwd, overwrite)` and `getMnemonicWithPin(pwd)` manage
43
43
  the backup; `overwrite` defaults to `false`.
44
- - `changePin(oldPin, newPin)` and `reset()` alter the card's state.
44
+ - `changePin(oldPin, newPin, expectedSerial?)` checks a supplied card serial before
45
+ changing the PIN; `reset()` resets the card's state. The identity guard requires
46
+ a native rebuild on iOS and Android.
45
47
  - `addConnectListener(listener)` subscribes to NFC UI events and returns the
46
48
  native subscription. Keep it and call `remove()` when the owner finishes.
47
49
  - `cancel()` invokes native cancellation on Android; `intoSetting()` opens
@@ -36,8 +36,14 @@ Pod::Spec.new do |s|
36
36
  s.private_header_files = "ios/**/*.h"
37
37
  s.preserve_paths = "sdk/**/*"
38
38
  s.libraries = "c++"
39
+ s.script_phase = {
40
+ :name => 'Generate Lite native source identity',
41
+ :execution_position => :before_compile,
42
+ :show_env_vars_in_log => '0',
43
+ :script => 'set -e; ruby "${PODS_TARGET_SRCROOT}/sdk/scripts/generate-source-id.rb" "${DERIVED_FILE_DIR}/GPChannelSourceId.h"'
44
+ }
39
45
  s.pod_target_xcconfig = {
40
- "HEADER_SEARCH_PATHS" => '$(inherited) "$(PODS_TARGET_SRCROOT)/sdk/include" "$(PODS_TARGET_SRCROOT)/sdk/gpc/include" "$(PODS_TARGET_SRCROOT)/sdk/deps/trezor-crypto/include" "$(PODS_TARGET_SRCROOT)/sdk/deps/trezor-crypto/src"'
46
+ "HEADER_SEARCH_PATHS" => '$(inherited) "$(DERIVED_FILE_DIR)" "$(PODS_TARGET_SRCROOT)/sdk/include" "$(PODS_TARGET_SRCROOT)/sdk/gpc/include" "$(PODS_TARGET_SRCROOT)/sdk/deps/trezor-crypto/include" "$(PODS_TARGET_SRCROOT)/sdk/deps/trezor-crypto/src"'
41
47
  }
42
48
 
43
49
 
@@ -37,6 +37,7 @@ android {
37
37
  compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
38
38
 
39
39
  defaultConfig {
40
+ consumerProguardFiles "consumer-rules.pro"
40
41
  minSdkVersion getExtOrIntegerDefault("minSdkVersion")
41
42
  targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
42
43
 
@@ -0,0 +1,4 @@
1
+ # The native diagnostics call this existing logger entry point through JNI.
2
+ -keep class com.margelo.nitro.nativelogger.OneKeyLog {
3
+ public static void info(java.lang.String, java.lang.String);
4
+ }
@@ -347,13 +347,14 @@ class ReactNativeLiteCardModule(val reactContext: ReactApplicationContext) :
347
347
  override fun changePin(
348
348
  oldPin: String,
349
349
  newPin: String,
350
+ expectedSerial: String?,
350
351
  callback: Callback?
351
352
  ) {
352
353
  launch {
353
354
  OneKeyLog.debug("LiteCard","changePin")
354
355
  handleOperation(callback, "changePin") { session ->
355
356
  OneKeyLog.debug("LiteCard","changePin Obtain the device")
356
- OneKeyLiteCard.changPin(session, oldPin, newPin)
357
+ OneKeyLiteCard.changPin(session, oldPin, newPin, expectedSerial)
357
358
  }
358
359
  }
359
360
  }
@@ -147,6 +147,25 @@ object OneKeyLiteCard {
147
147
  overwrite: Boolean = false,
148
148
  expectedSerial: String? = null
149
149
  ): Boolean {
150
+ val version = if (session.connection.getCardType() == AppleCardType.V2) 2 else 1
151
+ val maxBytes = if (version == 2) 65511 else 65535
152
+ val reason = when {
153
+ mnemonic == null -> "missing"
154
+ mnemonic.isEmpty() -> "empty"
155
+ mnemonic.length > maxBytes * 2 -> "too_large"
156
+ mnemonic.any { it !in '0'..'9' && it !in 'a'..'f' && it !in 'A'..'F' } -> "non_hex"
157
+ else -> "accepted"
158
+ }
159
+ val accepted = reason == "accepted"
160
+ val inputChars = mnemonic?.length ?: 0
161
+ try {
162
+ OneKeyLog.info("LiteCard", "operation=setMnemonic stage=input_preflight inputPresent=${mnemonic != null} inputChars=$inputChars odd=${inputChars % 2 != 0} versionKnown=true cardVersion=$version overwrite=$overwrite reason=$reason accepted=$accepted")
163
+ } catch (_: Exception) {
164
+ // Diagnostics must not alter the input decision.
165
+ }
166
+ if (mnemonic == null || !accepted) {
167
+ throw NFCExceptions.ExecFailureException()
168
+ }
150
169
  val cardState = session.cardState
151
170
  val serial = cardState.serialNum
152
171
  if (expectedSerial != null && (serial.isEmpty() ||
@@ -199,7 +218,6 @@ object OneKeyLiteCard {
199
218
  }
200
219
  }
201
220
 
202
- if (mnemonic.isNullOrEmpty()) throw NFCExceptions.ExecFailureException()
203
221
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=backup_begin")
204
222
  val backupSuccess = session.connection.backupData(mnemonic)
205
223
  OneKeyLog.info("LiteCard", "operation=setMnemonic stage=backup_result success=$backupSuccess")
@@ -228,8 +246,13 @@ object OneKeyLiteCard {
228
246
  }
229
247
 
230
248
  @Throws(NFCExceptions::class)
231
- internal fun changPin(session: CardSession, oldPwd: String, newPwd: String): Boolean {
249
+ internal fun changPin(session: CardSession, oldPwd: String, newPwd: String, expectedSerial: String? = null): Boolean {
232
250
  val cardState = session.cardState
251
+ val serial = cardState.serialNum
252
+ if (expectedSerial != null && (serial.isEmpty() ||
253
+ serial == NfcConstant.NOT_MATCH_DEVICE || expectedSerial != serial)) {
254
+ throw NFCExceptions.DeviceMismatchException()
255
+ }
233
256
 
234
257
  if (cardState.isNewCard || !cardState.hasBackup) {
235
258
  throw NFCExceptions.NotInitializedException()
@@ -9,6 +9,7 @@
9
9
  #if !TARGET_OS_SIMULATOR
10
10
 
11
11
  #import "GPChannelSDK.h"
12
+ #import "GPChannelSDKCore.h"
12
13
  #import "OKNFCLiteDefine.h"
13
14
  #import "NFCConfig.h"
14
15
 
@@ -19,6 +20,22 @@
19
20
  #import "OKNFCBridge.h"
20
21
  #import "LCLogger.h"
21
22
 
23
+ #if !TARGET_OS_SIMULATOR
24
+ static NSString *sourceIdForLog() {
25
+ NSString *source = [NSString stringWithUTF8String:(const char *)GPChannelSDKCoreVersionString];
26
+ if (source.length != 74 || ![source hasPrefix:@"source-v1:"]) return @"unavailable";
27
+ for (NSUInteger index = 10; index < source.length; ++index) {
28
+ unichar digit = [source characterAtIndex:index];
29
+ if (!((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f'))) return @"unavailable";
30
+ }
31
+ NSMutableArray<NSString *> *groups = [NSMutableArray array];
32
+ for (NSUInteger offset = 10; offset < source.length; offset += 8) {
33
+ [groups addObject:[source substringWithRange:NSMakeRange(offset, 8)]];
34
+ }
35
+ return [@"source-v1:" stringByAppendingString:[groups componentsJoinedByString:@"-"]];
36
+ }
37
+ #endif
38
+
22
39
  @implementation OKNFCBridge
23
40
 
24
41
  #if !TARGET_OS_SIMULATOR
@@ -39,6 +56,11 @@
39
56
  } else {
40
57
  rv = JUB_GPC_BuildAPDU(cla, ins, p1, p2, c_data, &c_apdu);
41
58
  }
59
+ @try {
60
+ [LCLogger info:[NSString stringWithFormat:@"stage=command_build nativeSourceId=%@ safe=%d sdkReturnCode=%lu outputPresent=%d", sourceIdForLog(), encrypt, (unsigned long)rv, c_apdu != nullptr]];
61
+ } @catch (NSException *exception) {
62
+ // Diagnostics must not replace the SDK result.
63
+ }
42
64
 
43
65
  if (JUBR_OK != rv) {
44
66
  return nil;
@@ -34,7 +34,7 @@
34
34
 
35
35
  - (void)getMnemonicWithPin:(NSString *)pin complete:(GetMnemonicCallback)complete;
36
36
 
37
- - (void)changePin:(NSString *)oldPin to:(NSString *)newPin complete:(ChangePinCallback)complete;
37
+ - (void)changePin:(NSString *)oldPin to:(NSString *)newPin expectedSerial:(NSString * _Nullable)expectedSerial complete:(ChangePinCallback)complete;
38
38
 
39
39
 
40
40
  @end
@@ -27,6 +27,25 @@
27
27
  #define kChangePinBlock @"kChangePinBlock"
28
28
  #define kResetBlock @"kResetBlock"
29
29
 
30
+ static NSString *backupInputReason(NSString *input, NSUInteger maxBytes) {
31
+ if (!input) return @"missing";
32
+ if (!input.length) return @"empty";
33
+ if (input.length > maxBytes * 2) return @"too_large";
34
+ for (NSUInteger index = 0; index < input.length; ++index) {
35
+ const unichar digit = [input characterAtIndex:index];
36
+ if (!((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f') ||
37
+ (digit >= 'A' && digit <= 'F'))) return @"non_hex";
38
+ }
39
+ return @"accepted";
40
+ }
41
+
42
+ static void logBackupPreflight(NSString *input, BOOL overwrite, NSString *reason, NSInteger version) {
43
+ @try {
44
+ [LCLogger info:[NSString stringWithFormat:@"operation=setMnemonic stage=input_preflight_%@ inputPresent=%d inputChars=%lu odd=%d versionKnown=%d cardVersion=%ld overwrite=%d reason=%@ accepted=%d", version ? @"detected" : @"entry", input != nil, (unsigned long)input.length, input.length % 2 != 0, version != 0, (long)version, overwrite, reason, [reason isEqualToString:@"accepted"]]];
45
+ } @catch (NSException *exception) {
46
+ // Diagnostics must not alter the input decision or callback.
47
+ }
48
+ }
30
49
 
31
50
 
32
51
 
@@ -146,7 +165,11 @@
146
165
  }
147
166
  } break;
148
167
  case OKNFCLiteSessionTypeChangePin: {
149
- ChangePinCallback callback = [self takeCompletionForKey:kChangePinBlock];
168
+ ChangePinCallback callback;
169
+ @synchronized (self) {
170
+ self.expectedSerial = nil;
171
+ callback = [self takeCompletionForKey:kChangePinBlock];
172
+ }
150
173
  if (callback) {
151
174
  callback(self.lite, asCancel ? OKNFCLiteChangePinStatusCancel : OKNFCLiteChangePinStatusError);
152
175
  }
@@ -279,6 +302,13 @@
279
302
  expectedSerial:(NSString * _Nullable)expectedSerial
280
303
  complete:(SetMnemonicCallback)complete {
281
304
 
305
+ NSString *reason = backupInputReason(mnemonic, 65535);
306
+ BOOL accepted = [reason isEqualToString:@"accepted"];
307
+ logBackupPreflight(mnemonic, overwrite, reason, 0);
308
+ if (!accepted) {
309
+ complete(nil, OKNFCLiteSetMncStatusError);
310
+ return;
311
+ }
282
312
  if (pin.length != OKNFC_PIN_LENGTH) {
283
313
  [self logSessionStage:@"input_rejected" details:@"operation=setMnemonic"];
284
314
  return;
@@ -305,6 +335,16 @@
305
335
  // Clear sensitive data from properties immediately
306
336
  self.exportMnemonic = nil;
307
337
  self.pin = nil;
338
+ const NSUInteger maxBytes = self.lite.version == OKNFCLiteVersionV2 ? 65511 : 65535;
339
+ NSString *reason = backupInputReason(mnemonic, maxBytes);
340
+ BOOL accepted = [reason isEqualToString:@"accepted"];
341
+ logBackupPreflight(mnemonic, force, reason, self.lite.version + 1);
342
+ if (!accepted) {
343
+ SetMnemonicCallback callback = [self takeCompletionForKey:kSetMnemonicBlock];
344
+ [self endNFCSessionWithError:YES];
345
+ if (callback) callback(nil, OKNFCLiteSetMncStatusError);
346
+ return;
347
+ }
308
348
  if (expectedSerial != nil) {
309
349
  BOOL infoValid = [self.lite syncLiteInfo];
310
350
  if (!infoValid || ![expectedSerial isEqualToString:self.lite.SN]) {
@@ -352,26 +392,42 @@
352
392
 
353
393
  #pragma mark - changePin
354
394
 
355
- - (void)changePin:(NSString *)oldPin to:(NSString *)newPin complete:(ChangePinCallback)complete {
395
+ - (void)changePin:(NSString *)oldPin to:(NSString *)newPin expectedSerial:(NSString *)expectedSerial complete:(ChangePinCallback)complete {
356
396
  self.pin = oldPin;
357
397
  self.neoPin = newPin;
398
+ self.expectedSerial = expectedSerial;
358
399
  self.sessionType = OKNFCLiteSessionTypeChangePin;
359
400
  [self.completionBlocks setObject:complete forKey:kChangePinBlock];
360
401
  [self beginNewNFCSession];
361
402
  }
362
403
 
363
404
  - (void)_changePin {
364
- NSString *oldPin = self.pin;
365
- NSString *newPin = self.neoPin;
366
- // Clear sensitive data from properties immediately
367
- self.pin = nil;
368
- self.neoPin = nil;
369
- __weak typeof(self) weakSelf = self;
370
- [self.lite changePin:oldPin to:newPin complete:^(OKLiteV1 *lite, OKNFCLiteChangePinStatus status) {
371
- ChangePinCallback callback = [weakSelf takeCompletionForKey:kChangePinBlock];
372
- if (callback) {
373
- callback(lite, status);
405
+ NSString *oldPin;
406
+ NSString *newPin;
407
+ NSString *expectedSerial;
408
+ ChangePinCallback callback;
409
+ @synchronized (self) {
410
+ // Claim the request and its guard together so cancellation cannot
411
+ // turn a late connection into an unguarded PIN change.
412
+ callback = [self takeCompletionForKey:kChangePinBlock];
413
+ if (!callback) return;
414
+ oldPin = self.pin;
415
+ newPin = self.neoPin;
416
+ expectedSerial = self.expectedSerial;
417
+ self.pin = nil;
418
+ self.neoPin = nil;
419
+ self.expectedSerial = nil;
420
+ }
421
+ if (expectedSerial != nil) {
422
+ BOOL infoValid = [self.lite syncLiteInfo];
423
+ if (!infoValid || !self.lite.SN.length || ![expectedSerial isEqualToString:self.lite.SN]) {
424
+ [self endNFCSessionWithError:YES];
425
+ callback(self.lite, infoValid ? OKNFCLiteChangePinStatusSNNotMatch : OKNFCLiteChangePinStatusError);
426
+ return;
374
427
  }
428
+ }
429
+ [self.lite changePin:oldPin to:newPin complete:^(OKLiteV1 *lite, OKNFCLiteChangePinStatus status) {
430
+ callback(lite, status);
375
431
  }];
376
432
  }
377
433
 
@@ -175,17 +175,20 @@ static RCTResponseSenderBlock OKLiteCallbackOnce(NSString *operation, RCTRespons
175
175
  }
176
176
  }
177
177
 
178
- - (void)changePin:(NSString *)oldPin newPin:(NSString *)newPin callback:(RCTResponseSenderBlock)callBack
178
+ - (void)changePin:(NSString *)oldPin newPin:(NSString *)newPin expectedSerial:(NSString * _Nullable)expectedSerial callback:(RCTResponseSenderBlock)callBack
179
179
  {
180
180
  callBack = OKLiteCallbackOnce(@"changePin", callBack);
181
181
  if ([ReactNativeLiteCard checkSDKVaild:callBack]) {
182
182
  __block OKNFCManager *liteManager = [[OKNFCManager alloc] init];
183
- [liteManager changePin:oldPin to:newPin complete:^(OKLiteV1 *lite, OKNFCLiteChangePinStatus status) {
183
+ [liteManager changePin:oldPin to:newPin expectedSerial:expectedSerial complete:^(OKLiteV1 *lite, OKNFCLiteChangePinStatus status) {
184
184
  NSDictionary *cardInfo = [lite cardInfo];
185
185
  switch (status) {
186
186
  case OKNFCLiteChangePinStatusSuccess: {
187
187
  callBack(@[[NSNull null],@(true),cardInfo]);
188
188
  } break;
189
+ case OKNFCLiteChangePinStatusSNNotMatch: {
190
+ callBack(@[@{@"code":@(NFCLiteExceptionsDeviceMismatch),@"message":@""},[NSNull null],[NSNull null]]);
191
+ } break;
189
192
  case OKNFCLiteChangePinStatusWiped: {
190
193
  callBack(@[@{@"code":@(NFCLiteExceptionsAutoReset),@"message":@""},[NSNull null],[NSNull null]]);
191
194
  } break;
@@ -36,9 +36,9 @@ class OnekeyLite {
36
36
  OKLiteManager.getMnemonicWithPin(pwd, this.convertToPromise(resolve));
37
37
  });
38
38
  }
39
- changePin(oldPin, newPin) {
39
+ changePin(oldPin, newPin, expectedSerial) {
40
40
  return new Promise(resolve => {
41
- OKLiteManager.changePin(oldPin, newPin, this.convertToPromise(resolve));
41
+ OKLiteManager.changePin(oldPin, newPin, expectedSerial ?? null, this.convertToPromise(resolve));
42
42
  });
43
43
  }
44
44
  reset() {
@@ -47,7 +47,7 @@ export interface Spec extends TurboModule {
47
47
  checkNFCPermission(callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
48
48
  setMnemonic(mnemonic: string, pwd: string, overwrite: boolean, expectedSerial: string | null, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
49
49
  getMnemonicWithPin(pwd: string, callback: (error: CallbackError | null, data: string | null, cardInfo: CardInfo | null) => void): void;
50
- changePin(oldPin: string, newPin: string, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
50
+ changePin(oldPin: string, newPin: string, expectedSerial: string | null, callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
51
51
  reset(callback: (error: CallbackError | null, data: boolean | null, cardInfo: CardInfo | null) => void): void;
52
52
  cancel(): void;
53
53
  intoSetting(): void;
@@ -11,7 +11,7 @@ declare class OnekeyLite {
11
11
  checkNFCPermission(): Promise<PromiseResult<boolean>>;
12
12
  setMnemonic(mnemonic: string, pwd: string, overwrite?: boolean, expectedSerial?: string): Promise<PromiseResult<boolean>>;
13
13
  getMnemonicWithPin(pwd: string): Promise<PromiseResult<string>>;
14
- changePin(oldPin: string, newPin: string): Promise<PromiseResult<boolean>>;
14
+ changePin(oldPin: string, newPin: string, expectedSerial?: string): Promise<PromiseResult<boolean>>;
15
15
  reset(): Promise<PromiseResult<boolean>>;
16
16
  convertToPromise<T>(resolve: (value: PromiseResult<T> | PromiseLike<PromiseResult<T>>) => void): (...result: CallbackResult<T>) => void;
17
17
  cancel(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-lite-card",
3
- "version": "6.7.0-24",
3
+ "version": "6.7.0-26",
4
4
  "description": "OneKey Lite NFC card operations and connection events for React Native",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -4,6 +4,7 @@ set(CMAKE_C_STANDARD 99)
4
4
  set(CMAKE_CXX_STANDARD 11)
5
5
  set(CMAKE_CXX_STANDARD_REQUIRED ON)
6
6
  set(CMAKE_POSITION_INDEPENDENT_CODE ON)
7
+ include(source-id.cmake)
7
8
 
8
9
  # Restore the original source dependencies without linking a vendor binary.
9
10
  set(TREZOR_FILES
@@ -66,12 +67,12 @@ set(TREZOR_FILES
66
67
  deps/trezor-crypto/src/cmac.c
67
68
  )
68
69
  add_library(gpchannel_core STATIC
69
- src/GPChannelSDK.cpp src/ApduBuilder.cpp src/random.c
70
+ src/GPChannelSDK.cpp src/ApduBuilder.cpp src/random.c src/version.c
70
71
  gpc/src/scp03.cpp gpc/src/scp11.cpp gpc/src/scp11c.cpp gpc/src/tlv.cpp
71
72
  ${TREZOR_FILES})
72
73
  target_include_directories(gpchannel_core PUBLIC include
73
- PRIVATE gpc/include deps/trezor-crypto/include deps/trezor-crypto/src)
74
- add_library(GPChannelSDKCore SHARED src/version.c
74
+ PRIVATE gpc/include deps/trezor-crypto/include deps/trezor-crypto/src "${GPCHANNEL_GENERATED_INCLUDE}")
75
+ add_library(GPChannelSDKCore SHARED
75
76
  include/GPChannelSDK.h include/GPChannelSDKCore.h)
76
77
  target_include_directories(GPChannelSDKCore PUBLIC include)
77
78
  set_target_properties(GPChannelSDKCore PROPERTIES LINKER_LANGUAGE CXX)
package/sdk/README.md CHANGED
@@ -105,6 +105,15 @@ The API has per-call locking; it does not support concurrent independent session
105
105
  There is no persistent cache. Returned allocations remain caller-owned across
106
106
  finalization and must be freed separately.
107
107
 
108
+ The existing native `GPChannelSDKCoreVersionString` reports
109
+ `source-v1:<SHA256>` for the package source/configuration manifest in
110
+ `source-id-manifest.txt`. CMake regenerates its private header when those inputs
111
+ change; CocoaPods runs the equivalent Ruby generator before compilation. The
112
+ identity is independent of checkout location, keys, user data and build
113
+ environment. It identifies the selected source snapshot, not the binary hash or
114
+ external toolchains. Command-build diagnostics read that compiled native symbol
115
+ and the actual call's return code without logging command data.
116
+
108
117
  ## Preserved platform differences
109
118
 
110
119
  These were observed against the installed binaries and retained explicitly:
@@ -165,6 +174,12 @@ On Linux use the `.so` filename. Omit `--reference` for oracle-only verification
165
174
  The Python dependency is a test tool, not an application/SDK dependency.
166
175
  `tests/safety.cpp` exercises 5000 malformed inputs and allocation/lifecycle checks;
167
176
  run it with AddressSanitizer/UBSan compiler and linker flags when supported.
177
+ With host JNI enabled it also captures the actual JNI logger calls, checks the
178
+ metadata allowlist and synthetic sensitive-data absence, and verifies logger
179
+ failure does not change build results. From the package root,
180
+ `node tests/ios-input.cjs` covers the production manager/bridge/LCLogger path and
181
+ `node tests/source-id.cjs` checks source identity generation and incremental
182
+ native rebuilding. These checks do not prove physical NFC or minified app logs.
168
183
 
169
184
  `tests/android/GPChannelProxy.java` and `tests/android_verify.py` run the same oracle
170
185
  against real Android ART/JNI and a separately loaded original `.so` in an isolated
@@ -3,10 +3,48 @@
3
3
  #include <atomic>
4
4
  #include <string>
5
5
  #include "GPChannelSDK.h"
6
+ #include "GPChannelSDKCore.h"
6
7
  #include "json/json.h"
7
8
 
8
9
  namespace {
9
10
  std::atomic<int> errorCode{0};
11
+ std::string sourceIdForLog() {
12
+ const std::string source(reinterpret_cast<const char*>(GPChannelSDKCoreVersionString));
13
+ if (source.size() != 74 || source.compare(0, 10, "source-v1:") != 0 ||
14
+ source.find_first_not_of("0123456789abcdef", 10) != std::string::npos) return "unavailable";
15
+ std::string display = "source-v1:";
16
+ for (size_t offset = 10; offset < source.size(); offset += 8) {
17
+ if (offset != 10) display += '-';
18
+ display.append(source, offset, 8);
19
+ }
20
+ return display;
21
+ }
22
+ void logBuild(JNIEnv* env, bool safe, JUB_RV code, bool outputPresent) {
23
+ // Preserve caller exceptions; only diagnostics-owned lookup/call failures may be cleared.
24
+ if (env->ExceptionCheck()) return;
25
+ try {
26
+ jclass logger = env->FindClass("com/margelo/nitro/nativelogger/OneKeyLog");
27
+ if (logger) {
28
+ jmethodID info = env->GetStaticMethodID(logger, "info", "(Ljava/lang/String;Ljava/lang/String;)V");
29
+ if (info) {
30
+ const std::string message = std::string("stage=command_build nativeSourceId=") +
31
+ sourceIdForLog() +
32
+ " safe=" + (safe ? "true" : "false") +
33
+ " sdkReturnCode=" + std::to_string(code) +
34
+ " outputPresent=" + (outputPresent ? "true" : "false");
35
+ jstring tag = env->NewStringUTF("LiteCard");
36
+ jstring text = tag && !env->ExceptionCheck() ? env->NewStringUTF(message.c_str()) : nullptr;
37
+ if (tag && text && !env->ExceptionCheck()) env->CallStaticVoidMethod(logger, info, tag, text);
38
+ if (tag) env->DeleteLocalRef(tag);
39
+ if (text) env->DeleteLocalRef(text);
40
+ }
41
+ env->DeleteLocalRef(logger);
42
+ }
43
+ } catch (...) {
44
+ // Diagnostics must not replace the actual command result on allocation failure.
45
+ }
46
+ if (env->ExceptionCheck()) env->ExceptionClear();
47
+ }
10
48
  class UtfChars {
11
49
  public:
12
50
  UtfChars(JNIEnv* env, jstring value) : env(env), value(value),
@@ -87,6 +125,7 @@ jstring build(JNIEnv* env, bool safe, jlong cla, jlong ins, jlong p1, jlong p2,
87
125
  Output output;
88
126
  auto code = safe ? JUB_GPC_BuildSafeAPDU(cla, ins, p1, p2, text.get(), &output.value)
89
127
  : JUB_GPC_BuildAPDU(cla, ins, p1, p2, text.get(), &output.value);
128
+ logBuild(env, safe, code, output.value != nullptr);
90
129
  return result(env, code, output);
91
130
  } catch (...) {
92
131
  errorCode.store(static_cast<int>(JUBR_ERROR));
@@ -0,0 +1,22 @@
1
+ # Generate a content identity without incorporating build paths or environment data.
2
+ require 'digest'
3
+ require 'fileutils'
4
+
5
+ package_root = File.expand_path('../..', __dir__)
6
+ manifest = File.join(package_root, 'sdk/source-id-manifest.txt')
7
+ paths = File.readlines(manifest, chomp: true).flat_map do |entry|
8
+ if entry.end_with?('/')
9
+ Dir.glob(File.join(package_root, entry, '**', '*')).select { |path| File.file?(path) }
10
+ .map { |path| path.delete_prefix("#{package_root}/") }
11
+ .select { |path| path.match?(/\.(c|cpp|h|hpp|inc|table|m|mm|swift|kt|java)\z/) }
12
+ .reject { |path| path.split('/').any? { |part| part.start_with?('.') || %w[build generated CMakeFiles node_modules __pycache__].include?(part) } }
13
+ else
14
+ [entry]
15
+ end
16
+ end.uniq.sort
17
+ content = paths.map { |path| "#{path} #{Digest::SHA256.file(File.join(package_root, path)).hexdigest}\n" }.join
18
+ source_id = "source-v1:#{Digest::SHA256.hexdigest(content)}"
19
+ header = "#define GPCHANNEL_NATIVE_SOURCE_ID \"#{source_id}\"\n"
20
+ output = ARGV.fetch(0)
21
+ FileUtils.mkdir_p(File.dirname(output))
22
+ File.write(output, header) unless File.file?(output) && File.read(output) == header
@@ -0,0 +1,19 @@
1
+ sdk/src/
2
+ sdk/include/
3
+ sdk/gpc/
4
+ sdk/deps/trezor-crypto/include/
5
+ sdk/deps/trezor-crypto/src/
6
+ sdk/deps/jsoncpp/include/
7
+ sdk/deps/jsoncpp/src/lib_json/
8
+ sdk/android/
9
+ sdk/CMakeLists.txt
10
+ sdk/source-id.cmake
11
+ sdk/source-id-manifest.txt
12
+ sdk/scripts/generate-source-id.rb
13
+ ReactNativeLiteCard.podspec
14
+ android/src/main/cpp/CMakeLists.txt
15
+ android/build.gradle
16
+ android/consumer-rules.pro
17
+ android/src/main/java/
18
+ android/src/main/assets/config/command.json
19
+ ios/
@@ -0,0 +1,31 @@
1
+ # Match scripts/generate-source-id.rb using only fixed relative paths and file content.
2
+ get_filename_component(GPCHANNEL_PACKAGE_ROOT "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
3
+ set(GPCHANNEL_SOURCE_MANIFEST "${CMAKE_CURRENT_LIST_DIR}/source-id-manifest.txt")
4
+ file(STRINGS "${GPCHANNEL_SOURCE_MANIFEST}" GPCHANNEL_SOURCE_ENTRIES)
5
+ set(GPCHANNEL_SOURCE_PATHS)
6
+ foreach(entry IN LISTS GPCHANNEL_SOURCE_ENTRIES)
7
+ if(entry MATCHES "/$")
8
+ file(GLOB_RECURSE contents CONFIGURE_DEPENDS LIST_DIRECTORIES false
9
+ RELATIVE "${GPCHANNEL_PACKAGE_ROOT}" "${GPCHANNEL_PACKAGE_ROOT}/${entry}*")
10
+ list(FILTER contents INCLUDE REGEX "\\.(c|cpp|h|hpp|inc|table|m|mm|swift|kt|java)$")
11
+ list(FILTER contents EXCLUDE REGEX "(^|/)(\\.[^/]*|build|generated|CMakeFiles|node_modules|__pycache__)(/|$)")
12
+ list(APPEND GPCHANNEL_SOURCE_PATHS ${contents})
13
+ else()
14
+ list(APPEND GPCHANNEL_SOURCE_PATHS "${entry}")
15
+ endif()
16
+ endforeach()
17
+ list(REMOVE_DUPLICATES GPCHANNEL_SOURCE_PATHS)
18
+ list(SORT GPCHANNEL_SOURCE_PATHS)
19
+ set(GPCHANNEL_SOURCE_CONTENT "")
20
+ foreach(path IN LISTS GPCHANNEL_SOURCE_PATHS)
21
+ file(SHA256 "${GPCHANNEL_PACKAGE_ROOT}/${path}" digest)
22
+ string(APPEND GPCHANNEL_SOURCE_CONTENT "${path} ${digest}\n")
23
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${GPCHANNEL_PACKAGE_ROOT}/${path}")
24
+ endforeach()
25
+ string(SHA256 GPCHANNEL_SOURCE_DIGEST "${GPCHANNEL_SOURCE_CONTENT}")
26
+ set(GPCHANNEL_GENERATED_INCLUDE "${CMAKE_CURRENT_BINARY_DIR}/generated")
27
+ file(MAKE_DIRECTORY "${GPCHANNEL_GENERATED_INCLUDE}")
28
+ file(WRITE "${GPCHANNEL_GENERATED_INCLUDE}/GPChannelSourceId.h.in"
29
+ "#define GPCHANNEL_NATIVE_SOURCE_ID \"source-v1:${GPCHANNEL_SOURCE_DIGEST}\"\n")
30
+ configure_file("${GPCHANNEL_GENERATED_INCLUDE}/GPChannelSourceId.h.in"
31
+ "${GPCHANNEL_GENERATED_INCLUDE}/GPChannelSourceId.h" COPYONLY)
@@ -67,8 +67,14 @@ JUB_RV build(bool safe, JUB_ULONG cla, JUB_ULONG ins, JUB_ULONG p1,
67
67
  auto result = configure(builder);
68
68
  if (result != JUBR_OK) return result;
69
69
  }
70
+ if (!hex) return JUBR_ARGUMENTS_BAD;
71
+ const auto length = strnlen(hex, 65535 * 2 + 1);
72
+ if (length > 65535 * 2) return JUBR_ARGUMENTS_BAD;
73
+ // The vendor treats an odd command as a leading zero nibble, not a trailing one.
74
+ const std::string command = length % 2 ? "0" + std::string(hex, length)
75
+ : std::string(hex, length);
70
76
  uchar_vector data;
71
- if (!decodeHex(hex, data)) return JUBR_ARGUMENTS_BAD;
77
+ if (!decodeHex(command.c_str(), data)) return JUBR_ARGUMENTS_BAD;
72
78
  // Encryption adds up to one AES block and an eight-byte MAC to Lc.
73
79
  if (safe && data.size() > 65511) return JUBR_ARGUMENTS_BAD;
74
80
  jub::APDU apdu(cla, ins, p1, p2, data.size(), data.data());
package/sdk/src/version.c CHANGED
@@ -1,2 +1,3 @@
1
+ #include <GPChannelSourceId.h>
1
2
  double GPChannelSDKCoreVersionNumber = 0.0;
2
- const unsigned char GPChannelSDKCoreVersionString[] = "source-recovery-experimental";
3
+ const unsigned char GPChannelSDKCoreVersionString[] = GPCHANNEL_NATIVE_SOURCE_ID;
@@ -74,8 +74,11 @@ class AndroidSDK:
74
74
  return c.string_at(self.buffers.pop(pointer.value)) if pointer.value else None
75
75
 
76
76
  def build(self, name, data, header=(0x80, 0x20, 0, 0)):
77
+ return self.build_hex(name, data.hex(), header)
78
+
79
+ def build_hex(self, name, text, header=(0x80, 0x20, 0, 0)):
77
80
  result = self.request("safe" if name == "BuildSafeAPDU" else "build",
78
- data=data.hex(), **dict(zip(("cla", "ins", "p1", "p2"), header)))
81
+ data=text, **dict(zip(("cla", "ins", "p1", "p2"), header)))
79
82
  return result["code"], result["output"].encode() if result["output"] is not None else None
80
83
 
81
84
  def parse(self, name, data):
@@ -1,4 +1,5 @@
1
1
  #include "GPChannelSDK.h"
2
+ #include "GPChannelSDKCore.h"
2
3
  #include <TrezorCrypto/aes.h>
3
4
  #include <TrezorCrypto/cmac.h>
4
5
  #include <TrezorCrypto/ecdsa.h>
@@ -7,7 +8,9 @@
7
8
  #include <algorithm>
8
9
  #include <cstdlib>
9
10
  #include <cstring>
11
+ #include <cstdarg>
10
12
  #include <iostream>
13
+ #include <fstream>
11
14
  #include <map>
12
15
  #include <random>
13
16
  #include <string>
@@ -196,6 +199,11 @@ struct MockJniRuntime {
196
199
  JavaVM vm;
197
200
  std::map<std::string, void*> methods;
198
201
  std::vector<std::string> allocatedStrings;
202
+ std::vector<std::string> logs;
203
+ bool exceptionPending = false;
204
+ bool loggerAvailable = true;
205
+ bool loggerThrows = false;
206
+ size_t clearedExceptions = 0;
199
207
 
200
208
  static MockJniRuntime*& active() {
201
209
  static MockJniRuntime* instance = nullptr;
@@ -208,11 +216,30 @@ struct MockJniRuntime {
208
216
  }
209
217
 
210
218
  static jclass JNICALL mockFindClass(JNIEnv*, const char* name) {
219
+ if (name && std::string(name) == "com/margelo/nitro/nativelogger/OneKeyLog") {
220
+ if (!active()->loggerAvailable) { active()->exceptionPending = true; return nullptr; }
221
+ return reinterpret_cast<jclass>(0x2);
222
+ }
211
223
  require(name && std::string(name) == "org/haobtc/onekey/card/gpchannel/GPChannelNatives",
212
224
  "Unexpected JNI class lookup");
213
225
  return reinterpret_cast<jclass>(0x1);
214
226
  }
215
227
 
228
+ static jboolean JNICALL mockExceptionCheck(JNIEnv*) { return active()->exceptionPending; }
229
+ static void JNICALL mockExceptionClear(JNIEnv*) { active()->exceptionPending = false; ++active()->clearedExceptions; }
230
+ static jmethodID JNICALL mockGetStaticMethodID(JNIEnv*, jclass type, const char* name, const char* signature) {
231
+ require(type == reinterpret_cast<jclass>(0x2) && std::string(name) == "info" &&
232
+ std::string(signature) == "(Ljava/lang/String;Ljava/lang/String;)V", "Existing logger method contract");
233
+ return reinterpret_cast<jmethodID>(0x3);
234
+ }
235
+ static void JNICALL mockCallStaticVoidMethodV(JNIEnv*, jclass, jmethodID, va_list args) {
236
+ const auto tag = va_arg(args, jstring);
237
+ const auto message = va_arg(args, jstring);
238
+ require(readJString(tag) == "LiteCard", "Diagnostic tag is fixed");
239
+ active()->logs.push_back(readJString(message));
240
+ if (active()->loggerThrows) active()->exceptionPending = true;
241
+ }
242
+
216
243
  static jint JNICALL mockRegisterNatives(JNIEnv*, jclass, const JNINativeMethod* methods, jint count) {
217
244
  for (jint i = 0; i < count; ++i) {
218
245
  active()->methods[methods[i].name] = methods[i].fnPtr;
@@ -245,6 +272,10 @@ struct MockJniRuntime {
245
272
  envTable.GetStringUTFChars = &mockGetStringUTFChars;
246
273
  envTable.ReleaseStringUTFChars = &mockReleaseStringUTFChars;
247
274
  envTable.NewStringUTF = &mockNewStringUTF;
275
+ envTable.ExceptionCheck = &mockExceptionCheck;
276
+ envTable.ExceptionClear = &mockExceptionClear;
277
+ envTable.GetStaticMethodID = &mockGetStaticMethodID;
278
+ envTable.CallStaticVoidMethodV = &mockCallStaticVoidMethodV;
248
279
  env.functions = &envTable;
249
280
  vmTable.GetEnv = &mockGetEnv;
250
281
  vm.functions = &vmTable;
@@ -274,7 +305,32 @@ int main() {
274
305
  require(JUB_GPC_OpenSecureChannel("") == JUBR_CONTEXT_NOT_SATISFIED);
275
306
  require(JUB_GPC_BuildSafeAPDU(0, 0, 0, 0, "", &output) == JUBR_CONTEXT_NOT_SATISFIED);
276
307
  require(JUB_GPC_BuildAPDU(0, 0, 0, 0, "zz", &output) == JUBR_ARGUMENTS_BAD);
308
+ for (const auto& text : {"0", "123", "AbC", "0123", "ABCDEF", ""}) {
309
+ require(JUB_GPC_BuildAPDU(0x80, 0x3b, 0, 0, text, &output) == JUBR_OK && output,
310
+ "Valid odd and even command inputs must build");
311
+ const std::string input(text);
312
+ const std::string normalized = input.size() % 2 ? "0" + input : input;
313
+ char* expected = nullptr;
314
+ require(JUB_GPC_BuildAPDU(0x80, 0x3b, 0, 0, normalized.c_str(), &expected) == JUBR_OK);
315
+ require(std::string(output) == expected, "Odd command must equal whole-input leading-zero encoding");
316
+ require(JUB_FreeMemory(output) == JUBR_OK);
317
+ require(JUB_FreeMemory(expected) == JUBR_OK);
318
+ }
319
+ for (const auto& text : {"z", "12z", "0x1", " 1", "+1", "1\n"}) {
320
+ output = reinterpret_cast<char*>(1);
321
+ require(JUB_GPC_BuildAPDU(0, 0, 0, 0, text, &output) == JUBR_ARGUMENTS_BAD && !output,
322
+ "Invalid odd/even command must fail with null output");
323
+ }
324
+ for (size_t digits : {size_t(131069), size_t(131070), size_t(131071)}) {
325
+ const std::string input(digits, 'a');
326
+ const auto result = JUB_GPC_BuildAPDU(0x80, 0x3b, 0, 0, input.c_str(), &output);
327
+ require(result == (digits <= 131070 ? JUBR_OK : JUBR_ARGUMENTS_BAD),
328
+ "Plain command limits count decoded bytes after leading-zero normalization");
329
+ if (output) require(JUB_FreeMemory(output) == JUBR_OK);
330
+ }
277
331
  JUB_UINT16 status = 0;
332
+ require(JUB_GPC_ParseAPDUResponse("900", &status, &output) == JUBR_ARGUMENTS_BAD && !output,
333
+ "Odd response input must remain rejected");
278
334
  require(JUB_GPC_ParseAPDUResponse("9000", &status, &output) == 0);
279
335
  require(status == 0x9000 && output && !*output);
280
336
  require(JUB_FreeMemory(output) == 0);
@@ -293,8 +349,19 @@ int main() {
293
349
  std::string validCert = buildCertificate(ocePub);
294
350
  std::string offCurveCert = buildCertificate(offCurvePub);
295
351
 
352
+ char* strictSerial = nullptr;
353
+ char* strictSubject = nullptr;
354
+ const std::string oddCert = validCert.substr(1);
355
+ require(JUB_GPC_ParseCertificate(oddCert.c_str(), &strictSerial, &strictSubject) == JUBR_ARGUMENTS_BAD &&
356
+ !strictSerial && !strictSubject, "Odd certificate must remain rejected");
357
+ JUB_ULONG strictTag = 0;
358
+ require(JUB_GPC_TLVDecode("53100", &strictTag, &output) == JUBR_ARGUMENTS_BAD && !output,
359
+ "Odd TLV input must remain rejected");
360
+
296
361
  require(JUB_GPC_Initialize(info, validCert.c_str(), validOcePriv.c_str()) == JUBR_OK,
297
362
  "Valid scalar and certificate should initialize");
363
+ require(JUB_GPC_OpenSecureChannel("5f490") == JUBR_ARGUMENTS_BAD,
364
+ "Odd handshake response must remain rejected");
298
365
  require(JUB_GPC_Finalize() == JUBR_OK);
299
366
 
300
367
  require(JUB_GPC_Initialize(info, validCert.c_str(), zeroPriv.c_str()) == JUBR_ARGUMENTS_BAD,
@@ -393,24 +460,47 @@ int main() {
393
460
  require(JUB_GPC_OpenSecureChannel(maRespHex.c_str()) == JUBR_OK,
394
461
  "Valid mutual authentication response must open secure channel");
395
462
 
463
+ for (const auto& input : {std::string("xyz"), std::string(131023, 'a'), std::string(131024, 'a')}) {
464
+ output = reinterpret_cast<char*>(1);
465
+ require(JUB_GPC_BuildSafeAPDU(0x80, 0x3b, 0, 0, input.c_str(), &output) == JUBR_ARGUMENTS_BAD && !output,
466
+ "Invalid and oversized safe command inputs must not build");
467
+ }
468
+
396
469
  // Encrypted APDU build must succeed while session is open
397
470
  char* safeApduHex = nullptr;
398
- require(JUB_GPC_BuildSafeAPDU(0x80, 0x20, 0x00, 0x00, "06313233343536", &safeApduHex) == JUBR_OK && safeApduHex);
471
+ const std::string oddBackup = "12345678901234567890123456789012345678900000001";
472
+ require(JUB_GPC_BuildSafeAPDU(0x80, 0x20, 0x00, 0x00, oddBackup.c_str(), &safeApduHex) == JUBR_OK && safeApduHex);
399
473
  std::vector<unsigned char> safeApduBytes = unhex(safeApduHex);
400
474
  require(JUB_FreeMemory(safeApduHex) == JUBR_OK);
401
- require(safeApduBytes.size() == 5 + 16 + 8 && safeApduBytes[0] == 0x84);
475
+ require(safeApduBytes.size() == 5 + 32 + 8 && safeApduBytes[0] == 0x84);
476
+ aes_encrypt_ctx commandEnc;
477
+ aes_encrypt_key128(derivedKeys.data() + 16, &commandEnc);
478
+ unsigned char commandCounter[16] = {0};
479
+ commandCounter[15] = 1;
480
+ unsigned char commandIv[16] = {0};
481
+ aes_ecb_encrypt(commandCounter, commandIv, 16, &commandEnc);
482
+ aes_decrypt_ctx commandDec;
483
+ aes_decrypt_key128(derivedKeys.data() + 16, &commandDec);
484
+ unsigned char commandPlain[32] = {0};
485
+ aes_cbc_decrypt(safeApduBytes.data() + 5, commandPlain, 32, commandIv, &commandDec);
486
+ const auto expectedCommand = unhex("0" + oddBackup);
487
+ require(std::equal(expectedCommand.begin(), expectedCommand.end(), commandPlain) &&
488
+ commandPlain[expectedCommand.size()] == 0x80 &&
489
+ std::all_of(commandPlain + expectedCommand.size() + 1, commandPlain + 32,
490
+ [](unsigned char byte) { return byte == 0; }),
491
+ "45-digit backup must encrypt whole-input leading-zero bytes with unchanged padding");
402
492
 
403
493
  // Verify JUB_GPC_ParseSafeAPDUResponse with valid RMAC, tampered RMAC, and status-only error:
404
494
  // derivedKeys layout: [0..16]=key_dek, [16..32]=s_enc, [32..48]=s_mac, [48..64]=s_rmac
405
495
  // After BuildSafeAPDU #1 (counter == 1), the SDK's 16-byte chaining CMAC is computed over:
406
- // receipt(16B) || 84 20 00 00 18 || ciphertext(16B)
496
+ // receipt(16B) || header/Lc || ciphertext
407
497
  std::vector<unsigned char> maRespBytes = unhex(maRespHex);
408
498
  std::vector<unsigned char> receiptBytes(maRespBytes.end() - 16, maRespBytes.end());
409
499
  std::vector<unsigned char> cmacInput = receiptBytes;
410
- cmacInput.insert(cmacInput.end(), safeApduBytes.begin(), safeApduBytes.begin() + 5 + 16);
500
+ cmacInput.insert(cmacInput.end(), safeApduBytes.begin(), safeApduBytes.end() - 8);
411
501
  unsigned char cmdChain[16] = {0};
412
502
  AES_CMAC(derivedKeys.data() + 32, cmacInput.data(), static_cast<unsigned>(cmacInput.size()), cmdChain);
413
- require(std::memcmp(cmdChain, safeApduBytes.data() + 5 + 16, 8) == 0,
503
+ require(std::memcmp(cmdChain, safeApduBytes.data() + safeApduBytes.size() - 8, 8) == 0,
414
504
  "Command CMAC prefix must match independent AES-CMAC");
415
505
 
416
506
  // Construct encrypted response for counter == 2 (incCounter() pre-increments 1 -> 2):
@@ -452,6 +542,9 @@ int main() {
452
542
  "Tampered RMAC response must be rejected");
453
543
  require(!output);
454
544
 
545
+ require(JUB_GPC_ParseSafeAPDUResponse("900", &status, &output) == JUBR_ARGUMENTS_BAD && !output,
546
+ "Odd protected response input must remain rejected");
547
+
455
548
  // Unauthenticated plain "9000" on safe channel must be rejected
456
549
  require(JUB_GPC_ParseSafeAPDUResponse("9000", &status, &output) != JUBR_OK,
457
550
  "Unauthenticated 9000 response on safe channel must be rejected");
@@ -471,6 +564,13 @@ int main() {
471
564
  require(status == 0x63c2 && output && std::string(output).empty());
472
565
  require(JUB_FreeMemory(output) == JUBR_OK);
473
566
 
567
+ for (size_t digits : {size_t(131021), size_t(131022)}) {
568
+ const std::string input(digits, 'a');
569
+ require(JUB_GPC_BuildSafeAPDU(0x80, 0x3b, 0, 0, input.c_str(), &output) == JUBR_OK && output,
570
+ "Safe command accepts both parities at the decoded-byte limit");
571
+ require(JUB_FreeMemory(output) == JUBR_OK);
572
+ }
573
+
474
574
  // Failed re-initialization must clear the open session
475
575
  require(JUB_GPC_Initialize(info, "deadbeef", validOcePriv.c_str()) == JUBR_ARGUMENTS_BAD);
476
576
  output = nullptr;
@@ -510,6 +610,7 @@ int main() {
510
610
  typedef jint (*OpenFn)(JNIEnv*, jobject, jstring);
511
611
  typedef jstring (*MutualFn)(JNIEnv*, jobject);
512
612
  typedef jstring (*ParseFn)(JNIEnv*, jobject, jstring);
613
+ typedef jstring (*BuildFn)(JNIEnv*, jobject, jlong, jlong, jlong, jlong, jstring);
513
614
 
514
615
  GetErrorFn jniGetError = reinterpret_cast<GetErrorFn>(jni.methods["nativeGetErrorCode"]);
515
616
  InitFn jniInit = reinterpret_cast<InitFn>(jni.methods["nativeGPCInitialize"]);
@@ -518,6 +619,43 @@ int main() {
518
619
  MutualFn jniMutual = reinterpret_cast<MutualFn>(jni.methods["nativeGPCBuildMutualAuthData"]);
519
620
  ParseFn jniParseSafe = reinterpret_cast<ParseFn>(jni.methods["nativeGPCParseSafeAPDUResponse"]);
520
621
  ParseFn jniParseCert = reinterpret_cast<ParseFn>(jni.methods["nativeGPCParseCertificate"]);
622
+ BuildFn jniBuild = reinterpret_cast<BuildFn>(jni.methods["nativeGPCBuildAPDU"]);
623
+ BuildFn jniBuildSafe = reinterpret_cast<BuildFn>(jni.methods["nativeGPCBuildSafeAPDU"]);
624
+
625
+ const std::string sourceId(reinterpret_cast<const char*>(GPChannelSDKCoreVersionString));
626
+ require(sourceId.size() == 74 && sourceId.substr(0, 10) == "source-v1:" &&
627
+ sourceId.find_first_not_of("0123456789abcdef", 10) == std::string::npos, "Compiled native source identity format");
628
+ std::string displayedSourceId = sourceId;
629
+ for (size_t offset = 66; offset > 10; offset -= 8) displayedSourceId.insert(offset, "-");
630
+ auto expectedBuildLog = [&](bool safe, int code, bool present) {
631
+ return "stage=command_build nativeSourceId=" + displayedSourceId + " safe=" + (safe ? "true" : "false") +
632
+ " sdkReturnCode=" + std::to_string(code) + " outputPresent=" + (present ? "true" : "false");
633
+ };
634
+ const std::string privateBackup = "12345678901234567890123456789012345678900000001";
635
+ require(jniBuildSafe(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup)) == nullptr);
636
+ require(jni.logs.back() == expectedBuildLog(true, 6, false), "Unavailable context diagnostic uses actual local code 6");
637
+ const std::string privateInvalid = "PIN-SEED-CERT-SERIAL-WALLET-PRIVATE\n/path/user@host";
638
+ require(jniBuild(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateInvalid)) == nullptr);
639
+ require(jni.logs.back() == expectedBuildLog(false, 3, false), "Invalid command diagnostic uses actual local code 3");
640
+ auto plain = jniBuild(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup));
641
+ require(plain && jni.logs.back() == expectedBuildLog(false, 0, true), "Success diagnostic reports 0 despite stale global error");
642
+ const auto privateApdu = MockJniRuntime::readJString(plain);
643
+ jni.loggerAvailable = false;
644
+ const auto beforeMissingLogger = jni.logs.size();
645
+ require(jniBuild(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup)) != nullptr &&
646
+ !jni.exceptionPending && jni.logs.size() == beforeMissingLogger, "Missing logger leaves SDK success intact");
647
+ jni.loggerAvailable = true;
648
+ jni.loggerThrows = true;
649
+ require(jniBuild(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup)) != nullptr &&
650
+ !jni.exceptionPending, "Logger exception leaves SDK success intact");
651
+ jni.loggerThrows = false;
652
+ jni.exceptionPending = true;
653
+ const auto beforePending = jni.logs.size();
654
+ const auto beforeClears = jni.clearedExceptions;
655
+ require(jniBuild(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup)) != nullptr &&
656
+ jni.exceptionPending && jni.logs.size() == beforePending && jni.clearedExceptions == beforeClears,
657
+ "Diagnostic helper must preserve a pre-existing pending exception");
658
+ jni.exceptionPending = false;
521
659
 
522
660
  require(jniFinalize(&jni.env, nullptr) == JUBR_OK);
523
661
  require(jniInit(&jni.env, nullptr, nullptr) == JUBR_ARGUMENTS_BAD,
@@ -564,6 +702,22 @@ int main() {
564
702
  require(jniMa != nullptr);
565
703
  std::string jniMaResp = buildCardMutualAuthResponse(validCardPriv, ocePub, MockJniRuntime::readJString(jniMa));
566
704
  require(jniOpen(&jni.env, nullptr, jni.makeJString(jniMaResp)) == JUBR_OK);
705
+ require(jniBuildSafe(&jni.env, nullptr, 0x80, 0x3b, 0, 0, jni.makeJString(privateBackup)) != nullptr &&
706
+ jni.logs.back() == expectedBuildLog(true, 0, true), "Safe success logs actual local code");
707
+ for (const auto& line : jni.logs) {
708
+ require(line == expectedBuildLog(false, 0, true) || line == expectedBuildLog(true, 0, true) ||
709
+ line == expectedBuildLog(false, 3, false) || line == expectedBuildLog(true, 6, false),
710
+ "Every emitted field is allowlisted; no extra diagnostic content");
711
+ for (const auto& secret : {privateBackup, privateInvalid, privateApdu, validOcePriv, validCert, jniMaResp, sourceId})
712
+ require(line.find(secret) == std::string::npos, "Diagnostic must not contain synthetic sensitive input or output");
713
+ }
714
+ if (const char* path = std::getenv("ONEKEY_LITE_JNI_LOG_TEST_OUTPUT")) {
715
+ std::ofstream captured(path);
716
+ captured << sourceId << '\n';
717
+ for (const auto& line : jni.logs) captured << line << '\n';
718
+ captured.flush();
719
+ require(captured.good(), "Captured JNI metadata must be available to the real logger regression");
720
+ }
567
721
 
568
722
  // Unauthenticated "9000" safe response through JNI must return nullptr and set errorCode
569
723
  require(jniParseSafe(&jni.env, nullptr, jni.makeJString("9000")) == nullptr,
@@ -50,8 +50,11 @@ class SDK:
50
50
  return value
51
51
 
52
52
  def build(self, name, data, header=(0x80, 0x20, 0, 0)):
53
+ return self.build_hex(name, data.hex(), header)
54
+
55
+ def build_hex(self, name, text, header=(0x80, 0x20, 0, 0)):
53
56
  output = c.c_void_p()
54
- result = getattr(self.lib, "JUB_GPC_" + name)(*header, data.hex().encode(), c.byref(output))
57
+ result = getattr(self.lib, "JUB_GPC_" + name)(*header, text.encode(), c.byref(output))
55
58
  return result, self.take(output)
56
59
 
57
60
  def parse(self, name, data):
@@ -147,6 +150,15 @@ def verify(recovered, reference=None):
147
150
  for sdk in peers:
148
151
  assert sdk.build("BuildAPDU", data, header) == (0, expected), "Plain APDU bytes"
149
152
  checks += 1
153
+ for text in ("1", "123", "AbC", "12345678901234567890123456789012345678900000001",
154
+ "0" * 131069, "0" * 131070):
155
+ data = bytes.fromhex(("0" if len(text) % 2 else "") + text)
156
+ size = len(data)
157
+ length = bytes([size]) if size <= 255 else b"\x00" + size.to_bytes(2, "big")
158
+ expected = (bytes.fromhex("803b0000") + length + data).hex().encode()
159
+ for sdk in peers:
160
+ assert sdk.build_hex("BuildAPDU", text, (0x80, 0x3b, 0, 0)) == (0, expected), "Raw odd command compatibility"
161
+ checks += 1
150
162
  for size in (0, 1, 5, 6, 7, 16, 255, 1024, 1025):
151
163
  for word in (b"\x90\x00", b"\x63\xc2", b"\x6a\x80"):
152
164
  data = rng.randbytes(size)
@@ -176,8 +188,13 @@ def verify(recovered, reference=None):
176
188
  if sdk is recovered:
177
189
  assert sdk.parse("ParseSafeAPDUResponse", bytes(8) + bytes.fromhex("63c2"))[0] == 3, "Reject missing encrypted response block"
178
190
  checks += 1
179
- for size in (0, 1, 15, 16, 17, 127, 128, 239, 240, 255, 256, 1024) + (1,) * 250:
180
- data = rng.randbytes(size)
191
+ command_inputs = [rng.randbytes(size).hex() for size in
192
+ (0, 1, 15, 16, 17, 127, 128, 239, 240, 255, 256, 1024)]
193
+ command_inputs += ["12345678901234567890123456789012345678900000001", "AbC", "1", "12"]
194
+ command_inputs += [rng.randbytes(1).hex() for _ in range(250)]
195
+ for text in command_inputs:
196
+ data = bytes.fromhex(("0" if len(text) % 2 else "") + text)
197
+ size = len(data)
181
198
  counter_bytes = counter.to_bytes(4, "big") if getattr(sdk, "wide_counter", False) else bytes([counter & 255])
182
199
  iv = aes(enc, bytes(16), counter_bytes.rjust(16, b"\0"))
183
200
  encrypted = aes(enc, iv, pad(data))
@@ -186,7 +203,7 @@ def verify(recovered, reference=None):
186
203
  chain = mac(cmac_key, chain + header + bytes([length & 255]) + encrypted)
187
204
  length_bytes = bytes([length]) if length <= 255 else b"\x00" + length.to_bytes(2, "big")
188
205
  expected = (header + length_bytes + encrypted + chain[:8]).hex().encode()
189
- assert sdk.build("BuildSafeAPDU", data) == (0, expected), "Encrypted APDU and chained CMAC"
206
+ assert sdk.build_hex("BuildSafeAPDU", text) == (0, expected), "Raw command encrypted APDU and chained CMAC"
190
207
  checks += 1
191
208
  reply = rng.randbytes(min(size, 1008))
192
209
  counter += 1
@@ -90,6 +90,7 @@ export interface Spec extends TurboModule {
90
90
  changePin(
91
91
  oldPin: string,
92
92
  newPin: string,
93
+ expectedSerial: string | null,
93
94
  callback: (
94
95
  error: CallbackError | null,
95
96
  data: boolean | null,
package/src/index.tsx CHANGED
@@ -62,9 +62,14 @@ class OnekeyLite {
62
62
  });
63
63
  }
64
64
 
65
- changePin(oldPin: string, newPin: string) {
65
+ changePin(oldPin: string, newPin: string, expectedSerial?: string) {
66
66
  return new Promise<PromiseResult<boolean>>((resolve) => {
67
- OKLiteManager.changePin(oldPin, newPin, this.convertToPromise(resolve));
67
+ OKLiteManager.changePin(
68
+ oldPin,
69
+ newPin,
70
+ expectedSerial ?? null,
71
+ this.convertToPromise(resolve)
72
+ );
68
73
  });
69
74
  }
70
75