@fountispanel/connect-react-native 1.0.0 → 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.
- package/CHANGELOG.md +3 -1
- package/README.md +2 -0
- package/android/build.gradle +3 -2
- package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +21 -3
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +234 -0
- package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +28 -3
- package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +18 -2
- package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +70 -0
- package/ios/FountisConnectSDK/ApiClient.swift +29 -5
- package/ios/FountisConnectSDK/Attestation.swift +276 -0
- package/ios/FountisConnectSDK/FountisConnect.swift +10 -5
- package/ios/FountisConnectSDK/Models.swift +17 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 1.1.0 — 2026-10-19
|
|
4
4
|
|
|
5
|
+
- Android: guest device check with Google Play Integrity when FOUNTIS asks for it for your app (see the Android SDK changelog). The Android build now depends on `com.google.android.play:integrity:1.6.0`. Link the FOUNTIS Google Cloud project to your app in Play Console (App integrity, Play Integrity API).
|
|
6
|
+
- iOS: guest device attestation with App Attest, from the bundled iOS SDK (see its changelog). If FOUNTIS asks for it on your guests, add the App Attest capability to the iOS app (entitlement `com.apple.developer.devicecheck.appattest-environment`; in Expo `ios.entitlements`). Nothing changes when attestation is off.
|
|
5
7
|
- npm package renamed to `@fountispanel/connect-react-native`. Nothing else changes; install and import it under the new name.
|
|
6
8
|
- Android: every API request now has an overall 15 second deadline (connection, request and the whole response), the same as the Web SDK, so a server that keeps sending a few bytes cannot keep `show()` busy. The failure ends as `noFill` like any network error. This comes from the bundled Android SDK (see its changelog).
|
|
7
9
|
- Docs: the Android minimum now names Android System WebView 88 or later next to API 23 (on an older WebView `show()` returns `noFill`), and the README token example reads the `{ "token": "..." }` reply of the sample server, treating a reply without a token as a failure.
|
package/README.md
CHANGED
|
@@ -78,6 +78,8 @@ Notes:
|
|
|
78
78
|
- The token function runs in JavaScript. A background check that wakes the app without JavaScript running gets no answer
|
|
79
79
|
and does nothing; checks work while the app is open or recently used, and the study also appears on app open.
|
|
80
80
|
- **Guests:** when the token function returns `null` and FOUNTIS has switched guests on for your app (adult-only apps only), the SDK offers the free studies marked open to guests, after an 18+ confirmation. There is nothing to call; an app without accounts can pass `setUserToken(() => null)`. Guests never see a reward. If your token request fails, throw instead of returning `null`, so a signed-in person is not shown guest studies.
|
|
81
|
+
- **Android guest device check:** when FOUNTIS asks for it, an Android guest's device is checked with Google Play Integrity before the guest session starts. Link the FOUNTIS Google Cloud project to your app in Play Console (App integrity, Play Integrity API); FOUNTIS gives you the project number. Nothing to call, and signed-in users are not checked. See the Android SDK README.
|
|
82
|
+
- **Guest attestation (iOS):** if FOUNTIS asks for device attestation on your guests, add the App Attest capability to the iOS app (entitlement `com.apple.developer.devicecheck.appattest-environment` = `production`; in Expo set it under `ios.entitlements`). There is nothing to call.
|
|
81
83
|
- On the web, `enableNotifications()` turns on the in-page invitation, and `handlePush` always resolves `false`.
|
|
82
84
|
- `start` also takes `engineUrl` on the web, to point at another hosted engine.
|
|
83
85
|
|
package/android/build.gradle
CHANGED
|
@@ -4,7 +4,7 @@ plugins {
|
|
|
4
4
|
}
|
|
5
5
|
|
|
6
6
|
group = 'org.fountis'
|
|
7
|
-
version = '1.
|
|
7
|
+
version = '1.1.0'
|
|
8
8
|
|
|
9
9
|
// In this repository the Kotlin SDK is next to this package. In the npm package, scripts/vendor-native.sh
|
|
10
10
|
// copies it to android/connect-sdk (run automatically on `npm pack`).
|
|
@@ -16,7 +16,7 @@ android {
|
|
|
16
16
|
namespace 'org.fountis.connect'
|
|
17
17
|
defaultConfig {
|
|
18
18
|
versionCode 1
|
|
19
|
-
versionName '1.
|
|
19
|
+
versionName '1.1.0'
|
|
20
20
|
}
|
|
21
21
|
sourceSets {
|
|
22
22
|
main {
|
|
@@ -33,4 +33,5 @@ dependencies {
|
|
|
33
33
|
implementation 'androidx.webkit:webkit:1.12.1'
|
|
34
34
|
implementation 'androidx.lifecycle:lifecycle-process:2.8.7'
|
|
35
35
|
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0'
|
|
36
|
+
implementation 'com.google.android.play:integrity:1.6.0'
|
|
36
37
|
}
|
|
@@ -15,6 +15,12 @@ internal class ApiError(val status: Int, val code: String, override val message:
|
|
|
15
15
|
/** Errors that end the attempt for good (the engine shows the matching screen). */
|
|
16
16
|
val isFatal: Boolean get() = code in FATAL
|
|
17
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
|
+
|
|
18
24
|
companion object {
|
|
19
25
|
val FATAL = setOf("invalid_token", "not_eligible", "already_taken", "closed", "quota_full")
|
|
20
26
|
}
|
|
@@ -131,12 +137,24 @@ internal class ApiClient(base: String, val key: String, private val deadlineMs:
|
|
|
131
137
|
suspend fun createAttempt(offerId: String, token: String, lang: String): JSONObject =
|
|
132
138
|
obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("token", token).put("lang", lang)) })
|
|
133
139
|
|
|
134
|
-
/**
|
|
135
|
-
|
|
136
|
-
|
|
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) })
|
|
137
149
|
return o.optString("guest_session", "").ifEmpty { throw ApiError(0, "bad_response", "no session") }
|
|
138
150
|
}
|
|
139
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
|
+
|
|
140
158
|
suspend fun createGuestAttempt(offerId: String, guestSession: String, lang: String): JSONObject =
|
|
141
159
|
obj(io { request("POST", "attempts", body = JSONObject().put("offer_id", offerId).put("guest_session", guestSession).put("lang", lang)) })
|
|
142
160
|
|
|
@@ -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
|
+
}
|
|
@@ -40,7 +40,9 @@ import org.json.JSONObject
|
|
|
40
40
|
*
|
|
41
41
|
* Guests: when the token provider returns `null` (nobody is signed in) and FOUNTIS has switched guests on for your
|
|
42
42
|
* app, the SDK offers the free studies marked open to guests, after an 18+ confirmation. Nothing to call; an app
|
|
43
|
-
* without accounts can pass `setUserToken { null }`.
|
|
43
|
+
* without accounts can pass `setUserToken { null }`. When FOUNTIS asks for it, a guest's device is also checked with
|
|
44
|
+
* Google Play Integrity (link your app to the FOUNTIS Google Cloud project in Play Console); an app installed outside
|
|
45
|
+
* Google Play works too, the check then just reports that it is unavailable.
|
|
44
46
|
*
|
|
45
47
|
* Every failure is silent and becomes [FountisResult.NoFill] plus a `Log.d` line with the tag `FountisConnect`.
|
|
46
48
|
* The SDK never throws into the host app.
|
|
@@ -193,6 +195,11 @@ internal object Core {
|
|
|
193
195
|
private var notificationsOn = false
|
|
194
196
|
private var lastSubHash: String? = null
|
|
195
197
|
private var guestSession: Pair<String, Long>? = null
|
|
198
|
+
private var guestAttest: GuestAttestation? = null
|
|
199
|
+
// Attests (when the app asks for it) and opens the guest session; after a refusal it sends nothing for 10 minutes.
|
|
200
|
+
private val guestOpener = GuestSessionOpener({ attestation() })
|
|
201
|
+
// Where Play Integrity is prepared (a few seconds, once per process). Never the main thread, never cancelled.
|
|
202
|
+
private val attestScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
|
196
203
|
private var resumed: WeakReference<Activity>? = null
|
|
197
204
|
private var webViewOk: Boolean? = null
|
|
198
205
|
private var cache: Cached? = null
|
|
@@ -439,15 +446,28 @@ internal object Core {
|
|
|
439
446
|
val lang = Strings.deviceLang()
|
|
440
447
|
val surveys = fetchSurveys(api, lang)
|
|
441
448
|
if (!surveys.guests || surveys.surveys.none { it.guest }) return null
|
|
449
|
+
// Get Play Integrity ready early, but only for a guest who can see a study now (not for the background check).
|
|
450
|
+
if (surveys.attest.isOn && foreground) attestation()?.warmUp(surveys.attest)
|
|
442
451
|
lastSubHash = "guest"
|
|
443
452
|
return Session(api, null, null, lang, surveys, LocalState(st, "guest"))
|
|
444
453
|
}
|
|
445
454
|
|
|
446
|
-
/**
|
|
455
|
+
/** The Play Integrity side of guest attestation; made only once an app asks for it (mode `report` or `enforce`). */
|
|
456
|
+
private fun attestation(): GuestAttestation? {
|
|
457
|
+
val a = app ?: return null
|
|
458
|
+
return synchronized(this) { guestAttest ?: GuestAttestation(PlayIntegrityAttestor(a), attestScope).also { guestAttest = it } }
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* A guest session token, kept in memory for most of its hour. `force` makes a new one.
|
|
463
|
+
* Only here, right before a new guest session, the device is attested (when the app's mode asks for it).
|
|
464
|
+
* After a refusal (403 `attestation_required` / `attestation_failed`) nothing is sent for 10 minutes: every attempt
|
|
465
|
+
* ends as that refusal, so a device FOUNTIS will turn away again does not spend a Play Integrity token on each show().
|
|
466
|
+
*/
|
|
447
467
|
private suspend fun guestToken(s: Session, force: Boolean = false): String {
|
|
448
468
|
val st = store ?: throw ApiError(0, "not_started", "not started")
|
|
449
469
|
guestSession?.let { if (!force && it.second > System.currentTimeMillis()) return it.first }
|
|
450
|
-
val t = s.api.
|
|
470
|
+
val t = guestOpener.open(s.api, s.surveys.attest, st.installId())
|
|
451
471
|
guestSession = t to (System.currentTimeMillis() + 55 * 60_000L)
|
|
452
472
|
return t
|
|
453
473
|
}
|
|
@@ -506,6 +526,11 @@ internal object Core {
|
|
|
506
526
|
val a = createAttempt(s, offer.offerId)
|
|
507
527
|
return present(offer, a, s, act)
|
|
508
528
|
} catch (e: ApiError) {
|
|
529
|
+
if (e.isAttestationRefusal) {
|
|
530
|
+
// FOUNTIS could not vouch for this device: no guest studies this time, and no retry.
|
|
531
|
+
logd("guest studies not offered: ${e.code}")
|
|
532
|
+
return FountisResult.NoFill
|
|
533
|
+
}
|
|
509
534
|
if (e.code == "already_taken") s.state.markTaken(offer.offerId)
|
|
510
535
|
if (e.code in setOf("already_taken", "not_eligible", "closed", "quota_full", "guests_not_allowed")) continue
|
|
511
536
|
logd("attempt failed: ${e.code}")
|
|
@@ -68,7 +68,14 @@ internal class Offer(
|
|
|
68
68
|
|
|
69
69
|
internal class SurveysConfig(val maxNotificationsPerDay: Int?, val quietHours: List<Int>?, val checkIntervalMinutes: Int?)
|
|
70
70
|
|
|
71
|
-
internal class SurveysResponse(
|
|
71
|
+
internal class SurveysResponse(
|
|
72
|
+
val appName: String?,
|
|
73
|
+
val config: SurveysConfig?,
|
|
74
|
+
val surveys: List<Offer>,
|
|
75
|
+
val guests: Boolean = false,
|
|
76
|
+
/** Device attestation for guest sessions (`app.attest`); off when the server sends nothing. */
|
|
77
|
+
val attest: AttestConfig = AttestConfig.OFF,
|
|
78
|
+
)
|
|
72
79
|
|
|
73
80
|
// ---- JSON helpers ----
|
|
74
81
|
|
|
@@ -114,7 +121,16 @@ internal fun parseSurveys(text: String): SurveysResponse {
|
|
|
114
121
|
offers.add(Offer(id, conds, attrs, o.optIntOrNull("loi_minutes"), reward, o.optStringOrNull("expires_at"), o.optBoolean("guest", false)))
|
|
115
122
|
}
|
|
116
123
|
val app = root.optJSONObject("app")
|
|
117
|
-
|
|
124
|
+
val attest = app?.optJSONObject("attest")?.let { a ->
|
|
125
|
+
// The project number is a string on the wire; a bare JSON number is accepted too.
|
|
126
|
+
val project = when (val p = a.opt("android_cloud_project")) {
|
|
127
|
+
is String -> p
|
|
128
|
+
is Number -> p.toLong().toString()
|
|
129
|
+
else -> null
|
|
130
|
+
}
|
|
131
|
+
AttestConfig(a.optString("mode", "off"), project)
|
|
132
|
+
} ?: AttestConfig.OFF
|
|
133
|
+
return SurveysResponse(app?.optStringOrNull("name"), cfg, offers, app?.optBoolean("guests", false) ?: false, attest)
|
|
118
134
|
}
|
|
119
135
|
|
|
120
136
|
internal const val TAG = "FountisConnect"
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
package org.fountis.connect
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import com.google.android.gms.tasks.Task
|
|
5
|
+
import com.google.android.play.core.integrity.IntegrityManagerFactory
|
|
6
|
+
import com.google.android.play.core.integrity.StandardIntegrityException
|
|
7
|
+
import com.google.android.play.core.integrity.StandardIntegrityManager
|
|
8
|
+
import com.google.android.play.core.integrity.StandardIntegrityManager.PrepareIntegrityTokenRequest
|
|
9
|
+
import com.google.android.play.core.integrity.StandardIntegrityManager.StandardIntegrityTokenProvider
|
|
10
|
+
import com.google.android.play.core.integrity.StandardIntegrityManager.StandardIntegrityTokenRequest
|
|
11
|
+
import java.util.concurrent.Executor
|
|
12
|
+
import kotlin.coroutines.resume
|
|
13
|
+
import kotlin.coroutines.resumeWithException
|
|
14
|
+
import kotlinx.coroutines.CancellationException
|
|
15
|
+
import kotlinx.coroutines.suspendCancellableCoroutine
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Play Integrity, Standard API. The only file that touches Google's classes. An app installed outside Google Play, or a
|
|
19
|
+
* device without Play Store or Play services, simply gets an [AttestUnavailable] here; nothing else changes for it.
|
|
20
|
+
*
|
|
21
|
+
* Play Integrity is not started until the first [prepare], which only happens for a guest of an app whose attestation
|
|
22
|
+
* mode is `report` or `enforce`.
|
|
23
|
+
*/
|
|
24
|
+
internal class PlayIntegrityAttestor(context: Context) : Attestor {
|
|
25
|
+
private val appContext: Context = context.applicationContext
|
|
26
|
+
|
|
27
|
+
private val manager: StandardIntegrityManager by lazy { IntegrityManagerFactory.createStandard(appContext) }
|
|
28
|
+
|
|
29
|
+
@Volatile private var provider: StandardIntegrityTokenProvider? = null
|
|
30
|
+
|
|
31
|
+
override suspend fun prepare(cloudProjectNumber: Long) {
|
|
32
|
+
try {
|
|
33
|
+
val prepareRequest = PrepareIntegrityTokenRequest.builder().setCloudProjectNumber(cloudProjectNumber).build()
|
|
34
|
+
provider = manager.prepareIntegrityToken(prepareRequest).awaitTask()
|
|
35
|
+
} catch (e: CancellationException) {
|
|
36
|
+
throw e
|
|
37
|
+
} catch (t: Throwable) {
|
|
38
|
+
throw unavailableFor(t)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
override suspend fun request(requestHash: String): String {
|
|
43
|
+
val p = provider ?: throw AttestUnavailable("error")
|
|
44
|
+
return try {
|
|
45
|
+
val tokenRequest = StandardIntegrityTokenRequest.builder().setRequestHash(requestHash).build()
|
|
46
|
+
p.request(tokenRequest).awaitTask().token()
|
|
47
|
+
} catch (e: CancellationException) {
|
|
48
|
+
throw e
|
|
49
|
+
} catch (t: Throwable) {
|
|
50
|
+
throw unavailableFor(t)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private fun unavailableFor(t: Throwable): AttestUnavailable {
|
|
55
|
+
if (t is AttestUnavailable) return t
|
|
56
|
+
// The Play Integrity classes missing at run time (for example stripped by a shrinker): this device cannot attest.
|
|
57
|
+
if (t is LinkageError) return AttestUnavailable("unsupported", t)
|
|
58
|
+
val errorCode = (t as? StandardIntegrityException)?.errorCode
|
|
59
|
+
return AttestUnavailable(attestCodeForPlayError(errorCode), t)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Callbacks run right where Google delivers them: they only resume the coroutine, so the main thread is not needed. */
|
|
64
|
+
private val DIRECT_EXECUTOR = Executor { it.run() }
|
|
65
|
+
|
|
66
|
+
private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->
|
|
67
|
+
addOnSuccessListener(DIRECT_EXECUTOR) { cont.resume(it) }
|
|
68
|
+
addOnFailureListener(DIRECT_EXECUTOR) { cont.resumeWithException(it) }
|
|
69
|
+
addOnCanceledListener(DIRECT_EXECUTOR) { cont.resumeWithException(AttestUnavailable("error")) }
|
|
70
|
+
}
|
|
@@ -4,6 +4,8 @@ struct APIError: Error {
|
|
|
4
4
|
let status: Int
|
|
5
5
|
let code: String
|
|
6
6
|
let message: String
|
|
7
|
+
/// The reply's optional `reason` field (for example `unknown_key` on `attest_invalid`); empty when absent.
|
|
8
|
+
var reason: String = ""
|
|
7
9
|
|
|
8
10
|
/// Errors that end the attempt for good (the engine shows the matching screen).
|
|
9
11
|
var isFatal: Bool { ["invalid_token", "not_eligible", "already_taken", "closed", "quota_full"].contains(code) }
|
|
@@ -14,7 +16,7 @@ struct APIError: Error {
|
|
|
14
16
|
/// Every request has a total deadline (`requestDeadline`, 15 s): connection, request and the whole response body. When it
|
|
15
17
|
/// passes the call fails with `URLError(.timedOut)`, the same error a URLSession timeout raises, so it ends as `noFill`
|
|
16
18
|
/// the way a timeout always did.
|
|
17
|
-
final class ApiClient {
|
|
19
|
+
final class ApiClient: Sendable {
|
|
18
20
|
let base: URL
|
|
19
21
|
let key: String
|
|
20
22
|
let session: URLSession
|
|
@@ -58,12 +60,13 @@ final class ApiClient {
|
|
|
58
60
|
let (data, resp) = try await runWithinDeadline(deadline) { [session] in try await session.data(for: sent) }
|
|
59
61
|
let status = (resp as? HTTPURLResponse)?.statusCode ?? 0
|
|
60
62
|
if (200..<300).contains(status) { return data }
|
|
61
|
-
var code = "http_\(status)", message = ""
|
|
63
|
+
var code = "http_\(status)", message = "", reason = ""
|
|
62
64
|
if let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
|
63
65
|
code = (o["error"] as? String) ?? code
|
|
64
66
|
message = (o["message"] as? String) ?? ""
|
|
67
|
+
reason = (o["reason"] as? String) ?? ""
|
|
65
68
|
}
|
|
66
|
-
throw APIError(status: status, code: code, message: message)
|
|
69
|
+
throw APIError(status: status, code: code, message: message, reason: reason)
|
|
67
70
|
}
|
|
68
71
|
|
|
69
72
|
private func object(_ data: Data) throws -> [String: Any] {
|
|
@@ -85,12 +88,33 @@ final class ApiClient {
|
|
|
85
88
|
}
|
|
86
89
|
|
|
87
90
|
/// Guests: the install id in, a short-lived guest session token out. 403 `guests_not_allowed` when the app has guests off.
|
|
88
|
-
|
|
89
|
-
|
|
91
|
+
/// `attest` is the device attestation (or why there is none), sent only when the app asked for it (see `Attestor`).
|
|
92
|
+
/// 403 `attestation_required` / `attestation_failed` when the app enforces attestation and it is missing / invalid.
|
|
93
|
+
func guestSession(installId: String, attest: AttestEvidence? = nil) async throws -> String {
|
|
94
|
+
var body: [String: Any] = ["install_id": installId]
|
|
95
|
+
if let attest { body["attest"] = attest.json }
|
|
96
|
+
let o = try object(await request("POST", "guest/session", body: body))
|
|
90
97
|
guard let s = o["guest_session"] as? String else { throw APIError(status: 0, code: "bad_response", message: "no session") }
|
|
91
98
|
return s
|
|
92
99
|
}
|
|
93
100
|
|
|
101
|
+
/// A single-use challenge for an attestation or assertion (key header only, no body).
|
|
102
|
+
func attestChallenge() async throws -> String {
|
|
103
|
+
let o = try object(await request("POST", "attest/challenge"))
|
|
104
|
+
guard let c = o["challenge"] as? String, !c.isEmpty else { throw APIError(status: 0, code: "bad_response", message: "no challenge") }
|
|
105
|
+
return c
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/// Registers an App Attest key for this install. 400 `attest_invalid`, 410 `challenge_expired`.
|
|
109
|
+
func attestRegister(installId: String, keyId: String, attestation: Data, challenge: String) async throws {
|
|
110
|
+
_ = try await request("POST", "attest/ios/register", body: [
|
|
111
|
+
"install_id": installId,
|
|
112
|
+
"key_id": keyId,
|
|
113
|
+
"attestation": attestation.base64EncodedString(),
|
|
114
|
+
"challenge": challenge,
|
|
115
|
+
])
|
|
116
|
+
}
|
|
117
|
+
|
|
94
118
|
func createGuestAttempt(offerId: String, guestSession: String, lang: String) async throws -> [String: Any] {
|
|
95
119
|
try object(await request("POST", "attempts", body: ["offer_id": offerId, "guest_session": guestSession, "lang": lang]))
|
|
96
120
|
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import CryptoKit
|
|
2
|
+
import DeviceCheck
|
|
3
|
+
import Foundation
|
|
4
|
+
|
|
5
|
+
// Device attestation for guests (App Attest). Only `POST /v1/guest/session` carries it; people signed in with a partner
|
|
6
|
+
// token are vouched for by that token and never touch any of this. Nothing here is ever shown to the person.
|
|
7
|
+
//
|
|
8
|
+
// Wire format: the shared protocol, section "iOS (DCAppAttestService)". In short:
|
|
9
|
+
// key registration, once per install: challenge -> generateKey -> attestKey(SHA256(challenge)) -> /attest/ios/register
|
|
10
|
+
// per guest session: challenge -> generateAssertion(SHA256(challenge + "|" + install_id)) -> /guest/session
|
|
11
|
+
|
|
12
|
+
/// How long all attestation steps of one guest session may take together (challenges, key registration, assertion).
|
|
13
|
+
/// Past it the SDK sends `unavailable: "timeout"` and carries on. Same 10 seconds as the Android SDK.
|
|
14
|
+
let attestTimeout: TimeInterval = 10
|
|
15
|
+
|
|
16
|
+
/// `app.attest.mode` from `/surveys`. Anything the SDK does not know reads as `off`.
|
|
17
|
+
enum AttestMode: Equatable, Sendable {
|
|
18
|
+
/// Never touch attestation: no challenge, no key, no `attest` field.
|
|
19
|
+
case off
|
|
20
|
+
/// Attest; FOUNTIS records the outcome and always grants the guest session.
|
|
21
|
+
case report
|
|
22
|
+
/// Attest; FOUNTIS grants the guest session only for a valid attestation (403 otherwise).
|
|
23
|
+
case enforce
|
|
24
|
+
|
|
25
|
+
static func parse(_ raw: String?) -> AttestMode {
|
|
26
|
+
switch raw {
|
|
27
|
+
case "report": return .report
|
|
28
|
+
case "enforce": return .enforce
|
|
29
|
+
default: return .off
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// The `attest` object of the guest session body: an assertion, or the reason there is none.
|
|
35
|
+
enum AttestEvidence: Equatable, Sendable {
|
|
36
|
+
case assertion(keyId: String, assertion: String, challenge: String)
|
|
37
|
+
/// `unsupported` (simulator, old OS), `timeout`, `error`.
|
|
38
|
+
case unavailable(String)
|
|
39
|
+
|
|
40
|
+
var json: [String: Any] {
|
|
41
|
+
switch self {
|
|
42
|
+
case let .assertion(keyId, assertion, challenge):
|
|
43
|
+
return ["platform": "ios", "key_id": keyId, "assertion": assertion, "challenge": challenge]
|
|
44
|
+
case .unavailable(let code):
|
|
45
|
+
return ["platform": "ios", "unavailable": code]
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// MARK: - The system service, behind a protocol
|
|
51
|
+
|
|
52
|
+
/// Why App Attest failed, in the few ways that change what the SDK does.
|
|
53
|
+
enum AppAttestFailure: Error, Equatable {
|
|
54
|
+
/// This device or OS cannot do App Attest.
|
|
55
|
+
case unsupported
|
|
56
|
+
/// This device does not know the key (a backup restore or OS reset kept our copy of its id, not the key).
|
|
57
|
+
case invalidKey
|
|
58
|
+
case failed(String)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// The part of `DCAppAttestService` the SDK uses, so tests can fake it (App Attest does not run on the simulator).
|
|
62
|
+
/// Implementations throw `AppAttestFailure` for the failures above, anything else for the rest.
|
|
63
|
+
protocol AppAttestService: Sendable {
|
|
64
|
+
var isSupported: Bool { get }
|
|
65
|
+
func generateKey() async throws -> String
|
|
66
|
+
func attestKey(_ keyId: String, clientDataHash: Data) async throws -> Data
|
|
67
|
+
func generateAssertion(_ keyId: String, clientDataHash: Data) async throws -> Data
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
struct SystemAppAttestService: AppAttestService {
|
|
71
|
+
var isSupported: Bool { DCAppAttestService.shared.isSupported }
|
|
72
|
+
|
|
73
|
+
func generateKey() async throws -> String {
|
|
74
|
+
do { return try await DCAppAttestService.shared.generateKey() } catch { throw Self.translate(error) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
func attestKey(_ keyId: String, clientDataHash: Data) async throws -> Data {
|
|
78
|
+
do { return try await DCAppAttestService.shared.attestKey(keyId, clientDataHash: clientDataHash) } catch { throw Self.translate(error) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
func generateAssertion(_ keyId: String, clientDataHash: Data) async throws -> Data {
|
|
82
|
+
do { return try await DCAppAttestService.shared.generateAssertion(keyId, clientDataHash: clientDataHash) } catch { throw Self.translate(error) }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
static func translate(_ error: Error) -> Error {
|
|
86
|
+
guard let e = error as? DCError else { return error }
|
|
87
|
+
switch e.code {
|
|
88
|
+
case .featureUnsupported: return AppAttestFailure.unsupported
|
|
89
|
+
case .invalidKey: return AppAttestFailure.invalidKey
|
|
90
|
+
default: return AppAttestFailure.failed("DCError \(e.errorCode)")
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// MARK: - Key storage
|
|
96
|
+
|
|
97
|
+
/// Where the App Attest key id lives: once per install, next to the guest install id.
|
|
98
|
+
protocol AttestKeyStore: Sendable {
|
|
99
|
+
func keyId() -> String?
|
|
100
|
+
func setKeyId(_ id: String?)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
struct UserDefaultsAttestKeyStore: AttestKeyStore {
|
|
104
|
+
private static let key = "guest.attest_key_id"
|
|
105
|
+
private var defaults: UserDefaults { UserDefaults(suiteName: "org.fountis.connect.state") ?? .standard }
|
|
106
|
+
|
|
107
|
+
func keyId() -> String? {
|
|
108
|
+
guard let v = defaults.string(forKey: Self.key), !v.isEmpty else { return nil }
|
|
109
|
+
return v
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
func setKeyId(_ id: String?) {
|
|
113
|
+
if let id { defaults.set(id, forKey: Self.key) } else { defaults.removeObject(forKey: Self.key) }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// MARK: - API surface
|
|
118
|
+
|
|
119
|
+
/// The two attestation calls the `Attestor` needs from the API.
|
|
120
|
+
protocol AttestAPI: Sendable {
|
|
121
|
+
func attestChallenge() async throws -> String
|
|
122
|
+
func attestRegister(installId: String, keyId: String, attestation: Data, challenge: String) async throws
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
protocol GuestSessionAPI: AttestAPI {
|
|
126
|
+
func guestSession(installId: String, attest: AttestEvidence?) async throws -> String
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
extension ApiClient: GuestSessionAPI {}
|
|
130
|
+
|
|
131
|
+
extension APIError {
|
|
132
|
+
/// 403 from `/guest/session` on an app that enforces attestation: nothing sent (`attestation_required`) or sent and
|
|
133
|
+
/// invalid (`attestation_failed`). The SDK offers no guest studies this time and does not retry.
|
|
134
|
+
var isAttestationRefusal: Bool { code == "attestation_required" || code == "attestation_failed" }
|
|
135
|
+
|
|
136
|
+
/// 400 `attest_invalid` because FOUNTIS no longer knows the key: register a new one, once.
|
|
137
|
+
var isUnknownAttestKey: Bool {
|
|
138
|
+
code == "attest_invalid" && (reason == "unknown_key" || message.contains("unknown_key"))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// A failed attempt that only rules out this offer: the check moves on to the next one. Any other failure ends the
|
|
142
|
+
/// check as `noFill`, attestation refusals included (they would repeat for every offer).
|
|
143
|
+
var skipsToNextOffer: Bool {
|
|
144
|
+
!isAttestationRefusal && ["already_taken", "not_eligible", "closed", "quota_full", "guests_not_allowed"].contains(code)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// MARK: - Attestor
|
|
149
|
+
|
|
150
|
+
/// Makes the attestation for a guest session: registers an App Attest key once per install, then answers each guest
|
|
151
|
+
/// session with an assertion. `evidence` never throws except for cancellation; whatever goes wrong becomes
|
|
152
|
+
/// `.unavailable(code)` and the guest session request goes on without an attestation (FOUNTIS decides what that means).
|
|
153
|
+
actor Attestor {
|
|
154
|
+
private let service: AppAttestService
|
|
155
|
+
private let keys: AttestKeyStore
|
|
156
|
+
private let failureCooldown: TimeInterval
|
|
157
|
+
private var registrationPausedUntil: Date?
|
|
158
|
+
|
|
159
|
+
/// `failureCooldown`: after a key registration that Apple or FOUNTIS turned down, no new key is made for this long
|
|
160
|
+
/// (Apple rate-limits attestation, and a server that rejects every key would otherwise cost one per show).
|
|
161
|
+
init(service: AppAttestService = SystemAppAttestService(), keys: AttestKeyStore = UserDefaultsAttestKeyStore(), failureCooldown: TimeInterval = 300) {
|
|
162
|
+
self.service = service
|
|
163
|
+
self.keys = keys
|
|
164
|
+
self.failureCooldown = failureCooldown
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// Everything shares `timeout` seconds. Past it: `.unavailable("timeout")`.
|
|
168
|
+
func evidence(api: AttestAPI, installId: String, timeout: TimeInterval = attestTimeout) async throws -> AttestEvidence {
|
|
169
|
+
guard service.isSupported else { return .unavailable("unsupported") }
|
|
170
|
+
do {
|
|
171
|
+
return try await runWithinDeadline(timeout) { [self] in try await self.produce(api: api, installId: installId) }
|
|
172
|
+
} catch is CancellationError {
|
|
173
|
+
throw CancellationError()
|
|
174
|
+
} catch {
|
|
175
|
+
let code = Self.unavailableCode(for: error)
|
|
176
|
+
fcLog.debug("attestation unavailable (\(code)): \(String(describing: error))")
|
|
177
|
+
return .unavailable(code)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/// FOUNTIS no longer knows this key: forget it so the next `evidence` registers a new one.
|
|
182
|
+
func forget(keyId: String) {
|
|
183
|
+
if keys.keyId() == keyId { keys.setKeyId(nil) }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
static func unavailableCode(for error: Error) -> String {
|
|
187
|
+
if let u = error as? URLError, u.code == .timedOut { return "timeout" }
|
|
188
|
+
if let f = error as? AppAttestFailure, f == .unsupported { return "unsupported" }
|
|
189
|
+
return "error"
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// MARK: steps
|
|
193
|
+
|
|
194
|
+
private func produce(api: AttestAPI, installId: String) async throws -> AttestEvidence {
|
|
195
|
+
var keyId = try await keyIdRegisteringIfNeeded(api: api, installId: installId)
|
|
196
|
+
do {
|
|
197
|
+
return try await assertion(keyId: keyId, api: api, installId: installId)
|
|
198
|
+
} catch AppAttestFailure.invalidKey {
|
|
199
|
+
// The device does not have the key our storage names (restored backup, OS reset): make a new one, once.
|
|
200
|
+
fcLog.debug("attest key unknown to this device; registering a new one")
|
|
201
|
+
keys.setKeyId(nil)
|
|
202
|
+
keyId = try await register(api: api, installId: installId)
|
|
203
|
+
return try await assertion(keyId: keyId, api: api, installId: installId)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private func keyIdRegisteringIfNeeded(api: AttestAPI, installId: String) async throws -> String {
|
|
208
|
+
if let k = keys.keyId() { return k }
|
|
209
|
+
return try await register(api: api, installId: installId)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/// Steps 1 to 3 of the protocol. The key id is stored only once FOUNTIS accepted it.
|
|
213
|
+
private func register(api: AttestAPI, installId: String) async throws -> String {
|
|
214
|
+
if let until = registrationPausedUntil, until > Date() {
|
|
215
|
+
throw AppAttestFailure.failed("key registration paused after an earlier failure")
|
|
216
|
+
}
|
|
217
|
+
var madeKey = false
|
|
218
|
+
do {
|
|
219
|
+
let challenge = try await api.attestChallenge()
|
|
220
|
+
let keyId = try await service.generateKey()
|
|
221
|
+
madeKey = true
|
|
222
|
+
let attestation = try await service.attestKey(keyId, clientDataHash: AttestHash.of(challenge))
|
|
223
|
+
try await api.attestRegister(installId: installId, keyId: keyId, attestation: attestation, challenge: challenge)
|
|
224
|
+
keys.setKeyId(keyId)
|
|
225
|
+
registrationPausedUntil = nil
|
|
226
|
+
return keyId
|
|
227
|
+
} catch {
|
|
228
|
+
// A timeout or cancellation says nothing about the key; a refusal after the key existed does.
|
|
229
|
+
if madeKey, !Task.isCancelled, !(error is CancellationError), (error as? URLError)?.code != .timedOut {
|
|
230
|
+
registrationPausedUntil = Date().addingTimeInterval(failureCooldown)
|
|
231
|
+
}
|
|
232
|
+
throw error
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/// Steps 4 and 5 of the protocol.
|
|
237
|
+
private func assertion(keyId: String, api: AttestAPI, installId: String) async throws -> AttestEvidence {
|
|
238
|
+
let challenge = try await api.attestChallenge()
|
|
239
|
+
let data = try await service.generateAssertion(keyId, clientDataHash: AttestHash.of(challenge + "|" + installId))
|
|
240
|
+
return .assertion(keyId: keyId, assertion: data.base64EncodedString(), challenge: challenge)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
enum AttestHash {
|
|
245
|
+
/// SHA-256 of the UTF-8 bytes: the `clientDataHash` App Attest takes.
|
|
246
|
+
static func of(_ text: String) -> Data { Data(SHA256.hash(data: Data(text.utf8))) }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// MARK: - Guest session with attestation
|
|
250
|
+
|
|
251
|
+
/// Opens a guest session the way the protocol says: no attestation when the mode is `off`, otherwise evidence first,
|
|
252
|
+
/// and one re-registration when FOUNTIS answers `attest_invalid` for a key it does not know.
|
|
253
|
+
struct GuestSessionMaker: Sendable {
|
|
254
|
+
let attestor: Attestor
|
|
255
|
+
/// Shared by the attestation steps of one call, re-registration included.
|
|
256
|
+
var attestBudget: TimeInterval = attestTimeout
|
|
257
|
+
|
|
258
|
+
/// Throws `APIError` as the guest session call does; `attestation_required` / `attestation_failed` (403) are not retried.
|
|
259
|
+
func make(api: GuestSessionAPI, mode: AttestMode, installId: String) async throws -> String {
|
|
260
|
+
guard mode != .off else { return try await api.guestSession(installId: installId, attest: nil) }
|
|
261
|
+
let started = Date()
|
|
262
|
+
var reRegistered = false
|
|
263
|
+
while true {
|
|
264
|
+
let remaining = max(attestBudget - Date().timeIntervalSince(started), 0)
|
|
265
|
+
let evidence = try await attestor.evidence(api: api, installId: installId, timeout: remaining)
|
|
266
|
+
do {
|
|
267
|
+
return try await api.guestSession(installId: installId, attest: evidence)
|
|
268
|
+
} catch let e as APIError where !reRegistered && e.isUnknownAttestKey {
|
|
269
|
+
guard case .assertion(let keyId, _, _) = evidence else { throw e }
|
|
270
|
+
reRegistered = true
|
|
271
|
+
fcLog.debug("attest key unknown to FOUNTIS; registering a new one")
|
|
272
|
+
await attestor.forget(keyId: keyId)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
@@ -87,6 +87,8 @@ final class Core {
|
|
|
87
87
|
private var forwardingDelegate: ForwardingNotificationDelegate?
|
|
88
88
|
private var lastSubHash: String?
|
|
89
89
|
private var guestSession: (token: String, expires: Date)?
|
|
90
|
+
/// Device attestation for guest sessions (only used when the app's `app.attest.mode` is `report` or `enforce`).
|
|
91
|
+
private let guestSessions = GuestSessionMaker(attestor: Attestor())
|
|
90
92
|
private let accentHex = "#5dc0a0"
|
|
91
93
|
|
|
92
94
|
private init() {
|
|
@@ -223,9 +225,10 @@ final class Core {
|
|
|
223
225
|
}
|
|
224
226
|
|
|
225
227
|
/// A guest session token, kept in memory for most of its hour. `force` makes a new one.
|
|
226
|
-
|
|
228
|
+
/// A new one is attested when the app asks for it (`app.attest.mode`); with mode `off` or absent attestation is never touched.
|
|
229
|
+
private func guestToken(_ s: Session, force: Bool = false) async throws -> String {
|
|
227
230
|
if !force, let g = guestSession, g.expires > Date() { return g.token }
|
|
228
|
-
let t = try await api.
|
|
231
|
+
let t = try await guestSessions.make(api: s.api, mode: s.surveys.app?.attestMode ?? .off, installId: GuestInstall.id())
|
|
229
232
|
guestSession = (t, Date().addingTimeInterval(55 * 60))
|
|
230
233
|
return t
|
|
231
234
|
}
|
|
@@ -268,11 +271,11 @@ final class Core {
|
|
|
268
271
|
/// Starts the attempt for a person with a token or a guest session (a stale guest session is renewed once).
|
|
269
272
|
private func createAttempt(_ s: Session, offerId: String) async throws -> [String: Any] {
|
|
270
273
|
if let token = s.token { return try await s.api.createAttempt(offerId: offerId, token: token, lang: s.lang) }
|
|
271
|
-
let session = try await guestToken(
|
|
274
|
+
let session = try await guestToken(s)
|
|
272
275
|
do {
|
|
273
276
|
return try await s.api.createGuestAttempt(offerId: offerId, guestSession: session, lang: s.lang)
|
|
274
277
|
} catch let e as APIError where e.code == "invalid_session" {
|
|
275
|
-
let fresh = try await guestToken(
|
|
278
|
+
let fresh = try await guestToken(s, force: true)
|
|
276
279
|
return try await s.api.createGuestAttempt(offerId: offerId, guestSession: fresh, lang: s.lang)
|
|
277
280
|
}
|
|
278
281
|
}
|
|
@@ -311,7 +314,9 @@ final class Core {
|
|
|
311
314
|
return await present(offer: offer, attempt: a, session: s)
|
|
312
315
|
} catch let e as APIError {
|
|
313
316
|
if e.code == "already_taken" { s.state.markTaken(offer.offerId) }
|
|
314
|
-
|
|
317
|
+
// The app enforces attestation and this device has none that passes: no guest offers this time, no retry.
|
|
318
|
+
if e.isAttestationRefusal { fcLog.debug("guest studies not offered: \(e.code)"); return .noFill }
|
|
319
|
+
if e.skipsToNextOffer { continue }
|
|
315
320
|
fcLog.debug("attempt failed: \(e.code)")
|
|
316
321
|
return .noFill
|
|
317
322
|
} catch {
|
|
@@ -107,6 +107,23 @@ struct SurveysAppInfo: Codable {
|
|
|
107
107
|
let name: String?
|
|
108
108
|
/// The app may offer free studies to guests.
|
|
109
109
|
let guests: Bool?
|
|
110
|
+
/// Device attestation for guests (`off` when absent).
|
|
111
|
+
let attest: SurveysAttestInfo?
|
|
112
|
+
|
|
113
|
+
var attestMode: AttestMode { AttestMode.parse(attest?.mode) }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/// `app.attest` from `/surveys`. Decoding never throws: a field of the wrong type reads as absent (so as `off`), because
|
|
117
|
+
/// a surprise here must not turn every check into `noFill`. Only `mode` matters on iOS (`android_cloud_project` is Android's).
|
|
118
|
+
struct SurveysAttestInfo: Codable {
|
|
119
|
+
let mode: String?
|
|
120
|
+
|
|
121
|
+
private enum CodingKeys: String, CodingKey { case mode }
|
|
122
|
+
|
|
123
|
+
init(from decoder: Decoder) throws {
|
|
124
|
+
let c = try? decoder.container(keyedBy: CodingKeys.self)
|
|
125
|
+
mode = try? c?.decodeIfPresent(String.self, forKey: .mode)
|
|
126
|
+
}
|
|
110
127
|
}
|
|
111
128
|
|
|
112
129
|
struct SurveysResponse: Codable {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fountispanel/connect-react-native",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "FOUNTIS Connect for React Native and Expo (development builds): native iOS and Android SDKs, Web SDK on React Native Web.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"main": "build/index.js",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"expo-modules-core": "*",
|
|
36
36
|
"react": "*",
|
|
37
37
|
"react-native": "*",
|
|
38
|
-
"@fountispanel/connect": "^1.
|
|
38
|
+
"@fountispanel/connect": "^1.1.0"
|
|
39
39
|
},
|
|
40
40
|
"peerDependenciesMeta": {
|
|
41
41
|
"@fountispanel/connect": {
|