-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathNativeBridge.swift
More file actions
528 lines (476 loc) · 22 KB
/
NativeBridge.swift
File metadata and controls
528 lines (476 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//
// NativeBridge.swift
// A0Auth0
//
// Created by Poovamraj T T on 15/06/23.
// Copyright © 2023 Facebook. All rights reserved.
//
import Auth0
import Foundation
import LocalAuthentication
@objc
public class NativeBridge: NSObject {
static let accessTokenKey = "accessToken";
static let idTokenKey = "idToken";
static let expiresAtKey = "expiresAt";
static let scopeKey = "scope";
static let refreshTokenKey = "refreshToken";
static let typeKey = "type";
static let tokenTypeKey = "tokenType";
static let dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
static let credentialsManagerErrorCode = "CREDENTIAL_MANAGER_ERROR"
static let biometricsAuthenticationErrorCode = "BIOMETRICS_CONFIGURATION_ERROR"
// DPoP error codes
static let dpopErrorCode = "DPOP_ERROR"
static let dpopKeyGenerationFailedCode = "DPOP_KEY_GENERATION_FAILED"
static let dpopKeyStorageFailedCode = "DPOP_KEY_STORAGE_FAILED"
static let dpopKeyRetrievalFailedCode = "DPOP_KEY_RETRIEVAL_FAILED"
static let dpopKeyNotFoundCode = "DPOP_KEY_NOT_FOUND"
static let dpopKeychainErrorCode = "DPOP_KEYCHAIN_ERROR"
static let dpopGenerationFailedCode = "DPOP_GENERATION_FAILED"
static let dpopProofFailedCode = "DPOP_PROOF_FAILED"
static let dpopNonceMismatchCode = "DPOP_NONCE_MISMATCH"
static let dpopInvalidTokenTypeCode = "DPOP_INVALID_TOKEN_TYPE"
static let dpopMissingParameterCode = "DPOP_MISSING_PARAMETER"
static let dpopClearKeyFailedCode = "DPOP_CLEAR_KEY_FAILED"
var credentialsManager: CredentialsManager
var clientId: String
var domain: String
var useDPoP: Bool
var maxRetries: Int
@objc public init(clientId: String, domain: String, localAuthenticationOptions: [String: Any]?, useDPoP: Bool, maxRetries: Int, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
var auth0 = Auth0
.authentication(clientId: clientId, domain: domain)
self.clientId = clientId
self.domain = domain
self.useDPoP = useDPoP
self.maxRetries = maxRetries
if self.useDPoP {
auth0 = auth0.useDPoP()
}
self.credentialsManager = CredentialsManager(authentication: auth0, maxRetries: maxRetries)
super.init()
if let localAuthenticationOptions = localAuthenticationOptions {
if let title = localAuthenticationOptions["title"] as? String {
var evaluationPolicy = LAPolicy.deviceOwnerAuthenticationWithBiometrics
if let evaluationPolicyInt = localAuthenticationOptions["evaluationPolicy"] as? Int {
evaluationPolicy = convert(policyInt: evaluationPolicyInt)
}
// Parse biometric policy
var biometricPolicy = BiometricPolicy.default
if let policyString = localAuthenticationOptions["biometricPolicy"] as? String {
let timeout = localAuthenticationOptions["biometricTimeout"] as? Int ?? 3600
biometricPolicy = convert(policyString: policyString, timeout: timeout)
}
self.credentialsManager.enableBiometrics(withTitle: title, cancelTitle: localAuthenticationOptions["cancelTitle"] as? String, fallbackTitle: localAuthenticationOptions["fallbackTitle"] as? String, evaluationPolicy: evaluationPolicy, policy: biometricPolicy)
resolve(true)
return
} else {
reject(NativeBridge.biometricsAuthenticationErrorCode, "Missing mandatory property title in LocalAuthenticationOptions, hence biometrics authentication cannot be enabled", nil)
return
}
}
resolve(true)
}
@objc public func webAuth(scheme: String, state: String?, redirectUri: String, nonce: String?, audience: String?, scope: String?, connection: String?, maxAge: Int, organization: String?, invitationUrl: String?, leeway: Int, ephemeralSession: Bool, safariViewControllerPresentationStyle: Int, additionalParameters: [String: String], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
var builder = Auth0.webAuth(clientId: self.clientId, domain: self.domain)
if self.useDPoP {
builder = builder.useDPoP()
}
if let value = URL(string: redirectUri) {
let _ = builder.redirectURL(value)
}
if let value = state {
let _ = builder.state(value)
}
if let value = nonce {
let _ = builder.nonce(value)
}
if let value = audience {
let _ = builder.audience(value)
}
if let value = scope {
let _ = builder.scope(value)
}
if let value = connection {
let _ = builder.connection(value)
}
if(maxAge != 0) {
let _ = builder.maxAge(maxAge)
}
if let value = organization {
let _ = builder.organization(value)
}
if let value = invitationUrl, let invitationURL = URL(string: value) {
let _ = builder.invitationURL(invitationURL)
}
if(leeway != 0) {
let _ = builder.leeway(leeway)
}
if(ephemeralSession) {
let _ = builder.useEphemeralSession()
}
// Check if scheme starts with https and use HTTPS if it does
if scheme.starts(with: "https") {
let _ = builder.useHTTPS()
}
//Since we cannot have a null value here, the JS layer sends 99 if we have to ignore setting this value
if let presentationStyle = UIModalPresentationStyle(rawValue: safariViewControllerPresentationStyle), safariViewControllerPresentationStyle != 99 {
let _ = builder.provider(WebAuthentication.safariProvider(style: presentationStyle))
}
let _ = builder
.parameters(additionalParameters)
builder.start { result in
switch result {
case .success(let credentials):
resolve(credentials.asDictionary())
case .failure(let error):
reject(error.reactNativeErrorCode(), error.errorDescription, error)
}
}
}
@objc public func webAuthLogout(scheme: String, federated: Bool, redirectUri: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
let builder = Auth0.webAuth(clientId: self.clientId, domain: self.domain)
if let value = URL(string: redirectUri) {
let _ = builder.redirectURL(value)
}
// Check if scheme starts with https and use HTTPS if it does
if scheme.starts(with: "https") {
let _ = builder.useHTTPS()
}
builder.clearSession(federated: federated) { result in
switch result {
case .success:
resolve(true)
case .failure(let error):
reject(error.reactNativeErrorCode(), error.errorDescription, error)
}
}
}
@objc public func resumeWebAuth(url: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if let value = URL(string: url), WebAuthentication.resume(with: value) {
resolve(true)
} else {
reject("ERROR_PARSING_URL", "The callback url \(url) is invalid", nil)
}
}
@objc public func cancelWebAuth(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
resolve(WebAuthentication.cancel())
}
@objc public func saveCredentials(credentialsDict: [String: Any], resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
guard let accessToken = credentialsDict[NativeBridge.accessTokenKey] as? String, let tokenType = credentialsDict[NativeBridge.tokenTypeKey] as? String, let idToken = credentialsDict[NativeBridge.idTokenKey] as? String else { reject(NativeBridge.credentialsManagerErrorCode, "Incomplete information provided for credentials", NSError.init(domain: NativeBridge.credentialsManagerErrorCode, code: -99999, userInfo: nil)); return; }
let refreshToken = credentialsDict[NativeBridge.refreshTokenKey] as? String
let scope = credentialsDict[NativeBridge.scopeKey] as? String
var expiresIn: Date?
if let string = credentialsDict[NativeBridge.expiresAtKey] as? String, let double = Double(string) {
expiresIn = Date(timeIntervalSince1970: double)
} else if let double = credentialsDict[NativeBridge.expiresAtKey] as? Double {
expiresIn = Date(timeIntervalSince1970: double)
} else if let dateStr = credentialsDict[NativeBridge.expiresAtKey] as? String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = NativeBridge.dateFormat
expiresIn = dateFormatter.date(from: dateStr)
}
if let expiresIn = expiresIn {
let credentials = Credentials(
accessToken: accessToken,
tokenType: tokenType,
idToken: idToken,
refreshToken: refreshToken,
expiresIn: expiresIn,
scope: scope,
recoveryCode: nil
)
if (credentialsManager.store(credentials: credentials)) {
resolve(true)
} else {
reject("STORE_FAILED", "Failed to store credentials in the Keychain.", nil)
}
} else {
reject(NativeBridge.credentialsManagerErrorCode, "Incomplete information provided for credentials - 'expiresIn' not found", NSError.init(domain: NativeBridge.credentialsManagerErrorCode, code: -99999, userInfo: nil));
}
}
@objc public func getCredentials(scope: String?, minTTL: Int, parameters: [String: Any], forceRefresh: Bool, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
if(forceRefresh) {
credentialsManager.renew(parameters: parameters) { result in
switch result {
case .success(let credentials):
resolve(credentials.asDictionary())
case .failure(let error):
reject(error.reactNativeErrorCode(), error.errorDescription, error)
}
}
} else {
credentialsManager.credentials(withScope: scope, minTTL: minTTL, parameters: parameters) { result in
switch result {
case .success(let credentials):
resolve(credentials.asDictionary())
case .failure(let error):
reject(error.reactNativeErrorCode(), error.errorDescription, error)
}
}
}
}
@objc public func hasValidCredentials(minTTL: Int, resolve: RCTPromiseResolveBlock) {
resolve(credentialsManager.canRenew() || credentialsManager.hasValid(minTTL: minTTL))
}
@objc public func clearCredentials(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
let removed = credentialsManager.clear()
// Also clear DPoP key if DPoP is enabled
if self.useDPoP {
do {
try DPoP.clearKeypair()
} catch {
// Log error but don't fail the operation
print("Warning: Failed to clear DPoP key: \(error.localizedDescription)")
}
}
resolve(removed)
}
@objc public func getSSOCredentials(parameters: [String: Any], headers: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
let stringHeaders = headers.compactMapValues { $0 as? String }
credentialsManager.ssoCredentials(parameters: parameters, headers: stringHeaders) { result in
switch result {
case .success(let ssoCredentials):
var response: [String: Any] = [
"sessionTransferToken": ssoCredentials.sessionTransferToken,
"tokenType": ssoCredentials.issuedTokenType,
"expiresIn": ssoCredentials.expiresIn,
"idToken": ssoCredentials.idToken
]
// Add optional fields if present
if let refreshToken = ssoCredentials.refreshToken {
response["refreshToken"] = refreshToken
}
resolve(response)
case .failure(let error):
reject(
NativeBridge.credentialsManagerErrorCode,
error.localizedDescription,
error
)
}
}
}
@objc public func getDPoPHeaders(url: String, method: String, accessToken: String, tokenType: String, nonce: String?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
// Validate parameters
guard !url.isEmpty else {
reject(
NativeBridge.dpopMissingParameterCode,
"URL parameter is required for DPoP header generation",
nil
)
return
}
guard !method.isEmpty else {
reject(
NativeBridge.dpopMissingParameterCode,
"HTTP method parameter is required for DPoP header generation",
nil
)
return
}
guard !accessToken.isEmpty else {
reject(
NativeBridge.dpopMissingParameterCode,
"Access token parameter is required for DPoP header generation",
nil
)
return
}
// Check if token type is DPoP
guard tokenType.uppercased() == "DPOP" else {
// If not DPoP, return Bearer token format
let headers = [
"Authorization": "Bearer \(accessToken)"
]
resolve(headers)
return
}
// Validate URL format
guard !url.isEmpty, let urlObj = URL(string: url) else {
reject(
NativeBridge.dpopMissingParameterCode,
"Invalid URL format: \(url)",
nil
)
return
}
var request = URLRequest(url: urlObj)
request.httpMethod = method
do {
if let nonce = nonce, !nonce.isEmpty {
try DPoP.addHeaders(to: &request, accessToken: accessToken, tokenType: tokenType, nonce: nonce)
} else {
try DPoP.addHeaders(to: &request, accessToken: accessToken, tokenType: tokenType)
}
resolve(request.allHTTPHeaderFields ?? [:])
} catch {
if let dpopError = error as? DPoPError {
reject(dpopError.reactNativeErrorCode(), dpopError.errorDescription, error)
} else {
reject(NativeBridge.dpopGenerationFailedCode, error.localizedDescription, error)
}
}
}
@objc public func clearDPoPKey(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
do {
try DPoP.clearKeypair()
resolve(nil)
} catch {
if let dpopError = error as? DPoPError {
reject(dpopError.reactNativeErrorCode(), dpopError.errorDescription, error)
} else {
reject(NativeBridge.dpopClearKeyFailedCode, error.localizedDescription, error)
}
}
}
@objc public func getApiCredentials(audience: String, scope: String?, minTTL: Int, parameters: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
credentialsManager.apiCredentials(forAudience: audience, scope: scope, minTTL: minTTL, parameters: parameters) { result in
switch result {
case .success(let credentials):
resolve(credentials.asDictionary())
case .failure(let error):
reject(error.reactNativeErrorCode(), error.errorDescription, error)
}
}
}
@objc public func clearApiCredentials(audience: String, scope: String?, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
// The clear(forAudience:scope:) method returns a boolean indicating success.
// We can resolve the promise with this boolean value.
resolve(credentialsManager.clear(forAudience: audience, scope: scope))
}
@objc public func customTokenExchange(subjectToken: String, subjectTokenType: String, audience: String?, scope: String?, organization: String?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
var auth = Auth0.authentication(clientId: self.clientId, domain: self.domain)
if self.useDPoP {
auth = auth.useDPoP()
}
let finalScope = scope ?? "openid profile email"
auth.customTokenExchange(
subjectToken: subjectToken,
subjectTokenType: subjectTokenType,
audience: audience,
scope: finalScope,
organization: organization
).start { result in
switch result {
case .success(let credentials):
resolve(credentials.asDictionary())
case .failure(let error):
reject(error.code, error.localizedDescription, error)
}
}
}
@objc public func getClientId() -> String {
return clientId
}
@objc public func getDomain() -> String {
return domain
}
func convert(policyInt: Int) -> LAPolicy {
if (policyInt == 2) {
return LAPolicy.deviceOwnerAuthentication
}
return LAPolicy.deviceOwnerAuthenticationWithBiometrics
}
func convert(policyString: String, timeout: Int) -> BiometricPolicy {
switch policyString {
case "default":
return .default
case "always":
return .always
case "session":
return .session(timeoutInSeconds: timeout)
case "appLifecycle":
return .appLifecycle(timeoutInSeconds: timeout)
default:
return .default
}
}
}
extension Credentials {
func asDictionary() -> [String: Any] {
return [
NativeBridge.accessTokenKey: self.accessToken,
NativeBridge.tokenTypeKey: self.tokenType,
NativeBridge.idTokenKey: self.idToken,
NativeBridge.refreshTokenKey: self.refreshToken as Any,
NativeBridge.expiresAtKey: floor(self.expiresIn.timeIntervalSince1970),
NativeBridge.scopeKey: self.scope as Any
]
}
}
extension APICredentials {
func asDictionary() -> [String: Any] {
return [
NativeBridge.accessTokenKey: self.accessToken,
NativeBridge.tokenTypeKey: self.tokenType,
NativeBridge.expiresAtKey: floor(self.expiresIn.timeIntervalSince1970),
NativeBridge.scopeKey: self.scope
]
}
}
extension WebAuthError {
func reactNativeErrorCode() -> String {
var code: String
switch self {
case WebAuthError.noBundleIdentifier: code = "NO_BUNDLE_IDENTIFIER"
case WebAuthError.transactionActiveAlready: code = "TRANSACTION_ACTIVE_ALREADY"
case WebAuthError.invalidInvitationURL: code = "INVALID_INVITATION_URL"
case WebAuthError.userCancelled: code = "USER_CANCELLED"
case WebAuthError.noAuthorizationCode: code = "NO_AUTHORIZATION_CODE"
case WebAuthError.pkceNotAllowed: code = "PKCE_NOT_ALLOWED"
case WebAuthError.idTokenValidationFailed: code = "ID_TOKEN_VALIDATION_FAILED"
case WebAuthError.other: if let cause = self.cause as? AuthenticationError {
code = cause.code
} else {
code = "OTHER"
}
default: code = "UNKNOWN"
}
return code
}
}
extension DPoPError {
func reactNativeErrorCode() -> String {
var code: String
switch self {
case DPoPError.secureEnclaveOperationFailed: code = NativeBridge.dpopKeyGenerationFailedCode
case DPoPError.keychainOperationFailed: code = NativeBridge.dpopKeyStorageFailedCode
case DPoPError.cryptoKitOperationFailed: code = NativeBridge.dpopProofFailedCode
case DPoPError.secKeyOperationFailed: code = NativeBridge.dpopProofFailedCode
case DPoPError.other: code = NativeBridge.dpopErrorCode
case DPoPError.unknown: code = NativeBridge.dpopErrorCode
default:
code = NativeBridge.dpopErrorCode
}
return code
}
}
extension CredentialsManagerError {
func reactNativeErrorCode() -> String {
var code: String
switch self {
case CredentialsManagerError.noCredentials: code = "NO_CREDENTIALS"
case CredentialsManagerError.noRefreshToken: code = "NO_REFRESH_TOKEN"
case CredentialsManagerError.renewFailed: if let cause = self.cause as? AuthenticationError {
code = cause.code
} else {
code = "RENEW_FAILED"
}
case CredentialsManagerError.storeFailed: code = "STORE_FAILED"
case CredentialsManagerError.biometricsFailed: code = "BIOMETRICS_FAILED"
case CredentialsManagerError.revokeFailed: if let cause = self.cause as? AuthenticationError {
code = cause.code
} else {
code = "REVOKE_FAILED"
}
case CredentialsManagerError.largeMinTTL: code = "LARGE_MIN_TTL"
case CredentialsManagerError.dpopKeyMissing: code = "DPOP_KEY_MISSING"
case CredentialsManagerError.dpopKeyMismatch: code = "DPOP_KEY_MISMATCH"
case CredentialsManagerError.dpopNotConfigured: code = "DPOP_NOT_CONFIGURED"
default: code = "UNKNOWN"
}
return code
}
}