@fountispanel/connect-react-native 1.1.0 → 1.4.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.
- package/CHANGELOG.md +22 -0
- package/README.md +10 -7
- package/android/build.gradle +35 -17
- package/android/src/main/AndroidManifest.xml +5 -16
- package/build/index.js +1 -126
- package/build/index.web.js +1 -57
- package/ios/FountisConnect.xcframework/Info.plist +44 -0
- package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine/engine.html +47 -0
- package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/ar.json +16 -19
- package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/en.json +17 -20
- package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/kmr.json +19 -22
- package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ku.json +19 -22
- package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/FountisConnect +0 -0
- package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Info.plist +53 -0
- package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
- package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftinterface +48 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine/engine.html +47 -0
- package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine}/i18n/ar.json +16 -19
- package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine}/i18n/en.json +17 -20
- package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine}/i18n/kmr.json +19 -22
- package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ku.json +19 -22
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/FountisConnect +0 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Info.plist +49 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftinterface +48 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +48 -0
- package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/PrivacyInfo.xcprivacy +23 -0
- package/ios/FountisConnectAppDelegateSubscriber.swift +3 -0
- package/ios/FountisConnectModule.swift +3 -0
- package/ios/FountisConnectReactNative.podspec +27 -6
- package/package.json +14 -12
- package/android/connect-sdk/main/assets/fountis-connect/engine.html +0 -47
- package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +0 -179
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +0 -234
- package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +0 -641
- package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +0 -321
- package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +0 -143
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +0 -167
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +0 -144
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +0 -109
- package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +0 -70
- package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +0 -74
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +0 -45
- package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +0 -72
- package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +0 -12
- package/android/connect-sdk/main/res/values/fountis_styles.xml +0 -13
- package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +0 -12
- package/build/types.js +0 -1
- package/ios/FountisConnectBundle.swift +0 -15
- package/ios/FountisConnectSDK/ApiClient.swift +0 -137
- package/ios/FountisConnectSDK/Attestation.swift +0 -276
- package/ios/FountisConnectSDK/Engine/engine.html +0 -47
- package/ios/FountisConnectSDK/FountisConnect.swift +0 -441
- package/ios/FountisConnectSDK/LocalState.swift +0 -81
- package/ios/FountisConnectSDK/Matcher.swift +0 -102
- package/ios/FountisConnectSDK/Models.swift +0 -133
- package/ios/FountisConnectSDK/Notifier.swift +0 -63
- package/ios/FountisConnectSDK/RequestDeadline.swift +0 -93
- package/ios/FountisConnectSDK/SheetController.swift +0 -259
- package/ios/FountisConnectSDK/Strings.swift +0 -34
- package/ios/FountisConnectSDK/TokenProviderCall.swift +0 -91
- package/scripts/vendor-native.sh +0 -16
- package/src/index.ts +0 -142
- package/src/index.web.ts +0 -64
- package/src/types.ts +0 -26
- /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/PrivacyInfo.xcprivacy +0 -0
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
package org.fountis.connect
|
|
2
|
-
|
|
3
|
-
import java.io.ByteArrayOutputStream
|
|
4
|
-
import java.io.IOException
|
|
5
|
-
import java.io.InputStream
|
|
6
|
-
import java.net.HttpURLConnection
|
|
7
|
-
import java.net.URL
|
|
8
|
-
import java.net.URLEncoder
|
|
9
|
-
import kotlinx.coroutines.CoroutineScope
|
|
10
|
-
import kotlinx.coroutines.Dispatchers
|
|
11
|
-
import kotlinx.coroutines.SupervisorJob
|
|
12
|
-
import org.json.JSONObject
|
|
13
|
-
|
|
14
|
-
internal class ApiError(val status: Int, val code: String, override val message: String) : Exception(message) {
|
|
15
|
-
/** Errors that end the attempt for good (the engine shows the matching screen). */
|
|
16
|
-
val isFatal: Boolean get() = code in FATAL
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* FOUNTIS refused this install a guest session because it could not vouch for the device (`attestation_required`: nothing
|
|
20
|
-
* usable was sent; `attestation_failed`: what was sent did not check out). The SDK offers no guest studies then.
|
|
21
|
-
*/
|
|
22
|
-
val isAttestationRefusal: Boolean get() = status == 403 && (code == "attestation_required" || code == "attestation_failed")
|
|
23
|
-
|
|
24
|
-
companion object {
|
|
25
|
-
val FATAL = setOf("invalid_token", "not_eligible", "already_taken", "closed", "quota_full")
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* One request in flight, reachable from the thread that gave up waiting for it: [abandon] closes its connection so the
|
|
31
|
-
* thread blocked on the socket is freed, and the read loop checks it so a body that is still trickling in stops too.
|
|
32
|
-
*/
|
|
33
|
-
internal class Exchange {
|
|
34
|
-
@Volatile private var conn: HttpURLConnection? = null
|
|
35
|
-
@Volatile private var abandoned = false
|
|
36
|
-
|
|
37
|
-
/** Remembers the connection. Throws if the caller has already given up, so the request never starts. */
|
|
38
|
-
fun attach(c: HttpURLConnection) {
|
|
39
|
-
conn = c
|
|
40
|
-
checkNotAbandoned()
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
fun checkNotAbandoned() {
|
|
44
|
-
if (abandoned) throw IOException("the request was abandoned")
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Called on another thread once the caller stopped waiting. Best effort: the caller is already released. */
|
|
48
|
-
fun abandon() {
|
|
49
|
-
abandoned = true
|
|
50
|
-
conn?.disconnect()
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Thin client for the connect-api (HttpURLConnection, no cookies, no cache). Tokens are only ever sent in headers or bodies.
|
|
56
|
-
*
|
|
57
|
-
* Every request has an overall deadline ([deadlineMs], 15 s): connection, request and the whole response body. The
|
|
58
|
-
* per-step limits on the connection alone cannot give that, because a server that sends a byte now and then keeps
|
|
59
|
-
* every single read within its limit. When the deadline passes the call fails with a [RequestTimeoutException], an
|
|
60
|
-
* [IOException] like the read timeout it replaces, so it ends as noFill the same way.
|
|
61
|
-
*/
|
|
62
|
-
internal class ApiClient(base: String, val key: String, private val deadlineMs: Long = REQUEST_DEADLINE_MS) {
|
|
63
|
-
private val base = base.trimEnd('/')
|
|
64
|
-
|
|
65
|
-
/** Where the blocking requests run. A SupervisorJob keeps a failed request in its Deferred. It owns no thread of its own. */
|
|
66
|
-
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
|
67
|
-
|
|
68
|
-
private fun Exchange.request(method: String, path: String, query: Map<String, String> = emptyMap(), body: JSONObject? = null, attemptToken: String? = null): String {
|
|
69
|
-
var url = "$base/$path"
|
|
70
|
-
if (query.isNotEmpty()) url += "?" + query.entries.joinToString("&") { URLEncoder.encode(it.key, "UTF-8") + "=" + URLEncoder.encode(it.value, "UTF-8") }
|
|
71
|
-
val conn = URL(url).openConnection() as HttpURLConnection
|
|
72
|
-
try {
|
|
73
|
-
attach(conn)
|
|
74
|
-
conn.requestMethod = method
|
|
75
|
-
// Second line of defence only: the deadline ends a request first (these are per step, the deadline is the whole).
|
|
76
|
-
conn.connectTimeout = 15_000
|
|
77
|
-
conn.readTimeout = 20_000
|
|
78
|
-
conn.useCaches = false
|
|
79
|
-
conn.instanceFollowRedirects = false
|
|
80
|
-
conn.setRequestProperty("X-Fountis-Key", key)
|
|
81
|
-
conn.setRequestProperty("Accept", "application/json")
|
|
82
|
-
if (attemptToken != null) conn.setRequestProperty("Authorization", "Attempt $attemptToken")
|
|
83
|
-
if (body != null) {
|
|
84
|
-
conn.doOutput = true
|
|
85
|
-
conn.setRequestProperty("Content-Type", "application/json")
|
|
86
|
-
conn.outputStream.use { it.write(body.toString().toByteArray(Charsets.UTF_8)) }
|
|
87
|
-
}
|
|
88
|
-
val status = conn.responseCode
|
|
89
|
-
val stream = if (status in 200..299) conn.inputStream else conn.errorStream
|
|
90
|
-
val text = readBody(stream)
|
|
91
|
-
if (status in 200..299) return text
|
|
92
|
-
var code = "http_$status"
|
|
93
|
-
var message = ""
|
|
94
|
-
try {
|
|
95
|
-
val o = JSONObject(text)
|
|
96
|
-
code = o.optString("error", code)
|
|
97
|
-
message = o.optString("message", "")
|
|
98
|
-
} catch (_: Exception) {
|
|
99
|
-
}
|
|
100
|
-
throw ApiError(status, code, message)
|
|
101
|
-
} finally {
|
|
102
|
-
conn.disconnect()
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** Reads the body in pieces, so an abandoned request stops at the next piece instead of waiting for the whole body. */
|
|
107
|
-
private fun Exchange.readBody(stream: InputStream?): String {
|
|
108
|
-
if (stream == null) return ""
|
|
109
|
-
return stream.use { s ->
|
|
110
|
-
val out = ByteArrayOutputStream()
|
|
111
|
-
val buf = ByteArray(8192)
|
|
112
|
-
var n = s.read(buf)
|
|
113
|
-
while (n >= 0) {
|
|
114
|
-
checkNotAbandoned()
|
|
115
|
-
out.write(buf, 0, n)
|
|
116
|
-
n = s.read(buf)
|
|
117
|
-
}
|
|
118
|
-
out.toString("UTF-8")
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
private suspend fun io(work: Exchange.() -> String): String {
|
|
123
|
-
val exchange = Exchange()
|
|
124
|
-
return callWithinDeadline(scope, deadlineMs, abandon = exchange::abandon) { exchange.work() }
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
private fun obj(text: String): JSONObject =
|
|
128
|
-
try {
|
|
129
|
-
JSONObject(text)
|
|
130
|
-
} catch (e: Exception) {
|
|
131
|
-
throw ApiError(0, "bad_response", "unexpected response")
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
suspend fun surveys(lang: String): SurveysResponse =
|
|
135
|
-
parseSurveys(io { request("GET", "surveys", query = mapOf("lang" to lang)) })
|
|
136
|
-
|
|
137
|
-
suspend fun createAttempt(offerId: String, token: String, lang: String): JSONObject =
|
|
138
|
-
obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("token", token).put("lang", lang)) })
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Guests: the install id in, a short-lived guest session token out. 403 `guests_not_allowed` when the app has guests off.
|
|
142
|
-
* [attest] is the device attestation object when the app asks for one (see [GuestAttestation]); null sends the install id alone.
|
|
143
|
-
* 403 `attestation_required` / `attestation_failed` when FOUNTIS requires an attestation it did not get (see [ApiError.isAttestationRefusal]).
|
|
144
|
-
*/
|
|
145
|
-
suspend fun guestSession(installId: String, attest: JSONObject? = null): String {
|
|
146
|
-
val body = JSONObject().put("install_id", installId)
|
|
147
|
-
if (attest != null) body.put("attest", attest)
|
|
148
|
-
val o = obj(io { request("POST", "guest/session", body = body) })
|
|
149
|
-
return o.optString("guest_session", "").ifEmpty { throw ApiError(0, "bad_response", "no session") }
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** Guest attestation: a single-use challenge (32 random bytes, base64url) for the next guest session. Key header only. */
|
|
153
|
-
suspend fun attestChallenge(): String {
|
|
154
|
-
val o = obj(io { request("POST", "attest/challenge", body = JSONObject()) })
|
|
155
|
-
return o.optString("challenge", "").ifEmpty { throw ApiError(0, "bad_response", "no challenge") }
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
suspend fun createGuestAttempt(offerId: String, guestSession: String, lang: String): JSONObject =
|
|
159
|
-
obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("guest_session", guestSession).put("lang", lang)) })
|
|
160
|
-
|
|
161
|
-
suspend fun putAnswer(code: String, value: Any?, attemptToken: String): JSONObject =
|
|
162
|
-
obj(io { request("PUT", "attempt/answers", body = JSONObject().put("code", code).put("value", value ?: JSONObject.NULL), attemptToken = attemptToken) })
|
|
163
|
-
|
|
164
|
-
suspend fun consent(attemptToken: String) {
|
|
165
|
-
io { request("POST", "attempt/consent", body = JSONObject(), attemptToken = attemptToken) }
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
suspend fun complete(attemptToken: String): JSONObject =
|
|
169
|
-
obj(io { request("POST", "attempt/complete", body = JSONObject(), attemptToken = attemptToken) })
|
|
170
|
-
|
|
171
|
-
suspend fun event(offerId: String, type: String) {
|
|
172
|
-
try {
|
|
173
|
-
io { request("POST", "events", body = JSONObject().put("offer_id", offerId).put("type", type)) }
|
|
174
|
-
} catch (_: IOException) {
|
|
175
|
-
} catch (_: ApiError) {
|
|
176
|
-
} catch (_: RuntimeException) {
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
}
|
|
@@ -1,234 +0,0 @@
|
|
|
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
|
-
}
|