@onetokenfe/react-native-nfc-wallet-sdk 0.1.5 → 0.1.6

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.
@@ -7,7 +7,7 @@
7
7
  @property (nonatomic, assign) NfcWalletOperationType operationType;
8
8
  @property (nonatomic, copy, nullable) NfcWalletOperationCompletion completion;
9
9
  @property (nonatomic, copy, nullable) NSString *pin;
10
- @property (nonatomic, copy, nullable) NSString *newPin;
10
+ @property (nonatomic, copy, nullable) NSString *replacementPin;
11
11
  @property (nonatomic, copy, nullable) NSString *hashHex;
12
12
  @property (nonatomic, copy, nullable) NSString *seedHex;
13
13
  @property (nonatomic, copy, nullable) NSString *derivationPath;
@@ -19,8 +19,21 @@
19
19
  @property (nonatomic, assign) NSInteger backupCount;
20
20
  @property (nonatomic, assign) BOOL operationFinished;
21
21
  @property (nonatomic, assign) BOOL operationInProgress;
22
+ /// Session moved out of `session` and waiting for didInvalidateWithError.
23
+ @property (nonatomic, strong, nullable) NFCTagReaderSession *releasingSession;
24
+ /// Set before the delegate queue observes `releasingSession`, so a new begin cannot slip in.
25
+ @property (nonatomic, assign) BOOL releasePending;
26
+ @property (nonatomic, copy, nullable) void (^sessionReleasedBlock)(void);
27
+ @property (nonatomic, assign) CFAbsoluteTime lastSessionReleasedAt;
28
+ @property (nonatomic, assign) NSUInteger launchGeneration;
29
+ @property (nonatomic, assign) NSInteger systemBusyRetryCount;
22
30
  @end
23
31
 
32
+ static const NSTimeInterval kNfcSessionCooldownSeconds = 0.7;
33
+ static const NSTimeInterval kNfcSessionReleaseTimeoutSeconds = 1.5;
34
+ static const NSInteger kNfcSystemBusyErrorCode = 203;
35
+ static const NSInteger kNfcMaxSystemBusyRetries = 2;
36
+
24
37
  @implementation NfcWalletNFCManager
25
38
 
26
39
  - (instancetype)init
@@ -38,8 +51,100 @@
38
51
 
39
52
  - (void)cancelSession
40
53
  {
41
- [self.session invalidateSession];
54
+ dispatch_async(self.nfcDelegateQueue, ^{
55
+ self.launchGeneration += 1;
56
+ NfcWalletOperationCompletion completion = nil;
57
+ @synchronized(self) {
58
+ if (!self.operationFinished) {
59
+ self.operationFinished = YES;
60
+ completion = self.completion;
61
+ self.completion = nil;
62
+ }
63
+ }
64
+ [self releaseActiveSessionThen:nil];
65
+ if (!completion) {
66
+ return;
67
+ }
68
+ dispatch_async(dispatch_get_main_queue(), ^{
69
+ completion(nil, [NSError errorWithDomain:@"NfcWallet"
70
+ code:2004
71
+ userInfo:@{NSLocalizedDescriptionKey : @"NFC wait cancelled"}]);
72
+ });
73
+ });
74
+ }
75
+
76
+ /// Invalidate any live session, then run `block` on the delegate queue after CoreNFC has released it.
77
+ - (void)releaseActiveSessionThen:(void (^_Nullable)(void))block
78
+ {
79
+ if (self.releasingSession || self.releasePending) {
80
+ self.sessionReleasedBlock = block;
81
+ return;
82
+ }
83
+ NFCTagReaderSession *active = self.session;
84
+ if (!active) {
85
+ [self cooldownThen:block];
86
+ return;
87
+ }
42
88
  self.session = nil;
89
+ self.releasePending = YES;
90
+ self.releasingSession = active;
91
+ self.sessionReleasedBlock = block;
92
+ [active invalidateSession];
93
+ [self armReleaseTimeoutForSession:active];
94
+ }
95
+
96
+ - (void)armReleaseTimeoutForSession:(NFCTagReaderSession *)session
97
+ {
98
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kNfcSessionReleaseTimeoutSeconds * NSEC_PER_SEC)), self.nfcDelegateQueue, ^{
99
+ if (self.releasingSession == session) {
100
+ [self noteSessionReleased:session];
101
+ }
102
+ });
103
+ }
104
+
105
+ - (void)noteSessionReleased:(NFCTagReaderSession *)session
106
+ {
107
+ if (session != self.releasingSession) {
108
+ return;
109
+ }
110
+ self.releasingSession = nil;
111
+ self.releasePending = NO;
112
+ self.lastSessionReleasedAt = CFAbsoluteTimeGetCurrent();
113
+ void (^block)(void) = self.sessionReleasedBlock;
114
+ self.sessionReleasedBlock = nil;
115
+ if (block) {
116
+ [self cooldownThen:block];
117
+ }
118
+ }
119
+
120
+ - (void)cooldownThen:(void (^_Nullable)(void))block
121
+ {
122
+ if (!block) {
123
+ return;
124
+ }
125
+ NSTimeInterval wait = 0;
126
+ if (self.lastSessionReleasedAt > 0) {
127
+ wait = kNfcSessionCooldownSeconds - (CFAbsoluteTimeGetCurrent() - self.lastSessionReleasedAt);
128
+ }
129
+ if (wait <= 0) {
130
+ block();
131
+ return;
132
+ }
133
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(wait * NSEC_PER_SEC)), self.nfcDelegateQueue, block);
134
+ }
135
+
136
+ - (void)beginPreparedSession
137
+ {
138
+ self.operationFinished = NO;
139
+ self.operationInProgress = NO;
140
+ NFCTagReaderSession *session = [[NFCTagReaderSession alloc] initWithPollingOption:NFCPollingISO14443
141
+ delegate:self
142
+ queue:self.nfcDelegateQueue];
143
+ session.alertMessage = NSLocalizedString(@"Hold near NFC wallet card", @"");
144
+ self.session = session;
145
+ dispatch_async(dispatch_get_main_queue(), ^{
146
+ [session beginSession];
147
+ });
43
148
  }
44
149
 
45
150
  - (void)runOperation:(NfcWalletOperationType)type
@@ -60,26 +165,35 @@
60
165
  completion(nil, [NSError errorWithDomain:@"NfcWallet" code:2001 userInfo:@{NSLocalizedDescriptionKey : @"NFC unavailable"}]);
61
166
  return;
62
167
  }
63
- [self cancelSession];
64
- self.operationType = type;
65
- self.completion = completion;
66
- self.pin = pin;
67
- self.newPin = newPin;
68
- self.hashHex = hashHex;
69
- self.seedHex = seedHex;
70
- self.derivationPath = derivationPath;
71
- self.pathsJson = pathsJson;
72
- self.expectedSerial = expectedSerial;
73
- self.backupStep = nil;
74
- self.payloadHex = nil;
75
- self.backupCount = 2;
76
- self.operationFinished = NO;
77
- self.operationInProgress = NO;
78
- self.session = [[NFCTagReaderSession alloc] initWithPollingOption:NFCPollingISO14443
79
- delegate:self
80
- queue:self.nfcDelegateQueue];
81
- self.session.alertMessage = NSLocalizedString(@"Hold near NFC wallet card", @"");
82
- [self.session beginSession];
168
+ dispatch_async(self.nfcDelegateQueue, ^{
169
+ self.launchGeneration += 1;
170
+ NSUInteger generation = self.launchGeneration;
171
+ self.systemBusyRetryCount = 0;
172
+ self.operationType = type;
173
+ self.completion = completion;
174
+ self.pin = pin;
175
+ self.replacementPin = newPin;
176
+ self.hashHex = hashHex;
177
+ self.seedHex = seedHex;
178
+ self.derivationPath = derivationPath;
179
+ self.pathsJson = pathsJson;
180
+ self.expectedSerial = expectedSerial;
181
+ // runBackupStep sets these before calling in. Clearing them here drops the
182
+ // step name and the card reports "Unknown backup step:".
183
+ if (type != NfcWalletOperationBackupStep) {
184
+ self.backupStep = nil;
185
+ self.payloadHex = nil;
186
+ self.backupCount = 2;
187
+ }
188
+ self.operationFinished = NO;
189
+ self.operationInProgress = NO;
190
+ [self releaseActiveSessionThen:^{
191
+ if (generation != self.launchGeneration) {
192
+ return;
193
+ }
194
+ [self beginPreparedSession];
195
+ }];
196
+ });
83
197
  }
84
198
 
85
199
  - (void)runOperation:(NfcWalletOperationType)type
@@ -150,12 +264,22 @@
150
264
  completion = self.completion;
151
265
  self.completion = nil;
152
266
  self.session = nil;
267
+ if (activeSession) {
268
+ self.releasePending = YES;
269
+ }
153
270
  }
154
271
 
155
- if (error) {
156
- [activeSession invalidateSessionWithErrorMessage:error.localizedDescription ?: @"Failed"];
157
- } else {
158
- [activeSession invalidateSession];
272
+ if (activeSession) {
273
+ dispatch_async(self.nfcDelegateQueue, ^{
274
+ self.releasePending = YES;
275
+ self.releasingSession = activeSession;
276
+ if (error) {
277
+ [activeSession invalidateSessionWithErrorMessage:error.localizedDescription ?: @"Failed"];
278
+ } else {
279
+ [activeSession invalidateSession];
280
+ }
281
+ [self armReleaseTimeoutForSession:activeSession];
282
+ });
159
283
  }
160
284
  if (completion) {
161
285
  dispatch_async(dispatch_get_main_queue(), ^{
@@ -173,7 +297,7 @@
173
297
  return [wallet setPin:self.pin ?: @""];
174
298
  case NfcWalletOperationChangePin:
175
299
  return [wallet changePin:self.pin ?: @""
176
- newPin:self.newPin ?: @""
300
+ newPin:self.replacementPin ?: @""
177
301
  expectedSerial:self.expectedSerial];
178
302
  case NfcWalletOperationVerifyPin:
179
303
  return [wallet verifyPin:self.pin ?: @"" expectedSerial:self.expectedSerial];
@@ -217,6 +341,27 @@
217
341
 
218
342
  - (void)tagReaderSession:(NFCTagReaderSession *)session didInvalidateWithError:(NSError *)error
219
343
  {
344
+ if (session == self.releasingSession) {
345
+ [self noteSessionReleased:session];
346
+ return;
347
+ }
348
+
349
+ // CoreNFC still holds the radio. Retry on this same call instead of toasting.
350
+ if (session == self.session && error.code == kNfcSystemBusyErrorCode &&
351
+ self.systemBusyRetryCount < kNfcMaxSystemBusyRetries && !self.operationInProgress) {
352
+ self.systemBusyRetryCount += 1;
353
+ NSUInteger generation = self.launchGeneration;
354
+ self.session = nil;
355
+ self.lastSessionReleasedAt = CFAbsoluteTimeGetCurrent();
356
+ [self cooldownThen:^{
357
+ if (generation != self.launchGeneration) {
358
+ return;
359
+ }
360
+ [self beginPreparedSession];
361
+ }];
362
+ return;
363
+ }
364
+
220
365
  NfcWalletOperationCompletion completion = nil;
221
366
 
222
367
  @synchronized(self) {
@@ -7,8 +7,20 @@ static const uint8_t kWalletAppletAid[] = {0x6F, 0x6E, 0x65, 0x74, 0x6F, 0x6B, 0
7
7
  static const uint8_t kCla = 0x80;
8
8
  static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
9
9
 
10
+ /**
11
+ * Match Android buildApdu.
12
+ * No body → Le=0x00 (expectedResponseLength 256).
13
+ * Body present → omit Le (expectedResponseLength -1). Forcing Le=256 on
14
+ * VERIFY/CREATE makes CoreNFC wait until the card leaves the field and then
15
+ * report "Tag response error / no response".
16
+ */
17
+ static NSInteger NfcWalletExpectedResponseLength(NSData *_Nullable data)
18
+ {
19
+ return data.length > 0 ? -1 : 256;
20
+ }
21
+
10
22
  @interface NfcWalletSession ()
11
- @property (nonatomic, weak) id<NFCISO7816Tag> tag;
23
+ @property (nonatomic, strong) id<NFCISO7816Tag> tag;
12
24
  @property (nonatomic, strong) dispatch_queue_t commandQueue;
13
25
  @property (nonatomic, copy, nullable) NfcWalletApduLogBlock apduLogBlock;
14
26
  /** Applet SELECT once per tag connection. Re-SELECT clears PIN session (SW=6982). */
@@ -275,6 +287,10 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
275
287
 
276
288
  - (NSDictionary *)verifyPin:(NSString *)pin expectedSerial:(NSString *_Nullable)expectedSerial
277
289
  {
290
+ // Device management passes {"memberSerials":[...]} so probe + VERIFY stay one session.
291
+ if ([expectedSerial hasPrefix:@"{"]) {
292
+ return [self verifyPin:pin allowedSerialsJson:expectedSerial];
293
+ }
278
294
  NSData *pinData = [pin dataUsingEncoding:NSUTF8StringEncoding];
279
295
  if (expectedSerial.length == 0) {
280
296
  return [self simpleCommand:0x20 data:pinData];
@@ -305,6 +321,61 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
305
321
  return [self okResult:NfcWalletHexFromData(resp ?: [NSData data]) walletInfo:nil];
306
322
  }
307
323
 
324
+ /** getWalletInfo + VERIFY in this session. expectedSerial JSON: {"memberSerials":["..."]}. */
325
+ - (NSDictionary *)verifyPin:(NSString *)pin allowedSerialsJson:(NSString *)json
326
+ {
327
+ NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
328
+ NSDictionary *root = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] : nil;
329
+ NSArray *memberSerials = [root isKindOfClass:[NSDictionary class]] ? root[@"memberSerials"] : nil;
330
+ if (![memberSerials isKindOfClass:[NSArray class]] || memberSerials.count == 0) {
331
+ return @{
332
+ @"error" : @{@"code" : @1000, @"message" : @"memberSerials required"},
333
+ @"resultCode" : @1000,
334
+ @"walletInfo" : [NSNull null],
335
+ @"data" : [NSNull null]
336
+ };
337
+ }
338
+
339
+ NSDictionary *infoResult = [self getWalletInfo];
340
+ if (infoResult[@"error"] != [NSNull null] && infoResult[@"error"] != nil) {
341
+ return infoResult;
342
+ }
343
+ NSDictionary *walletInfo = infoResult[@"walletInfo"];
344
+ NSString *serial = [walletInfo isKindOfClass:[NSDictionary class]] ? walletInfo[@"serialNumber"] : nil;
345
+ BOOL matched = NO;
346
+ if ([serial isKindOfClass:[NSString class]]) {
347
+ for (id item in memberSerials) {
348
+ if ([item isKindOfClass:[NSString class]] &&
349
+ [serial caseInsensitiveCompare:(NSString *)item] == NSOrderedSame) {
350
+ matched = YES;
351
+ break;
352
+ }
353
+ }
354
+ }
355
+ if (!matched) {
356
+ return @{
357
+ @"error" : @{
358
+ @"code" : @2015,
359
+ @"message" : [NSString stringWithFormat:@"Wrong NFC card for this wallet (got %@)",
360
+ serial ?: @"(nil)"]
361
+ },
362
+ @"resultCode" : @2015,
363
+ @"walletInfo" : walletInfo ?: [NSNull null],
364
+ @"data" : [NSNull null]
365
+ };
366
+ }
367
+
368
+ NSDictionary *verify = [self verifyPin:pin expectedSerial:serial];
369
+ if (verify[@"error"] != [NSNull null] && verify[@"error"] != nil) {
370
+ NSMutableDictionary *failed = [verify mutableCopy];
371
+ if (walletInfo) {
372
+ failed[@"walletInfo"] = walletInfo;
373
+ }
374
+ return failed;
375
+ }
376
+ return [self okResult:verify[@"data"] == [NSNull null] ? nil : verify[@"data"] walletInfo:walletInfo];
377
+ }
378
+
308
379
  - (NSDictionary *)logout
309
380
  {
310
381
  return [self simpleCommand:0x21 data:nil];
@@ -547,6 +618,9 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
547
618
  expectedSerial:(NSString *_Nullable)expectedSerial
548
619
  {
549
620
  NSDictionary *info = [self getWalletInfo];
621
+ if (info[@"error"] != nil && info[@"error"] != [NSNull null]) {
622
+ return info;
623
+ }
550
624
  NSDictionary *walletInfo = info[@"walletInfo"];
551
625
  if (expectedSerial.length > 0) {
552
626
  NSString *tapped = [walletInfo[@"serialNumber"] description];
@@ -751,6 +825,48 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
751
825
  }
752
826
 
753
827
  if ([normalized isEqualToString:@"enroll"]) {
828
+ // One CoreNFC session: read the card, then enroll. A second session started
829
+ // while the first sheet is still dismissing fails with
830
+ // "Session invalidated unexpectedly".
831
+ NSDictionary *info = [self getWalletInfo];
832
+ if (info[@"error"] != nil && info[@"error"] != [NSNull null]) {
833
+ return info;
834
+ }
835
+ NSDictionary *walletInfo = [info[@"walletInfo"] isKindOfClass:[NSDictionary class]]
836
+ ? info[@"walletInfo"]
837
+ : nil;
838
+ BOOL skipEnroll = NO;
839
+ if (payloadHex.length > 0) {
840
+ NSData *rawPayload = NfcWalletDataFromHex(payloadHex);
841
+ id root = rawPayload.length
842
+ ? [NSJSONSerialization JSONObjectWithData:rawPayload options:0 error:nil]
843
+ : nil;
844
+ if ([root isKindOfClass:[NSDictionary class]]) {
845
+ NSString *serial = [walletInfo[@"serialNumber"] isKindOfClass:[NSString class]]
846
+ ? walletInfo[@"serialNumber"]
847
+ : @"";
848
+ NSString *primary = root[@"primarySerial"];
849
+ NSArray *already = root[@"alreadyEnrolled"];
850
+ BOOL hasKey = [walletInfo[@"hasKey"] boolValue];
851
+ if (hasKey) {
852
+ skipEnroll = YES;
853
+ } else if ([primary isKindOfClass:[NSString class]] && primary.length > 0 &&
854
+ [serial caseInsensitiveCompare:primary] == NSOrderedSame) {
855
+ skipEnroll = YES;
856
+ } else if ([already isKindOfClass:[NSArray class]]) {
857
+ for (id item in already) {
858
+ if ([item isKindOfClass:[NSString class]] &&
859
+ [serial caseInsensitiveCompare:(NSString *)item] == NSOrderedSame) {
860
+ skipEnroll = YES;
861
+ break;
862
+ }
863
+ }
864
+ }
865
+ }
866
+ }
867
+ if (skipEnroll) {
868
+ return [self okResult:nil walletInfo:walletInfo];
869
+ }
754
870
  NSData *resp = [self transceiveIns:0x45 p1:0x00 p2:0x00 data:nil error:&error];
755
871
  if (!resp) {
756
872
  return [self errorResult:error];
@@ -758,7 +874,7 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
758
874
  if (resp.length != 65) {
759
875
  return [self errorResult:[NSError errorWithDomain:@"NfcWallet" code:1000 userInfo:@{NSLocalizedDescriptionKey : @"BACKUP_ENROLL expected 65 bytes"}]];
760
876
  }
761
- return [self okResult:NfcWalletHexFromData(resp) walletInfo:nil];
877
+ return [self okResult:NfcWalletHexFromData(resp) walletInfo:walletInfo];
762
878
  }
763
879
 
764
880
  if ([normalized isEqualToString:@"exportpeer"]) {
@@ -914,7 +1030,26 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
914
1030
  }
915
1031
  [out addObject:@{@"serialNumber" : serial, @"peerBlob" : NfcWalletHexFromData(resp)}];
916
1032
  }
917
- // Confirm is a separate App step after peerBlobs are persisted.
1033
+ // iOS cannot open a second NFC session while this sheet is still up.
1034
+ // Confirm in this same hold when the App sent memberSerials.
1035
+ NSArray *memberSerials = peersRoot[@"memberSerials"];
1036
+ if ([memberSerials isKindOfClass:[NSArray class]] && memberSerials.count > 0) {
1037
+ NSError *encErr = nil;
1038
+ NSData *cardSet = [self encodeCardSetWithMemberSerials:memberSerials error:&encErr];
1039
+ if (!cardSet) {
1040
+ return [self errorResult:encErr];
1041
+ }
1042
+ NSDictionary *verify = [self verifyPin:pin];
1043
+ if (verify[@"error"] != [NSNull null]) {
1044
+ return verify;
1045
+ }
1046
+ error = nil;
1047
+ NSData *confirmResp = [self transceiveIns:0x44 p1:0x00 p2:0x00 data:cardSet error:&error];
1048
+ // 6A1D: primary was already confirmed. Export blobs are still valid.
1049
+ if (!confirmResp && !(error && error.code == 0x6A1D)) {
1050
+ return [self errorResult:error];
1051
+ }
1052
+ }
918
1053
  NSData *outData = [NSJSONSerialization dataWithJSONObject:out options:0 error:&jsonError];
919
1054
  NSString *outJson = outData ? [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding] : @"[]";
920
1055
  return [self okResult:outJson walletInfo:nil];
@@ -1003,7 +1138,7 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
1003
1138
  p1Parameter:0x04
1004
1139
  p2Parameter:0x00
1005
1140
  data:aid
1006
- expectedResponseLength:256];
1141
+ expectedResponseLength:NfcWalletExpectedResponseLength(aid)];
1007
1142
  if ([self sendAPDU:apdu error:error] == nil) {
1008
1143
  return NO;
1009
1144
  }
@@ -1040,7 +1175,7 @@ static const NSTimeInterval kNfcWalletApduTimeoutSeconds = 30;
1040
1175
  p1Parameter:p1
1041
1176
  p2Parameter:p2
1042
1177
  data:data
1043
- expectedResponseLength:256];
1178
+ expectedResponseLength:NfcWalletExpectedResponseLength(data)];
1044
1179
  return [self sendAPDU:apdu error:error];
1045
1180
  }
1046
1181
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onetokenfe/react-native-nfc-wallet-sdk",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "React Native SDK for OneToken NFC Wallet card (instance 6F6E65746F6B656E02)",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",