react-native-face-match-sdk 0.0.0-stage → 1.0.1

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 (58) hide show
  1. package/FaceMatch.podspec +55 -0
  2. package/README.md +174 -2
  3. package/android/build.gradle +59 -0
  4. package/android/consumer-rules.pro +5 -0
  5. package/android/src/main/AndroidManifest.xml +11 -0
  6. package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
  7. package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
  8. package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
  9. package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
  10. package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
  11. package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
  12. package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
  13. package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
  14. package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
  15. package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
  16. package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
  17. package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
  18. package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
  19. package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
  20. package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
  21. package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
  22. package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
  23. package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
  24. package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
  25. package/ios/Sources/AntiSpoofHelper.swift +239 -0
  26. package/ios/Sources/FaceAlignmentHelper.swift +169 -0
  27. package/ios/Sources/FaceCameraView.swift +1161 -0
  28. package/ios/Sources/FaceCameraViewManager.m +28 -0
  29. package/ios/Sources/FaceCameraViewManager.swift +57 -0
  30. package/ios/Sources/FaceCandidateFilter.swift +62 -0
  31. package/ios/Sources/FaceDetectionHelper.swift +283 -0
  32. package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
  33. package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
  34. package/ios/Sources/FaceFrameResult.swift +96 -0
  35. package/ios/Sources/FaceMatchBundle.swift +26 -0
  36. package/ios/Sources/FaceMatchEngine.swift +136 -0
  37. package/ios/Sources/FaceMatchError.swift +40 -0
  38. package/ios/Sources/FaceMatchModule.m +55 -0
  39. package/ios/Sources/FaceMatchModule.swift +288 -0
  40. package/ios/Sources/FaceMatcherHelper.swift +107 -0
  41. package/ios/Sources/FaceOverlayView.swift +285 -0
  42. package/ios/Sources/ImageUtils.swift +322 -0
  43. package/ios/Sources/LivenessDetector.swift +505 -0
  44. package/ios/Sources/LivenessPrompts.swift +121 -0
  45. package/ios/Sources/LivenessVoice.swift +229 -0
  46. package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
  47. package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
  48. package/ios/Sources/PrivateCaptureStore.swift +71 -0
  49. package/ios/Sources/VisionFaceFallback.swift +95 -0
  50. package/ios/onnxruntime-c.podspec +47 -0
  51. package/models/anti_spoof_minifasnet_v2.onnx +0 -0
  52. package/models/w600k_mbf.onnx +0 -0
  53. package/package.json +38 -4
  54. package/react-native.config.js +16 -0
  55. package/src/FaceCameraView.tsx +75 -0
  56. package/src/FaceMatch.ts +66 -0
  57. package/src/index.ts +4 -0
  58. package/src/types.ts +87 -0
@@ -0,0 +1,95 @@
1
+ import CoreGraphics
2
+ import Foundation
3
+ import Vision
4
+
5
+ /// iOS-only safety net for `FaceDetectionHelper`.
6
+ ///
7
+ /// The ML Kit face model bundled for iOS is not the one Google Play Services
8
+ /// ships on Android, and it misses some faces — especially in stored
9
+ /// reference / registration photos — that Android detects. Apple Vision is
10
+ /// used only after ML Kit has found nothing, and produces the same
11
+ /// `DetectedFace` (5 points, top-left-origin pixels) so alignment, anti-spoof
12
+ /// and embeddings are unchanged.
13
+ enum VisionFaceFallback {
14
+ static func detect(_ image: CGImage) -> [DetectedFace] {
15
+ let request = VNDetectFaceLandmarksRequest()
16
+ let handler = VNImageRequestHandler(cgImage: image, orientation: .up, options: [:])
17
+ do {
18
+ try handler.perform([request])
19
+ } catch {
20
+ return []
21
+ }
22
+ let size = CGSize(width: image.width, height: image.height)
23
+ return (request.results ?? []).compactMap { face(from: $0, imageSize: size) }
24
+ }
25
+
26
+ private static func face(from observation: VNFaceObservation, imageSize: CGSize) -> DetectedFace? {
27
+ // Vision is normalised with a bottom-left origin; flip to top-left pixels.
28
+ let normalized = observation.boundingBox
29
+ let box = CGRect(
30
+ x: normalized.minX * imageSize.width,
31
+ y: (1 - normalized.maxY) * imageSize.height,
32
+ width: normalized.width * imageSize.width,
33
+ height: normalized.height * imageSize.height
34
+ )
35
+ guard box.width > 1, box.height > 1 else { return nil }
36
+
37
+ func points(_ region: VNFaceLandmarkRegion2D?) -> [CGPoint] {
38
+ guard let region, region.pointCount > 0 else { return [] }
39
+ return region.pointsInImage(imageSize: imageSize).map {
40
+ CGPoint(x: $0.x, y: imageSize.height - $0.y)
41
+ }
42
+ }
43
+ func centroid(_ pts: [CGPoint]) -> CGPoint? {
44
+ guard !pts.isEmpty else { return nil }
45
+ let sum = pts.reduce(CGPoint.zero) { CGPoint(x: $0.x + $1.x, y: $0.y + $1.y) }
46
+ return CGPoint(x: sum.x / CGFloat(pts.count), y: sum.y / CGFloat(pts.count))
47
+ }
48
+
49
+ let landmarks = observation.landmarks
50
+ let eyeA = centroid(points(landmarks?.leftPupil)) ?? centroid(points(landmarks?.leftEye))
51
+ let eyeB = centroid(points(landmarks?.rightPupil)) ?? centroid(points(landmarks?.rightEye))
52
+ // Nose tip: lowest point of the nose crest, else the nose-region centroid.
53
+ let nose = points(landmarks?.noseCrest).max { $0.y < $1.y }
54
+ ?? centroid(points(landmarks?.nose))
55
+ let lips = points(landmarks?.outerLips)
56
+ let mouthA = lips.min { $0.x < $1.x }
57
+ let mouthB = lips.max { $0.x < $1.x }
58
+
59
+ let hasAll = eyeA != nil && eyeB != nil && nose != nil && mouthA != nil && mouthB != nil
60
+
61
+ // Same geometric fallbacks FaceDetectionHelper uses for ML Kit.
62
+ let cx = box.midX, cy = box.midY
63
+ let eyes = ordered(eyeA, eyeB, cx: cx, fallbackY: cy - box.height * 0.10, half: box.width * 0.15)
64
+ let mouth = ordered(mouthA, mouthB, cx: cx, fallbackY: cy + box.height * 0.20, half: box.width * 0.10)
65
+ let noseTip = nose ?? CGPoint(x: cx, y: cy)
66
+
67
+ return DetectedFace(
68
+ landmarks: [
69
+ eyes.0.x, eyes.0.y,
70
+ eyes.1.x, eyes.1.y,
71
+ noseTip.x, noseTip.y,
72
+ mouth.0.x, mouth.0.y,
73
+ mouth.1.x, mouth.1.y
74
+ ],
75
+ boundingBox: box,
76
+ hasFullSet: hasAll
77
+ )
78
+ }
79
+
80
+ private static func ordered(
81
+ _ a: CGPoint?,
82
+ _ b: CGPoint?,
83
+ cx: CGFloat,
84
+ fallbackY: CGFloat,
85
+ half: CGFloat
86
+ ) -> (CGPoint, CGPoint) {
87
+ if let a, let b { return a.x <= b.x ? (a, b) : (b, a) }
88
+ guard let p = a ?? b else {
89
+ return (CGPoint(x: cx - half, y: fallbackY), CGPoint(x: cx + half, y: fallbackY))
90
+ }
91
+ return p.x <= cx
92
+ ? (p, CGPoint(x: cx + half, y: fallbackY))
93
+ : (CGPoint(x: cx - half, y: fallbackY), p)
94
+ }
95
+ }
@@ -0,0 +1,47 @@
1
+ # Local replacement for the CocoaPods-trunk `onnxruntime-c` 1.22.0 spec.
2
+ #
3
+ # The trunk spec downloads https://download.onnxruntime.ai/pod-archive-onnxruntime-c-1.22.0.zip,
4
+ # which has returned 404 since ~2026-11-21 (every version, not just 1.22.0), so
5
+ # `pod install` can no longer fetch it. The identical prebuilt
6
+ # onnxruntime.xcframework is also shipped inside Microsoft's official NuGet
7
+ # package Microsoft.ML.OnnxRuntime, which is what this spec downloads.
8
+ #
9
+ # Integrity: the .nupkg is pinned by SHA-256 below. Its SHA-512 was also
10
+ # verified against the packageHash nuget.org publishes for 1.22.0
11
+ # (zb3eqkL6hHPGzZgArsuTH9VWdUs4ooKTJHBXF6ZZfQsPvzModaAEv3u69zwtqKuwUJ/DPc8i+uKoyXMzdwqrPg==).
12
+ #
13
+ # Keep the version in sync with onnxruntime-android in
14
+ # android/build.gradle (of react-native-face-match-sdk).
15
+ Pod::Spec.new do |s|
16
+ s.name = 'onnxruntime-c'
17
+ s.version = '1.22.0'
18
+ s.summary = 'ONNX Runtime C/C++ Pod'
19
+ s.description = 'A pod for the ONNX Runtime C/C++ library, sourced from the official NuGet package.'
20
+ s.homepage = 'https://onnxruntime.ai'
21
+ s.license = { :type => 'MIT', :file => 'LICENSE' }
22
+ s.authors = { 'ONNX Runtime' => 'onnxruntime@microsoft.com' }
23
+ s.platforms = { :ios => '15.1' }
24
+
25
+ s.source = {
26
+ :http => "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/#{s.version}/microsoft.ml.onnxruntime.#{s.version}.nupkg",
27
+ :type => :zip,
28
+ :sha256 => 'd571e63a2329baacb713f441e65ad75284de354db6e1ac435fe4bebbb417986a'
29
+ }
30
+
31
+ # The .nupkg carries every platform (Windows, Linux, Android, ...). Unpack only
32
+ # the iOS xcframework and drop everything else to keep the Pods dir small.
33
+ s.prepare_command = <<-CMD
34
+ set -e
35
+ unzip -q -o runtimes/ios/native/onnxruntime.xcframework.zip
36
+ find . -mindepth 1 -maxdepth 1 ! -name onnxruntime.xcframework ! -name LICENSE -exec rm -rf {} +
37
+ CMD
38
+
39
+ s.vendored_frameworks = 'onnxruntime.xcframework'
40
+ s.preserve_paths = ['LICENSE']
41
+ s.static_framework = true
42
+ s.weak_frameworks = ['CoreML']
43
+ s.libraries = 'c++'
44
+ s.pod_target_xcconfig = {
45
+ 'OTHER_CPLUSPLUSFLAGS' => '-fvisibility=hidden -fvisibility-inlines-hidden'
46
+ }
47
+ end
Binary file
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "react-native-face-match-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Offline on-device face liveness, anti-spoofing and face matching for React Native (Android and iOS).",
5
+ "main": "src/index.ts",
6
+ "types": "src/index.ts",
7
+ "react-native": "src/index.ts",
8
+ "source": "src/index.ts",
9
+ "files": [
10
+ "src",
11
+ "android/build.gradle",
12
+ "android/consumer-rules.pro",
13
+ "android/src/main",
14
+ "ios/Sources",
15
+ "models",
16
+ "ios/onnxruntime-c.podspec",
17
+ "FaceMatch.podspec",
18
+ "react-native.config.js",
19
+ "README.md"
20
+ ],
21
+ "keywords": [
22
+ "react-native",
23
+ "face-match",
24
+ "face-recognition",
25
+ "liveness",
26
+ "anti-spoofing",
27
+ "android",
28
+ "ios"
29
+ ],
30
+ "author": "androidmasterid",
31
+ "license": "UNLICENSED",
32
+ "private": false,
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "peerDependencies": {
37
+ "react": "*",
38
+ "react-native": ">=0.76.0"
39
+ }
40
+ }
@@ -0,0 +1,16 @@
1
+ // Autolinking config: the app needs no manual Gradle include, no
2
+ // MainApplication registration and no Podfile entry for the FaceMatch pod.
3
+ module.exports = {
4
+ dependency: {
5
+ platforms: {
6
+ android: {
7
+ sourceDir: './android',
8
+ packageImportPath: 'import com.facematch.sdk.FaceMatchPackage;',
9
+ packageInstance: 'new FaceMatchPackage()',
10
+ },
11
+ ios: {
12
+ podspecPath: require('path').join(__dirname, 'FaceMatch.podspec'),
13
+ },
14
+ },
15
+ },
16
+ };
@@ -0,0 +1,75 @@
1
+ import React, {forwardRef, useImperativeHandle, useRef} from 'react';
2
+ import {
3
+ findNodeHandle,
4
+ requireNativeComponent,
5
+ UIManager,
6
+ type NativeSyntheticEvent,
7
+ type ViewProps,
8
+ } from 'react-native';
9
+ import type {
10
+ CaptureResult,
11
+ FaceLanguage,
12
+ FaceMatchError,
13
+ FaceState,
14
+ LivenessAction,
15
+ LivenessState,
16
+ } from './types';
17
+
18
+ export type FaceCameraHandle = {
19
+ startCamera(): void;
20
+ stopCamera(): void;
21
+ capture(): void;
22
+ startLiveness(actions?: LivenessAction[]): void;
23
+ };
24
+
25
+ export type FaceCameraProps = ViewProps & {
26
+ autoStart?: boolean;
27
+ requireLiveness?: boolean;
28
+ autoCaptureOnLiveness?: boolean;
29
+ antiSpoofThreshold?: number;
30
+ brightenOnLowLight?: boolean;
31
+ voiceLanguage?: FaceLanguage;
32
+ voiceGender?: 'female' | 'male';
33
+ onFaceState?: (event: NativeSyntheticEvent<FaceState>) => void;
34
+ onLiveness?: (event: NativeSyntheticEvent<LivenessState>) => void;
35
+ onCapture?: (event: NativeSyntheticEvent<CaptureResult>) => void;
36
+ onError?: (event: NativeSyntheticEvent<FaceMatchError>) => void;
37
+ onCameraState?: (
38
+ event: NativeSyntheticEvent<{state: 'started' | 'stopped'}>,
39
+ ) => void;
40
+ };
41
+
42
+ const COMPONENT_NAME = 'FaceCameraView';
43
+ const NativeFaceCameraView = requireNativeComponent<FaceCameraProps>(COMPONENT_NAME);
44
+
45
+ export const FaceCamera = forwardRef<FaceCameraHandle, FaceCameraProps>(
46
+ function FaceCamera(props, forwardedRef) {
47
+ const nativeRef = useRef<React.ElementRef<typeof NativeFaceCameraView>>(null);
48
+
49
+ const dispatch = (commandName: string, args: unknown[] = []) => {
50
+ const handle = findNodeHandle(nativeRef.current);
51
+ const command = UIManager.getViewManagerConfig(COMPONENT_NAME)?.Commands?.[
52
+ commandName
53
+ ];
54
+ if (handle == null || command == null) {
55
+ throw new Error(`Unable to dispatch FaceCameraView.${commandName}`);
56
+ }
57
+ UIManager.dispatchViewManagerCommand(handle, command, args);
58
+ };
59
+
60
+ useImperativeHandle(forwardedRef, () => ({
61
+ startCamera: () => dispatch('startCamera'),
62
+ stopCamera: () => dispatch('stopCamera'),
63
+ capture: () => dispatch('capture'),
64
+ // No actions => the native detector picks a fresh random challenge set:
65
+ // a blink and exactly one movement in a random order, then a neutral hold.
66
+ // Only one movement is ever drawn, so a session never asks for both a left
67
+ // and a right turn. Passing an explicit list bypasses that choice, but the
68
+ // terminal hold is still appended so auto-capture lands on a usable still.
69
+ startLiveness: (actions?: LivenessAction[]) =>
70
+ dispatch('startLiveness', [actions ?? []]),
71
+ }));
72
+
73
+ return <NativeFaceCameraView ref={nativeRef} {...props} />;
74
+ },
75
+ );
@@ -0,0 +1,66 @@
1
+ import {NativeModules, Platform} from 'react-native';
2
+ import type {
3
+ DetectionResult,
4
+ EmbeddingResult,
5
+ MatchResult,
6
+ } from './types';
7
+
8
+ type NativeFaceMatchModule = {
9
+ isModelReady(): Promise<boolean>;
10
+ pickImage(): Promise<string | null>;
11
+ detectFaces(uri: string): Promise<DetectionResult>;
12
+ generateEmbedding(uri: string): Promise<EmbeddingResult>;
13
+ generateReferenceEmbedding(uri: string): Promise<EmbeddingResult>;
14
+ compareFaces(referenceUri: string, selfieUri: string): Promise<MatchResult>;
15
+ compareFacesWithThreshold(
16
+ referenceUri: string,
17
+ selfieUri: string,
18
+ antiSpoofThreshold: number,
19
+ ): Promise<MatchResult>;
20
+ compareEmbeddings(first: number[], second: number[]): Promise<MatchResult>;
21
+ discardCapture(uri: string): Promise<boolean>;
22
+ };
23
+
24
+ const LINKING_ERROR =
25
+ `The FaceMatch native library is not linked. Rebuild the ${Platform.OS} app ` +
26
+ (Platform.OS === 'ios'
27
+ ? "after running 'pod install' (see the react-native-face-match-sdk README for the onnxruntime-c Podfile line)."
28
+ : '(autolinking registers FaceMatchPackage; remove any manual registration).');
29
+
30
+ function nativeModule(): NativeFaceMatchModule {
31
+ const module = NativeModules.FaceMatch as NativeFaceMatchModule | undefined;
32
+ if (!module) {
33
+ throw new Error(LINKING_ERROR);
34
+ }
35
+ return module;
36
+ }
37
+
38
+ /** Typed, reusable facade over the Android and iOS native bridge. */
39
+ export const FaceMatch = {
40
+ isAvailable:
41
+ (Platform.OS === 'android' || Platform.OS === 'ios') &&
42
+ NativeModules.FaceMatch != null,
43
+ isModelReady: async () => nativeModule().isModelReady(),
44
+ pickImage: async () => nativeModule().pickImage(),
45
+ detectFaces: async (uri: string) => nativeModule().detectFaces(uri),
46
+ generateEmbedding: async (uri: string) => nativeModule().generateEmbedding(uri),
47
+ generateReferenceEmbedding: async (uri: string) =>
48
+ nativeModule().generateReferenceEmbedding(uri),
49
+ compareFaces: async (
50
+ referenceUri: string,
51
+ selfieUri: string,
52
+ options?: {antiSpoofThreshold?: number},
53
+ ) => {
54
+ const threshold = options?.antiSpoofThreshold;
55
+ return threshold == null
56
+ ? nativeModule().compareFaces(referenceUri, selfieUri)
57
+ : nativeModule().compareFacesWithThreshold(
58
+ referenceUri,
59
+ selfieUri,
60
+ threshold,
61
+ );
62
+ },
63
+ compareEmbeddings: async (first: number[], second: number[]) =>
64
+ nativeModule().compareEmbeddings(first, second),
65
+ discardCapture: async (uri: string) => nativeModule().discardCapture(uri),
66
+ };
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export {FaceMatch} from './FaceMatch';
2
+ export {FaceCamera} from './FaceCameraView';
3
+ export type {FaceCameraHandle, FaceCameraProps} from './FaceCameraView';
4
+ export type * from './types';
package/src/types.ts ADDED
@@ -0,0 +1,87 @@
1
+ export type LivenessAction =
2
+ | 'blink'
3
+ | 'smile'
4
+ | 'left'
5
+ | 'right'
6
+ | 'up'
7
+ | 'near'
8
+ | 'far'
9
+ | 'hold';
10
+
11
+ export type FaceLanguage = 'en' | 'hi' | 'none';
12
+
13
+ export type MatchStatus = 'match' | 'possible_match' | 'no_match';
14
+
15
+ export type MatchResult = {
16
+ similarityScore: number;
17
+ status: MatchStatus;
18
+ label: string;
19
+ isMatch: boolean;
20
+ };
21
+
22
+ export type FaceBounds = {
23
+ left: number;
24
+ top: number;
25
+ right: number;
26
+ bottom: number;
27
+ hasFullLandmarkSet: boolean;
28
+ };
29
+
30
+ export type DetectionResult = {
31
+ faceCount: number;
32
+ faces: FaceBounds[];
33
+ };
34
+
35
+ export type EmbeddingResult = {
36
+ faceCount: number;
37
+ embedding: number[];
38
+ };
39
+
40
+ export type FaceState = {
41
+ hasFace: boolean;
42
+ faceCount: number;
43
+ hasMultipleFaces: boolean;
44
+ isPositioned: boolean;
45
+ isGoodPose: boolean;
46
+ yaw: number;
47
+ pitch: number;
48
+ roll: number;
49
+ leftEyeOpenProbability?: number;
50
+ rightEyeOpenProbability?: number;
51
+ antiSpoofStatus?: 'real' | 'spoof' | 'error';
52
+ antiSpoofRealScore?: number;
53
+ antiSpoofThreshold?: number;
54
+ lowLight?: boolean;
55
+ luminance?: number;
56
+ };
57
+
58
+ export type LivenessState = {
59
+ currentAction?: LivenessAction;
60
+ completedActions: LivenessAction[];
61
+ /** English instruction text (kept for logging / fallback). */
62
+ instruction: string;
63
+ /** Stable prompt identifier — map this to your own copy if needed. */
64
+ promptKey?: string;
65
+ /** Prompt in English. */
66
+ promptEn?: string;
67
+ /** Prompt in Hindi (Devanagari). */
68
+ promptHi?: string;
69
+ isComplete: boolean;
70
+ /** Confidence toward completing the current action, 0..1. */
71
+ actionProgress?: number;
72
+ /** Zero-based index of the step in progress (equals stepCount once complete). */
73
+ stepIndex?: number;
74
+ /** Total number of liveness steps in the active challenge. */
75
+ stepCount?: number;
76
+ };
77
+
78
+ export type CaptureResult = EmbeddingResult & {
79
+ uri: string;
80
+ width: number;
81
+ height: number;
82
+ };
83
+
84
+ export type FaceMatchError = {
85
+ code: string;
86
+ message: string;
87
+ };