-PreactNativeArchitectures=x86_64
28 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
29 |
30 | # Use this property to enable support to the new architecture.
31 | # This will allow you to use TurboModules and the Fabric render in
32 | # your application. You should enable this flag either if you want
33 | # to write custom TurboModules/Fabric components OR use libraries that
34 | # are providing them.
35 | newArchEnabled=true
36 |
37 | # Use this property to enable or disable the Hermes JS engine.
38 | # If set to false, you will be using JSC instead.
39 | hermesEnabled=true
40 |
41 | newArchEnabled=true
--------------------------------------------------------------------------------
/react-native-credentials-manager.podspec:
--------------------------------------------------------------------------------
1 | require "json"
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4 | folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
5 |
6 | Pod::Spec.new do |s|
7 | s.name = "react-native-credentials-manager"
8 | s.version = package["version"]
9 | s.summary = package["description"]
10 | s.homepage = package["homepage"]
11 | s.license = package["license"]
12 | s.authors = package["author"]
13 |
14 | s.platforms = { :ios => "15.1" }
15 | s.source = { :git => "https://github.com/benjamineruvieru/react-native-credentials-manager.git", :tag => "#{s.version}" }
16 |
17 | s.source_files = "ios/**/*.{h,m,mm,cpp}"
18 | s.private_header_files = "ios/generated/**/*.h"
19 |
20 | # iOS frameworks for credential management
21 | s.frameworks = 'AuthenticationServices', 'LocalAuthentication', 'Security'
22 |
23 | # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
24 | # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
25 | if respond_to?(:install_modules_dependencies, true)
26 | install_modules_dependencies(s)
27 | else
28 | s.dependency "React-Core"
29 |
30 | # Don't install the dependencies when we run `pod install` in the old architecture.
31 | if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
32 | s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
33 | s.pod_target_xcconfig = {
34 | "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
35 | "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
36 | "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
37 | }
38 | s.dependency "React-Codegen"
39 | s.dependency "RCT-Folly"
40 | s.dependency "RCTRequired"
41 | s.dependency "RCTTypeSafety"
42 | s.dependency "ReactCommon/turbomodule/core"
43 | end
44 | end
45 | end
46 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
22 |
23 |
24 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/example/src/helpers/passkeyTestHelper.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Generates a proper base64 challenge string
3 | * @returns A valid base64-encoded challenge string
4 | */
5 | export function generateValidChallenge(): string {
6 | // Generate random bytes
7 | const randomBytes = new Uint8Array(32);
8 | for (let i = 0; i < randomBytes.length; i++) {
9 | randomBytes[i] = Math.floor(Math.random() * 256);
10 | }
11 |
12 | // Convert to base64
13 | return bytesToBase64(randomBytes);
14 | }
15 |
16 | /**
17 | * Convert Uint8Array to base64 string
18 | */
19 | function bytesToBase64(bytes: Uint8Array): string {
20 | const binString = Array.from(bytes)
21 | .map((byte) => String.fromCharCode(byte))
22 | .join('');
23 |
24 | return btoa(binString);
25 | }
26 |
27 | /**
28 | * Generate a valid RP ID for testing
29 | */
30 | export function getTestRpId(): string {
31 | return 'www.benjamineruvieru.com';
32 | }
33 |
34 | /**
35 | * Generate a valid registration request for testing
36 | */
37 | export function generateTestRegistrationRequest(
38 | username: string = 'testuser'
39 | ): any {
40 | const userId = bytesToBase64(
41 | new TextEncoder().encode(
42 | `user_id_${Math.random().toString(36).substring(2, 15)}`
43 | )
44 | );
45 |
46 | return {
47 | challenge: generateValidChallenge(),
48 | rp: {
49 | name: 'Test App',
50 | id: getTestRpId(),
51 | },
52 | user: {
53 | id: userId,
54 | name: username,
55 | displayName: username,
56 | },
57 | pubKeyCredParams: [
58 | {
59 | type: 'public-key',
60 | alg: -7, // ES256
61 | },
62 | {
63 | type: 'public-key',
64 | alg: -257, // RS256
65 | },
66 | ],
67 | timeout: 60000, // 1 minute is usually enough for testing
68 | attestation: 'none',
69 | excludeCredentials: [],
70 | authenticatorSelection: {
71 | residentKey: 'preferred',
72 | requireResidentKey: false,
73 | userVerification: 'preferred',
74 | authenticatorAttachment: 'platform',
75 | },
76 | };
77 | }
78 |
79 | /**
80 | * Generate a valid authentication request for testing
81 | */
82 | export function generateTestAuthenticationRequest(): any {
83 | return {
84 | challenge: generateValidChallenge(),
85 | timeout: 60000,
86 | userVerification: 'required',
87 | rpId: getTestRpId(),
88 | };
89 | }
90 |
--------------------------------------------------------------------------------
/android/src/main/java/com/credentialsmanager/handlers/ErrorHandler.kt:
--------------------------------------------------------------------------------
1 | package com.credentialsmanager.handlers
2 |
3 | import android.util.Log
4 | import androidx.credentials.exceptions.CreateCredentialCancellationException
5 | import androidx.credentials.exceptions.CreateCredentialCustomException
6 | import androidx.credentials.exceptions.CreateCredentialException
7 | import androidx.credentials.exceptions.CreateCredentialInterruptedException
8 | import androidx.credentials.exceptions.CreateCredentialProviderConfigurationException
9 | import androidx.credentials.exceptions.CreateCredentialUnknownException
10 | import androidx.credentials.exceptions.GetCredentialCancellationException
11 | import androidx.credentials.exceptions.GetCredentialException
12 | import androidx.credentials.exceptions.GetCredentialInterruptedException
13 | import androidx.credentials.exceptions.GetCredentialUnknownException
14 | import androidx.credentials.exceptions.publickeycredential.CreatePublicKeyCredentialDomException
15 |
16 | object ErrorHandler {
17 | fun handleCredentialError(e: CreateCredentialException) {
18 | when (e) {
19 | is CreatePublicKeyCredentialDomException -> {
20 | Log.d("CredentialManager", "passkey DOM errors")
21 | }
22 | is CreateCredentialCancellationException -> {
23 | Log.d("CredentialManager", "User cancelled")
24 | }
25 | is CreateCredentialInterruptedException -> {
26 | Log.d("CredentialManager", "Retry process")
27 | }
28 | is CreateCredentialProviderConfigurationException -> {
29 | Log.d("CredentialManager", "Missing provider configuration")
30 | }
31 | is CreateCredentialUnknownException -> {
32 | Log.d("CredentialManager", "Unknown error")
33 | }
34 | is CreateCredentialCustomException -> {
35 | Log.d("CredentialManager", "Custom credential error")
36 | }
37 | else -> Log.w("CredentialManager", "Unexpected exception type ${e::class.java.name}")
38 | }
39 | }
40 |
41 | fun handleGetCredentialError(e: GetCredentialException) {
42 | when (e) {
43 | is GetCredentialCancellationException -> {
44 | Log.d("CredentialManager", "GetCredentialCancellationException")
45 | }
46 | is GetCredentialInterruptedException -> {
47 | Log.d("CredentialManager", "User interputted")
48 | }
49 | is GetCredentialUnknownException -> {
50 | Log.d("CredentialManager", "Unknown error")
51 | }
52 |
53 | else -> Log.w("CredentialManager", "Unexpected exception type ${e::class.java.name}")
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | React Native Credentials Manager
3 |
4 |
5 | 
6 |
7 | A React Native library that implements the [Credential Manager](https://developer.android.com/identity/sign-in/credential-manager) API for Android and [AuthenticationServices](https://developer.apple.com/documentation/authenticationservices) for iOS. This library allows you to manage passwords, passkeys and platform-specific sign-in (Google Sign-In on Android, Apple Sign In on iOS) in your React Native applications.
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 | ## Platform Support
22 |
23 | - ✅ **Android**: Implementation with Credential Manager API (Android 4.4+ / API 19+)
24 | - **Android 4.4+ (API 19+)**: Username/password storage and federated sign-in (Google Sign-In)
25 | - **Android 9+ (API 28+)**: Full passkey (FIDO2/WebAuthn) support
26 | - ✅ **iOS**: Full implementation with AuthenticationServices (iOS 16.0+)
27 |
28 | ### Platform-Specific Features
29 |
30 | | Feature | Android | iOS |
31 | | ------------------------- | ------------------------- | --------------------------------- |
32 | | Passkeys | ✅ Credential Manager API | ✅ AuthenticationServices |
33 | | AutoFill Password Support | ✅ Credential Manager API | ✅ AuthenticationServices |
34 | | Manual Password Storage | ✅ Credential Manager API | ❌ Not supported (iOS limitation) |
35 | | Third-party Sign In | ✅ Google Sign In | ✅ Apple Sign In |
36 |
37 | > [!IMPORTANT]
38 | > 📚 **Documentation has moved!** The complete documentation is now available at [https://docs.benjamineruvieru.com/docs/react-native-credentials-manager/](https://docs.benjamineruvieru.com/docs/react-native-credentials-manager/)
39 |
40 | > [!NOTE] > **iOS Implementation**: This library strictly follows Apple's Authentication Services framework. Manual password storage is not supported on iOS as it's not part of Apple's official Authentication Services APIs. Use AutoFill passwords instead.
41 |
42 | > [!NOTE] > **Android Implementation**: Features are available based on Android version:
43 | >
44 | > - **API 19+**: Basic credential storage and Google Sign-In
45 | > - **API 28+**: Passkey support added
46 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/example/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | CFPropertyList (3.0.7)
5 | base64
6 | nkf
7 | rexml
8 | activesupport (7.1.5.1)
9 | base64
10 | benchmark (>= 0.3)
11 | bigdecimal
12 | concurrent-ruby (~> 1.0, >= 1.0.2)
13 | connection_pool (>= 2.2.5)
14 | drb
15 | i18n (>= 1.6, < 2)
16 | logger (>= 1.4.2)
17 | minitest (>= 5.1)
18 | mutex_m
19 | securerandom (>= 0.3)
20 | tzinfo (~> 2.0)
21 | addressable (2.8.7)
22 | public_suffix (>= 2.0.2, < 7.0)
23 | algoliasearch (1.27.5)
24 | httpclient (~> 2.8, >= 2.8.3)
25 | json (>= 1.5.1)
26 | atomos (0.1.3)
27 | base64 (0.2.0)
28 | benchmark (0.4.0)
29 | bigdecimal (3.1.9)
30 | claide (1.1.0)
31 | cocoapods (1.15.2)
32 | addressable (~> 2.8)
33 | claide (>= 1.0.2, < 2.0)
34 | cocoapods-core (= 1.15.2)
35 | cocoapods-deintegrate (>= 1.0.3, < 2.0)
36 | cocoapods-downloader (>= 2.1, < 3.0)
37 | cocoapods-plugins (>= 1.0.0, < 2.0)
38 | cocoapods-search (>= 1.0.0, < 2.0)
39 | cocoapods-trunk (>= 1.6.0, < 2.0)
40 | cocoapods-try (>= 1.1.0, < 2.0)
41 | colored2 (~> 3.1)
42 | escape (~> 0.0.4)
43 | fourflusher (>= 2.3.0, < 3.0)
44 | gh_inspector (~> 1.0)
45 | molinillo (~> 0.8.0)
46 | nap (~> 1.0)
47 | ruby-macho (>= 2.3.0, < 3.0)
48 | xcodeproj (>= 1.23.0, < 2.0)
49 | cocoapods-core (1.15.2)
50 | activesupport (>= 5.0, < 8)
51 | addressable (~> 2.8)
52 | algoliasearch (~> 1.0)
53 | concurrent-ruby (~> 1.1)
54 | fuzzy_match (~> 2.0.4)
55 | nap (~> 1.0)
56 | netrc (~> 0.11)
57 | public_suffix (~> 4.0)
58 | typhoeus (~> 1.0)
59 | cocoapods-deintegrate (1.0.5)
60 | cocoapods-downloader (2.1)
61 | cocoapods-plugins (1.0.0)
62 | nap
63 | cocoapods-search (1.0.1)
64 | cocoapods-trunk (1.6.0)
65 | nap (>= 0.8, < 2.0)
66 | netrc (~> 0.11)
67 | cocoapods-try (1.2.0)
68 | colored2 (3.1.2)
69 | concurrent-ruby (1.3.3)
70 | connection_pool (2.5.0)
71 | drb (2.2.1)
72 | escape (0.0.4)
73 | ethon (0.16.0)
74 | ffi (>= 1.15.0)
75 | ffi (1.17.1)
76 | fourflusher (2.3.1)
77 | fuzzy_match (2.0.4)
78 | gh_inspector (1.1.3)
79 | httpclient (2.8.3)
80 | i18n (1.14.7)
81 | concurrent-ruby (~> 1.0)
82 | json (2.9.1)
83 | logger (1.6.5)
84 | minitest (5.25.4)
85 | molinillo (0.8.0)
86 | mutex_m (0.3.0)
87 | nanaimo (0.3.0)
88 | nap (1.1.0)
89 | netrc (0.11.0)
90 | nkf (0.2.0)
91 | public_suffix (4.0.7)
92 | rexml (3.4.0)
93 | ruby-macho (2.5.1)
94 | securerandom (0.3.2)
95 | typhoeus (1.4.1)
96 | ethon (>= 0.9.0)
97 | tzinfo (2.0.6)
98 | concurrent-ruby (~> 1.0)
99 | xcodeproj (1.25.1)
100 | CFPropertyList (>= 2.3.3, < 4.0)
101 | atomos (~> 0.1.3)
102 | claide (>= 1.0.2, < 2.0)
103 | colored2 (~> 3.1)
104 | nanaimo (~> 0.3.0)
105 | rexml (>= 3.3.6, < 4.0)
106 |
107 | PLATFORMS
108 | ruby
109 |
110 | DEPENDENCIES
111 | activesupport (>= 6.1.7.5, != 7.1.0)
112 | cocoapods (>= 1.13, != 1.15.1, != 1.15.0)
113 | concurrent-ruby (< 1.3.4)
114 | xcodeproj (< 1.26.0)
115 |
116 | RUBY VERSION
117 | ruby 2.7.6p219
118 |
119 | BUNDLED WITH
120 | 2.1.4
121 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.getExtOrDefault = {name ->
3 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['CredentialsManager_' + name]
4 | }
5 |
6 | repositories {
7 | google()
8 | mavenCentral()
9 | }
10 |
11 | dependencies {
12 | classpath "com.android.tools.build:gradle:8.7.2"
13 | // noinspection DifferentKotlinGradleVersion
14 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
15 | }
16 | }
17 |
18 |
19 | def isNewArchitectureEnabled() {
20 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
21 | }
22 |
23 | apply plugin: "com.android.library"
24 | apply plugin: "kotlin-android"
25 |
26 | if (isNewArchitectureEnabled()) {
27 | apply plugin: "com.facebook.react"
28 | }
29 |
30 | def getExtOrIntegerDefault(name) {
31 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["CredentialsManager_" + name]).toInteger()
32 | }
33 |
34 | def supportsNamespace() {
35 | def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
36 | def major = parsed[0].toInteger()
37 | def minor = parsed[1].toInteger()
38 |
39 | // Namespace support was added in 7.3.0
40 | return (major == 7 && minor >= 3) || major >= 8
41 | }
42 |
43 | android {
44 | if (supportsNamespace()) {
45 | namespace "com.credentialsmanager"
46 |
47 | sourceSets {
48 | main {
49 | manifest.srcFile "src/main/AndroidManifestNew.xml"
50 | }
51 | }
52 | }
53 |
54 | compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
55 |
56 | defaultConfig {
57 | minSdkVersion getExtOrIntegerDefault("minSdkVersion")
58 | targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
59 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
60 |
61 | }
62 |
63 | buildFeatures {
64 | buildConfig true
65 | }
66 |
67 | buildTypes {
68 | release {
69 | minifyEnabled false
70 | }
71 | }
72 |
73 | lintOptions {
74 | disable "GradleCompatible"
75 | }
76 |
77 | compileOptions {
78 | sourceCompatibility JavaVersion.VERSION_1_8
79 | targetCompatibility JavaVersion.VERSION_1_8
80 | }
81 |
82 | sourceSets {
83 | main {
84 | if (isNewArchitectureEnabled()) {
85 | java.srcDirs += ['src/newarch',"generated/java",]
86 | } else {
87 | java.srcDirs += ['src/oldarch']
88 | }
89 | }
90 | }
91 | }
92 |
93 | repositories {
94 | mavenCentral()
95 | google()
96 | }
97 |
98 | def kotlin_version = getExtOrDefault("kotlinVersion")
99 |
100 | dependencies {
101 | implementation "com.facebook.react:react-android"
102 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
103 | implementation("androidx.credentials:credentials:1.6.0-alpha02")
104 |
105 | implementation("androidx.credentials:credentials-play-services-auth:1.6.0-alpha02")
106 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4"
107 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"
108 | implementation "com.google.android.libraries.identity.googleid:googleid:1.1.1"
109 | }
110 |
111 | if (isNewArchitectureEnabled()) {
112 | react {
113 | jsRootDir = file("../src/")
114 | libraryName = "CredentialsManager"
115 | codegenJavaPackageName = "com.credentialsmanager"
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/NativeCredentialsManager.ts:
--------------------------------------------------------------------------------
1 | import type { TurboModule } from 'react-native';
2 | import { TurboModuleRegistry } from 'react-native';
3 |
4 | export type SignInOption =
5 | | 'passkeys'
6 | | 'password'
7 | | 'google-signin'
8 | | 'apple-signin';
9 |
10 | // Password authentication types
11 | type CredObject = {
12 | username: string;
13 | password: string;
14 | };
15 |
16 | export type PasswordCredential = {
17 | type: 'password';
18 | username: string;
19 | password: string;
20 | };
21 |
22 | // Passkey authentication types
23 | export type PasskeyCredential = {
24 | type: 'passkey';
25 | authenticationResponseJson: string;
26 | };
27 |
28 | // Google Sign In types
29 | type GoogleSignInParams = {
30 | nonce: string;
31 | serverClientId: string;
32 | autoSelectEnabled: boolean;
33 | filterByAuthorizedAccounts?: boolean;
34 | };
35 |
36 | export type GoogleCredential = {
37 | type: 'google-signin';
38 | id: string;
39 | idToken: string;
40 | displayName?: string;
41 | familyName?: string;
42 | givenName?: string;
43 | profilePicture?: string;
44 | phoneNumber?: string;
45 | };
46 |
47 | // Apple Sign In types
48 | type AppleSignInParams = {
49 | nonce: string;
50 | requestedScopes: string[];
51 | };
52 |
53 | export type AppleCredential = {
54 | type: 'apple-signin';
55 | id: string;
56 | idToken: string;
57 | displayName?: string;
58 | familyName?: string;
59 | givenName?: string;
60 | email?: string;
61 | };
62 |
63 | // Combined credential type
64 | export type Credential =
65 | | PasskeyCredential
66 | | PasswordCredential
67 | | GoogleCredential
68 | | AppleCredential;
69 |
70 | // Native module interface
71 | export interface Spec extends TurboModule {
72 | /**
73 | * Sign up with passkeys (supported on both Android and iOS)
74 | * @param requestJson WebAuthn request object
75 | * @param preferImmediatelyAvailableCredentials Android-specific parameter, ignored on iOS
76 | */
77 | signUpWithPasskeys(
78 | requestJson: Object,
79 | preferImmediatelyAvailableCredentials: boolean
80 | ): Promise;
81 |
82 | /**
83 | * Sign up with password (Android only - not supported on iOS)
84 | * iOS will reject with UNSUPPORTED_OPERATION error
85 | */
86 | signUpWithPassword(credObject: CredObject): Promise;
87 |
88 | /**
89 | * Sign in with various methods
90 | * - 'passkeys': Supported on both platforms
91 | * - 'password': Supported on android
92 | * - 'google-signin': Android only
93 | * - 'apple-signin': iOS only (not available on Android)
94 | */
95 | signIn(
96 | options: SignInOption[],
97 | params: {
98 | passkeys?: Object;
99 | googleSignIn?: GoogleSignInParams; // Used only on Android
100 | appleSignIn?: AppleSignInParams; // Used only on iOS
101 | }
102 | ): Promise;
103 |
104 | /**
105 | * Sign up with Google (Android-specific implementation)
106 | */
107 | signUpWithGoogle(params: GoogleSignInParams): Promise;
108 |
109 | /**
110 | * Sign up with Apple (iOS-specific implementation)
111 | * Will reject with UNSUPPORTED_OPERATION on Android
112 | */
113 | signUpWithApple(params: AppleSignInParams): Promise;
114 |
115 | /**
116 | * Sign out (behavior varies by platform)
117 | * On iOS, this is a no-op as AuthenticationServices doesn't provide a sign-out method
118 | */
119 | signOut(): Promise;
120 | }
121 |
122 | export default TurboModuleRegistry.getEnforcing('CredentialsManager');
123 |
--------------------------------------------------------------------------------
/example/ios/CredentialsManagerExample.xcodeproj/xcshareddata/xcschemes/CredentialsManagerExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).
2 |
3 | # Getting Started
4 |
5 | > **Note**: Make sure you have completed the [Set Up Your Environment](https://reactnative.dev/docs/set-up-your-environment) guide before proceeding.
6 |
7 | ## Step 1: Start Metro
8 |
9 | First, you will need to run **Metro**, the JavaScript build tool for React Native.
10 |
11 | To start the Metro dev server, run the following command from the root of your React Native project:
12 |
13 | ```sh
14 | # Using npm
15 | npm start
16 |
17 | # OR using Yarn
18 | yarn start
19 | ```
20 |
21 | ## Step 2: Build and run your app
22 |
23 | With Metro running, open a new terminal window/pane from the root of your React Native project, and use one of the following commands to build and run your Android or iOS app:
24 |
25 | ### Android
26 |
27 | ```sh
28 | # Using npm
29 | npm run android
30 |
31 | # OR using Yarn
32 | yarn android
33 | ```
34 |
35 | ### iOS
36 |
37 | For iOS, remember to install CocoaPods dependencies (this only needs to be run on first clone or after updating native deps).
38 |
39 | The first time you create a new project, run the Ruby bundler to install CocoaPods itself:
40 |
41 | ```sh
42 | bundle install
43 | ```
44 |
45 | Then, and every time you update your native dependencies, run:
46 |
47 | ```sh
48 | bundle exec pod install
49 | ```
50 |
51 | For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html).
52 |
53 | ```sh
54 | # Using npm
55 | npm run ios
56 |
57 | # OR using Yarn
58 | yarn ios
59 | ```
60 |
61 | If everything is set up correctly, you should see your new app running in the Android Emulator, iOS Simulator, or your connected device.
62 |
63 | This is one way to run your app — you can also build it directly from Android Studio or Xcode.
64 |
65 | ## Step 3: Modify your app
66 |
67 | Now that you have successfully run the app, let's make changes!
68 |
69 | Open `App.tsx` in your text editor of choice and make some changes. When you save, your app will automatically update and reflect these changes — this is powered by [Fast Refresh](https://reactnative.dev/docs/fast-refresh).
70 |
71 | When you want to forcefully reload, for example to reset the state of your app, you can perform a full reload:
72 |
73 | - **Android**: Press the R key twice or select **"Reload"** from the **Dev Menu**, accessed via Ctrl + M (Windows/Linux) or Cmd ⌘ + M (macOS).
74 | - **iOS**: Press R in iOS Simulator.
75 |
76 | ## Congratulations! :tada:
77 |
78 | You've successfully run and modified your React Native App. :partying_face:
79 |
80 | ### Now what?
81 |
82 | - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
83 | - If you're curious to learn more about React Native, check out the [docs](https://reactnative.dev/docs/getting-started).
84 |
85 | # Troubleshooting
86 |
87 | If you're having issues getting the above steps to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
88 |
89 | # Learn More
90 |
91 | To learn more about React Native, take a look at the following resources:
92 |
93 | - [React Native Website](https://reactnative.dev) - learn more about React Native.
94 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
95 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
96 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
97 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
98 |
--------------------------------------------------------------------------------
/example/ios/CredentialsManagerExample/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | import CredentialsManager from './NativeCredentialsManager';
2 | import type {
3 | Credential,
4 | GoogleCredential,
5 | AppleCredential,
6 | SignInOption,
7 | PasskeyCredential,
8 | PasswordCredential,
9 | } from './NativeCredentialsManager';
10 | import { Platform } from 'react-native';
11 |
12 | type GoogleSignInParams = {
13 | nonce?: string;
14 | serverClientId: string;
15 | autoSelectEnabled?: boolean;
16 | filterByAuthorizedAccounts?: boolean;
17 | };
18 |
19 | type AppleSignInParams = {
20 | nonce?: string;
21 | requestedScopes?: ('fullName' | 'email')[];
22 | };
23 |
24 | type CredentialMap = {
25 | 'passkeys': PasskeyCredential;
26 | 'password': PasswordCredential;
27 | 'google-signin': GoogleCredential;
28 | 'apple-signin': AppleCredential;
29 | };
30 |
31 | type SignInResult = CredentialMap[T[number]];
32 |
33 | export function signUpWithPasskeys(
34 | requestJson: Object,
35 | preferImmediatelyAvailableCredentials: boolean = false
36 | ): Promise {
37 | return CredentialsManager.signUpWithPasskeys(
38 | requestJson,
39 | preferImmediatelyAvailableCredentials
40 | );
41 | }
42 |
43 | export function signUpWithPassword({
44 | username,
45 | password,
46 | }: {
47 | username: string;
48 | password: string;
49 | }): Promise {
50 | if (Platform.OS === 'ios') {
51 | return Promise.reject(
52 | new Error(
53 | 'Manual password storage is not supported on iOS. Use AutoFill passwords through signIn method instead.'
54 | )
55 | );
56 | }
57 | return CredentialsManager.signUpWithPassword({ password, username });
58 | }
59 |
60 | export function signIn(
61 | options: T,
62 | params: {
63 | passkeys?: Object;
64 | googleSignIn?: GoogleSignInParams;
65 | appleSignIn?: AppleSignInParams;
66 | }
67 | ): Promise> {
68 | const signInParams: {
69 | passkeys?: Object;
70 | googleSignIn?: {
71 | serverClientId: string;
72 | nonce: string;
73 | autoSelectEnabled: boolean;
74 | filterByAuthorizedAccounts: boolean;
75 | };
76 | appleSignIn?: {
77 | nonce: string;
78 | requestedScopes: ('fullName' | 'email')[];
79 | };
80 | } = {
81 | passkeys: params.passkeys,
82 | };
83 |
84 | if (options.includes('google-signin')) {
85 | signInParams.googleSignIn = {
86 | serverClientId: params.googleSignIn?.serverClientId ?? '',
87 | nonce: params.googleSignIn?.nonce ?? '',
88 | autoSelectEnabled: params.googleSignIn?.autoSelectEnabled ?? true,
89 | filterByAuthorizedAccounts:
90 | params.googleSignIn?.filterByAuthorizedAccounts ?? true,
91 | };
92 | }
93 |
94 | // If we have Apple Sign In option on iOS, add Apple params
95 | if (Platform.OS === 'ios' && options.includes('apple-signin')) {
96 | signInParams.appleSignIn = {
97 | nonce: params.appleSignIn?.nonce ?? '',
98 | requestedScopes: params.appleSignIn?.requestedScopes ?? [
99 | 'fullName',
100 | 'email',
101 | ],
102 | };
103 | }
104 |
105 | return CredentialsManager.signIn([...options], signInParams) as Promise<
106 | SignInResult
107 | >;
108 | }
109 |
110 | export function signUpWithGoogle(
111 | params: GoogleSignInParams
112 | ): Promise {
113 | if (Platform.OS === 'ios') {
114 | return Promise.reject(
115 | new Error(
116 | 'Google Sign In is only available on Android. Use signUpWithApple on iOS.'
117 | )
118 | );
119 | }
120 |
121 | return CredentialsManager.signUpWithGoogle({
122 | ...params,
123 | nonce: params.nonce ?? '',
124 | autoSelectEnabled: params.autoSelectEnabled ?? true,
125 | filterByAuthorizedAccounts: params.filterByAuthorizedAccounts ?? false,
126 | });
127 | }
128 |
129 | export function signUpWithApple(
130 | params: AppleSignInParams = {}
131 | ): Promise {
132 | if (Platform.OS !== 'ios') {
133 | return Promise.reject(
134 | new Error(
135 | 'Apple Sign In is only available on iOS. Use signUpWithGoogle on Android.'
136 | )
137 | );
138 | }
139 |
140 | // Call the native signUpWithApple method directly - uses Apple's Authentication Services
141 | return CredentialsManager.signUpWithApple({
142 | nonce: params.nonce || '',
143 | requestedScopes: params.requestedScopes || ['fullName', 'email'],
144 | });
145 | }
146 |
147 | export function signOut(): Promise {
148 | return CredentialsManager.signOut();
149 | }
150 |
151 | // Export types
152 | export type {
153 | Credential,
154 | GoogleCredential,
155 | AppleCredential,
156 | SignInOption,
157 | GoogleSignInParams,
158 | AppleSignInParams,
159 | PasskeyCredential,
160 | PasswordCredential,
161 | };
162 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are always welcome, no matter how large or small!
4 |
5 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. Before contributing, please read the [code of conduct](./CODE_OF_CONDUCT.md).
6 |
7 | ## Development workflow
8 |
9 | This project is a monorepo managed using [Yarn workspaces](https://yarnpkg.com/features/workspaces). It contains the following packages:
10 |
11 | - The library package in the root directory.
12 | - An example app in the `example/` directory.
13 |
14 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
15 |
16 | ```sh
17 | yarn
18 | ```
19 |
20 | > Since the project relies on Yarn workspaces, you cannot use [`npm`](https://github.com/npm/cli) for development.
21 |
22 | The [example app](/example/) demonstrates usage of the library. You need to run it to test any changes you make.
23 |
24 | It is configured to use the local version of the library, so any changes you make to the library's source code will be reflected in the example app. Changes to the library's JavaScript code will be reflected in the example app without a rebuild, but native code changes will require a rebuild of the example app.
25 |
26 | If you want to use Android Studio or XCode to edit the native code, you can open the `example/android` or `example/ios` directories respectively in those editors. To edit the Objective-C or Swift files, open `example/ios/CredentialsManagerExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-credentials-manager`.
27 |
28 | To edit the Java or Kotlin files, open `example/android` in Android studio and find the source files at `react-native-credentials-manager` under `Android`.
29 |
30 | You can use various commands from the root directory to work with the project.
31 |
32 | To start the packager:
33 |
34 | ```sh
35 | yarn example start
36 | ```
37 |
38 | To run the example app on Android:
39 |
40 | ```sh
41 | yarn example android
42 | ```
43 |
44 | To run the example app on iOS:
45 |
46 | ```sh
47 | yarn example ios
48 | ```
49 |
50 | To confirm that the app is running with the new architecture, you can check the Metro logs for a message like this:
51 |
52 | ```sh
53 | Running "CredentialsManagerExample" with {"fabric":true,"initialProps":{"concurrentRoot":true},"rootTag":1}
54 | ```
55 |
56 | Note the `"fabric":true` and `"concurrentRoot":true` properties.
57 |
58 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
59 |
60 | ```sh
61 | yarn typecheck
62 | yarn lint
63 | ```
64 |
65 | To fix formatting errors, run the following:
66 |
67 | ```sh
68 | yarn lint --fix
69 | ```
70 |
71 | Remember to add tests for your change if possible. Run the unit tests by:
72 |
73 | ```sh
74 | yarn test
75 | ```
76 |
77 | ### Commit message convention
78 |
79 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
80 |
81 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
82 | - `feat`: new features, e.g. add new method to the module.
83 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
84 | - `docs`: changes into documentation, e.g. add usage example for the module..
85 | - `test`: adding or updating tests, e.g. add integration tests using detox.
86 | - `chore`: tooling changes, e.g. change CI config.
87 |
88 | Our pre-commit hooks verify that your commit message matches this format when committing.
89 |
90 | ### Linting and tests
91 |
92 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
93 |
94 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
95 |
96 | Our pre-commit hooks verify that the linter and tests pass when committing.
97 |
98 | ### Publishing to npm
99 |
100 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc.
101 |
102 | To publish new versions, run the following:
103 |
104 | ```sh
105 | yarn release
106 | ```
107 |
108 | ### Scripts
109 |
110 | The `package.json` file contains various scripts for common tasks:
111 |
112 | - `yarn`: setup project by installing dependencies.
113 | - `yarn typecheck`: type-check files with TypeScript.
114 | - `yarn lint`: lint files with ESLint.
115 | - `yarn test`: run unit tests with Jest.
116 | - `yarn example start`: start the Metro server for the example app.
117 | - `yarn example android`: run the example app on Android.
118 | - `yarn example ios`: run the example app on iOS.
119 |
120 | ### Sending a pull request
121 |
122 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github).
123 |
124 | When you're sending a pull request:
125 |
126 | - Prefer small pull requests focused on one change.
127 | - Verify that linters and tests are passing.
128 | - Review the documentation to make sure it looks good.
129 | - Follow the pull request template when opening a pull request.
130 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
131 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 | apply plugin: "org.jetbrains.kotlin.android"
3 | apply plugin: "com.facebook.react"
4 |
5 | /**
6 | * This is the configuration block to customize your React Native Android app.
7 | * By default you don't need to apply any configuration, just uncomment the lines you need.
8 | */
9 | react {
10 | /* Folders */
11 | // The root of your project, i.e. where "package.json" lives. Default is '../..'
12 | // root = file("../../")
13 | // The folder where the react-native NPM package is. Default is ../../node_modules/react-native
14 | // reactNativeDir = file("../../node_modules/react-native")
15 | // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
16 | // codegenDir = file("../../node_modules/@react-native/codegen")
17 | // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
18 | // cliFile = file("../../node_modules/react-native/cli.js")
19 |
20 | /* Variants */
21 | // The list of variants to that are debuggable. For those we're going to
22 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'.
23 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
24 | // debuggableVariants = ["liteDebug", "prodDebug"]
25 |
26 | /* Bundling */
27 | // A list containing the node command and its flags. Default is just 'node'.
28 | // nodeExecutableAndArgs = ["node"]
29 | //
30 | // The command to run when bundling. By default is 'bundle'
31 | // bundleCommand = "ram-bundle"
32 | //
33 | // The path to the CLI configuration file. Default is empty.
34 | // bundleConfig = file(../rn-cli.config.js)
35 | //
36 | // The name of the generated asset file containing your JS bundle
37 | // bundleAssetName = "MyApplication.android.bundle"
38 | //
39 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
40 | // entryFile = file("../js/MyApplication.android.js")
41 | //
42 | // A list of extra flags to pass to the 'bundle' commands.
43 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
44 | // extraPackagerArgs = []
45 |
46 | /* Hermes Commands */
47 | // The hermes compiler command to run. By default it is 'hermesc'
48 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
49 | //
50 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
51 | // hermesFlags = ["-O", "-output-source-map"]
52 |
53 | /* Autolinking */
54 | autolinkLibrariesWithApp()
55 | }
56 |
57 | /**
58 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
59 | */
60 | def enableProguardInReleaseBuilds = false
61 |
62 | /**
63 | * The preferred build flavor of JavaScriptCore (JSC)
64 | *
65 | * For example, to use the international variant, you can use:
66 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
67 | *
68 | * The international variant includes ICU i18n library and necessary data
69 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
70 | * give correct results when using with locales other than en-US. Note that
71 | * this variant is about 6MiB larger per architecture than default.
72 | */
73 | def jscFlavor = 'org.webkit:android-jsc:+'
74 |
75 | android {
76 | ndkVersion rootProject.ext.ndkVersion
77 | buildToolsVersion rootProject.ext.buildToolsVersion
78 | compileSdk rootProject.ext.compileSdkVersion
79 |
80 | namespace "credentialsmanager.example"
81 | defaultConfig {
82 | applicationId "credentialsmanager.example"
83 | minSdkVersion rootProject.ext.minSdkVersion
84 | targetSdkVersion rootProject.ext.targetSdkVersion
85 | versionCode 1
86 | versionName "1.0"
87 | }
88 | signingConfigs {
89 | debug {
90 | storeFile file('debug.keystore')
91 | storePassword 'android'
92 | keyAlias 'androiddebugkey'
93 | keyPassword 'android'
94 | }
95 | }
96 | buildTypes {
97 | debug {
98 | signingConfig signingConfigs.debug
99 | }
100 | release {
101 | // Caution! In production, you need to generate your own keystore file.
102 | // see https://reactnative.dev/docs/signed-apk-android.
103 | signingConfig signingConfigs.debug
104 | minifyEnabled enableProguardInReleaseBuilds
105 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
106 | }
107 | }
108 | }
109 |
110 | dependencies {
111 | // The version of react-native is set by the React Native Gradle Plugin
112 | implementation("com.facebook.react:react-android")
113 |
114 | if (hermesEnabled.toBoolean()) {
115 | implementation("com.facebook.react:hermes-android")
116 | } else {
117 | implementation jscFlavor
118 | }
119 | }
120 |
121 | def isNewArchitectureEnabled() {
122 | return rootProject.hasProperty("newArchEnabled") && rootProject.getProperty("newArchEnabled") == "true"
123 | }
124 |
125 | if (isNewArchitectureEnabled()) {
126 | // Since our library doesn't invoke codegen automatically we need to do it here.
127 | tasks.register('invokeLibraryCodegen', Exec) {
128 | workingDir "$rootDir/../../"
129 | def isWindows = System.getProperty('os.name').toLowerCase().contains('windows')
130 |
131 | if (isWindows) {
132 | commandLine 'cmd', '/c', 'npx bob build --target codegen'
133 | } else {
134 | commandLine 'sh', '-c', 'npx bob build --target codegen'
135 | }
136 | }
137 | preBuild.dependsOn invokeLibraryCodegen
138 | }
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 | merge_group:
10 | types:
11 | - checks_requested
12 |
13 | jobs:
14 | lint:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - name: Checkout
18 | uses: actions/checkout@v4
19 |
20 | - name: Setup
21 | uses: ./.github/actions/setup
22 |
23 | - name: Lint files
24 | run: yarn lint
25 |
26 | - name: Typecheck files
27 | run: yarn typecheck
28 |
29 | test:
30 | runs-on: ubuntu-latest
31 | steps:
32 | - name: Checkout
33 | uses: actions/checkout@v4
34 |
35 | - name: Setup
36 | uses: ./.github/actions/setup
37 |
38 | - name: Run unit tests
39 | run: yarn test --maxWorkers=2 --coverage
40 |
41 | build-library:
42 | runs-on: ubuntu-latest
43 | steps:
44 | - name: Checkout
45 | uses: actions/checkout@v4
46 |
47 | - name: Setup
48 | uses: ./.github/actions/setup
49 |
50 | - name: Build package
51 | run: yarn prepare
52 |
53 | build-android:
54 | runs-on: ubuntu-latest
55 | env:
56 | TURBO_CACHE_DIR: .turbo/android
57 | steps:
58 | - name: Checkout
59 | uses: actions/checkout@v4
60 |
61 | - name: Setup
62 | uses: ./.github/actions/setup
63 |
64 | - name: Cache turborepo for Android
65 | uses: actions/cache@v4
66 | with:
67 | path: ${{ env.TURBO_CACHE_DIR }}
68 | key: ${{ runner.os }}-turborepo-android-${{ hashFiles('yarn.lock') }}
69 | restore-keys: |
70 | ${{ runner.os }}-turborepo-android-
71 |
72 | - name: Check turborepo cache for Android
73 | run: |
74 | TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:android --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.find(t => t.task === 'build:android').cache.status")
75 |
76 | if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then
77 | echo "turbo_cache_hit=1" >> $GITHUB_ENV
78 | fi
79 |
80 | - name: Install JDK
81 | if: env.turbo_cache_hit != 1
82 | uses: actions/setup-java@v4
83 | with:
84 | distribution: 'zulu'
85 | java-version: '17'
86 |
87 | - name: Finalize Android SDK
88 | if: env.turbo_cache_hit != 1
89 | run: |
90 | /bin/bash -c "yes | $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses > /dev/null"
91 |
92 | - name: Cache Gradle
93 | if: env.turbo_cache_hit != 1
94 | uses: actions/cache@v4
95 | with:
96 | path: |
97 | ~/.gradle/wrapper
98 | ~/.gradle/caches
99 | key: ${{ runner.os }}-gradle-${{ hashFiles('example/android/gradle/wrapper/gradle-wrapper.properties') }}
100 | restore-keys: |
101 | ${{ runner.os }}-gradle-
102 |
103 | - name: Build example for Android
104 | env:
105 | JAVA_OPTS: '-XX:MaxHeapSize=6g'
106 | run: |
107 | yarn turbo run build:android --cache-dir="${{ env.TURBO_CACHE_DIR }}"
108 |
109 | build-ios:
110 | runs-on: macos-14
111 | env:
112 | TURBO_CACHE_DIR: .turbo/ios
113 | steps:
114 | - name: Checkout
115 | uses: actions/checkout@v4
116 |
117 | - name: Setup
118 | uses: ./.github/actions/setup
119 |
120 | - name: Setup Ruby
121 | uses: ruby/setup-ruby@v1
122 | with:
123 | ruby-version: '3.2'
124 | bundler-cache: true
125 | working-directory: example
126 |
127 | - name: Select Xcode version
128 | run: sudo xcode-select -s /Applications/Xcode_15.4.app
129 |
130 | - name: Show build environment
131 | run: |
132 | xcodebuild -version
133 | xcode-select -p
134 | clang --version
135 |
136 | - name: Cache turborepo for iOS
137 | uses: actions/cache@v4
138 | with:
139 | path: ${{ env.TURBO_CACHE_DIR }}
140 | key: ${{ runner.os }}-turborepo-ios-${{ hashFiles('yarn.lock') }}
141 | restore-keys: |
142 | ${{ runner.os }}-turborepo-ios-
143 |
144 | - name: Check turborepo cache for iOS
145 | run: |
146 | TURBO_CACHE_STATUS=$(node -p "($(yarn turbo run build:ios --cache-dir="${{ env.TURBO_CACHE_DIR }}" --dry=json)).tasks.find(t => t.task === 'build:ios').cache.status")
147 |
148 | if [[ $TURBO_CACHE_STATUS == "HIT" ]]; then
149 | echo "turbo_cache_hit=1" >> $GITHUB_ENV
150 | fi
151 |
152 | - name: Restore cocoapods
153 | if: env.turbo_cache_hit != 1
154 | id: cocoapods-cache
155 | uses: actions/cache/restore@v4
156 | with:
157 | path: |
158 | **/ios/Pods
159 | key: ${{ runner.os }}-cocoapods-${{ hashFiles('example/ios/Podfile.lock', 'example/ios/Podfile') }}
160 | restore-keys: |
161 | ${{ runner.os }}-cocoapods-
162 |
163 | - name: Install cocoapods
164 | if: env.turbo_cache_hit != 1 && steps.cocoapods-cache.outputs.cache-hit != 'true'
165 | run: |
166 | cd example/ios
167 | pod install
168 | env:
169 | NO_FLIPPER: 1
170 |
171 | - name: Cache cocoapods
172 | if: env.turbo_cache_hit != 1 && steps.cocoapods-cache.outputs.cache-hit != 'true'
173 | uses: actions/cache/save@v4
174 | with:
175 | path: |
176 | **/ios/Pods
177 | key: ${{ steps.cocoapods-cache.outputs.cache-key }}
178 |
179 | - name: Clean iOS build folder
180 | if: env.turbo_cache_hit != 1
181 | run: |
182 | rm -rf example/ios/build
183 |
184 | - name: Build example for iOS
185 | run: |
186 | yarn turbo run build:ios --cache-dir="${{ env.TURBO_CACHE_DIR }}"
187 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # Contributor Covenant Code of Conduct
3 |
4 | ## Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, caste, color, religion, or sexual
11 | identity and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the overall
27 | community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or advances of
32 | any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email address,
36 | without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | [INSERT CONTACT METHOD].
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of this Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series of
87 | actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or permanent
94 | ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within the
114 | community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.1, available at
120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121 |
122 | Community Impact Guidelines were inspired by
123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124 |
125 | For answers to common questions about this code of conduct, see the FAQ at
126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127 | [https://www.contributor-covenant.org/translations][translations].
128 |
129 | [homepage]: https://www.contributor-covenant.org
130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131 | [Mozilla CoC]: https://github.com/mozilla/diversity
132 | [FAQ]: https://www.contributor-covenant.org/faq
133 | [translations]: https://www.contributor-covenant.org/translations
134 |
--------------------------------------------------------------------------------
/android/src/newarch/java/com/credentialsmanager/CredentialsManagerModule.kt:
--------------------------------------------------------------------------------
1 | package com.credentialsmanager
2 | import android.util.Log
3 | import androidx.credentials.exceptions.ClearCredentialException
4 | import androidx.credentials.exceptions.CreateCredentialException
5 | import androidx.credentials.exceptions.GetCredentialException
6 | import androidx.credentials.exceptions.NoCredentialException
7 | import com.credentialsmanager.handlers.CredentialHandler
8 | import com.credentialsmanager.handlers.ErrorHandler
9 | import com.facebook.react.bridge.Promise
10 | import com.facebook.react.bridge.ReactApplicationContext
11 | import com.facebook.react.bridge.ReadableArray
12 | import com.facebook.react.bridge.ReadableMap
13 | import kotlinx.coroutines.CoroutineScope
14 | import kotlinx.coroutines.Dispatchers
15 | import kotlinx.coroutines.launch
16 |
17 | class CredentialsManagerModule(
18 | reactContext: ReactApplicationContext,
19 | ) : NativeCredentialsManagerSpec(reactContext) {
20 | private val coroutineScope = CoroutineScope(Dispatchers.IO)
21 | private val credentialHandler = CredentialHandler(reactContext)
22 |
23 | private var implementation: CredentialsManagerModuleImpl = CredentialsManagerModuleImpl()
24 |
25 | override fun getName(): String = CredentialsManagerModuleImpl.NAME
26 |
27 | override fun signUpWithPasskeys(
28 | requestJson: ReadableMap,
29 | preferImmediatelyAvailableCredentials: Boolean,
30 | promise: Promise,
31 | ) {
32 | val jsonString = requestJson.toString()
33 |
34 | coroutineScope.launch {
35 | try {
36 | val response =
37 | credentialHandler.createPasskey(
38 | jsonString,
39 | preferImmediatelyAvailableCredentials,
40 | )
41 |
42 | response?.let {
43 | promise.resolve(it)
44 | } ?: promise.reject("ERROR", "No response received")
45 | } catch (e: CreateCredentialException) {
46 | ErrorHandler.handleCredentialError(e)
47 | promise.reject("ERROR", e.message.toString())
48 | }
49 | }
50 | }
51 |
52 | override fun signUpWithPassword(credObject: ReadableMap, promise: Promise) {
53 | val username = credObject.getString("username") ?: ""
54 | val password = credObject.getString("password") ?: ""
55 |
56 | if (username.isEmpty()) {
57 | promise.reject("INVALID_USERNAME", "Username cannot be empty")
58 | return
59 | }
60 |
61 | if (password.isEmpty()) {
62 | promise.reject("INVALID_PASSWORD", "Password cannot be empty")
63 | return
64 | }
65 |
66 | coroutineScope.launch {
67 | try {
68 | credentialHandler.createPassword(username, password)
69 |
70 | // Create success response
71 | val result = mapOf(
72 | "type" to "password",
73 | "username" to username,
74 | "success" to true
75 | )
76 | promise.resolve(result)
77 | } catch (e: CreateCredentialException) {
78 | ErrorHandler.handleCredentialError(e)
79 | promise.reject("CREDENTIAL_ERROR", e.message.toString())
80 | }
81 | }
82 | }
83 |
84 | override fun signIn(
85 | options: ReadableArray,
86 | params: ReadableMap,
87 | promise: Promise,
88 | ) {
89 | coroutineScope.launch {
90 | try {
91 | val data = credentialHandler.signIn(options = options, params = params)
92 | promise.resolve(data)
93 | } catch (e: GetCredentialException) {
94 | Log.e("CredentialManager", "Error during sign out", e)
95 | promise.reject("ERROR", e.message.toString())
96 | }
97 | }
98 | }
99 |
100 |
101 | override fun signOut(promise: Promise) {
102 | coroutineScope.launch {
103 | try {
104 | credentialHandler.signOut()
105 | promise.resolve(null)
106 | } catch (e: ClearCredentialException) {
107 | Log.e("CredentialManager", "Error during sign out", e)
108 | promise.reject("ERROR", e.message.toString())
109 | }
110 | }
111 | }
112 |
113 | override fun signUpWithGoogle(
114 | requestObject: ReadableMap,
115 | promise: Promise,
116 | ) {
117 | val nonce = requestObject.getString("nonce") ?: ""
118 | val serverClientId = requestObject.getString("serverClientId") ?: ""
119 | val autoSelectEnabled = requestObject.getBoolean("autoSelectEnabled")
120 | // Default to false for sign-up (show all accounts)
121 | val filterByAuthorizedAccounts = if (requestObject.hasKey("filterByAuthorizedAccounts")) {
122 | requestObject.getBoolean("filterByAuthorizedAccounts")
123 | } else {
124 | false
125 | }
126 |
127 | val googleIdOption =
128 | credentialHandler.getGoogleId(
129 | setFilterByAuthorizedAccounts = filterByAuthorizedAccounts,
130 | nonce = nonce,
131 | serverClientId = serverClientId,
132 | autoSelectEnabled = autoSelectEnabled,
133 | )
134 | coroutineScope.launch {
135 | try {
136 | val result = credentialHandler.googleSignInRequest(googleIdOption)
137 | val data = credentialHandler.handleSignInResult(result)
138 | promise.resolve(data)
139 | } catch (e: GetCredentialException) {
140 | Log.d("CredentialManager", "First sign in attempt failed", e)
141 |
142 | when (e) {
143 | is NoCredentialException -> {
144 | try {
145 | Log.d("CredentialManager", "NoCredentialException")
146 | val googleIdOption2 =
147 | credentialHandler.getGoogleId(
148 | setFilterByAuthorizedAccounts = false,
149 | nonce = nonce,
150 | serverClientId = serverClientId,
151 | autoSelectEnabled = autoSelectEnabled,
152 | )
153 | val result2 = credentialHandler.googleSignInRequest(googleIdOption2)
154 | val data2 = credentialHandler.handleSignInResult(result2)
155 | promise.resolve(data2)
156 | } catch (e2: GetCredentialException) {
157 | ErrorHandler.handleGetCredentialError(e2)
158 | Log.e("CredentialManager", "Error during sign in", e2)
159 | promise.reject("ERROR", e2.message.toString())
160 | }
161 | }
162 | else -> {
163 | ErrorHandler.handleGetCredentialError(e)
164 | Log.e("CredentialManager", "Error during sign in", e)
165 | promise.reject("ERROR", e.message.toString())
166 | }
167 | }
168 | }
169 | }
170 | }
171 |
172 | override fun signUpWithApple(params: ReadableMap, promise: Promise) {
173 | promise.reject(
174 | "PLATFORM_NOT_SUPPORTED",
175 | "Sign up with Apple is only supported on iOS devices"
176 | )
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-credentials-manager",
3 | "version": "0.8.1",
4 | "description": "A React Native library that implements the Credential Manager API for Android. This library allows you to manage passwords and passkeys in your React Native applications.",
5 | "source": "./src/index.tsx",
6 | "main": "./lib/commonjs/index.js",
7 | "module": "./lib/module/index.js",
8 | "types": "./lib/typescript/module/src/index.d.ts",
9 | "exports": {
10 | ".": {
11 | "import": {
12 | "types": "./lib/typescript/module/src/index.d.ts",
13 | "default": "./lib/module/index.js"
14 | },
15 | "require": {
16 | "types": "./lib/typescript/commonjs/src/index.d.ts",
17 | "default": "./lib/commonjs/index.js"
18 | }
19 | }
20 | },
21 | "files": [
22 | "src",
23 | "lib",
24 | "android",
25 | "ios",
26 | "cpp",
27 | "*.podspec",
28 | "react-native.config.js",
29 | "app.plugin.js",
30 | "!ios/build",
31 | "!android/build",
32 | "!android/gradle",
33 | "!android/gradlew",
34 | "!android/gradlew.bat",
35 | "!android/local.properties",
36 | "!**/__tests__",
37 | "!**/__fixtures__",
38 | "!**/__mocks__",
39 | "!**/.*"
40 | ],
41 | "scripts": {
42 | "example": "yarn workspace react-native-credentials-manager-example",
43 | "test": "jest",
44 | "typecheck": "tsc",
45 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
46 | "clean": "del-cli android/build example/android/build example/android/app/build example/ios/build lib",
47 | "prepare": "bob build",
48 | "release": "release-it"
49 | },
50 | "keywords": [
51 | "react-native",
52 | "ios",
53 | "android",
54 | "passkeys",
55 | "webauthn",
56 | "authentication",
57 | "credential-manager",
58 | "google-signin",
59 | "passwordless",
60 | "biometric",
61 | "security",
62 | "identity",
63 | "fido2",
64 | "signin"
65 | ],
66 | "repository": {
67 | "type": "git",
68 | "url": "git+https://github.com/benjamineruvieru/react-native-credentials-manager.git"
69 | },
70 | "author": "Benjamin (https://github.com/benjamineruvieru)",
71 | "license": "MIT",
72 | "bugs": {
73 | "url": "https://github.com/benjamineruvieru/react-native-credentials-manager/issues"
74 | },
75 | "homepage": "https://docs.benjamineruvieru.com/docs/react-native-credentials-manager/",
76 | "publishConfig": {
77 | "registry": "https://registry.npmjs.org/"
78 | },
79 | "devDependencies": {
80 | "@commitlint/config-conventional": "^17.0.2",
81 | "@evilmartians/lefthook": "^1.5.0",
82 | "@react-native-community/cli": "15.0.1",
83 | "@react-native/eslint-config": "^0.73.1",
84 | "@release-it/conventional-changelog": "^9.0.2",
85 | "@types/jest": "^29.5.5",
86 | "@types/react": "^18.2.44",
87 | "commitlint": "^17.0.2",
88 | "del-cli": "^5.1.0",
89 | "eslint": "^8.51.0",
90 | "eslint-config-prettier": "^9.0.0",
91 | "eslint-plugin-prettier": "^5.0.1",
92 | "flow-bin": "^0.259.1",
93 | "jest": "^29.7.0",
94 | "prettier": "^3.0.3",
95 | "react": "18.3.1",
96 | "react-native": "0.77.0",
97 | "react-native-builder-bob": "^0.36.0",
98 | "react-native-dotenv": "^3.4.11",
99 | "release-it": "^17.10.0",
100 | "turbo": "^1.10.7",
101 | "typescript": "^5.2.2"
102 | },
103 | "resolutions": {
104 | "@types/react": "^18.2.44"
105 | },
106 | "peerDependencies": {
107 | "react": "*",
108 | "react-native": "*"
109 | },
110 | "workspaces": [
111 | "example"
112 | ],
113 | "packageManager": "yarn@3.6.1",
114 | "jest": {
115 | "preset": "react-native",
116 | "modulePathIgnorePatterns": [
117 | "/example/node_modules",
118 | "/lib/"
119 | ]
120 | },
121 | "commitlint": {
122 | "extends": [
123 | "@commitlint/config-conventional"
124 | ]
125 | },
126 | "release-it": {
127 | "git": {
128 | "commitMessage": "chore: release ${version}",
129 | "tagName": "v${version}"
130 | },
131 | "npm": {
132 | "publish": true
133 | },
134 | "github": {
135 | "release": true
136 | },
137 | "plugins": {
138 | "@release-it/conventional-changelog": {
139 | "preset": {
140 | "name": "conventionalcommits",
141 | "types": [
142 | {
143 | "type": "feat",
144 | "section": "✨ Features"
145 | },
146 | {
147 | "type": "fix",
148 | "section": "🐛 Bug Fixes"
149 | },
150 | {
151 | "type": "perf",
152 | "section": "💨 Performance Improvements"
153 | },
154 | {
155 | "type": "chore(deps)",
156 | "section": "🛠️ Dependency Upgrades"
157 | },
158 | {
159 | "type": "docs",
160 | "section": "📚 Documentation"
161 | }
162 | ]
163 | }
164 | }
165 | }
166 | },
167 | "eslintConfig": {
168 | "root": true,
169 | "extends": [
170 | "@react-native",
171 | "prettier"
172 | ],
173 | "rules": {
174 | "react/react-in-jsx-scope": "off",
175 | "prettier/prettier": [
176 | "error",
177 | {
178 | "quoteProps": "consistent",
179 | "singleQuote": true,
180 | "tabWidth": 2,
181 | "trailingComma": "es5",
182 | "useTabs": false
183 | }
184 | ]
185 | }
186 | },
187 | "eslintIgnore": [
188 | "node_modules/",
189 | "lib/"
190 | ],
191 | "prettier": {
192 | "quoteProps": "consistent",
193 | "singleQuote": true,
194 | "tabWidth": 2,
195 | "trailingComma": "es5",
196 | "useTabs": false
197 | },
198 | "react-native-builder-bob": {
199 | "source": "src",
200 | "output": "lib",
201 | "targets": [
202 | "codegen",
203 | [
204 | "commonjs",
205 | {
206 | "esm": true
207 | }
208 | ],
209 | [
210 | "module",
211 | {
212 | "esm": true
213 | }
214 | ],
215 | [
216 | "typescript",
217 | {
218 | "project": "tsconfig.build.json",
219 | "esm": true
220 | }
221 | ]
222 | ]
223 | },
224 | "codegenConfig": {
225 | "name": "RNCredentialsManagerSpec",
226 | "type": "modules",
227 | "jsSrcsDir": "src",
228 | "outputDir": {
229 | "ios": "ios/generated",
230 | "android": "android/generated"
231 | },
232 | "android": {
233 | "javaPackageName": "com.credentialsmanager"
234 | },
235 | "includesGeneratedCode": true
236 | },
237 | "create-react-native-library": {
238 | "type": "turbo-module",
239 | "languages": "kotlin-objc",
240 | "version": "0.47.0"
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import { View, StyleSheet, Button, Platform } from 'react-native';
2 | import {
3 | signUpWithPasskeys,
4 | signUpWithPassword,
5 | signUpWithGoogle,
6 | signUpWithApple,
7 | signOut,
8 | signIn,
9 | } from 'react-native-credentials-manager';
10 | import {
11 | generateTestRegistrationRequest,
12 | generateTestAuthenticationRequest,
13 | } from './helpers/passkeyTestHelper';
14 |
15 | const WEB_CLIENT_ID = process.env.WEB_CLIENT_ID || '';
16 |
17 | export default function App() {
18 | return (
19 |
20 | {
23 | try {
24 | // Use the helper to generate a valid registration request
25 | const validRequest = generateTestRegistrationRequest();
26 | const res = await signUpWithPasskeys(validRequest);
27 | console.log(JSON.stringify(res));
28 | console.log(res);
29 | } catch (e) {
30 | console.log(e);
31 | }
32 | }}
33 | />
34 | {Platform.OS === 'android' && (
35 | {
38 | try {
39 | const result = await signUpWithPassword({
40 | username: 'User1',
41 | password: 'Password123!',
42 | });
43 | console.log('Password registration result:', result);
44 | } catch (e) {
45 | console.error('Password registration error:', e);
46 | }
47 | }}
48 | />
49 | )}
50 | {
53 | try {
54 | // Use the helper to generate a valid authentication request
55 | const validAuthRequest = generateTestAuthenticationRequest();
56 | // Example 1: Using multiple auth options (returns Credential union type)
57 | const credential = await signIn(
58 | ['passkeys', 'password', 'google-signin', 'apple-signin'],
59 | {
60 | passkeys: validAuthRequest,
61 | googleSignIn: {
62 | serverClientId: WEB_CLIENT_ID,
63 | autoSelectEnabled: true,
64 | // Show only accounts that have previously authorized the app
65 | filterByAuthorizedAccounts: true,
66 | },
67 | appleSignIn: {
68 | requestedScopes: ['fullName', 'email'],
69 | },
70 | }
71 | );
72 |
73 | if (credential.type === 'passkey') {
74 | console.log('Passkey:', credential.authenticationResponseJson);
75 | } else if (credential.type === 'password') {
76 | console.log('Password credentials:', {
77 | username: credential.username,
78 | password: credential.password,
79 | });
80 | } else if (credential.type === 'google-signin') {
81 | console.log('Google credentials:', {
82 | id: credential.id,
83 | idToken: credential.idToken,
84 | displayName: credential.displayName,
85 | familyName: credential.familyName,
86 | givenName: credential.givenName,
87 | profilePicture: credential.profilePicture,
88 | phoneNumber: credential.phoneNumber,
89 | });
90 | } else if (credential.type === 'apple-signin') {
91 | console.log('Apple credentials:', {
92 | id: credential.id,
93 | idToken: credential.idToken,
94 | displayName: credential.displayName,
95 | familyName: credential.familyName,
96 | givenName: credential.givenName,
97 | email: credential.email,
98 | });
99 | }
100 |
101 | // Example 2: Using single auth option (returns specific type)
102 | // const passkeyCredential = await signIn(['passkeys'], {
103 | // passkeys: validAuthRequest,
104 | // });
105 | // // TypeScript knows this is PasskeyCredential, so we can access properties directly
106 | // console.log('Passkey:', passkeyCredential.authenticationResponseJson);
107 | } catch (e) {
108 | console.error(e);
109 | }
110 | }}
111 | />
112 |
113 | {Platform.OS === 'android' && (
114 | {
117 | try {
118 | const credential = await signUpWithGoogle({
119 | serverClientId: WEB_CLIENT_ID,
120 | autoSelectEnabled: false,
121 | // Show all Google accounts on the device, not just authorized ones
122 | filterByAuthorizedAccounts: false,
123 | });
124 | if (credential.type === 'google-signin') {
125 | console.log('Google credentials:', {
126 | id: credential.id,
127 | idToken: credential.idToken,
128 | displayName: credential.displayName,
129 | familyName: credential.familyName,
130 | givenName: credential.givenName,
131 | profilePicture: credential.profilePicture,
132 | phoneNumber: credential.phoneNumber,
133 | });
134 | }
135 | } catch (e) {
136 | console.error(e);
137 | }
138 | }}
139 | />
140 | )}
141 |
142 | {Platform.OS === 'ios' && (
143 | {
146 | try {
147 | const credential = await signUpWithApple({
148 | requestedScopes: ['fullName', 'email'],
149 | });
150 | console.log('Apple credentials:', {
151 | id: credential.id,
152 | idToken: credential.idToken,
153 | displayName: credential.displayName,
154 | familyName: credential.familyName,
155 | givenName: credential.givenName,
156 | email: credential.email,
157 | });
158 | } catch (e) {
159 | console.error(e);
160 | }
161 | }}
162 | />
163 | )}
164 |
165 | {Platform.OS === 'android' && (
166 | {
169 | try {
170 | await signOut();
171 | } catch (e) {
172 | console.error(e);
173 | }
174 | }}
175 | />
176 | )}
177 |
178 | );
179 | }
180 |
181 | const styles = StyleSheet.create({
182 | container: {
183 | flex: 1,
184 | alignItems: 'center',
185 | justifyContent: 'center',
186 | },
187 | });
188 |
--------------------------------------------------------------------------------
/android/src/oldarch/java/com/credentialsmanager/CredentialsManagerModule.kt:
--------------------------------------------------------------------------------
1 | package com.credentialsmanager
2 | import android.util.Log
3 | import androidx.credentials.exceptions.ClearCredentialException
4 | import androidx.credentials.exceptions.CreateCredentialException
5 | import androidx.credentials.exceptions.GetCredentialException
6 | import androidx.credentials.exceptions.NoCredentialException
7 | import com.credentialsmanager.handlers.CredentialHandler
8 | import com.credentialsmanager.handlers.ErrorHandler
9 | import com.facebook.react.bridge.Promise
10 | import com.facebook.react.bridge.ReactApplicationContext
11 | import com.facebook.react.bridge.ReactContextBaseJavaModule
12 | import com.facebook.react.bridge.ReactMethod
13 | import com.facebook.react.bridge.ReadableArray
14 | import com.facebook.react.bridge.ReadableMap
15 | import com.facebook.react.module.annotations.ReactModule
16 | import kotlinx.coroutines.CoroutineScope
17 | import kotlinx.coroutines.Dispatchers
18 | import kotlinx.coroutines.launch
19 |
20 | @ReactModule(name = CredentialsManagerModuleImpl.NAME)
21 | class CredentialsManagerModule(
22 | reactContext: ReactApplicationContext,
23 | ) : ReactContextBaseJavaModule(reactContext) {
24 | private val coroutineScope = CoroutineScope(Dispatchers.IO)
25 | private val credentialHandler = CredentialHandler(reactContext)
26 |
27 | private var implementation: CredentialsManagerModuleImpl = CredentialsManagerModuleImpl()
28 |
29 | override fun getName(): String = CredentialsManagerModuleImpl.NAME
30 |
31 | @ReactMethod
32 | fun signUpWithPasskeys(
33 | requestJson: ReadableMap,
34 | preferImmediatelyAvailableCredentials: Boolean,
35 | promise: Promise,
36 | ) {
37 | val jsonString = requestJson.toString()
38 |
39 | coroutineScope.launch {
40 | try {
41 | val response =
42 | credentialHandler.createPasskey(
43 | jsonString,
44 | preferImmediatelyAvailableCredentials,
45 | )
46 |
47 | response?.let {
48 | promise.resolve(it)
49 | } ?: promise.reject("ERROR", "No response received")
50 | } catch (e: CreateCredentialException) {
51 | ErrorHandler.handleCredentialError(e)
52 | promise.reject("ERROR", e.message.toString())
53 | }
54 | }
55 | }
56 |
57 | @ReactMethod
58 | fun signUpWithPassword(credObject: ReadableMap, promise: Promise) {
59 | val username = credObject.getString("username") ?: ""
60 | val password = credObject.getString("password") ?: ""
61 |
62 | if (username.isEmpty()) {
63 | promise.reject("INVALID_USERNAME", "Username cannot be empty")
64 | return
65 | }
66 |
67 | if (password.isEmpty()) {
68 | promise.reject("INVALID_PASSWORD", "Password cannot be empty")
69 | return
70 | }
71 |
72 | coroutineScope.launch {
73 | try {
74 | credentialHandler.createPassword(username, password)
75 |
76 | // Create success response
77 | val result = mapOf(
78 | "type" to "password",
79 | "username" to username,
80 | "success" to true
81 | )
82 | promise.resolve(result)
83 | } catch (e: CreateCredentialException) {
84 | ErrorHandler.handleCredentialError(e)
85 | promise.reject("CREDENTIAL_ERROR", e.message.toString())
86 | }
87 | }
88 | }
89 |
90 | @ReactMethod
91 | fun signIn(
92 | options: ReadableArray,
93 | params: ReadableMap,
94 | promise: Promise,
95 | ) {
96 | coroutineScope.launch {
97 | try {
98 | val data = credentialHandler.signIn(options = options, params = params)
99 | promise.resolve(data)
100 | } catch (e: GetCredentialException) {
101 | Log.e("CredentialManager", "Error during sign out", e)
102 | promise.reject("ERROR", e.message.toString())
103 | }
104 | }
105 | }
106 |
107 |
108 | // @ReactMethod
109 | // fun signInWithSavedCredentials(
110 | // requestJson: ReadableMap,
111 | // promise: Promise,
112 | // ) {
113 | // val jsonString = requestJson.toString()
114 | // coroutineScope.launch {
115 | // val data = credentialHandler.getSavedCredentials(jsonString)
116 | // promise.resolve(data)
117 | // }
118 | // }
119 |
120 | @ReactMethod
121 | fun signOut(promise: Promise) {
122 | coroutineScope.launch {
123 | try {
124 | credentialHandler.signOut()
125 | promise.resolve(null)
126 | } catch (e: ClearCredentialException) {
127 | Log.e("CredentialManager", "Error during sign out", e)
128 | promise.reject("ERROR", e.message.toString())
129 | }
130 | }
131 | }
132 |
133 | @ReactMethod
134 | fun signUpWithGoogle(
135 | requestObject: ReadableMap,
136 | promise: Promise,
137 | ) {
138 | val nonce = requestObject.getString("nonce") ?: ""
139 | val serverClientId = requestObject.getString("serverClientId") ?: ""
140 | val autoSelectEnabled = requestObject.getBoolean("autoSelectEnabled")
141 | // Default to false for sign-up (show all accounts)
142 | val filterByAuthorizedAccounts = if (requestObject.hasKey("filterByAuthorizedAccounts")) {
143 | requestObject.getBoolean("filterByAuthorizedAccounts")
144 | } else {
145 | false
146 | }
147 |
148 | val googleIdOption =
149 | credentialHandler.getGoogleId(
150 | setFilterByAuthorizedAccounts = filterByAuthorizedAccounts,
151 | nonce = nonce,
152 | serverClientId = serverClientId,
153 | autoSelectEnabled = autoSelectEnabled,
154 | )
155 | coroutineScope.launch {
156 | try {
157 | val result = credentialHandler.googleSignInRequest(googleIdOption)
158 | val data = credentialHandler.handleSignInResult(result)
159 | promise.resolve(data)
160 | } catch (e: GetCredentialException) {
161 | when (e) {
162 | is NoCredentialException -> {
163 | try {
164 | Log.d("CredentialManager", "NoCredentialException")
165 | val googleIdOption =
166 | credentialHandler.getGoogleId(
167 | setFilterByAuthorizedAccounts = filterByAuthorizedAccounts,
168 | nonce = nonce,
169 | serverClientId = serverClientId,
170 | autoSelectEnabled = autoSelectEnabled,
171 | )
172 | val result = credentialHandler.googleSignInRequest(googleIdOption)
173 | val data = credentialHandler.handleSignInResult(result)
174 | promise.resolve(data)
175 | } catch (e: GetCredentialException) {
176 | ErrorHandler.handleGetCredentialError(e)
177 | Log.e("CredentialManager", "Error during sign in", e)
178 | promise.reject("ERROR", e.message.toString())
179 | }
180 | }
181 | else -> {
182 | ErrorHandler.handleGetCredentialError(e)
183 | Log.e("CredentialManager", "Error during sign in", e)
184 | promise.reject("ERROR", e.message.toString())
185 | }
186 | }
187 | }
188 | }
189 | }
190 |
191 | @ReactMethod
192 | fun signUpWithApple(params: ReadableMap, promise: Promise) {
193 | // Since this is an iOS-specific function, we just reject with an appropriate message on Android
194 | promise.reject(
195 | "PLATFORM_NOT_SUPPORTED",
196 | "Sign up with Apple is only supported on iOS devices"
197 | )
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
90 | ' "$PWD" ) || exit
91 |
92 | # Use the maximum available, or set MAX_FD != -1 to use that value.
93 | MAX_FD=maximum
94 |
95 | warn () {
96 | echo "$*"
97 | } >&2
98 |
99 | die () {
100 | echo
101 | echo "$*"
102 | echo
103 | exit 1
104 | } >&2
105 |
106 | # OS specific support (must be 'true' or 'false').
107 | cygwin=false
108 | msys=false
109 | darwin=false
110 | nonstop=false
111 | case "$( uname )" in #(
112 | CYGWIN* ) cygwin=true ;; #(
113 | Darwin* ) darwin=true ;; #(
114 | MSYS* | MINGW* ) msys=true ;; #(
115 | NONSTOP* ) nonstop=true ;;
116 | esac
117 |
118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
119 |
120 |
121 | # Determine the Java command to use to start the JVM.
122 | if [ -n "$JAVA_HOME" ] ; then
123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
124 | # IBM's JDK on AIX uses strange locations for the executables
125 | JAVACMD=$JAVA_HOME/jre/sh/java
126 | else
127 | JAVACMD=$JAVA_HOME/bin/java
128 | fi
129 | if [ ! -x "$JAVACMD" ] ; then
130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
131 |
132 | Please set the JAVA_HOME variable in your environment to match the
133 | location of your Java installation."
134 | fi
135 | else
136 | JAVACMD=java
137 | if ! command -v java >/dev/null 2>&1
138 | then
139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
140 |
141 | Please set the JAVA_HOME variable in your environment to match the
142 | location of your Java installation."
143 | fi
144 | fi
145 |
146 | # Increase the maximum file descriptors if we can.
147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
148 | case $MAX_FD in #(
149 | max*)
150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
151 | # shellcheck disable=SC2039,SC3045
152 | MAX_FD=$( ulimit -H -n ) ||
153 | warn "Could not query maximum file descriptor limit"
154 | esac
155 | case $MAX_FD in #(
156 | '' | soft) :;; #(
157 | *)
158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
159 | # shellcheck disable=SC2039,SC3045
160 | ulimit -n "$MAX_FD" ||
161 | warn "Could not set maximum file descriptor limit to $MAX_FD"
162 | esac
163 | fi
164 |
165 | # Collect all arguments for the java command, stacking in reverse order:
166 | # * args from the command line
167 | # * the main class name
168 | # * -classpath
169 | # * -D...appname settings
170 | # * --module-path (only if needed)
171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
172 |
173 | # For Cygwin or MSYS, switch paths to Windows format before running java
174 | if "$cygwin" || "$msys" ; then
175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
177 |
178 | JAVACMD=$( cygpath --unix "$JAVACMD" )
179 |
180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
181 | for arg do
182 | if
183 | case $arg in #(
184 | -*) false ;; # don't mess with options #(
185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
186 | [ -e "$t" ] ;; #(
187 | *) false ;;
188 | esac
189 | then
190 | arg=$( cygpath --path --ignore --mixed "$arg" )
191 | fi
192 | # Roll the args list around exactly as many times as the number of
193 | # args, so each arg winds up back in the position where it started, but
194 | # possibly modified.
195 | #
196 | # NB: a `for` loop captures its iteration list before it begins, so
197 | # changing the positional parameters here affects neither the number of
198 | # iterations, nor the values presented in `arg`.
199 | shift # remove old arg
200 | set -- "$@" "$arg" # push replacement arg
201 | done
202 | fi
203 |
204 |
205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
207 |
208 | # Collect all arguments for the java command:
209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
210 | # and any embedded shellness will be escaped.
211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
212 | # treated as '${Hostname}' itself on the command line.
213 |
214 | set -- \
215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
216 | -classpath "$CLASSPATH" \
217 | org.gradle.wrapper.GradleWrapperMain \
218 | "$@"
219 |
220 | # Stop when "xargs" is not available.
221 | if ! command -v xargs >/dev/null 2>&1
222 | then
223 | die "xargs is not available"
224 | fi
225 |
226 | # Use "xargs" to parse quoted args.
227 | #
228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
229 | #
230 | # In Bash we could simply go:
231 | #
232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
233 | # set -- "${ARGS[@]}" "$@"
234 | #
235 | # but POSIX shell has neither arrays nor command substitution, so instead we
236 | # post-process each arg (as a line of input to sed) to backslash-escape any
237 | # character that might be a shell metacharacter, then use eval to reverse
238 | # that process (while maintaining the separation between arguments), and wrap
239 | # the whole thing up as a single "set" statement.
240 | #
241 | # This will of course break if any of these variables contains a newline or
242 | # an unmatched quote.
243 | #
244 |
245 | eval "set -- $(
246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
247 | xargs -n1 |
248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
249 | tr '\n' ' '
250 | )" '"$@"'
251 |
252 | exec "$JAVACMD" "$@"
253 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.ts:
--------------------------------------------------------------------------------
1 | // Mock the native module to isolate JavaScript logic testing
2 | jest.mock('../NativeCredentialsManager', () => ({
3 | __esModule: true,
4 | default: {
5 | signUpWithPasskeys: jest.fn(() =>
6 | Promise.resolve({ type: 'passkey', authenticationResponseJson: '{}' })
7 | ),
8 | signUpWithPassword: jest.fn(() =>
9 | Promise.resolve({ type: 'password', username: 'test', password: 'test' })
10 | ),
11 | signIn: jest.fn((_options, _params) =>
12 | Promise.resolve({
13 | type: 'passkey',
14 | authenticationResponseJson: '{}',
15 | })
16 | ),
17 | signUpWithGoogle: jest.fn(() =>
18 | Promise.resolve({
19 | type: 'google-signin',
20 | id: 'test-id',
21 | idToken: 'test-token',
22 | })
23 | ),
24 | signUpWithApple: jest.fn(() =>
25 | Promise.resolve({
26 | type: 'apple-signin',
27 | id: 'test-id',
28 | idToken: 'test-token',
29 | })
30 | ),
31 | signOut: jest.fn(() => Promise.resolve(null)),
32 | addListener: jest.fn(),
33 | removeListeners: jest.fn(),
34 | },
35 | }));
36 |
37 | import {
38 | signUpWithPasskeys,
39 | signUpWithPassword,
40 | signUpWithGoogle,
41 | signUpWithApple,
42 | signIn,
43 | signOut,
44 | } from '../index';
45 | import CredentialsManager from '../NativeCredentialsManager';
46 |
47 | // Get the mocked module for assertions
48 | const mockNativeModule = CredentialsManager as jest.Mocked<
49 | typeof CredentialsManager
50 | >;
51 |
52 | describe('react-native-credentials-manager', () => {
53 | beforeEach(() => {
54 | // Clear all mocks before each test
55 | jest.clearAllMocks();
56 | });
57 |
58 | describe('signUpWithPasskeys', () => {
59 | it('should call native module with correct parameters', async () => {
60 | const requestJson = { challenge: 'test-challenge' };
61 | await signUpWithPasskeys(requestJson, true);
62 |
63 | expect(mockNativeModule.signUpWithPasskeys).toHaveBeenCalledWith(
64 | requestJson,
65 | true
66 | );
67 | expect(mockNativeModule.signUpWithPasskeys).toHaveBeenCalledTimes(1);
68 | });
69 |
70 | it('should use default value for preferImmediatelyAvailableCredentials', async () => {
71 | const requestJson = { challenge: 'test-challenge' };
72 | await signUpWithPasskeys(requestJson);
73 |
74 | expect(mockNativeModule.signUpWithPasskeys).toHaveBeenCalledWith(
75 | requestJson,
76 | false
77 | );
78 | });
79 | });
80 |
81 | describe('signUpWithPassword', () => {
82 | it('should reject on iOS with appropriate error', async () => {
83 | const originalPlatform = require('react-native').Platform.OS;
84 | require('react-native').Platform.OS = 'ios';
85 |
86 | await expect(
87 | signUpWithPassword({ username: 'test', password: 'pass' })
88 | ).rejects.toThrow(
89 | 'Manual password storage is not supported on iOS. Use AutoFill passwords through signIn method instead.'
90 | );
91 |
92 | expect(mockNativeModule.signUpWithPassword).not.toHaveBeenCalled();
93 | require('react-native').Platform.OS = originalPlatform;
94 | });
95 |
96 | it('should call native module on Android', async () => {
97 | const originalPlatform = require('react-native').Platform.OS;
98 | require('react-native').Platform.OS = 'android';
99 |
100 | await signUpWithPassword({ username: 'testuser', password: 'testpass' });
101 |
102 | expect(mockNativeModule.signUpWithPassword).toHaveBeenCalledWith({
103 | password: 'testpass',
104 | username: 'testuser',
105 | });
106 | expect(mockNativeModule.signUpWithPassword).toHaveBeenCalledTimes(1);
107 |
108 | require('react-native').Platform.OS = originalPlatform;
109 | });
110 | });
111 |
112 | describe('signUpWithGoogle', () => {
113 | it('should reject on iOS with appropriate error', async () => {
114 | const originalPlatform = require('react-native').Platform.OS;
115 | require('react-native').Platform.OS = 'ios';
116 |
117 | await expect(
118 | signUpWithGoogle({ serverClientId: 'test-client-id' })
119 | ).rejects.toThrow(
120 | 'Google Sign In is only available on Android. Use signUpWithApple on iOS.'
121 | );
122 |
123 | expect(mockNativeModule.signUpWithGoogle).not.toHaveBeenCalled();
124 | require('react-native').Platform.OS = originalPlatform;
125 | });
126 |
127 | it('should apply default values correctly on Android', async () => {
128 | const originalPlatform = require('react-native').Platform.OS;
129 | require('react-native').Platform.OS = 'android';
130 |
131 | await signUpWithGoogle({ serverClientId: 'test-client-id' });
132 |
133 | expect(mockNativeModule.signUpWithGoogle).toHaveBeenCalledWith({
134 | serverClientId: 'test-client-id',
135 | nonce: '',
136 | autoSelectEnabled: true,
137 | filterByAuthorizedAccounts: false,
138 | });
139 |
140 | require('react-native').Platform.OS = originalPlatform;
141 | });
142 |
143 | it('should use provided values when specified', async () => {
144 | const originalPlatform = require('react-native').Platform.OS;
145 | require('react-native').Platform.OS = 'android';
146 |
147 | await signUpWithGoogle({
148 | serverClientId: 'test-client-id',
149 | nonce: 'custom-nonce',
150 | autoSelectEnabled: false,
151 | filterByAuthorizedAccounts: true,
152 | });
153 |
154 | expect(mockNativeModule.signUpWithGoogle).toHaveBeenCalledWith({
155 | serverClientId: 'test-client-id',
156 | nonce: 'custom-nonce',
157 | autoSelectEnabled: false,
158 | filterByAuthorizedAccounts: true,
159 | });
160 |
161 | require('react-native').Platform.OS = originalPlatform;
162 | });
163 | });
164 |
165 | describe('signUpWithApple', () => {
166 | it('should reject on non-iOS platforms with appropriate error', async () => {
167 | const originalPlatform = require('react-native').Platform.OS;
168 | require('react-native').Platform.OS = 'android';
169 |
170 | await expect(signUpWithApple()).rejects.toThrow(
171 | 'Apple Sign In is only available on iOS. Use signUpWithGoogle on Android.'
172 | );
173 |
174 | expect(mockNativeModule.signUpWithApple).not.toHaveBeenCalled();
175 | require('react-native').Platform.OS = originalPlatform;
176 | });
177 |
178 | it('should apply default values correctly on iOS', async () => {
179 | const originalPlatform = require('react-native').Platform.OS;
180 | require('react-native').Platform.OS = 'ios';
181 |
182 | await signUpWithApple();
183 |
184 | expect(mockNativeModule.signUpWithApple).toHaveBeenCalledWith({
185 | nonce: '',
186 | requestedScopes: ['fullName', 'email'],
187 | });
188 |
189 | require('react-native').Platform.OS = originalPlatform;
190 | });
191 |
192 | it('should use provided values when specified', async () => {
193 | const originalPlatform = require('react-native').Platform.OS;
194 | require('react-native').Platform.OS = 'ios';
195 |
196 | await signUpWithApple({
197 | nonce: 'custom-nonce',
198 | requestedScopes: ['email'],
199 | });
200 |
201 | expect(mockNativeModule.signUpWithApple).toHaveBeenCalledWith({
202 | nonce: 'custom-nonce',
203 | requestedScopes: ['email'],
204 | });
205 |
206 | require('react-native').Platform.OS = originalPlatform;
207 | });
208 | });
209 |
210 | describe('signIn', () => {
211 | it('should apply default values for Google Sign In params', async () => {
212 | await signIn(['google-signin'], {
213 | googleSignIn: { serverClientId: 'test-id' },
214 | });
215 |
216 | expect(mockNativeModule.signIn).toHaveBeenCalledWith(['google-signin'], {
217 | passkeys: undefined,
218 | googleSignIn: {
219 | serverClientId: 'test-id',
220 | nonce: '',
221 | autoSelectEnabled: true,
222 | filterByAuthorizedAccounts: true,
223 | },
224 | });
225 | });
226 |
227 | it('should apply default values for Apple Sign In params on iOS', async () => {
228 | const originalPlatform = require('react-native').Platform.OS;
229 | require('react-native').Platform.OS = 'ios';
230 |
231 | await signIn(['apple-signin'], { appleSignIn: {} });
232 |
233 | expect(mockNativeModule.signIn).toHaveBeenCalledWith(['apple-signin'], {
234 | passkeys: undefined,
235 | appleSignIn: {
236 | nonce: '',
237 | requestedScopes: ['fullName', 'email'],
238 | },
239 | });
240 |
241 | require('react-native').Platform.OS = originalPlatform;
242 | });
243 |
244 | it('should not add Apple params on non-iOS platforms', async () => {
245 | const originalPlatform = require('react-native').Platform.OS;
246 | require('react-native').Platform.OS = 'android';
247 |
248 | await signIn(['apple-signin'], { appleSignIn: {} });
249 |
250 | expect(mockNativeModule.signIn).toHaveBeenCalledWith(['apple-signin'], {
251 | passkeys: undefined,
252 | });
253 |
254 | require('react-native').Platform.OS = originalPlatform;
255 | });
256 |
257 | it('should pass through passkey params', async () => {
258 | const passkeyParams = { challenge: 'test-challenge' };
259 | await signIn(['passkeys'], { passkeys: passkeyParams });
260 |
261 | expect(mockNativeModule.signIn).toHaveBeenCalledWith(['passkeys'], {
262 | passkeys: passkeyParams,
263 | });
264 | });
265 |
266 | it('should handle multiple sign-in options', async () => {
267 | await signIn(['passkeys', 'password', 'google-signin'], {
268 | passkeys: { challenge: 'test' },
269 | googleSignIn: { serverClientId: 'test-id' },
270 | });
271 |
272 | expect(mockNativeModule.signIn).toHaveBeenCalledWith(
273 | ['passkeys', 'password', 'google-signin'],
274 | {
275 | passkeys: { challenge: 'test' },
276 | googleSignIn: {
277 | serverClientId: 'test-id',
278 | nonce: '',
279 | autoSelectEnabled: true,
280 | filterByAuthorizedAccounts: true,
281 | },
282 | }
283 | );
284 | });
285 | });
286 |
287 | describe('signOut', () => {
288 | it('should call native signOut method', async () => {
289 | await signOut();
290 |
291 | expect(mockNativeModule.signOut).toHaveBeenCalledTimes(1);
292 | });
293 | });
294 | });
295 |
--------------------------------------------------------------------------------
/android/src/main/java/com/credentialsmanager/handlers/CredentialHandler.kt:
--------------------------------------------------------------------------------
1 | package com.credentialsmanager.handlers
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.util.Log
6 | import androidx.credentials.ClearCredentialStateRequest
7 | import androidx.credentials.CreatePasswordRequest
8 | import androidx.credentials.CreatePublicKeyCredentialRequest
9 | import androidx.credentials.CreatePublicKeyCredentialResponse
10 | import androidx.credentials.CredentialManager
11 | import androidx.credentials.CredentialOption
12 | import androidx.credentials.CustomCredential
13 | import androidx.credentials.GetCredentialRequest
14 | import androidx.credentials.GetCredentialResponse
15 | import androidx.credentials.GetPasswordOption
16 | import androidx.credentials.GetPublicKeyCredentialOption
17 | import androidx.credentials.PasswordCredential
18 | import androidx.credentials.PublicKeyCredential
19 | import com.facebook.react.bridge.Arguments
20 | import com.facebook.react.bridge.ReactApplicationContext
21 | import com.facebook.react.bridge.ReadableArray
22 | import com.facebook.react.bridge.ReadableMap
23 | import com.google.android.libraries.identity.googleid.GetGoogleIdOption
24 | import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
25 | import com.google.android.libraries.identity.googleid.GoogleIdTokenParsingException
26 | import org.json.JSONObject
27 |
28 | class CredentialHandler(
29 | private val context: Context,
30 | ) {
31 | private val credentialManager = CredentialManager.create(context)
32 |
33 | // Helper function to get activity context
34 | private fun getActivityContext(): Context {
35 | if (context is ReactApplicationContext) {
36 | val activity = context.currentActivity
37 | if (activity != null) {
38 | return activity
39 | } else {
40 | Log.w("CredentialManager", "No current activity found. UI operations may fail - ensure you're calling from the main/UI thread.")
41 | }
42 | } else {
43 | Log.w("CredentialManager", "Context is not ReactApplicationContext. UI operations may fail.")
44 | }
45 | // If we can't get an activity context, use the original context
46 | // This might still cause issues for UI operations, but it's better than null
47 | return context
48 | }
49 |
50 | suspend fun signOut() {
51 | credentialManager.clearCredentialState(ClearCredentialStateRequest())
52 | }
53 |
54 | suspend fun createPasskey(
55 | jsonString: String,
56 | preferImmediatelyAvailableCredentials: Boolean,
57 | ): ReadableMap? {
58 | Log.d("CredentialManager", "Creating passkey with request: $jsonString")
59 |
60 | try {
61 | val request =
62 | CreatePublicKeyCredentialRequest(
63 | requestJson = jsonString,
64 | preferImmediatelyAvailableCredentials = preferImmediatelyAvailableCredentials,
65 | )
66 |
67 | val activityContext = getActivityContext()
68 | val response =
69 | credentialManager.createCredential(
70 | activityContext,
71 | request,
72 | ) as CreatePublicKeyCredentialResponse
73 |
74 | return response.data.getString("androidx.credentials.BUNDLE_KEY_REGISTRATION_RESPONSE_JSON")?.let { json ->
75 | val jsonObject = Arguments.createMap()
76 | val parsedObject = JSONObject(json)
77 |
78 | parsedObject.keys().forEach { key ->
79 | jsonObject.putString(key, parsedObject.getString(key))
80 | }
81 | jsonObject
82 | }
83 | } catch (e: Exception) {
84 | Log.e("CredentialManager", "Error creating passkey", e)
85 | throw e
86 | }
87 | }
88 |
89 | suspend fun createPassword(
90 | username: String,
91 | password: String,
92 | ) {
93 | Log.d("CredentialManager", "Creating password credential for username: $username")
94 |
95 | try {
96 | val activityContext = getActivityContext()
97 | val createPasswordRequest = CreatePasswordRequest(id = username, password = password)
98 | credentialManager.createCredential(activityContext, createPasswordRequest)
99 | } catch (e: Exception) {
100 | Log.e("CredentialManager", "Error creating password credential", e)
101 | throw e
102 | }
103 | }
104 |
105 | suspend fun signIn(
106 | options: ReadableArray,
107 | params: ReadableMap,
108 | ): ReadableMap? {
109 | val credentialOptions = mutableListOf()
110 | for (i in 0 until options.size()) {
111 | when (options.getString(i)) {
112 | "passkeys" -> {
113 | if (params.hasKey("passkeys")) {
114 | val jsonString = params.getMap("passkeys")?.toString()
115 | jsonString?.let {
116 | credentialOptions.add(GetPublicKeyCredentialOption(it, null))
117 | }
118 | }
119 | }
120 | "password" -> {
121 | credentialOptions.add(GetPasswordOption())
122 | }
123 | "google-signin" -> {
124 | if (params.hasKey("googleSignIn")) {
125 | val googleParams = params.getMap("googleSignIn")
126 | val nonce = googleParams?.getString("nonce") ?: ""
127 | val serverClientId = googleParams?.getString("serverClientId") ?: ""
128 | val autoSelectEnabled = googleParams?.getBoolean("autoSelectEnabled") ?: false
129 | // Default to true for sign-in (show only authorized accounts)
130 | val filterByAuthorizedAccounts = if (googleParams?.hasKey("filterByAuthorizedAccounts") == true) {
131 | googleParams.getBoolean("filterByAuthorizedAccounts")
132 | } else {
133 | true
134 | }
135 |
136 | credentialOptions.add(
137 | getGoogleId(
138 | filterByAuthorizedAccounts,
139 | nonce,
140 | serverClientId,
141 | autoSelectEnabled,
142 | ),
143 | )
144 | }
145 | }
146 | }
147 | }
148 |
149 | val request = GetCredentialRequest(credentialOptions)
150 | val activityContext = getActivityContext()
151 | val result = credentialManager.getCredential(activityContext, request)
152 | return handleSignInResult(result)
153 | }
154 |
155 | suspend fun getSavedCredentials(jsonString: String): ReadableMap? {
156 | val getPublicKeyCredentialOption = GetPublicKeyCredentialOption(jsonString, null)
157 | val getPasswordOption = GetPasswordOption()
158 | val activityContext = getActivityContext()
159 |
160 | val result =
161 | credentialManager.getCredential(
162 | activityContext,
163 | GetCredentialRequest(
164 | listOf(
165 | getPublicKeyCredentialOption,
166 | getPasswordOption,
167 | ),
168 | ),
169 | )
170 |
171 | return handleSignInResult(result)
172 | }
173 |
174 | fun handleSignInResult(result: GetCredentialResponse): ReadableMap? {
175 | // Handle the successfully returned credential.
176 | val credential = result.credential
177 | Log.d("CredentialManager", "Handle results called")
178 |
179 | return when (credential) {
180 | is PublicKeyCredential -> {
181 | val cred = result.credential as PublicKeyCredential
182 | Arguments.createMap().apply {
183 | putString("type", "passkey")
184 | putString("authenticationResponseJson", cred.authenticationResponseJson)
185 | }
186 | }
187 | is PasswordCredential -> {
188 | val cred = result.credential as PasswordCredential
189 | Arguments.createMap().apply {
190 | putString("type", "password")
191 | putString("username", cred.id)
192 | putString("password", cred.password)
193 | }
194 | }
195 | // GoogleIdToken credential
196 | is CustomCredential -> {
197 | if (credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
198 | try {
199 | val googleIdTokenCredential =
200 | GoogleIdTokenCredential
201 | .createFrom(credential.data)
202 | Log.d("CredentialManager", "Google ID Token Credential ID: ${googleIdTokenCredential.id}")
203 |
204 | return Arguments.createMap().apply {
205 | putString("type", "google-signin")
206 | putString("id", googleIdTokenCredential.id)
207 | putString("idToken", googleIdTokenCredential.idToken)
208 | googleIdTokenCredential.displayName?.let { putString("displayName", it) }
209 | googleIdTokenCredential.familyName?.let { putString("familyName", it) }
210 | googleIdTokenCredential.givenName?.let { putString("givenName", it) }
211 | googleIdTokenCredential.profilePictureUri?.let { putString("profilePicture", it.toString()) }
212 | googleIdTokenCredential.phoneNumber?.let { putString("phoneNumber", it) }
213 | }
214 | } catch (e: GoogleIdTokenParsingException) {
215 | Log.e("CredentialManager", "Received an invalid google id token response", e)
216 | return null
217 | }
218 | } else {
219 | Log.e("CredentialManager", "Received an unexpected credential type")
220 | return null
221 | }
222 | }
223 |
224 | else -> {
225 | // Catch any unrecognized credential type here.
226 | Log.e("CredentialManager", "Unexpected type of credential")
227 | return null
228 | }
229 | }
230 | }
231 |
232 | fun getGoogleId(
233 | setFilterByAuthorizedAccounts: Boolean,
234 | nonce: String,
235 | serverClientId: String,
236 | autoSelectEnabled: Boolean,
237 | ): GetGoogleIdOption {
238 | Log.d("CredentialManager", "getGoogleId - setFilterByAuthorizedAccounts: $setFilterByAuthorizedAccounts autoSelectEnabled: $autoSelectEnabled")
239 |
240 | return GetGoogleIdOption
241 | .Builder()
242 | .setFilterByAuthorizedAccounts(setFilterByAuthorizedAccounts)
243 | .setServerClientId(serverClientId)
244 | .setAutoSelectEnabled(autoSelectEnabled)
245 | .setNonce(nonce)
246 | .build()
247 | }
248 |
249 | suspend fun googleSignInRequest(googleIdOption: GetGoogleIdOption): GetCredentialResponse {
250 | val request: GetCredentialRequest =
251 | GetCredentialRequest
252 | .Builder()
253 | .addCredentialOption(googleIdOption)
254 | .build()
255 |
256 | val activityContext = getActivityContext()
257 | val result =
258 | credentialManager.getCredential(
259 | request = request,
260 | context = activityContext,
261 | )
262 |
263 | return result
264 | }
265 | }
266 |
--------------------------------------------------------------------------------
/ios/CredentialsManager.mm:
--------------------------------------------------------------------------------
1 | #import "CredentialsManager.h"
2 | #import
3 | #import
4 | #import
5 |
6 | @implementation CredentialsManager
7 |
8 | RCT_EXPORT_MODULE()
9 |
10 | - (instancetype)init {
11 | self = [super init];
12 | if (self) {
13 | // Default relying party identifier - should be configurable
14 | self.relyingPartyIdentifier = @"www.benjamineruvieru.com";
15 |
16 | // Get the main window as the authentication anchor
17 | dispatch_async(dispatch_get_main_queue(), ^{
18 | UIWindow *keyWindow = nil;
19 | for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {
20 | if (windowScene.activationState == UISceneActivationStateForegroundActive) {
21 | for (UIWindow *window in windowScene.windows) {
22 | if (window.isKeyWindow) {
23 | keyWindow = window;
24 | break;
25 | }
26 | }
27 | }
28 | }
29 | self.authenticationAnchor = keyWindow;
30 | });
31 | }
32 | return self;
33 | }
34 |
35 | #pragma mark - TurboModule
36 |
37 | - (std::shared_ptr)getTurboModule:
38 | (const facebook::react::ObjCTurboModule::InitParams &)params
39 | {
40 | return std::make_shared(params);
41 | }
42 |
43 | #pragma mark - NativeCredentialsManagerSpec
44 |
45 | - (void)signUpWithPasskeys:(NSDictionary *)requestJson
46 | preferImmediatelyAvailableCredentials:(BOOL)preferImmediatelyAvailableCredentials
47 | resolve:(RCTPromiseResolveBlock)resolve
48 | reject:(RCTPromiseRejectBlock)reject {
49 |
50 | dispatch_async(dispatch_get_main_queue(), ^{
51 | self.currentResolve = resolve;
52 | self.currentReject = reject;
53 |
54 | // Extract challenge and user info from requestJson
55 | NSString *challengeString = requestJson[@"challenge"];
56 | NSDictionary *userInfo = requestJson[@"user"];
57 | NSDictionary *rpInfo = requestJson[@"rp"];
58 |
59 | if (!challengeString || !userInfo || !rpInfo) {
60 | reject(@"INVALID_REQUEST", @"Missing required fields in request JSON", nil);
61 | return;
62 | }
63 |
64 | // Decode base64 challenge
65 | NSData *challenge = [[NSData alloc] initWithBase64EncodedString:challengeString options:0];
66 | if (!challenge) {
67 | reject(@"INVALID_CHALLENGE", @"Invalid base64 challenge", nil);
68 | return;
69 | }
70 |
71 | // Extract user information
72 | NSString *userName = userInfo[@"name"];
73 | NSString *userIdString = userInfo[@"id"];
74 |
75 | // Decode user ID
76 | NSData *userId = [[NSData alloc] initWithBase64EncodedString:userIdString options:0];
77 | if (!userId) {
78 | // If not base64, use the string directly
79 | userId = [userIdString dataUsingEncoding:NSUTF8StringEncoding];
80 | }
81 |
82 | // Update relying party identifier
83 | NSString *rpId = rpInfo[@"id"];
84 | if (rpId) {
85 | self.relyingPartyIdentifier = rpId;
86 | }
87 |
88 | // Create the passkey registration request using Apple's Authentication Services
89 | ASAuthorizationPlatformPublicKeyCredentialProvider *provider =
90 | [[ASAuthorizationPlatformPublicKeyCredentialProvider alloc] initWithRelyingPartyIdentifier:self.relyingPartyIdentifier];
91 |
92 | ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest *registrationRequest =
93 | [provider createCredentialRegistrationRequestWithChallenge:challenge name:userName userID:userId];
94 |
95 | // Configure the request
96 | registrationRequest.userVerificationPreference = ASAuthorizationPublicKeyCredentialUserVerificationPreferenceRequired;
97 |
98 | // Create and configure the authorization controller
99 | ASAuthorizationController *authController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[registrationRequest]];
100 | authController.delegate = self;
101 | authController.presentationContextProvider = self;
102 |
103 | // Perform the request
104 | [authController performRequests];
105 | });
106 | }
107 |
108 | - (void)signUpWithPassword:(JS::NativeCredentialsManager::CredObject &)credObject
109 | resolve:(RCTPromiseResolveBlock)resolve
110 | reject:(RCTPromiseRejectBlock)reject {
111 | // Apple's Authentication Services only supports AutoFill passwords, not manual credential storage
112 | // Manual keychain storage is not part of Authentication Services framework
113 | reject(@"UNSUPPORTED_OPERATION", @"Manual password storage is not supported. Use AutoFill passwords through signIn method instead.", nil);
114 | }
115 |
116 | - (void)signIn:(NSArray *)options
117 | params:(JS::NativeCredentialsManager::SpecSignInParams &)params
118 | resolve:(RCTPromiseResolveBlock)resolve
119 | reject:(RCTPromiseRejectBlock)reject {
120 |
121 | id passkeyParams = params.passkeys();
122 |
123 | dispatch_async(dispatch_get_main_queue(), ^{
124 | self.currentResolve = resolve;
125 | self.currentReject = reject;
126 |
127 | NSMutableArray *authRequests = [[NSMutableArray alloc] init];
128 |
129 | for (NSString *option in options) {
130 | if ([option isEqualToString:@"passkeys"]) {
131 | if (!passkeyParams || ![passkeyParams isKindOfClass:[NSDictionary class]]) {
132 | RCTLogError(@"Missing or invalid passkeys parameters");
133 | continue;
134 | }
135 |
136 | NSDictionary *passkeyDict = (NSDictionary *)passkeyParams;
137 | NSString *challengeString = passkeyDict[@"challenge"];
138 |
139 | if (!challengeString || ![challengeString isKindOfClass:[NSString class]]) {
140 | RCTLogError(@"Missing or invalid challenge in passkeys parameters");
141 | continue;
142 | }
143 |
144 | NSData *challenge = [[NSData alloc] initWithBase64EncodedString:challengeString options:0];
145 |
146 | if (challenge) {
147 | // Update relying party identifier if provided
148 | NSString *rpId = passkeyDict[@"rpId"];
149 | if (rpId && [rpId isKindOfClass:[NSString class]]) {
150 | self.relyingPartyIdentifier = rpId;
151 | }
152 |
153 | ASAuthorizationPlatformPublicKeyCredentialProvider *provider =
154 | [[ASAuthorizationPlatformPublicKeyCredentialProvider alloc] initWithRelyingPartyIdentifier:self.relyingPartyIdentifier];
155 |
156 | ASAuthorizationPlatformPublicKeyCredentialAssertionRequest *assertionRequest =
157 | [provider createCredentialAssertionRequestWithChallenge:challenge];
158 | assertionRequest.userVerificationPreference = ASAuthorizationPublicKeyCredentialUserVerificationPreferenceRequired;
159 |
160 | [authRequests addObject:assertionRequest];
161 | } else {
162 | RCTLogError(@"Failed to decode challenge for passkey authentication");
163 | }
164 | } else if ([option isEqualToString:@"password"]) {
165 | // Use Apple's AutoFill password provider (not manual keychain)
166 | ASAuthorizationPasswordProvider *passwordProvider = [[ASAuthorizationPasswordProvider alloc] init];
167 | ASAuthorizationPasswordRequest *passwordRequest = [passwordProvider createRequest];
168 | [authRequests addObject:passwordRequest];
169 | } else if ([option isEqualToString:@"apple-signin"]) {
170 | ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
171 | ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
172 |
173 | NSArray *defaultScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
174 | appleIDRequest.requestedScopes = defaultScopes;
175 |
176 | [authRequests addObject:appleIDRequest];
177 | } else if ([option isEqualToString:@"google-signin"]) {
178 | // Google Sign In is not part of Apple's Authentication Services framework
179 | RCTLogError(@"Google Sign In is not supported on iOS. Use Apple Sign In instead.");
180 | continue;
181 | }
182 | }
183 |
184 | if (authRequests.count == 0) {
185 | reject(@"NO_AUTH_METHODS", @"No valid authentication methods provided", nil);
186 | return;
187 | }
188 |
189 | // Create and configure the authorization controller
190 | ASAuthorizationController *authController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:authRequests];
191 | authController.delegate = self;
192 | authController.presentationContextProvider = self;
193 |
194 | // Perform the request
195 | [authController performRequests];
196 | });
197 | }
198 |
199 | - (void)signUpWithGoogle:(JS::NativeCredentialsManager::GoogleSignInParams &)params
200 | resolve:(RCTPromiseResolveBlock)resolve
201 | reject:(RCTPromiseRejectBlock)reject {
202 | // Google Sign In is not part of Apple's Authentication Services framework
203 | reject(@"UNSUPPORTED_OPERATION", @"Google Sign In is not available on iOS. Use Apple Sign In instead.", nil);
204 | }
205 |
206 | - (void)signUpWithApple:(JS::NativeCredentialsManager::AppleSignInParams &)params
207 | resolve:(RCTPromiseResolveBlock)resolve
208 | reject:(RCTPromiseRejectBlock)reject {
209 |
210 | dispatch_async(dispatch_get_main_queue(), ^{
211 | self.currentResolve = resolve;
212 | self.currentReject = reject;
213 |
214 | ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
215 | ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
216 |
217 | appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
218 |
219 | ASAuthorizationController *authController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
220 | authController.delegate = self;
221 | authController.presentationContextProvider = self;
222 |
223 | [authController performRequests];
224 | });
225 | }
226 |
227 | - (void)signOut:(RCTPromiseResolveBlock)resolve
228 | reject:(RCTPromiseRejectBlock)reject {
229 | // Apple's Authentication Services doesn't provide a direct sign-out method
230 | // Sign-out is typically handled at the application level
231 | // AutoFill passwords and passkeys are managed by the system
232 | resolve([NSNull null]);
233 | }
234 |
235 | #pragma mark - ASAuthorizationControllerDelegate
236 |
237 | - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization {
238 | if (!self.currentResolve) {
239 | return;
240 | }
241 |
242 | RCTPromiseResolveBlock resolve = self.currentResolve;
243 | self.currentReject = nil;
244 | self.currentResolve = nil;
245 |
246 | if ([authorization.credential isKindOfClass:[ASAuthorizationPlatformPublicKeyCredentialRegistration class]]) {
247 | // Passkey registration - handled by Apple's Authentication Services
248 | ASAuthorizationPlatformPublicKeyCredentialRegistration *registration = (ASAuthorizationPlatformPublicKeyCredentialRegistration *)authorization.credential;
249 |
250 | NSDictionary *result = @{
251 | @"id": registration.credentialID ? [registration.credentialID base64EncodedStringWithOptions:0] : @"",
252 | @"rawId": registration.credentialID ? [registration.credentialID base64EncodedStringWithOptions:0] : @"",
253 | @"response": @{
254 | @"attestationObject": registration.rawAttestationObject ? [registration.rawAttestationObject base64EncodedStringWithOptions:0] : @"",
255 | @"clientDataJSON": registration.rawClientDataJSON ? [registration.rawClientDataJSON base64EncodedStringWithOptions:0] : @""
256 | },
257 | @"type": @"public-key"
258 | };
259 |
260 | resolve(result);
261 | return;
262 | } else if ([authorization.credential isKindOfClass:[ASAuthorizationPlatformPublicKeyCredentialAssertion class]]) {
263 | // Passkey authentication - handled by Apple's Authentication Services
264 | ASAuthorizationPlatformPublicKeyCredentialAssertion *assertion = (ASAuthorizationPlatformPublicKeyCredentialAssertion *)authorization.credential;
265 |
266 | NSDictionary *result = @{
267 | @"type": @"passkey",
268 | @"authenticationResponseJson": [self createAuthenticationResponseJSON:assertion]
269 | };
270 |
271 | resolve(result);
272 | return;
273 | } else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
274 | // AutoFill password authentication - handled by Apple's Authentication Services
275 | ASPasswordCredential *passwordCredential = (ASPasswordCredential *)authorization.credential;
276 |
277 | NSDictionary *result = @{
278 | @"type": @"password",
279 | @"username": passwordCredential.user,
280 | @"password": passwordCredential.password
281 | };
282 |
283 | resolve(result);
284 | return;
285 | } else if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
286 | // Apple Sign In - officially supported by Authentication Services
287 | ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)authorization.credential;
288 |
289 | NSMutableDictionary *result = [@{
290 | @"type": @"apple-signin",
291 | @"id": appleIDCredential.user,
292 | @"idToken": appleIDCredential.identityToken ? [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding] : @""
293 | } mutableCopy];
294 |
295 | if (appleIDCredential.fullName) {
296 | if (appleIDCredential.fullName.givenName) {
297 | result[@"givenName"] = appleIDCredential.fullName.givenName;
298 | }
299 | if (appleIDCredential.fullName.familyName) {
300 | result[@"familyName"] = appleIDCredential.fullName.familyName;
301 | }
302 | if (appleIDCredential.fullName.givenName || appleIDCredential.fullName.familyName) {
303 | NSString *fullName = [NSString stringWithFormat:@"%@ %@",
304 | appleIDCredential.fullName.givenName ?: @"",
305 | appleIDCredential.fullName.familyName ?: @""];
306 | result[@"displayName"] = [fullName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
307 | }
308 | }
309 |
310 | if (appleIDCredential.email) {
311 | result[@"email"] = appleIDCredential.email;
312 | }
313 |
314 | resolve([result copy]);
315 | return;
316 | }
317 |
318 | // If we reach here, we couldn't handle the credential type
319 | resolve(@{@"type": @"unknown"});
320 | }
321 |
322 | - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error {
323 | if (!self.currentReject) {
324 | return;
325 | }
326 |
327 | RCTPromiseRejectBlock reject = self.currentReject;
328 | self.currentResolve = nil;
329 | self.currentReject = nil;
330 |
331 | NSString *errorCode = @"UNKNOWN_ERROR";
332 | NSString *errorMessage = error.localizedDescription;
333 |
334 | if ([error.domain isEqualToString:ASAuthorizationErrorDomain]) {
335 | switch (error.code) {
336 | case ASAuthorizationErrorCanceled:
337 | errorCode = @"USER_CANCELED";
338 | errorMessage = @"User canceled the authorization request";
339 | break;
340 | case ASAuthorizationErrorFailed:
341 | errorCode = @"AUTHORIZATION_FAILED";
342 | break;
343 | case ASAuthorizationErrorInvalidResponse:
344 | errorCode = @"INVALID_RESPONSE";
345 | break;
346 | case ASAuthorizationErrorNotHandled:
347 | errorCode = @"NOT_HANDLED";
348 | break;
349 | case ASAuthorizationErrorUnknown:
350 | errorCode = @"UNKNOWN_ERROR";
351 | break;
352 | }
353 | }
354 |
355 | reject(errorCode, errorMessage, error);
356 | }
357 |
358 | #pragma mark - ASAuthorizationControllerPresentationContextProviding
359 |
360 | - (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller {
361 | if (self.authenticationAnchor) {
362 | return self.authenticationAnchor;
363 | }
364 |
365 | // Fallback to finding a key window
366 | UIWindow *keyWindow = nil;
367 | for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {
368 | if (windowScene.activationState == UISceneActivationStateForegroundActive) {
369 | for (UIWindow *window in windowScene.windows) {
370 | if (window.isKeyWindow) {
371 | keyWindow = window;
372 | break;
373 | }
374 | }
375 | }
376 | }
377 |
378 | return keyWindow ?: [[UIApplication sharedApplication] windows].firstObject;
379 | }
380 |
381 | #pragma mark - Helper Methods
382 |
383 | - (NSString *)createAuthenticationResponseJSON:(ASAuthorizationPlatformPublicKeyCredentialAssertion *)assertion {
384 | NSDictionary *response = @{
385 | @"id": assertion.credentialID ? [assertion.credentialID base64EncodedStringWithOptions:0] : @"",
386 | @"rawId": assertion.credentialID ? [assertion.credentialID base64EncodedStringWithOptions:0] : @"",
387 | @"response": @{
388 | @"authenticatorData": assertion.rawAuthenticatorData ? [assertion.rawAuthenticatorData base64EncodedStringWithOptions:0] : @"",
389 | @"clientDataJSON": assertion.rawClientDataJSON ? [assertion.rawClientDataJSON base64EncodedStringWithOptions:0] : @"",
390 | @"signature": assertion.signature ? [assertion.signature base64EncodedStringWithOptions:0] : @"",
391 | @"userHandle": assertion.userID ? [assertion.userID base64EncodedStringWithOptions:0] : @""
392 | },
393 | @"type": @"public-key"
394 | };
395 |
396 | NSError *error;
397 | NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&error];
398 | if (error) {
399 | return @"{}";
400 | }
401 |
402 | return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
403 | }
404 |
405 | @end
406 |
--------------------------------------------------------------------------------
/example/ios/CredentialsManagerExample.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 54;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 0C80B921A6F3F58F76C31292 /* libPods-CredentialsManagerExample.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-CredentialsManagerExample.a */; };
11 | 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
12 | 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; };
13 | 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
14 | E85B69695C5D7AC95173C134 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */; };
15 | /* End PBXBuildFile section */
16 |
17 | /* Begin PBXFileReference section */
18 | 13B07F961A680F5B00A75B9A /* CredentialsManagerExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CredentialsManagerExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
19 | 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = CredentialsManagerExample/Images.xcassets; sourceTree = ""; };
20 | 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = CredentialsManagerExample/Info.plist; sourceTree = ""; };
21 | 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = CredentialsManagerExample/PrivacyInfo.xcprivacy; sourceTree = ""; };
22 | 3B4392A12AC88292D35C810B /* Pods-CredentialsManagerExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CredentialsManagerExample.debug.xcconfig"; path = "Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample.debug.xcconfig"; sourceTree = ""; };
23 | 5709B34CF0A7D63546082F79 /* Pods-CredentialsManagerExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CredentialsManagerExample.release.xcconfig"; path = "Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample.release.xcconfig"; sourceTree = ""; };
24 | 5DCACB8F33CDC322A6C60F78 /* libPods-CredentialsManagerExample.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-CredentialsManagerExample.a"; sourceTree = BUILT_PRODUCTS_DIR; };
25 | 761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = CredentialsManagerExample/AppDelegate.swift; sourceTree = ""; };
26 | 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = CredentialsManagerExample/LaunchScreen.storyboard; sourceTree = ""; };
27 | B546FE0F2DE77843007A8E3F /* CredentialsManagerExample.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = CredentialsManagerExample.entitlements; path = CredentialsManagerExample/CredentialsManagerExample.entitlements; sourceTree = ""; };
28 | ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
29 | /* End PBXFileReference section */
30 |
31 | /* Begin PBXFrameworksBuildPhase section */
32 | 13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
33 | isa = PBXFrameworksBuildPhase;
34 | buildActionMask = 2147483647;
35 | files = (
36 | 0C80B921A6F3F58F76C31292 /* libPods-CredentialsManagerExample.a in Frameworks */,
37 | );
38 | runOnlyForDeploymentPostprocessing = 0;
39 | };
40 | /* End PBXFrameworksBuildPhase section */
41 |
42 | /* Begin PBXGroup section */
43 | 13B07FAE1A68108700A75B9A /* CredentialsManagerExample */ = {
44 | isa = PBXGroup;
45 | children = (
46 | B546FE0F2DE77843007A8E3F /* CredentialsManagerExample.entitlements */,
47 | 13B07FB51A68108700A75B9A /* Images.xcassets */,
48 | 761780EC2CA45674006654EE /* AppDelegate.swift */,
49 | 13B07FB61A68108700A75B9A /* Info.plist */,
50 | 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
51 | 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
52 | );
53 | name = CredentialsManagerExample;
54 | sourceTree = "";
55 | };
56 | 2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
57 | isa = PBXGroup;
58 | children = (
59 | ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
60 | 5DCACB8F33CDC322A6C60F78 /* libPods-CredentialsManagerExample.a */,
61 | );
62 | name = Frameworks;
63 | sourceTree = "";
64 | };
65 | 832341AE1AAA6A7D00B99B32 /* Libraries */ = {
66 | isa = PBXGroup;
67 | children = (
68 | );
69 | name = Libraries;
70 | sourceTree = "";
71 | };
72 | 83CBB9F61A601CBA00E9B192 = {
73 | isa = PBXGroup;
74 | children = (
75 | 13B07FAE1A68108700A75B9A /* CredentialsManagerExample */,
76 | 832341AE1AAA6A7D00B99B32 /* Libraries */,
77 | 83CBBA001A601CBA00E9B192 /* Products */,
78 | 2D16E6871FA4F8E400B85C8A /* Frameworks */,
79 | BBD78D7AC51CEA395F1C20DB /* Pods */,
80 | );
81 | indentWidth = 2;
82 | sourceTree = "";
83 | tabWidth = 2;
84 | usesTabs = 0;
85 | };
86 | 83CBBA001A601CBA00E9B192 /* Products */ = {
87 | isa = PBXGroup;
88 | children = (
89 | 13B07F961A680F5B00A75B9A /* CredentialsManagerExample.app */,
90 | );
91 | name = Products;
92 | sourceTree = "";
93 | };
94 | BBD78D7AC51CEA395F1C20DB /* Pods */ = {
95 | isa = PBXGroup;
96 | children = (
97 | 3B4392A12AC88292D35C810B /* Pods-CredentialsManagerExample.debug.xcconfig */,
98 | 5709B34CF0A7D63546082F79 /* Pods-CredentialsManagerExample.release.xcconfig */,
99 | );
100 | path = Pods;
101 | sourceTree = "";
102 | };
103 | /* End PBXGroup section */
104 |
105 | /* Begin PBXNativeTarget section */
106 | 13B07F861A680F5B00A75B9A /* CredentialsManagerExample */ = {
107 | isa = PBXNativeTarget;
108 | buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "CredentialsManagerExample" */;
109 | buildPhases = (
110 | C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
111 | 13B07F871A680F5B00A75B9A /* Sources */,
112 | 13B07F8C1A680F5B00A75B9A /* Frameworks */,
113 | 13B07F8E1A680F5B00A75B9A /* Resources */,
114 | 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
115 | 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
116 | E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
117 | );
118 | buildRules = (
119 | );
120 | dependencies = (
121 | );
122 | name = CredentialsManagerExample;
123 | productName = CredentialsManagerExample;
124 | productReference = 13B07F961A680F5B00A75B9A /* CredentialsManagerExample.app */;
125 | productType = "com.apple.product-type.application";
126 | };
127 | /* End PBXNativeTarget section */
128 |
129 | /* Begin PBXProject section */
130 | 83CBB9F71A601CBA00E9B192 /* Project object */ = {
131 | isa = PBXProject;
132 | attributes = {
133 | LastUpgradeCheck = 1210;
134 | TargetAttributes = {
135 | 13B07F861A680F5B00A75B9A = {
136 | LastSwiftMigration = 1120;
137 | };
138 | };
139 | };
140 | buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "CredentialsManagerExample" */;
141 | compatibilityVersion = "Xcode 12.0";
142 | developmentRegion = en;
143 | hasScannedForEncodings = 0;
144 | knownRegions = (
145 | en,
146 | Base,
147 | );
148 | mainGroup = 83CBB9F61A601CBA00E9B192;
149 | productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
150 | projectDirPath = "";
151 | projectRoot = "";
152 | targets = (
153 | 13B07F861A680F5B00A75B9A /* CredentialsManagerExample */,
154 | );
155 | };
156 | /* End PBXProject section */
157 |
158 | /* Begin PBXResourcesBuildPhase section */
159 | 13B07F8E1A680F5B00A75B9A /* Resources */ = {
160 | isa = PBXResourcesBuildPhase;
161 | buildActionMask = 2147483647;
162 | files = (
163 | 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
164 | 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
165 | E85B69695C5D7AC95173C134 /* PrivacyInfo.xcprivacy in Resources */,
166 | );
167 | runOnlyForDeploymentPostprocessing = 0;
168 | };
169 | /* End PBXResourcesBuildPhase section */
170 |
171 | /* Begin PBXShellScriptBuildPhase section */
172 | 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
173 | isa = PBXShellScriptBuildPhase;
174 | buildActionMask = 2147483647;
175 | files = (
176 | );
177 | inputPaths = (
178 | "$(SRCROOT)/.xcode.env.local",
179 | "$(SRCROOT)/.xcode.env",
180 | );
181 | name = "Bundle React Native code and images";
182 | outputPaths = (
183 | );
184 | runOnlyForDeploymentPostprocessing = 0;
185 | shellPath = /bin/sh;
186 | shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n";
187 | };
188 | 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
189 | isa = PBXShellScriptBuildPhase;
190 | buildActionMask = 2147483647;
191 | files = (
192 | );
193 | inputFileListPaths = (
194 | "${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-frameworks-${CONFIGURATION}-input-files.xcfilelist",
195 | );
196 | name = "[CP] Embed Pods Frameworks";
197 | outputFileListPaths = (
198 | "${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-frameworks-${CONFIGURATION}-output-files.xcfilelist",
199 | );
200 | runOnlyForDeploymentPostprocessing = 0;
201 | shellPath = /bin/sh;
202 | shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-frameworks.sh\"\n";
203 | showEnvVarsInLog = 0;
204 | };
205 | C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
206 | isa = PBXShellScriptBuildPhase;
207 | buildActionMask = 2147483647;
208 | files = (
209 | );
210 | inputFileListPaths = (
211 | );
212 | inputPaths = (
213 | "${PODS_PODFILE_DIR_PATH}/Podfile.lock",
214 | "${PODS_ROOT}/Manifest.lock",
215 | );
216 | name = "[CP] Check Pods Manifest.lock";
217 | outputFileListPaths = (
218 | );
219 | outputPaths = (
220 | "$(DERIVED_FILE_DIR)/Pods-CredentialsManagerExample-checkManifestLockResult.txt",
221 | );
222 | runOnlyForDeploymentPostprocessing = 0;
223 | shellPath = /bin/sh;
224 | shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
225 | showEnvVarsInLog = 0;
226 | };
227 | E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
228 | isa = PBXShellScriptBuildPhase;
229 | buildActionMask = 2147483647;
230 | files = (
231 | );
232 | inputFileListPaths = (
233 | "${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-resources-${CONFIGURATION}-input-files.xcfilelist",
234 | );
235 | name = "[CP] Copy Pods Resources";
236 | outputFileListPaths = (
237 | "${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-resources-${CONFIGURATION}-output-files.xcfilelist",
238 | );
239 | runOnlyForDeploymentPostprocessing = 0;
240 | shellPath = /bin/sh;
241 | shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-CredentialsManagerExample/Pods-CredentialsManagerExample-resources.sh\"\n";
242 | showEnvVarsInLog = 0;
243 | };
244 | /* End PBXShellScriptBuildPhase section */
245 |
246 | /* Begin PBXSourcesBuildPhase section */
247 | 13B07F871A680F5B00A75B9A /* Sources */ = {
248 | isa = PBXSourcesBuildPhase;
249 | buildActionMask = 2147483647;
250 | files = (
251 | 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */,
252 | );
253 | runOnlyForDeploymentPostprocessing = 0;
254 | };
255 | /* End PBXSourcesBuildPhase section */
256 |
257 | /* Begin XCBuildConfiguration section */
258 | 13B07F941A680F5B00A75B9A /* Debug */ = {
259 | isa = XCBuildConfiguration;
260 | baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-CredentialsManagerExample.debug.xcconfig */;
261 | buildSettings = {
262 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
263 | CLANG_ENABLE_MODULES = YES;
264 | CODE_SIGN_ENTITLEMENTS = CredentialsManagerExample/CredentialsManagerExample.entitlements;
265 | CURRENT_PROJECT_VERSION = 1;
266 | DEVELOPMENT_TEAM = UDVM22XGUG;
267 | ENABLE_BITCODE = NO;
268 | INFOPLIST_FILE = CredentialsManagerExample/Info.plist;
269 | IPHONEOS_DEPLOYMENT_TARGET = 15.1;
270 | LD_RUNPATH_SEARCH_PATHS = (
271 | "$(inherited)",
272 | "@executable_path/Frameworks",
273 | );
274 | MARKETING_VERSION = 1.0;
275 | OTHER_LDFLAGS = (
276 | "$(inherited)",
277 | "-ObjC",
278 | "-lc++",
279 | );
280 | PRODUCT_BUNDLE_IDENTIFIER = com.jobpro.id;
281 | PRODUCT_NAME = CredentialsManagerExample;
282 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
283 | SWIFT_VERSION = 5.0;
284 | VERSIONING_SYSTEM = "apple-generic";
285 | };
286 | name = Debug;
287 | };
288 | 13B07F951A680F5B00A75B9A /* Release */ = {
289 | isa = XCBuildConfiguration;
290 | baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-CredentialsManagerExample.release.xcconfig */;
291 | buildSettings = {
292 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
293 | CLANG_ENABLE_MODULES = YES;
294 | CODE_SIGN_ENTITLEMENTS = CredentialsManagerExample/CredentialsManagerExample.entitlements;
295 | CURRENT_PROJECT_VERSION = 1;
296 | DEVELOPMENT_TEAM = UDVM22XGUG;
297 | INFOPLIST_FILE = CredentialsManagerExample/Info.plist;
298 | IPHONEOS_DEPLOYMENT_TARGET = 15.1;
299 | LD_RUNPATH_SEARCH_PATHS = (
300 | "$(inherited)",
301 | "@executable_path/Frameworks",
302 | );
303 | MARKETING_VERSION = 1.0;
304 | OTHER_LDFLAGS = (
305 | "$(inherited)",
306 | "-ObjC",
307 | "-lc++",
308 | );
309 | PRODUCT_BUNDLE_IDENTIFIER = com.jobpro.id;
310 | PRODUCT_NAME = CredentialsManagerExample;
311 | SWIFT_VERSION = 5.0;
312 | VERSIONING_SYSTEM = "apple-generic";
313 | };
314 | name = Release;
315 | };
316 | 83CBBA201A601CBA00E9B192 /* Debug */ = {
317 | isa = XCBuildConfiguration;
318 | buildSettings = {
319 | ALWAYS_SEARCH_USER_PATHS = NO;
320 | CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
321 | CLANG_CXX_LANGUAGE_STANDARD = "c++20";
322 | CLANG_CXX_LIBRARY = "libc++";
323 | CLANG_ENABLE_MODULES = YES;
324 | CLANG_ENABLE_OBJC_ARC = YES;
325 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
326 | CLANG_WARN_BOOL_CONVERSION = YES;
327 | CLANG_WARN_COMMA = YES;
328 | CLANG_WARN_CONSTANT_CONVERSION = YES;
329 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
330 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
331 | CLANG_WARN_EMPTY_BODY = YES;
332 | CLANG_WARN_ENUM_CONVERSION = YES;
333 | CLANG_WARN_INFINITE_RECURSION = YES;
334 | CLANG_WARN_INT_CONVERSION = YES;
335 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
336 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
337 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
338 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
339 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
340 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
341 | CLANG_WARN_STRICT_PROTOTYPES = YES;
342 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
343 | CLANG_WARN_UNREACHABLE_CODE = YES;
344 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
345 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
346 | COPY_PHASE_STRIP = NO;
347 | ENABLE_STRICT_OBJC_MSGSEND = YES;
348 | ENABLE_TESTABILITY = YES;
349 | "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
350 | GCC_C_LANGUAGE_STANDARD = gnu99;
351 | GCC_DYNAMIC_NO_PIC = NO;
352 | GCC_NO_COMMON_BLOCKS = YES;
353 | GCC_OPTIMIZATION_LEVEL = 0;
354 | GCC_PREPROCESSOR_DEFINITIONS = (
355 | "DEBUG=1",
356 | "$(inherited)",
357 | );
358 | GCC_SYMBOLS_PRIVATE_EXTERN = NO;
359 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
360 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
361 | GCC_WARN_UNDECLARED_SELECTOR = YES;
362 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
363 | GCC_WARN_UNUSED_FUNCTION = YES;
364 | GCC_WARN_UNUSED_VARIABLE = YES;
365 | IPHONEOS_DEPLOYMENT_TARGET = 15.1;
366 | LD_RUNPATH_SEARCH_PATHS = (
367 | /usr/lib/swift,
368 | "$(inherited)",
369 | );
370 | LIBRARY_SEARCH_PATHS = (
371 | "\"$(SDKROOT)/usr/lib/swift\"",
372 | "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
373 | "\"$(inherited)\"",
374 | );
375 | MTL_ENABLE_DEBUG_INFO = YES;
376 | ONLY_ACTIVE_ARCH = YES;
377 | OTHER_CPLUSPLUSFLAGS = (
378 | "$(OTHER_CFLAGS)",
379 | "-DFOLLY_NO_CONFIG",
380 | "-DFOLLY_MOBILE=1",
381 | "-DFOLLY_USE_LIBCPP=1",
382 | "-DFOLLY_CFG_NO_COROUTINES=1",
383 | "-DFOLLY_HAVE_CLOCK_GETTIME=1",
384 | );
385 | OTHER_LDFLAGS = (
386 | "$(inherited)",
387 | " ",
388 | );
389 | REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
390 | SDKROOT = iphoneos;
391 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
392 | USE_HERMES = true;
393 | };
394 | name = Debug;
395 | };
396 | 83CBBA211A601CBA00E9B192 /* Release */ = {
397 | isa = XCBuildConfiguration;
398 | buildSettings = {
399 | ALWAYS_SEARCH_USER_PATHS = NO;
400 | CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
401 | CLANG_CXX_LANGUAGE_STANDARD = "c++20";
402 | CLANG_CXX_LIBRARY = "libc++";
403 | CLANG_ENABLE_MODULES = YES;
404 | CLANG_ENABLE_OBJC_ARC = YES;
405 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
406 | CLANG_WARN_BOOL_CONVERSION = YES;
407 | CLANG_WARN_COMMA = YES;
408 | CLANG_WARN_CONSTANT_CONVERSION = YES;
409 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
410 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
411 | CLANG_WARN_EMPTY_BODY = YES;
412 | CLANG_WARN_ENUM_CONVERSION = YES;
413 | CLANG_WARN_INFINITE_RECURSION = YES;
414 | CLANG_WARN_INT_CONVERSION = YES;
415 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
416 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
417 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
418 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
419 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
420 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
421 | CLANG_WARN_STRICT_PROTOTYPES = YES;
422 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
423 | CLANG_WARN_UNREACHABLE_CODE = YES;
424 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
425 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
426 | COPY_PHASE_STRIP = YES;
427 | ENABLE_NS_ASSERTIONS = NO;
428 | ENABLE_STRICT_OBJC_MSGSEND = YES;
429 | "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
430 | GCC_C_LANGUAGE_STANDARD = gnu99;
431 | GCC_NO_COMMON_BLOCKS = YES;
432 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
433 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
434 | GCC_WARN_UNDECLARED_SELECTOR = YES;
435 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
436 | GCC_WARN_UNUSED_FUNCTION = YES;
437 | GCC_WARN_UNUSED_VARIABLE = YES;
438 | IPHONEOS_DEPLOYMENT_TARGET = 15.1;
439 | LD_RUNPATH_SEARCH_PATHS = (
440 | /usr/lib/swift,
441 | "$(inherited)",
442 | );
443 | LIBRARY_SEARCH_PATHS = (
444 | "\"$(SDKROOT)/usr/lib/swift\"",
445 | "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
446 | "\"$(inherited)\"",
447 | );
448 | MTL_ENABLE_DEBUG_INFO = NO;
449 | OTHER_CPLUSPLUSFLAGS = (
450 | "$(OTHER_CFLAGS)",
451 | "-DFOLLY_NO_CONFIG",
452 | "-DFOLLY_MOBILE=1",
453 | "-DFOLLY_USE_LIBCPP=1",
454 | "-DFOLLY_CFG_NO_COROUTINES=1",
455 | "-DFOLLY_HAVE_CLOCK_GETTIME=1",
456 | );
457 | OTHER_LDFLAGS = (
458 | "$(inherited)",
459 | " ",
460 | );
461 | REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
462 | SDKROOT = iphoneos;
463 | USE_HERMES = true;
464 | VALIDATE_PRODUCT = YES;
465 | };
466 | name = Release;
467 | };
468 | /* End XCBuildConfiguration section */
469 |
470 | /* Begin XCConfigurationList section */
471 | 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "CredentialsManagerExample" */ = {
472 | isa = XCConfigurationList;
473 | buildConfigurations = (
474 | 13B07F941A680F5B00A75B9A /* Debug */,
475 | 13B07F951A680F5B00A75B9A /* Release */,
476 | );
477 | defaultConfigurationIsVisible = 0;
478 | defaultConfigurationName = Release;
479 | };
480 | 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "CredentialsManagerExample" */ = {
481 | isa = XCConfigurationList;
482 | buildConfigurations = (
483 | 83CBBA201A601CBA00E9B192 /* Debug */,
484 | 83CBBA211A601CBA00E9B192 /* Release */,
485 | );
486 | defaultConfigurationIsVisible = 0;
487 | defaultConfigurationName = Release;
488 | };
489 | /* End XCConfigurationList section */
490 | };
491 | rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
492 | }
493 |
--------------------------------------------------------------------------------