@fountispanel/connect-react-native 0.0.0-stage → 1.1.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 (60) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +24 -0
  3. package/README.md +92 -2
  4. package/android/build.gradle +37 -0
  5. package/android/connect-sdk/main/assets/fountis-connect/engine.html +47 -0
  6. package/android/connect-sdk/main/assets/fountis-connect/i18n/ar.json +70 -0
  7. package/android/connect-sdk/main/assets/fountis-connect/i18n/en.json +70 -0
  8. package/android/connect-sdk/main/assets/fountis-connect/i18n/kmr.json +70 -0
  9. package/android/connect-sdk/main/assets/fountis-connect/i18n/ku.json +70 -0
  10. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +179 -0
  11. package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +234 -0
  12. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +641 -0
  13. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +321 -0
  14. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +143 -0
  15. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +167 -0
  16. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +144 -0
  17. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +109 -0
  18. package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +70 -0
  19. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +74 -0
  20. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +45 -0
  21. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +72 -0
  22. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +12 -0
  23. package/android/connect-sdk/main/res/values/fountis_styles.xml +13 -0
  24. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +12 -0
  25. package/android/src/main/AndroidManifest.xml +18 -0
  26. package/android/src/main/java/org/fountis/connect/rn/FountisConnectModule.kt +113 -0
  27. package/app.plugin.js +41 -0
  28. package/build/index.d.ts +34 -0
  29. package/build/index.js +126 -0
  30. package/build/index.web.d.ts +22 -0
  31. package/build/index.web.js +57 -0
  32. package/build/types.d.ts +23 -0
  33. package/build/types.js +1 -0
  34. package/expo-module.config.json +10 -0
  35. package/ios/FountisConnectAppDelegateSubscriber.swift +16 -0
  36. package/ios/FountisConnectBundle.swift +15 -0
  37. package/ios/FountisConnectModule.swift +131 -0
  38. package/ios/FountisConnectReactNative.podspec +35 -0
  39. package/ios/FountisConnectSDK/ApiClient.swift +137 -0
  40. package/ios/FountisConnectSDK/Attestation.swift +276 -0
  41. package/ios/FountisConnectSDK/Engine/engine.html +47 -0
  42. package/ios/FountisConnectSDK/Engine/i18n/ar.json +70 -0
  43. package/ios/FountisConnectSDK/Engine/i18n/en.json +70 -0
  44. package/ios/FountisConnectSDK/Engine/i18n/kmr.json +70 -0
  45. package/ios/FountisConnectSDK/Engine/i18n/ku.json +70 -0
  46. package/ios/FountisConnectSDK/FountisConnect.swift +441 -0
  47. package/ios/FountisConnectSDK/LocalState.swift +81 -0
  48. package/ios/FountisConnectSDK/Matcher.swift +102 -0
  49. package/ios/FountisConnectSDK/Models.swift +133 -0
  50. package/ios/FountisConnectSDK/Notifier.swift +63 -0
  51. package/ios/FountisConnectSDK/PrivacyInfo.xcprivacy +23 -0
  52. package/ios/FountisConnectSDK/RequestDeadline.swift +93 -0
  53. package/ios/FountisConnectSDK/SheetController.swift +259 -0
  54. package/ios/FountisConnectSDK/Strings.swift +34 -0
  55. package/ios/FountisConnectSDK/TokenProviderCall.swift +91 -0
  56. package/package.json +67 -4
  57. package/scripts/vendor-native.sh +16 -0
  58. package/src/index.ts +142 -0
  59. package/src/index.web.ts +64 -0
  60. package/src/types.ts +26 -0
@@ -0,0 +1,234 @@
1
+ package org.fountis.connect
2
+
3
+ import java.security.MessageDigest
4
+ import kotlinx.coroutines.CancellationException
5
+ import kotlinx.coroutines.CoroutineScope
6
+ import kotlinx.coroutines.Deferred
7
+ import kotlinx.coroutines.Dispatchers
8
+ import kotlinx.coroutines.async
9
+ import kotlinx.coroutines.withContext
10
+ import kotlinx.coroutines.withTimeoutOrNull
11
+ import org.json.JSONObject
12
+
13
+ // Device attestation for guests (Play Integrity, Standard API). Only guest sessions are attested: a signed-in partner
14
+ // user is vouched for by the partner's signed token. Everything here is silent, nothing about it is shown to the person.
15
+ // This file has no Play Integrity import on purpose: the plain-JVM unit tests run it with a fake [Attestor].
16
+
17
+ /** The most the whole attestation may take (challenge, waiting for Play Integrity, token), as on iOS. */
18
+ internal const val ATTEST_TIMEOUT_MS: Long = 10_000L
19
+
20
+ /** `app.attest` from `GET /surveys`: whether to attest, and the Google Cloud project NUMBER the partner linked in Play Console. */
21
+ internal class AttestConfig(val mode: String, val androidCloudProject: String?) {
22
+ /** Only `report` and `enforce` attest. `off`, a missing `attest` object and any mode this SDK does not know do not. */
23
+ val isOn: Boolean get() = mode == "report" || mode == "enforce"
24
+
25
+ /** The project number, or null when none is configured (or it is not a positive number). */
26
+ val cloudProjectNumber: Long? get() = androidCloudProject?.trim()?.toLongOrNull()?.takeIf { it > 0L }
27
+
28
+ companion object {
29
+ val OFF = AttestConfig("off", null)
30
+ }
31
+ }
32
+
33
+ /** The device could not attest. [code] is the wire code the server expects: `unsupported`, `error` or `no_cloud_project`. */
34
+ internal class AttestUnavailable(val code: String, cause: Throwable? = null) : Exception("attestation unavailable: $code", cause)
35
+
36
+ /** What Play Integrity offers the SDK, so the unit tests can fake it. */
37
+ internal interface Attestor {
38
+ /** Gets Play Integrity ready for [cloudProjectNumber]. The slow part (a few seconds); the SDK calls it once per process. Throws [AttestUnavailable]. */
39
+ suspend fun prepare(cloudProjectNumber: Long)
40
+
41
+ /** An integrity token bound to [requestHash]. Needs [prepare] to have finished. Throws [AttestUnavailable]. */
42
+ suspend fun request(requestHash: String): String
43
+ }
44
+
45
+ /**
46
+ * The `requestHash` Play Integrity binds into the token: lowercase hex SHA-256 of `challenge + "|" + installId`
47
+ * (UTF-8). The server recomputes it from the challenge it issued and the install id of the guest session request.
48
+ */
49
+ internal fun attestRequestHash(challenge: String, installId: String): String {
50
+ val digest = MessageDigest.getInstance("SHA-256").digest("$challenge|$installId".toByteArray(Charsets.UTF_8))
51
+ return digest.joinToString("") { "%02x".format(it.toInt() and 0xff) }
52
+ }
53
+
54
+ /**
55
+ * The wire code for a Play Integrity Standard API error (`StandardIntegrityErrorCode`), or `error` when the code is
56
+ * unknown or there is none. `unsupported`: this device or Play setup cannot attest (no Play Store or Play services, too
57
+ * old, API not available, app not installed from Play). A cloud project Google rejects counts as `no_cloud_project`: it
58
+ * is the same fix (the project number in the FOUNTIS console). Everything else (network, quota, Google busy) is `error`.
59
+ */
60
+ internal fun attestCodeForPlayError(errorCode: Int?): String {
61
+ if (errorCode == null) return "error"
62
+ if (errorCode in PLAY_UNSUPPORTED) return "unsupported"
63
+ if (errorCode == -16) return "no_cloud_project" // CLOUD_PROJECT_NUMBER_IS_INVALID
64
+ return "error"
65
+ }
66
+
67
+ /**
68
+ * API_NOT_AVAILABLE -1, PLAY_STORE_NOT_FOUND -2, PLAY_STORE_ACCOUNT_NOT_FOUND -4, APP_NOT_INSTALLED -5,
69
+ * PLAY_SERVICES_NOT_FOUND -6, CANNOT_BIND_TO_SERVICE -9, PLAY_STORE_VERSION_OUTDATED -14, PLAY_SERVICES_VERSION_OUTDATED -15.
70
+ */
71
+ private val PLAY_UNSUPPORTED: Set<Int> = setOf(-1, -2, -4, -5, -6, -9, -14, -15)
72
+
73
+ /**
74
+ * Builds the `attest` object of `POST /guest/session`.
75
+ *
76
+ * - Attestation off: [attest] returns null and nothing is touched (no request, no Play Integrity).
77
+ * - Otherwise it always returns an object: the token, or `unavailable` with a code when the device could not attest
78
+ * (the server decides what an unavailable attestation means: `report` grants the session, `enforce` refuses it).
79
+ * It never throws, except to pass on the caller's own cancellation.
80
+ *
81
+ * Play Integrity is prepared once per process (and project): [warmUp] starts it early in the background, [attest]
82
+ * starts it if nobody did and waits for it. A failed preparation is forgotten, so the next guest session tries again.
83
+ * The preparation is not tied to the caller, so an attestation that timed out leaves it running for the next one.
84
+ *
85
+ * [scope] must have a `SupervisorJob`. The work runs on `Dispatchers.Default`, never on the main thread.
86
+ */
87
+ internal class GuestAttestation(
88
+ private val attestor: Attestor,
89
+ private val scope: CoroutineScope,
90
+ private val timeoutMs: Long = ATTEST_TIMEOUT_MS,
91
+ ) {
92
+ /** [ready] ends with null when Play Integrity is prepared, or with the unavailable code when it could not be. */
93
+ private class Warm(val project: Long, val ready: Deferred<String?>)
94
+
95
+ private var warm: Warm? = null
96
+
97
+ @Synchronized
98
+ private fun warmFor(project: Long): Warm {
99
+ val have = warm
100
+ if (have != null && have.project == project) return have
101
+ val w = Warm(project, scope.async(Dispatchers.Default) { prepared(project) })
102
+ warm = w
103
+ return w
104
+ }
105
+
106
+ @Synchronized
107
+ private fun forget(w: Warm) {
108
+ if (warm === w) warm = null
109
+ }
110
+
111
+ private suspend fun prepared(project: Long): String? = try {
112
+ attestor.prepare(project)
113
+ null
114
+ } catch (e: CancellationException) {
115
+ throw e
116
+ } catch (e: AttestUnavailable) {
117
+ e.code
118
+ } catch (t: Throwable) {
119
+ logd("attest: Play Integrity could not be prepared: $t")
120
+ "error"
121
+ }
122
+
123
+ /** Starts preparing Play Integrity in the background, once. Does nothing when attestation is off or no project is set. */
124
+ fun warmUp(config: AttestConfig) {
125
+ if (!config.isOn) return
126
+ val project = config.cloudProjectNumber ?: return
127
+ warmFor(project)
128
+ }
129
+
130
+ /**
131
+ * The `attest` object for the guest session of [installId], or null when [config] has attestation off.
132
+ * [challenge] fetches a fresh single-use challenge from FOUNTIS; it is only called once Play Integrity is ready.
133
+ */
134
+ suspend fun attest(config: AttestConfig, installId: String, challenge: suspend () -> String): JSONObject? {
135
+ if (!config.isOn) return null
136
+ val result = withTimeoutOrNull(timeoutMs) {
137
+ withContext(Dispatchers.Default) { attestInTime(config, installId, challenge) }
138
+ }
139
+ if (result == null) logd("attest: no result within ${timeoutMs / 1000.0} s")
140
+ return result ?: unavailable("timeout")
141
+ }
142
+
143
+ private suspend fun attestInTime(config: AttestConfig, installId: String, challenge: suspend () -> String): JSONObject {
144
+ val project = config.cloudProjectNumber ?: return unavailable("no_cloud_project")
145
+
146
+ val w = warmFor(project)
147
+ val notReady = w.ready.await()
148
+ if (notReady != null) {
149
+ forget(w)
150
+ return unavailable(notReady)
151
+ }
152
+
153
+ val c = try {
154
+ challenge()
155
+ } catch (e: CancellationException) {
156
+ throw e
157
+ } catch (t: Throwable) {
158
+ logd("attest: no challenge: $t")
159
+ return unavailable("error")
160
+ }
161
+
162
+ val token = try {
163
+ attestor.request(attestRequestHash(c, installId))
164
+ } catch (e: CancellationException) {
165
+ throw e
166
+ } catch (t: Throwable) {
167
+ // The token provider may have expired or been invalidated: prepare it again for the next guest session.
168
+ forget(w)
169
+ logd("attest: no token: $t")
170
+ return unavailable(if (t is AttestUnavailable) t.code else "error")
171
+ }
172
+
173
+ return JSONObject().put("platform", "android").put("token", token).put("challenge", c)
174
+ }
175
+
176
+ private fun unavailable(code: String): JSONObject = JSONObject().put("platform", "android").put("unavailable", code)
177
+ }
178
+
179
+ /** After FOUNTIS refuses a guest session for lack of a valid attestation, the SDK leaves it alone for this long. */
180
+ internal const val ATTEST_REFUSAL_COOLDOWN_MS: Long = 10 * 60_000L
181
+
182
+ /**
183
+ * Remembers, in memory only, that FOUNTIS refused this install a guest session (403 `attestation_required` /
184
+ * `attestation_failed`). Every attestation spends one Play Integrity token from the app's daily quota, so a device that
185
+ * will be refused again must not try on every `show()`. The clock is monotonic.
186
+ */
187
+ internal class RefusalCooldown(
188
+ private val now: () -> Long = { System.nanoTime() / 1_000_000L },
189
+ private val windowMs: Long = ATTEST_REFUSAL_COOLDOWN_MS,
190
+ ) {
191
+ private var until: Long? = null
192
+ private var code = "attestation_failed"
193
+
194
+ @Synchronized
195
+ fun record(code: String) {
196
+ this.code = code
197
+ until = now() + windowMs
198
+ }
199
+
200
+ /** The code of the refusal while the window is open, otherwise null. */
201
+ @Synchronized
202
+ fun active(): String? {
203
+ val u = until ?: return null
204
+ return if (now() < u) code else null
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Gets a guest session from FOUNTIS: attests first when [cfg] asks for it, and keeps to the [cooldown] after a refusal.
210
+ * [attestation] is only called for an app whose mode is `report` or `enforce`, so Play Integrity stays untouched otherwise.
211
+ */
212
+ internal class GuestSessionOpener(
213
+ private val attestation: () -> GuestAttestation?,
214
+ private val cooldown: RefusalCooldown = RefusalCooldown(),
215
+ ) {
216
+ /**
217
+ * The guest session token. Throws the same [ApiError] FOUNTIS refused with (see [ApiError.isAttestationRefusal]),
218
+ * and, within the cooldown after such a refusal, a 403 with the same code without sending anything at all.
219
+ */
220
+ suspend fun open(api: ApiClient, cfg: AttestConfig, installId: String): String {
221
+ var attest: JSONObject? = null
222
+ if (cfg.isOn) {
223
+ val recent = cooldown.active()
224
+ if (recent != null) throw ApiError(403, recent, "refused a moment ago")
225
+ attest = attestation()?.attest(cfg, installId) { api.attestChallenge() }
226
+ }
227
+ try {
228
+ return api.guestSession(installId, attest)
229
+ } catch (e: ApiError) {
230
+ if (e.isAttestationRefusal) cooldown.record(e.code)
231
+ throw e
232
+ }
233
+ }
234
+ }