@circle-fin/daa-react-native-sdk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/DaaReactNativeSdk.podspec +14 -8
  2. package/README.md +498 -24
  3. package/android/build.gradle +12 -7
  4. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +1 -18
  5. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +38 -4
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +139 -6
  7. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +50 -1
  8. package/build/DaaClient.d.ts +183 -3
  9. package/build/DaaClient.js +296 -12
  10. package/build/api/AccountsClient.d.ts +3 -0
  11. package/build/api/AccountsClient.js +3 -0
  12. package/build/api/AuthClient.d.ts +17 -42
  13. package/build/api/AuthClient.js +26 -62
  14. package/build/api/ContractExecutionsClient.d.ts +114 -0
  15. package/build/api/ContractExecutionsClient.js +462 -0
  16. package/build/api/DaaUserClient.d.ts +74 -11
  17. package/build/api/DaaUserClient.js +84 -17
  18. package/build/api/TransactionsClient.d.ts +1 -1
  19. package/build/api/TransactionsClient.js +1 -0
  20. package/build/api/TransfersClient.d.ts +3 -0
  21. package/build/api/TransfersClient.js +3 -0
  22. package/build/api/WithdrawalsClient.d.ts +3 -0
  23. package/build/api/WithdrawalsClient.js +3 -0
  24. package/build/api/deviceApproval.d.ts +48 -0
  25. package/build/api/deviceApproval.js +247 -0
  26. package/build/api/deviceStatus.d.ts +61 -0
  27. package/build/api/deviceStatus.js +216 -0
  28. package/build/api/loginFailure.d.ts +10 -2
  29. package/build/api/loginFailure.js +33 -2
  30. package/build/api/signedResource.d.ts +49 -2
  31. package/build/api/signedResource.js +135 -36
  32. package/build/auth/RegistrationFlowKey.js +1 -1
  33. package/build/auth/daaRegistrationNative.d.ts +0 -22
  34. package/build/auth/daaRegistrationNative.js +3 -29
  35. package/build/auth/deviceAuthorization.d.ts +17 -3
  36. package/build/auth/deviceAuthorization.js +60 -8
  37. package/build/auth/registrationAuthorization.d.ts +2 -2
  38. package/build/auth/registrationAuthorization.js +13 -10
  39. package/build/config.d.ts +27 -0
  40. package/build/config.js +15 -0
  41. package/build/crypto/matchingCode.d.ts +47 -0
  42. package/build/crypto/matchingCode.js +93 -0
  43. package/build/errors.d.ts +150 -33
  44. package/build/errors.js +208 -47
  45. package/build/index.d.ts +11 -3
  46. package/build/models/ContractExecution.d.ts +197 -0
  47. package/build/models/ContractExecution.js +130 -0
  48. package/build/models/CreateContractExecutionRequest.d.ts +81 -0
  49. package/build/models/CreateContractExecutionRequest.js +19 -0
  50. package/build/models/DaaUserContext.d.ts +53 -3
  51. package/build/models/DaaUserContext.js +33 -2
  52. package/build/models/DeviceStatus.d.ts +69 -0
  53. package/build/models/DeviceStatus.js +19 -0
  54. package/build/models/PendingDeviceApproval.d.ts +121 -0
  55. package/build/models/PendingDeviceApproval.js +208 -0
  56. package/build/models/PendingDeviceRegistration.d.ts +162 -23
  57. package/build/models/PendingDeviceRegistration.js +525 -69
  58. package/build/models/PreparedContractExecution.d.ts +70 -0
  59. package/build/models/PreparedContractExecution.js +77 -0
  60. package/build/models/PreparedSocialLogin.d.ts +19 -26
  61. package/build/models/PreparedSocialLogin.js +32 -15
  62. package/build/models/Transaction.d.ts +48 -2
  63. package/build/models/Transaction.js +52 -4
  64. package/build/models/codeSecrets.d.ts +100 -0
  65. package/build/models/codeSecrets.js +321 -0
  66. package/build/securekey/InMemorySecureKey.d.ts +3 -1
  67. package/build/securekey/InMemorySecureKey.js +47 -6
  68. package/build/securekey/NativeSecureKey.d.ts +3 -1
  69. package/build/securekey/NativeSecureKey.js +204 -27
  70. package/build/securekey/NativeSecureKeyBridge.d.ts +72 -4
  71. package/build/securekey/SecureKey.d.ts +128 -8
  72. package/build/securekey/alias.d.ts +9 -0
  73. package/build/securekey/alias.js +11 -2
  74. package/build/securekey/ownerAuthKeyResolver.d.ts +26 -9
  75. package/build/securekey/ownerAuthKeyResolver.js +35 -20
  76. package/build/securekey/registration.d.ts +19 -0
  77. package/build/securekey/registration.js +38 -0
  78. package/build/securekey/resolveNativeBridge.d.ts +3 -0
  79. package/build/securekey/resolveNativeBridge.js +88 -7
  80. package/build/transport/headers.d.ts +11 -0
  81. package/build/transport/headers.js +36 -0
  82. package/build/wire/contractExecutionPayload.d.ts +24 -0
  83. package/build/wire/contractExecutionPayload.js +130 -0
  84. package/build/wire/daaStatusCodes.d.ts +20 -3
  85. package/build/wire/daaStatusCodes.js +20 -3
  86. package/build/wire/deviceContextPayload.d.ts +9 -7
  87. package/build/wire/deviceContextPayload.js +9 -7
  88. package/build/wire/deviceRegistrationResultPayload.d.ts +55 -10
  89. package/build/wire/deviceRegistrationResultPayload.js +116 -82
  90. package/build/wire/deviceStatusPayload.d.ts +20 -0
  91. package/build/wire/deviceStatusPayload.js +66 -0
  92. package/build/wire/instant.js +4 -1
  93. package/build/wire/pendingRegistrationPayload.d.ts +16 -0
  94. package/build/wire/pendingRegistrationPayload.js +18 -0
  95. package/build/wire/socialLoginRequestPayload.d.ts +0 -5
  96. package/build/wire/socialLoginRequestPayload.js +2 -19
  97. package/build/wire/transactionPayload.d.ts +2 -2
  98. package/build/wire/transactionPayload.js +27 -4
  99. package/ios/DaaRegistrationModule.swift +1 -19
  100. package/ios/DaaSecureKeyExceptions.swift +53 -5
  101. package/ios/DaaSecureKeyModule.swift +149 -5
  102. package/ios/InstallationIdentityStore.swift +43 -7
  103. package/package.json +1 -1
  104. package/src/DaaClient.ts +353 -15
  105. package/src/api/AccountsClient.ts +3 -0
  106. package/src/api/AuthClient.ts +33 -98
  107. package/src/api/ContractExecutionsClient.ts +527 -0
  108. package/src/api/DaaUserClient.ts +92 -17
  109. package/src/api/TransactionsClient.ts +1 -0
  110. package/src/api/TransfersClient.ts +3 -0
  111. package/src/api/WithdrawalsClient.ts +3 -0
  112. package/src/api/deviceApproval.ts +306 -0
  113. package/src/api/deviceStatus.ts +238 -0
  114. package/src/api/loginFailure.ts +39 -2
  115. package/src/api/signedResource.ts +206 -46
  116. package/src/auth/RegistrationFlowKey.ts +1 -1
  117. package/src/auth/daaRegistrationNative.ts +4 -49
  118. package/src/auth/deviceAuthorization.ts +74 -11
  119. package/src/auth/registrationAuthorization.ts +12 -9
  120. package/src/config.ts +36 -0
  121. package/src/crypto/matchingCode.ts +100 -0
  122. package/src/errors.ts +309 -52
  123. package/src/index.ts +36 -1
  124. package/src/models/ContractExecution.ts +250 -0
  125. package/src/models/CreateContractExecutionRequest.ts +100 -0
  126. package/src/models/DaaUserContext.ts +59 -3
  127. package/src/models/DeviceStatus.ts +50 -0
  128. package/src/models/PendingDeviceApproval.ts +229 -0
  129. package/src/models/PendingDeviceRegistration.ts +673 -79
  130. package/src/models/PreparedContractExecution.ts +128 -0
  131. package/src/models/PreparedSocialLogin.ts +41 -31
  132. package/src/models/Transaction.ts +77 -2
  133. package/src/models/codeSecrets.ts +360 -0
  134. package/src/securekey/InMemorySecureKey.ts +61 -7
  135. package/src/securekey/NativeSecureKey.ts +234 -25
  136. package/src/securekey/NativeSecureKeyBridge.ts +84 -4
  137. package/src/securekey/SecureKey.ts +138 -8
  138. package/src/securekey/alias.ts +11 -3
  139. package/src/securekey/ownerAuthKeyResolver.ts +63 -24
  140. package/src/securekey/registration.ts +40 -0
  141. package/src/securekey/resolveNativeBridge.ts +167 -9
  142. package/src/transport/headers.ts +47 -0
  143. package/src/wire/contractExecutionPayload.ts +152 -0
  144. package/src/wire/daaStatusCodes.ts +20 -3
  145. package/src/wire/deviceContextPayload.ts +9 -7
  146. package/src/wire/deviceRegistrationResultPayload.ts +156 -98
  147. package/src/wire/deviceStatusPayload.ts +68 -0
  148. package/src/wire/instant.ts +4 -1
  149. package/src/wire/pendingRegistrationPayload.ts +44 -1
  150. package/src/wire/socialLoginRequestPayload.ts +2 -25
  151. package/src/wire/transactionPayload.ts +40 -4
  152. package/build/auth/prepareReceipt.d.ts +0 -150
  153. package/build/auth/prepareReceipt.js +0 -357
  154. package/build/crypto/es256Jws.d.ts +0 -56
  155. package/build/crypto/es256Jws.js +0 -196
  156. package/src/auth/prepareReceipt.ts +0 -522
  157. package/src/crypto/es256Jws.ts +0 -240
@@ -76,21 +76,26 @@ android {
76
76
 
77
77
  dependencies {
78
78
  // Pin the native SDK so dependency resolution is reproducible and updates
79
- // are deliberate. 0.6.0 provides the APIs and behaviour this module relies
80
- // on: it sets all of the BiometricPrompt text itself from the validated
81
- // operation, so signDeviceAuthorization and
79
+ // are deliberate. 0.8.0 provides the APIs and behaviour this module relies
80
+ // on: it has resolveExisting() and acknowledgeRegistration(authKeyId,
81
+ // ownerBindingId), which NativeSecureKeyStore.resolveExisting and the
82
+ // acknowledgement call through DaaSecureKeyModule.kt; it sets all of the
83
+ // BiometricPrompt text itself from the validated operation, so signDeviceAuthorization and
82
84
  // signRegistrationDeviceAuthorization take the FragmentActivity directly
83
85
  // and DaaSecureKeyModule.kt passes no prompt text; its registration signer
84
- // accepts the minimal device-proof claim set this package sends; it has
86
+ // accepts the minimal device-proof claim set this package sends and allows
87
+ // `register_device_key` version 3 on `/v1/accounts/auth/keys` (first
88
+ // released in 0.8.0; 0.7.0 and earlier refuse to sign Device Registration
89
+ // Complete); it has
85
90
  // the native SCA ceremony (DaaScaApproveContract / DaaScaEnrollContract)
86
91
  // with strict callback parsing, which DaaScaModule.kt bridges, and runs a
87
92
  // custom-scheme enrollment redirect only in an Auth Tab (with no allowed
88
93
  // Auth Tab browser the ceremony fails Unsupported(InsecureRedirect)); and
89
- // it has DaaPrepareReceiptSignature, DaaSecureRandom, and
90
- // DaaRegistrationFlowKey, which DaaRegistrationModule.kt calls. The SCA
94
+ // it has DaaSecureRandom and DaaRegistrationFlowKey, which
95
+ // DaaRegistrationModule.kt calls. The SCA
91
96
  // ceremony requires compileSdk 36 and AGP 8.9.1+ of every consumer
92
97
  // (androidx.browser 1.9.0), hence the 36 defaults above.
93
- api("com.circle.daa:daa-android-sdk:0.6.0")
98
+ api("com.circle.daa:daa-android-sdk:0.8.0")
94
99
  // This module calls runBlocking. daa-android-sdk scopes coroutines as
95
100
  // implementation, so it is not on this compile classpath transitively.
96
101
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
@@ -16,7 +16,6 @@
16
16
 
17
17
  package com.circle.daa.reactnative
18
18
 
19
- import com.circle.daa.sdk.DaaPrepareReceiptSignature
20
19
  import com.circle.daa.sdk.DaaRegistrationAuthorizationSigningInput
21
20
  import com.circle.daa.sdk.DaaRegistrationFlowKey
22
21
  import com.circle.daa.sdk.DaaSecureRandom
@@ -28,8 +27,7 @@ import java.util.concurrent.ConcurrentHashMap
28
27
  // Thin Expo bridge to the native registration primitives. THIS IS NOT
29
28
  // DaaSecureKey. Verifier bytes come from DaaSecureRandom; the ephemeral
30
29
  // flow key is DaaRegistrationFlowKey, cached here so the private key never
31
- // crosses into JavaScript; the Prepare receipt signature is checked by
32
- // DaaPrepareReceiptSignature.
30
+ // crosses into JavaScript.
33
31
 
34
32
  class DaaRegistrationModule : Module() {
35
33
  private val flowKeys = ConcurrentHashMap<String, DaaRegistrationFlowKey>()
@@ -94,21 +92,6 @@ class DaaRegistrationModule : Module() {
94
92
  unpaddedBase64Url(signature)
95
93
  }
96
94
  }
97
-
98
- // Verify-only, against a key JS pinned from the SDK's own trust
99
- // anchor — never a key from the token. DaaPrepareReceiptSignature
100
- // (daa-android-sdk) does the check with java.security: a signature
101
- // problem is `false`, and a key that is not a P-256 point throws
102
- // and maps to CONTRACT_VIOLATION.
103
- AsyncFunction("verifyPrepareReceiptSignature") { publicKeyX963Base64Url: String, signingInputBase64Url: String, signatureBase64Url: String ->
104
- runRegistration {
105
- DaaPrepareReceiptSignature.verify(
106
- decodeUnpaddedBase64Url(publicKeyX963Base64Url),
107
- decodeUnpaddedBase64Url(signingInputBase64Url),
108
- decodeUnpaddedBase64Url(signatureBase64Url),
109
- )
110
- }
111
- }
112
95
  }
113
96
 
114
97
  private fun <T> runRegistration(block: () -> T): T {
@@ -23,9 +23,40 @@ import expo.modules.kotlin.exception.CodedException
23
23
  internal class UserAuthRequiredException :
24
24
  CodedException("USER_AUTH_REQUIRED", "User authentication is required", null)
25
25
 
26
+ // The user dismissed the BiometricPrompt. Kept distinct from
27
+ // USER_AUTH_REQUIRED: a cancel is the user's choice, not a credential problem,
28
+ // and the TypeScript side reports it as `user_cancelled`.
29
+ internal class UserCancelledException :
30
+ CodedException("USER_CANCELLED", "User authentication was cancelled", null)
31
+
26
32
  internal class NotInitializedException :
27
33
  CodedException("NOT_INITIALIZED", "Secure key is not initialized", null)
28
34
 
35
+ // No screen lock, or (StrongBiometricNotEnrolled) a screen lock but no
36
+ // fingerprint or face enrolled, so no device key can be created. The user
37
+ // fixes it in Settings; retrying does not help.
38
+ internal class DeviceLockNotSetException :
39
+ CodedException("DEVICE_LOCK_NOT_SET", "The device has no screen lock or biometric set up", null)
40
+
41
+ // Usually no hardware-backed keystore or biometric hardware, so this device can
42
+ // never hold a device key. daa-android-sdk 0.7.0 also reports
43
+ // SecureHardwareUnavailable for temporary failures (BIOMETRIC_ERROR_HW_UNAVAILABLE,
44
+ // a keystore ProviderException), so this is not always permanent.
45
+ internal class DeviceNotSupportedException :
46
+ CodedException("DEVICE_NOT_SUPPORTED", "Secure hardware is unavailable for this operation", null)
47
+
48
+ // Android invalidated the key, for example after a new fingerprint or face was
49
+ // enrolled, all were removed, or the screen lock was removed. The key cannot
50
+ // sign again. It stays in the keystore and nothing here can delete it, so a new
51
+ // key today needs a reinstall or cleared app data, then a new registration.
52
+ internal class KeyInvalidatedException :
53
+ CodedException("KEY_INVALIDATED", "The device key was invalidated and cannot be recovered", null)
54
+
55
+ // The typed matching code is not the code the approval body and code secret
56
+ // produce. Checked before the BiometricPrompt; the user can type it again.
57
+ internal class MatchingCodeMismatchException :
58
+ CodedException("MATCHING_CODE_MISMATCH", "The typed code is not the matching code", null)
59
+
29
60
  internal class ContractViolationException(
30
61
  message: String = "Native secure-key operation failed",
31
62
  ) : CodedException("CONTRACT_VIOLATION", message, null)
@@ -41,19 +72,22 @@ internal fun mappedSecureKeyException(error: Throwable): CodedException {
41
72
  return ContractViolationException()
42
73
  }
43
74
  return when (keyError) {
44
- DaaSecureKeyError.UserCancelled,
75
+ DaaSecureKeyError.UserCancelled -> UserCancelledException()
45
76
  DaaSecureKeyError.AuthenticationFailed,
46
- DaaSecureKeyError.DeviceCredentialNotSet,
47
77
  -> UserAuthRequiredException()
78
+ DaaSecureKeyError.DeviceCredentialNotSet,
79
+ DaaSecureKeyError.StrongBiometricNotEnrolled,
80
+ -> DeviceLockNotSetException()
81
+ DaaSecureKeyError.SecureHardwareUnavailable -> DeviceNotSupportedException()
82
+ DaaSecureKeyError.KeyInvalidated -> KeyInvalidatedException()
48
83
  DaaSecureKeyError.KeyNotFound,
49
84
  DaaSecureKeyError.ResolutionRequired,
50
85
  -> NotInitializedException()
86
+ DaaSecureKeyError.MatchingCodeMismatch -> MatchingCodeMismatchException()
51
87
  DaaSecureKeyError.InvalidAppId,
52
88
  DaaSecureKeyError.InvalidSigningInput,
53
89
  DaaSecureKeyError.AuthKeyRegistrationRequired,
54
- DaaSecureKeyError.SecureHardwareUnavailable,
55
90
  DaaSecureKeyError.KeyCreationFailed,
56
- DaaSecureKeyError.KeyInvalidated,
57
91
  DaaSecureKeyError.KeyAccessFailed,
58
92
  DaaSecureKeyError.KeyMetadataUnavailable,
59
93
  DaaSecureKeyError.KeyMetadataVersionUnsupported,
@@ -68,10 +68,52 @@ class DaaSecureKeyModule : Module() {
68
68
  runKey { keyFor(appId, environment).publicKeySpkiBase64Url() }
69
69
  }
70
70
 
71
- // Reached from OwnerAuthKey.acknowledgeRegistration() via the TS bridge.
72
- // This is the only registration-ack entry point; do not add a parallel one.
73
- AsyncFunction("acknowledgeRegistration") { appId: String, environment: String ->
74
- runKey { keyFor(appId, environment).acknowledgeRegistration() }
71
+ // Reached from OwnerAuthKey.acknowledgeRegistration(registration) via
72
+ // the TS bridge. This is the only registration-ack entry point; do not
73
+ // add a parallel one. Native always upserts the identifiers into the
74
+ // durable registration record, so a re-registration that assigned new
75
+ // ones replaces the old ones. The deprecated no-identifier variant is
76
+ // not reached: it records nothing resolveExisting could return.
77
+ AsyncFunction("acknowledgeRegistration") {
78
+ appId: String,
79
+ environment: String,
80
+ authKeyId: String,
81
+ ownerBindingId: String,
82
+ ->
83
+ runKey {
84
+ keyFor(appId, environment).acknowledgeRegistration(
85
+ authKeyId = authKeyId,
86
+ ownerBindingId = ownerBindingId,
87
+ )
88
+ }
89
+ }
90
+
91
+ // Read-only lookup: never mints a key and never shows
92
+ // a BiometricPrompt. Returns the registration record, or null when
93
+ // there is no key or it has no recorded identifiers.
94
+ AsyncFunction("resolveExisting") { appId: String, environment: String ->
95
+ runKey {
96
+ // existingKeyFor, not keyFor: this lookup must not mint an
97
+ // installation ID, or replace a malformed one, on its way to
98
+ // "no key".
99
+ existingKeyFor(appId, environment)?.resolveExisting()?.let { registered ->
100
+ mapOf(
101
+ "authKeyId" to registered.authKeyId,
102
+ "ownerBindingId" to registered.ownerBindingId,
103
+ )
104
+ }
105
+ }
106
+ }
107
+
108
+ // Explicit, user-initiated local delete of the key and its metadata.
109
+ // Local only: it does not revoke the key with Circle. Idempotent.
110
+ AsyncFunction("forgetLocalKey") { appId: String, environment: String ->
111
+ runKey {
112
+ // existingKeyFor, not keyFor: a delete must not mint an
113
+ // installation ID. With none, no key can exist, so there is
114
+ // nothing to delete.
115
+ existingKeyFor(appId, environment)?.forgetLocalKey()
116
+ }
75
117
  }
76
118
 
77
119
  // Typed native signDeviceAuthorization — not a generic sign(bytes). The
@@ -102,6 +144,63 @@ class DaaSecureKeyModule : Module() {
102
144
  }
103
145
  }
104
146
 
147
+ // Typed native device approval — signDeviceAuthorization with
148
+ // DaaDeviceAuthorizationSigningInput.forDeviceApproval, which checks
149
+ // that the approval body is the one the signing input commits to, that
150
+ // the code secret opens its codeSeal, and that enteredCode is the code
151
+ // they produce, all before the BiometricPrompt. A wrong code throws
152
+ // MatchingCodeMismatch (MATCHING_CODE_MISMATCH). The prompt shows the
153
+ // code; nothing here sets its text.
154
+ AsyncFunction("signDeviceApproval") {
155
+ appId: String,
156
+ environment: String,
157
+ signingInputBase64Url: String,
158
+ requestBodyBase64Url: String,
159
+ codeSecretBase64Url: String,
160
+ enteredCode: String,
161
+ ->
162
+ val activity =
163
+ appContext.currentActivity as? FragmentActivity
164
+ ?: throw ContractViolationException(
165
+ "signDeviceApproval requires a FragmentActivity",
166
+ )
167
+ runKey {
168
+ val signature =
169
+ keyFor(appId, environment).signDeviceAuthorization(
170
+ DaaDeviceAuthorizationSigningInput.forDeviceApproval(
171
+ exactBytes = decodeUnpaddedBase64Url(signingInputBase64Url),
172
+ requestBody = decodeUnpaddedBase64Url(requestBodyBase64Url),
173
+ codeSecret = decodeUnpaddedBase64Url(codeSecretBase64Url),
174
+ enteredCode = enteredCode,
175
+ ),
176
+ activity,
177
+ )
178
+ unpaddedBase64Url(signature)
179
+ }
180
+ }
181
+
182
+ // The key's add-a-device code secret, kept in Keystore-encrypted
183
+ // storage across restarts. Never prompts. Once the TS side sends a
184
+ // secret it deletes it here, and keeps the sent copy in process
185
+ // memory only.
186
+ AsyncFunction("codeSecret") { appId: String, environment: String ->
187
+ runKey { unpaddedBase64Url(keyFor(appId, environment).codeSecret()) }
188
+ }
189
+
190
+ // Deletes the stored code secret only when it equals these bytes.
191
+ AsyncFunction("deleteCodeSecret") {
192
+ appId: String,
193
+ environment: String,
194
+ secretBase64Url: String,
195
+ ->
196
+ runKey {
197
+ // existingKeyFor, not keyFor: a delete must not mint an
198
+ // installation ID. With none, no key or secret can exist.
199
+ existingKeyFor(appId, environment)
200
+ ?.deleteCodeSecret(decodeUnpaddedBase64Url(secretBase64Url))
201
+ }
202
+ }
203
+
105
204
  // Typed native signRegistrationDeviceAuthorization — the registration
106
205
  // counterpart of signDeviceAuthorization above, NOT the same call. The
107
206
  // Base64URL payload is the exact Device Registration Complete
@@ -144,7 +243,20 @@ class DaaSecureKeyModule : Module() {
144
243
  }
145
244
  }
146
245
 
147
- private fun keyFor(appId: String, environmentWire: String): DaaSecureKey {
246
+ private fun keyFor(appId: String, environmentWire: String): DaaSecureKey =
247
+ resolveKey(appId, environmentWire, mintInstallationId = true)
248
+ ?: throw ContractViolationException()
249
+
250
+ // For resolveExisting: like keyFor, but never mints or replaces the
251
+ // installation ID. null when this install has none yet, so no key can exist.
252
+ private fun existingKeyFor(appId: String, environmentWire: String): DaaSecureKey? =
253
+ resolveKey(appId, environmentWire, mintInstallationId = false)
254
+
255
+ private fun resolveKey(
256
+ appId: String,
257
+ environmentWire: String,
258
+ mintInstallationId: Boolean,
259
+ ): DaaSecureKey? {
148
260
  val environment =
149
261
  DaaEnvironment.entries.find { it.wireValue == environmentWire }
150
262
  ?: throw ContractViolationException()
@@ -156,11 +268,16 @@ class DaaSecureKeyModule : Module() {
156
268
  val context =
157
269
  appContext.reactContext?.applicationContext
158
270
  ?: throw ContractViolationException()
271
+ val installation =
272
+ if (mintInstallationId) installationId(context) else existingInstallationId(context)
273
+ if (installation == null) {
274
+ return null
275
+ }
159
276
  val identity =
160
277
  DaaAuthKeyIdentity(
161
278
  appId = appId,
162
279
  environment = environment,
163
- installationId = installationId(context),
280
+ installationId = installation,
164
281
  )
165
282
  val created = DaaSecureKey(context, identity)
166
283
  val raced = keys.putIfAbsent(alias, created)
@@ -182,4 +299,20 @@ class DaaSecureKeyModule : Module() {
182
299
  return loaded
183
300
  }
184
301
  }
302
+
303
+ private fun existingInstallationId(context: Context): UUID? {
304
+ val cached = installationId
305
+ if (cached != null) {
306
+ return cached
307
+ }
308
+ synchronized(installationLock) {
309
+ val locked = installationId
310
+ if (locked != null) {
311
+ return locked
312
+ }
313
+ val loaded = InstallationIdentityStore.loadExisting(context) ?: return null
314
+ installationId = loaded
315
+ return loaded
316
+ }
317
+ }
185
318
  }
@@ -17,7 +17,11 @@
17
17
  package com.circle.daa.reactnative
18
18
 
19
19
  import android.content.Context
20
+ import android.system.ErrnoException
21
+ import android.system.Os
22
+ import android.system.OsConstants
20
23
  import java.io.File
24
+ import java.io.IOException
21
25
  import java.util.UUID
22
26
 
23
27
  // Durable per-install UUID for DaaAuthKeyIdentity.installationId.
@@ -27,6 +31,20 @@ import java.util.UUID
27
31
 
28
32
  internal object InstallationIdentityStore {
29
33
  private const val FILE_NAME = "daa-installation-id"
34
+
35
+ // UUID.fromString accepts shortened groups ("1-1-1-1-1"), so a corrupt
36
+ // file could parse as a different installation ID. Only the full
37
+ // 8-4-4-4-12 form this store writes is accepted.
38
+ private val CANONICAL_UUID =
39
+ Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
40
+
41
+ private fun parseCanonical(text: String): UUID? {
42
+ val trimmed = text.trim()
43
+ if (!CANONICAL_UUID.matches(trimmed)) {
44
+ return null
45
+ }
46
+ return runCatching { UUID.fromString(trimmed) }.getOrNull()
47
+ }
30
48
  private val lock = Any()
31
49
 
32
50
  fun loadOrCreate(context: Context): UUID {
@@ -54,6 +72,37 @@ internal object InstallationIdentityStore {
54
72
  }
55
73
  }
56
74
 
75
+ // Read-only lookup for resolveExisting: never mints and never deletes.
76
+ // null only when the file does not exist (no key can exist under an
77
+ // installation ID that was never minted). An unreadable or malformed
78
+ // file throws and is left in place, so resolveExisting reports an error rather
79
+ // than "no key"; loadOrCreate's delete-and-remint stays on the create path.
80
+ fun loadExisting(context: Context): UUID? {
81
+ synchronized(lock) {
82
+ val file = File(context.noBackupFilesDir, FILE_NAME)
83
+ // Not file.exists(): it also returns false when the path cannot be
84
+ // inspected (for example a directory without search permission),
85
+ // which would report "no key" for an ID that exists. stat gives
86
+ // the errno, and only ENOENT means absent.
87
+ try {
88
+ Os.stat(file.path)
89
+ } catch (error: ErrnoException) {
90
+ if (error.errno == OsConstants.ENOENT) {
91
+ return null
92
+ }
93
+ throw ContractViolationException("Installation identity is unreadable")
94
+ }
95
+ val text =
96
+ try {
97
+ file.readText()
98
+ } catch (error: IOException) {
99
+ throw ContractViolationException("Installation identity is unreadable")
100
+ }
101
+ return parseCanonical(text)
102
+ ?: throw ContractViolationException("Installation identity is malformed")
103
+ }
104
+ }
105
+
57
106
  // Truncated or garbage files are wiped so the next mint is a new UUID.
58
107
  // That does NOT uninstall: the previous Keystore key remains under the
59
108
  // old alias, still registered with Circle if enrollment happened, never
@@ -63,7 +112,7 @@ internal object InstallationIdentityStore {
63
112
  if (!file.exists()) {
64
113
  return null
65
114
  }
66
- val parsed = runCatching { UUID.fromString(file.readText().trim()) }.getOrNull()
115
+ val parsed = parseCanonical(file.readText())
67
116
  if (parsed == null) {
68
117
  file.delete()
69
118
  return null
@@ -18,8 +18,28 @@
18
18
  import { AuthClient } from './api/AuthClient';
19
19
  import { type DaaUserClient } from './api/DaaUserClient';
20
20
  import type { DaaEnvironment, DaaSdkConfiguration, DeviceKeyPolicy } from './config';
21
+ import type { DeviceStatus } from './models/DeviceStatus';
21
22
  import { type DaaUserContext } from './models/DaaUserContext';
22
23
  import type { DaaTransport } from './transport/DaaTransport';
24
+ /**
25
+ * The result of {@link DaaClient.restore}.
26
+ *
27
+ * - `ACTIVE` — Circle confirmed the AuthKey registered on this device; pass
28
+ * `context` to {@link DaaClient.forUser}.
29
+ * - `no_local_key` — this device holds no registered AuthKey for that
30
+ * `clientEntityId`: the app was reinstalled, the key was forgotten, or the
31
+ * `clientEntityId` is not the one this device enrolled. Run the social login
32
+ * ceremony (`auth.prepareSocialLogin`) when the user chooses to sign in.
33
+ *
34
+ * Every other outcome is a thrown `DaaError`, never a variant here, so an app
35
+ * cannot mistake a failure for "no key" and silently start a new login.
36
+ */
37
+ export type SessionRestoreResult = Readonly<{
38
+ status: 'ACTIVE';
39
+ context: DaaUserContext;
40
+ }> | Readonly<{
41
+ status: 'no_local_key';
42
+ }>;
23
43
  /**
24
44
  * Root DAA client.
25
45
  *
@@ -40,9 +60,12 @@ export declare class DaaClient {
40
60
  /**
41
61
  * The authenticated operations surface for one user.
42
62
  *
43
- * Opens only for an `ACTIVE` `DaaUserContext` decoded from Device Registration
44
- * Complete. A fabricated object, a `RECOVERY_PENDING` result, or a missing
45
- * context fail closed — they are not an Owner-bound credential.
63
+ * Opens only for an `ACTIVE` `DaaUserContext` this SDK minted: one decoded
64
+ * from Device Registration Complete, or one returned by {@link restore} after
65
+ * the service confirmed the stored registration. Both are bound to the local
66
+ * AuthKey's thumbprint, which every signed operation re-checks. A fabricated
67
+ * object, a `RECOVERY_PENDING` result, or a missing context fail closed —
68
+ * they are not an Owner-bound credential.
46
69
  *
47
70
  * The context is carried into the surface rather than only checked at the
48
71
  * door. `deviceContext.authKeyId` is the `kid` every signed write's
@@ -54,4 +77,161 @@ export declare class DaaClient {
54
77
  * to sign with at all.
55
78
  */
56
79
  forUser(context: DaaUserContext): DaaUserClient;
80
+ /**
81
+ * Restore a signed-in user after an app restart with the AuthKey this device
82
+ * already registered, instead of a new social login.
83
+ *
84
+ * `clientEntityId` is the value the app stored, keyed by its own user id,
85
+ * when that user last completed login (`DaaUserContext.clientEntityId`). It
86
+ * only selects which local key to look for; it grants nothing by itself — see
87
+ * the `OwnerKeyIdentity` note in `securekey/SecureKey.ts`.
88
+ *
89
+ * Steps:
90
+ *
91
+ * 1. Look up the registered AuthKey and the `authKeyId` recorded when Circle
92
+ * registered it. This never creates a key and never prompts. None found
93
+ * resolves `{ status: 'no_local_key' }`.
94
+ * 2. Sign `GET /v1/accounts/auth/context` (`get_device_context`) with that
95
+ * key, `kid` = the stored `authKeyId`. This is the one user-authentication
96
+ * prompt (biometrics or device credential).
97
+ * 3. Require the returned `authKeyId` and `ownerBindingId` to equal the
98
+ * stored ones, then return an `ACTIVE` context bound to the key, for
99
+ * {@link forUser}.
100
+ *
101
+ * Call it while the app is in the foreground: iOS cannot show the
102
+ * authentication prompt during a background launch.
103
+ *
104
+ * Concurrent calls for the same `clientEntityId` share one restore.
105
+ *
106
+ * On failure this deletes nothing and starts no login. An application must
107
+ * not do either automatically: keep the key, report the error, and let the
108
+ * user decide (retry, or sign in again). A throw is never "no key" — that is
109
+ * only ever the `no_local_key` result. In particular a native failure while
110
+ * reading the key (for example its local protection metadata is
111
+ * unreadable) throws through the usual native error mapping; it is not
112
+ * turned into `no_local_key`, so it must not start enrollment either.
113
+ *
114
+ * `clientEntityId` must be the lowercase UUID exactly as
115
+ * `DaaUserContext.clientEntityId` returned it. The key slot is derived from
116
+ * those exact characters, so an uppercase copy (for example after a round
117
+ * trip through Swift's `UUID.uuidString`) would find no key; it is rejected
118
+ * instead of being reported as `no_local_key`.
119
+ *
120
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a
121
+ * `clientEntityId` that is not a lowercase UUID, for a returned `authKeyId`
122
+ * or `ownerBindingId` that does not match the stored one, for a key
123
+ * forgotten while the restore was reading it, for a response the SDK
124
+ * cannot read, and when the service rejects the device
125
+ * authorization (the credential is no longer accepted — the same mapping
126
+ * as every signed write; on a revoked or unknown AuthKey the service
127
+ * answers `403` with DAA status `420036`). The application's response is
128
+ * the same for all of them: keep the key and offer sign-in. One exception:
129
+ * on iOS a prompt the system or the app interrupted also arrives as
130
+ * `contract_violation` today, so retry `restore` in the foreground first
131
+ * if the app left it during the prompt (see the README);
132
+ * `user_cancelled` when the user dismisses the authentication prompt:
133
+ * nothing was sent and the key is untouched, so calling `restore` again
134
+ * prompts again; `local_user_authentication_required` when user
135
+ * authentication failed or is unavailable; `clock_skew` when the service
136
+ * rejected the authorization because the device clock is off, the same as
137
+ * `refreshContext`; `api` for any other status besides `200`; `transport` if
138
+ * the consumer's transport throws, with the thrown value as `err.cause`.
139
+ */
140
+ restore(args: {
141
+ clientEntityId: string;
142
+ }): Promise<SessionRestoreResult>;
143
+ /**
144
+ * Delete this device's AuthKey for `clientEntityId`, and its local
145
+ * registration record.
146
+ *
147
+ * Call it only on an explicit user action, such as "remove this device",
148
+ * confirming the removal of a key Circle has revoked, or confirming that the
149
+ * user starts over after this new device was declined (status `denied` from
150
+ * {@link getDeviceStatus}, or a registration refused with `device_denied`) —
151
+ * never as an
152
+ * automatic reaction to a failed {@link restore}, a rejected write, or any
153
+ * other status or error. The SDK never deletes the key by itself.
154
+ *
155
+ * It is local only and does NOT revoke the key with Circle, which keeps the
156
+ * registered public key. It cannot be undone: the next login on this device registers a new
157
+ * AuthKey. Succeeds when no key exists.
158
+ *
159
+ * Contexts and `DaaUserClient`s already handed out are not invalidated by
160
+ * this call. Operations that need a new signature fail once the key is gone,
161
+ * but an authorization signed before the delete stays valid, because Circle
162
+ * still accepts the key: a contract execution prepared earlier can still be
163
+ * sent with `contractExecutions.submit`. Close those clients and drop any
164
+ * prepared value you do not intend to send as part of the same action.
165
+ *
166
+ * Do not call it while a login or a {@link restore} for the same
167
+ * `clientEntityId` is still in flight; finish or abandon that first. A
168
+ * restore that is reading the key when the delete starts fails closed with
169
+ * `contract_violation`. A login ceremony that already holds the key is not
170
+ * cancelled: whether its key survives depends on the order the native SDK
171
+ * runs the two calls in, so the outcome is not defined.
172
+ *
173
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a
174
+ * `clientEntityId` that is not a lowercase UUID, and for a native failure
175
+ * that has no more specific mapping. Native failures go through the same
176
+ * mapping as every other AuthKey operation, so the delete can also report
177
+ * `local_user_authentication_required` or `device_not_initialized` if the
178
+ * platform raises one of those.
179
+ */
180
+ forgetLocalKey(args: {
181
+ clientEntityId: string;
182
+ }): Promise<void>;
183
+ /**
184
+ * The add-a-device status of this device's new AuthKey:
185
+ * `GET /v1/accounts/auth/devices/{authKeyId}`, with the `authKeyId` DAA
186
+ * returned when it added the key as waiting. One read, for example when the app is reopened
187
+ * while a request was waiting (the app must have saved `authKeyId`); use
188
+ * {@link watchDeviceStatus} to wait for the outcome.
189
+ *
190
+ * `denied` means the user declined this device on another one. The key
191
+ * can't ask again: after the user confirms, the app may delete it with
192
+ * {@link forgetLocalKey} and sign in again with a new key. The SDK never
193
+ * deletes it by itself.
194
+ *
195
+ * `authKeyId` may be in either case.
196
+ *
197
+ * @throws DaaError with `detail.kind === 'contract_violation'` for an
198
+ * `authKeyId` that is not a UUID string and for a response the SDK cannot read;
199
+ * `transport` (retryable) when the transport throws; `api` for any status
200
+ * but `200`, including `404` when DAA doesn't know the key.
201
+ */
202
+ getDeviceStatus(args: {
203
+ authKeyId: string;
204
+ }): Promise<DeviceStatus>;
205
+ /**
206
+ * Wait for the add-a-device outcome: read {@link getDeviceStatus} until it is
207
+ * no longer `pending_approval` or `pending_activation` (so `active`,
208
+ * `denied`, `expired`, `cancelled`, or `unrecognized`), and resolve with it.
209
+ *
210
+ * Reads every 5 s while `pending_approval`, and during the cool-down
211
+ * (`pending_activation`) at `readyAt` or every 30 s, whichever is sooner.
212
+ * DAA reports `expired` once `expiresAt` passes on its clock, so this
213
+ * device's clock never ends the watch. After a retryable failure the wait
214
+ * doubles, up to 30 s, with a random part so that watches that failed
215
+ * together don't retry together. `onStatus` gets the first status and every
216
+ * change; if it throws, the watch rejects with that error. Aborting `signal`
217
+ * stops the watch at once, even during a read, and rejects with the
218
+ * signal's reason; a late response is ignored.
219
+ *
220
+ * Every call runs its own loop. Run one watch per `authKeyId` and abort it
221
+ * when the screen that started it goes away: each extra watch is another
222
+ * read every 5 s against the partner's rate limit for this route.
223
+ *
224
+ * @throws the same errors as {@link getDeviceStatus}, and
225
+ * `contract_violation` for an `onStatus` that is not a function or a
226
+ * `signal` that is not an `AbortSignal`, before anything is sent.
227
+ * Ones marked `retryable` (`transport`, or `api` with `429`/`5xx`) are
228
+ * retried, and the watch rejects with the last one after 10 in a row; any
229
+ * other, such as a transport's own `DaaError` with `retryable: false`,
230
+ * rejects at once.
231
+ */
232
+ watchDeviceStatus(args: {
233
+ authKeyId: string;
234
+ onStatus?: (status: DeviceStatus) => void;
235
+ signal?: AbortSignal;
236
+ }): Promise<DeviceStatus>;
57
237
  }