@sanctum-key/react-native-sdk 1.0.41 → 1.0.43

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.
@@ -1,5 +1,5 @@
1
1
  import React, { useEffect, useMemo, useRef, useState } from 'react';
2
- import { View, Text, StyleSheet, Image, ScrollView, Platform, ActivityIndicator, TouchableOpacity, useWindowDimensions } from 'react-native';
2
+ import { View, Text, StyleSheet, Image, ScrollView, Platform, ActivityIndicator, TouchableOpacity, useWindowDimensions, Alert } from 'react-native';
3
3
  import { showAlert } from '../../utils/platformAlert';
4
4
  import { EnhancedCameraView } from '../EnhancedCameraView';
5
5
  import { TemplateComponent, LocalizedText, GovernmentDocumentType, ISilentCaptureResult, IBbox, GovernmentDocumentTypeShorted, GovernmentDocumentTypeBackend } from '../../types/KYC.types';
@@ -15,7 +15,7 @@ import { cropByObb, getObbConfidence, OBB_CONFIDENCE_THRESHOLD } from '../../uti
15
15
  import REGION_MAPPING from '../../config/region_mapping.json';
16
16
  import QRCode from 'react-native-qrcode-svg';
17
17
  import { cropImageWithBBoxWithTolerance } from '../../utils/cropByObb';
18
- import kycService, { authentification } from '../../modules/api/KYCService';
18
+ import kycService, { authentification, clearAuthToken } from '../../modules/api/KYCService';
19
19
 
20
20
  const ISO_TO_COUNTRY_NAME: Record<string, string> = {
21
21
  'KE': 'Kenya', 'CM': 'Cameroon', 'NG': 'Nigeria', 'CA': 'Canada',
@@ -97,6 +97,7 @@ export const IDCardCapture: React.FC<IDCardCaptureProps> = ({ component, value =
97
97
  const { actions, state, env, apiKey } = useTemplateKYCFlowContext();
98
98
  const { width: screenWidth, height: screenHeight } = useWindowDimensions();
99
99
 
100
+
100
101
  const countrySelectionData = useMemo(() => {
101
102
  const countrySelectionComponent = state.template.components.find(c => c.type === 'country_selection');
102
103
  return countrySelectionComponent ? state.componentData[countrySelectionComponent.id] : null;
@@ -407,12 +408,37 @@ export const IDCardCapture: React.FC<IDCardCaptureProps> = ({ component, value =
407
408
  }
408
409
  };
409
410
 
411
+ const handleExitKYCFlow = () => {
412
+ clearAuthToken();
413
+
414
+ // 2. Clear all local camera/capture states
415
+ setCapturedImages({});
416
+ if (onValueChange) onValueChange({}); // Clear the parent's form state
417
+ setCurrentSide('front');
418
+ setScanPhase('image');
419
+ setSilentCaptureResult({ success: false, isAnalyzing: false, path: '', error: '' });
420
+ scannedBarcodeRef.current = null;
421
+ setPendingCAImage(null);
422
+ setIsProcessingCapture(false);
423
+ setProcessingImagePath(null);
424
+
425
+ // 3. Restart the flow
426
+ if (actions.resetTemplate) {
427
+ // This is the best method: it wipes the context and rebuilds the initial state
428
+ actions.resetTemplate();
429
+ } else if (actions.goToComponent && state.template?.components?.length > 0) {
430
+ actions.goToComponent(state.template.components[0].id);
431
+ } else {
432
+ console.warn("Could not restart flow. Check your KYC context actions.");
433
+ }
434
+ };
435
+
410
436
  const handleSilentCapture = async (result: { success: boolean; path?: string; error?: string; barcode?: unknown }) => {
411
437
  if (isProcessingCaptureRef.current) return;
412
438
  if (scanPhaseRef.current === 'barcode') return;
413
439
  if (isAnalyzingRef.current) return;
414
440
 
415
- // USE REFS TO AVOID IOS NATIVE STALE CLOSURE
441
+
416
442
  const side = currentSideRef.current;
417
443
  const captured = capturedImagesRef.current;
418
444
  const docType = selectedDocTypeRef.current;
@@ -510,41 +536,59 @@ export const IDCardCapture: React.FC<IDCardCaptureProps> = ({ component, value =
510
536
  } catch (error: any) {
511
537
  clearTimeout(watchdog);
512
538
 
513
- const rawMessage = (error?.message || '').toLowerCase();
539
+ const rawMessage = (typeof error === 'string' ? error : (error?.message || '')).toLowerCase();
540
+ const statusCode = error?.response?.status || error?.status;
541
+
542
+ if (
543
+ statusCode === 401 ||
544
+ statusCode === 403 ||
545
+ rawMessage.includes('401') ||
546
+ rawMessage.includes('unauthorized') ||
547
+ rawMessage.includes('token') ||
548
+ rawMessage.includes('unauthenticated')
549
+ ) {
550
+ setShowCamera(false);
551
+ setIsProcessingCapture(false);
552
+ setSilentCaptureResult(prev => ({ ...prev, isAnalyzing: false, success: false, error: '' }));
553
+
554
+ // Use React Native's native Alert to wait for the user's tap
555
+ Alert.alert(
556
+ state.currentLanguage === 'en' ? 'Session Expired' : 'Session Expirée',
557
+ state.currentLanguage === 'en'
558
+ ? 'Your secure session has expired. Please restart the process.'
559
+ : 'Votre session sécurisée a expiré. Veuillez recommencer.',
560
+ [
561
+ {
562
+ text: state.currentLanguage === 'en' ? 'Restart' : 'Recommencer',
563
+ onPress: () => handleExitKYCFlow() // Redirects ONLY when they click the button
564
+ }
565
+ ],
566
+ { cancelable: false } // Forces them to click the button
567
+ );
568
+
569
+ return;
570
+ }
571
+
514
572
  let hintMessage = '';
515
573
 
574
+ // 2. Business Logic Errors
516
575
  if (rawMessage.includes('pays sélectionné') || rawMessage.includes('country mismatch')) {
517
- hintMessage = state.currentLanguage === 'en'
518
- ? 'Does not match the selected country.'
519
- : 'Ne correspond pas au pays sélectionné.';
520
- }
521
- else if (rawMessage.includes('impossible') || rawMessage.includes('unreadable')) {
522
- hintMessage = state.currentLanguage === 'en'
523
- ? 'Move to better lighting.'
524
- : 'Améliorez l\'éclairage.';
525
- }
526
- else if (rawMessage.includes('card_not_fully_in_frame') || rawMessage.includes('frame')) {
527
- hintMessage = state.currentLanguage === 'en'
528
- ? 'Move closer to the document.'
529
- : 'Rapprochez-vous du document.';
530
- }
531
- else if (rawMessage.includes('ne correspond pas au recto')) {
532
- hintMessage = state.currentLanguage === 'en'
533
- ? 'Please scan the same ID.'
534
- : 'Veuillez scanner la même pièce.';
576
+ hintMessage = state.currentLanguage === 'en' ? 'Does not match the selected country.' : 'Ne correspond pas au pays sélectionné.';
577
+ } else if (rawMessage.includes('impossible') || rawMessage.includes('unreadable')) {
578
+ hintMessage = state.currentLanguage === 'en' ? 'Move to better lighting and ensure card is in frame.' : 'Améliorez l\'éclairage et assurez-vous que la carte est bien cadrée.';
579
+ } else if (rawMessage.includes('card_not_fully_in_frame') || rawMessage.includes('frame')) {
580
+ hintMessage = state.currentLanguage === 'en' ? 'Move closer to the document.' : 'Rapprochez-vous du document.';
581
+ } else if (rawMessage.includes('ne correspond pas au recto')) {
582
+ hintMessage = state.currentLanguage === 'en' ? 'Please scan the same ID.' : 'Veuillez scanner la même pièce.';
535
583
  }
536
- // 2. If it's not a known logical error, assume it's a network/API failure
584
+ // 3. Fallback to Network/API failure
537
585
  else {
538
586
  const isNetworkError = error.isAxiosError || error.message === 'Network Error' || error.code === 'ECONNABORTED' || rawMessage.includes('network') || !error.response;
539
587
 
540
588
  if (isNetworkError) {
541
- hintMessage = state.currentLanguage === 'en'
542
- ? 'Poor connection. Retrying...'
543
- : 'Connexion faible. Nouvelle tentative...';
589
+ hintMessage = state.currentLanguage === 'en' ? 'Poor connection. Retrying...' : 'Connexion faible. Nouvelle tentative...';
544
590
  } else {
545
- hintMessage = state.currentLanguage === 'en'
546
- ? 'Analyzing...' // Generic fallback if an unknown API error occurs
547
- : 'Analyse en cours...';
591
+ hintMessage = state.currentLanguage === 'en' ? 'Analyzing...' : 'Analyse en cours...';
548
592
  }
549
593
  }
550
594
 
@@ -3,7 +3,7 @@ import { cropByObb, getObbConfidence, OBB_CONFIDENCE_THRESHOLD } from "../../uti
3
3
  import { GovernmentDocumentType, IBbox } from "../../types/KYC.types";
4
4
  import { KycEnvironment } from "../../types/env.types";
5
5
  import { logger } from "../../utils/logger";
6
- // import { countryData } from "../../config/countriesData";
6
+ import { countryData } from "../../config/countriesData";
7
7
 
8
8
  interface CardObbData {
9
9
  obb: number[][];
@@ -301,11 +301,18 @@ export async function backVerification(
301
301
  const activeTemplatePath = templateResponse.template_path || result.templatePath || '';
302
302
 
303
303
  if (activeTemplatePath) {
304
- // Note: Make sure ISO_TO_COUNTRY_NAME is properly defined or imported if needed here
305
- const hasCodeMatch = activeTemplatePath.includes(`_${result.code}_`);
306
- // Assuming you have countryData available, otherwise you can rely just on CodeMatch
307
- if (!hasCodeMatch && !activeTemplatePath.toLowerCase().includes(result.code.toLowerCase())) {
308
- logger.log(`Template mismatch! Expected region: ${result.code}, Detected: ${activeTemplatePath}`);
304
+ const countryInfo = countryData[result.code];
305
+
306
+ const countryName = countryInfo?.name_en || countryInfo?.name || '';
307
+
308
+ const hasCodeMatch = activeTemplatePath.toUpperCase().includes(`_${result.code.toUpperCase()}_`) ||
309
+ activeTemplatePath.toUpperCase().includes(`${result.code.toUpperCase()}/`);
310
+
311
+ const hasNameMatch = countryName && activeTemplatePath.toLowerCase().includes(countryName.toLowerCase());
312
+
313
+ // 5. If NEITHER match, throw the error
314
+ if (!hasCodeMatch && !hasNameMatch) {
315
+ logger.log(`Template mismatch! Expected region: ${result.code} (${countryName}), Detected: ${activeTemplatePath}`);
309
316
  throw new Error(`Le document ne correspond pas au pays sélectionné (${result.code}).`);
310
317
  }
311
318
  }
@@ -499,6 +506,9 @@ export async function checkTemplateType(
499
506
 
500
507
  } catch (e: any) {
501
508
  logger.log('Error checking template type:', JSON.stringify(errorMessage(e), null, 2));
509
+ if (e?.response?.status === 401 || e?.response?.status === 403 || e?.isAxiosError) {
510
+ throw e;
511
+ }
502
512
  if (e?.message === 'CARD_NOT_FULLY_IN_FRAME' || e?.message?.includes('ne correspond pas')) throw e;
503
513
  throw new Error(e?.message || 'Erreur de vérification du template');
504
514
  }
@@ -488,6 +488,10 @@ export const authentification = async (): Promise<string> => {
488
488
  }
489
489
  }
490
490
 
491
+ export const clearAuthToken = () => {
492
+ cachedToken = null; // Clear memory cache
493
+ };
494
+
491
495
  export const errorMessage = (error: any) => {
492
496
  return error.response?.data?.message || error.response?.data?.detail || error.response?.data?.error || error.response?.data || error.message;
493
497
  }