@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +10 -7
  3. package/android/build.gradle +35 -17
  4. package/android/src/main/AndroidManifest.xml +5 -16
  5. package/build/index.js +1 -126
  6. package/build/index.web.js +1 -57
  7. package/ios/FountisConnect.xcframework/Info.plist +44 -0
  8. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine/engine.html +47 -0
  9. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/ar.json +16 -19
  10. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/en.json +17 -20
  11. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/Engine/i18n/kmr.json +19 -22
  12. package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Engine}/i18n/ku.json +19 -22
  13. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/FountisConnect +0 -0
  14. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Info.plist +53 -0
  15. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftdoc +0 -0
  16. package/ios/FountisConnect.xcframework/ios-arm64/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios.swiftinterface +48 -0
  17. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine/engine.html +47 -0
  18. package/{android/connect-sdk/main/assets/fountis-connect → ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Engine}/i18n/ar.json +16 -19
  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
  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
  21. package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework}/Engine/i18n/ku.json +19 -22
  22. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/FountisConnect +0 -0
  23. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Info.plist +49 -0
  24. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftdoc +0 -0
  25. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/arm64-apple-ios-simulator.swiftinterface +48 -0
  26. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftdoc +0 -0
  27. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/Modules/FountisConnect.swiftmodule/x86_64-apple-ios-simulator.swiftinterface +48 -0
  28. package/ios/FountisConnect.xcframework/ios-arm64_x86_64-simulator/FountisConnect.framework/PrivacyInfo.xcprivacy +23 -0
  29. package/ios/FountisConnectAppDelegateSubscriber.swift +3 -0
  30. package/ios/FountisConnectModule.swift +3 -0
  31. package/ios/FountisConnectReactNative.podspec +27 -6
  32. package/package.json +14 -12
  33. package/android/connect-sdk/main/assets/fountis-connect/engine.html +0 -47
  34. package/android/connect-sdk/main/kotlin/org/fountis/connect/ApiClient.kt +0 -179
  35. package/android/connect-sdk/main/kotlin/org/fountis/connect/Attest.kt +0 -234
  36. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisConnect.kt +0 -641
  37. package/android/connect-sdk/main/kotlin/org/fountis/connect/FountisSurveyActivity.kt +0 -321
  38. package/android/connect-sdk/main/kotlin/org/fountis/connect/LocalState.kt +0 -143
  39. package/android/connect-sdk/main/kotlin/org/fountis/connect/Matcher.kt +0 -167
  40. package/android/connect-sdk/main/kotlin/org/fountis/connect/Models.kt +0 -144
  41. package/android/connect-sdk/main/kotlin/org/fountis/connect/Notifier.kt +0 -109
  42. package/android/connect-sdk/main/kotlin/org/fountis/connect/PlayIntegrityAttestor.kt +0 -70
  43. package/android/connect-sdk/main/kotlin/org/fountis/connect/RequestDeadline.kt +0 -74
  44. package/android/connect-sdk/main/kotlin/org/fountis/connect/Strings.kt +0 -45
  45. package/android/connect-sdk/main/kotlin/org/fountis/connect/TokenProviderCall.kt +0 -72
  46. package/android/connect-sdk/main/res/drawable/fountis_ic_notification.xml +0 -12
  47. package/android/connect-sdk/main/res/values/fountis_styles.xml +0 -13
  48. package/android/connect-sdk/main/res/values-v27/fountis_styles.xml +0 -12
  49. package/build/types.js +0 -1
  50. package/ios/FountisConnectBundle.swift +0 -15
  51. package/ios/FountisConnectSDK/ApiClient.swift +0 -137
  52. package/ios/FountisConnectSDK/Attestation.swift +0 -276
  53. package/ios/FountisConnectSDK/Engine/engine.html +0 -47
  54. package/ios/FountisConnectSDK/FountisConnect.swift +0 -441
  55. package/ios/FountisConnectSDK/LocalState.swift +0 -81
  56. package/ios/FountisConnectSDK/Matcher.swift +0 -102
  57. package/ios/FountisConnectSDK/Models.swift +0 -133
  58. package/ios/FountisConnectSDK/Notifier.swift +0 -63
  59. package/ios/FountisConnectSDK/RequestDeadline.swift +0 -93
  60. package/ios/FountisConnectSDK/SheetController.swift +0 -259
  61. package/ios/FountisConnectSDK/Strings.swift +0 -34
  62. package/ios/FountisConnectSDK/TokenProviderCall.swift +0 -91
  63. package/scripts/vendor-native.sh +0 -16
  64. package/src/index.ts +0 -142
  65. package/src/index.web.ts +0 -64
  66. package/src/types.ts +0 -26
  67. /package/ios/{FountisConnectSDK → FountisConnect.xcframework/ios-arm64/FountisConnect.framework}/PrivacyInfo.xcprivacy +0 -0
@@ -1,137 +0,0 @@
1
- import Foundation
2
-
3
- struct APIError: Error {
4
- let status: Int
5
- let code: String
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 = ""
9
-
10
- /// Errors that end the attempt for good (the engine shows the matching screen).
11
- var isFatal: Bool { ["invalid_token", "not_eligible", "already_taken", "closed", "quota_full"].contains(code) }
12
- }
13
-
14
- /// Thin client for the connect-api. Own ephemeral session; only the headers the contract names.
15
- ///
16
- /// Every request has a total deadline (`requestDeadline`, 15 s): connection, request and the whole response body. When it
17
- /// passes the call fails with `URLError(.timedOut)`, the same error a URLSession timeout raises, so it ends as `noFill`
18
- /// the way a timeout always did.
19
- final class ApiClient: Sendable {
20
- let base: URL
21
- let key: String
22
- let session: URLSession
23
- /// Total time one request may take (see `requestDeadline`).
24
- let deadline: TimeInterval
25
-
26
- /// `deadline` and `protocolClasses` exist for tests (a shortened deadline, a stubbed network); the SDK passes neither.
27
- init(base: URL, key: String, deadline: TimeInterval = requestDeadline, protocolClasses: [AnyClass]? = nil) {
28
- self.base = base
29
- self.key = key
30
- self.deadline = deadline
31
- let cfg = URLSessionConfiguration.ephemeral
32
- cfg.httpCookieStorage = nil
33
- cfg.httpShouldSetCookies = false
34
- cfg.urlCache = nil
35
- cfg.requestCachePolicy = .reloadIgnoringLocalCacheData
36
- // Idle limit (restarts whenever bytes arrive): kept at the deadline so no single wait can outlast it.
37
- cfg.timeoutIntervalForRequest = deadline
38
- // Total limit for the whole transfer. The deadline in `request` is the one that is relied on; this is the second line.
39
- cfg.timeoutIntervalForResource = deadline
40
- cfg.waitsForConnectivity = false
41
- if let protocolClasses { cfg.protocolClasses = protocolClasses }
42
- session = URLSession(configuration: cfg)
43
- }
44
-
45
- private func request(_ method: String, _ path: String, query: [URLQueryItem] = [], body: Any? = nil, attemptToken: String? = nil) async throws -> Data {
46
- var comps = URLComponents(url: base.appendingPathComponent(path), resolvingAgainstBaseURL: false)
47
- if !query.isEmpty { comps?.queryItems = query }
48
- guard let url = comps?.url else { throw APIError(status: 0, code: "bad_url", message: "bad url") }
49
- var req = URLRequest(url: url)
50
- req.httpMethod = method
51
- req.timeoutInterval = deadline
52
- req.setValue(key, forHTTPHeaderField: "X-Fountis-Key")
53
- if let t = attemptToken { req.setValue("Attempt \(t)", forHTTPHeaderField: "Authorization") }
54
- if let body = body {
55
- req.setValue("application/json", forHTTPHeaderField: "Content-Type")
56
- req.httpBody = try JSONSerialization.data(withJSONObject: body)
57
- }
58
- // Connection, request and the whole body must finish within the deadline; a body that trickles in cannot hold the call open.
59
- let sent = req
60
- let (data, resp) = try await runWithinDeadline(deadline) { [session] in try await session.data(for: sent) }
61
- let status = (resp as? HTTPURLResponse)?.statusCode ?? 0
62
- if (200..<300).contains(status) { return data }
63
- var code = "http_\(status)", message = "", reason = ""
64
- if let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
65
- code = (o["error"] as? String) ?? code
66
- message = (o["message"] as? String) ?? ""
67
- reason = (o["reason"] as? String) ?? ""
68
- }
69
- throw APIError(status: status, code: code, message: message, reason: reason)
70
- }
71
-
72
- private func object(_ data: Data) throws -> [String: Any] {
73
- guard let o = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
74
- throw APIError(status: 0, code: "bad_response", message: "unexpected response")
75
- }
76
- return o
77
- }
78
-
79
- func surveys(lang: String) async throws -> SurveysResponse {
80
- let data = try await request("GET", "surveys", query: [URLQueryItem(name: "lang", value: lang)])
81
- let dec = JSONDecoder()
82
- dec.keyDecodingStrategy = .convertFromSnakeCase
83
- return try dec.decode(SurveysResponse.self, from: data)
84
- }
85
-
86
- func createAttempt(offerId: String, token: String, lang: String) async throws -> [String: Any] {
87
- try object(await request("POST", "attempts", body: ["offer_id": offerId, "token": token, "lang": lang]))
88
- }
89
-
90
- /// Guests: the install id in, a short-lived guest session token out. 403 `guests_not_allowed` when the app has guests off.
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))
97
- guard let s = o["guest_session"] as? String else { throw APIError(status: 0, code: "bad_response", message: "no session") }
98
- return s
99
- }
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
-
118
- func createGuestAttempt(offerId: String, guestSession: String, lang: String) async throws -> [String: Any] {
119
- try object(await request("POST", "attempts", body: ["offer_id": offerId, "guest_session": guestSession, "lang": lang]))
120
- }
121
-
122
- func putAnswer(code: String, value: Any, attemptToken: String) async throws -> [String: Any] {
123
- try object(await request("PUT", "attempt/answers", body: ["code": code, "value": value], attemptToken: attemptToken))
124
- }
125
-
126
- func consent(attemptToken: String) async throws {
127
- _ = try await request("POST", "attempt/consent", body: [String: Any](), attemptToken: attemptToken)
128
- }
129
-
130
- func complete(attemptToken: String) async throws -> [String: Any] {
131
- try object(await request("POST", "attempt/complete", body: [String: Any](), attemptToken: attemptToken))
132
- }
133
-
134
- func event(offerId: String, type: String) async {
135
- _ = try? await request("POST", "events", body: ["offer_id": offerId, "type": type])
136
- }
137
- }
@@ -1,276 +0,0 @@
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
- }