react-native-docusign 1.0.3
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 +48 -0
- package/LICENSE +21 -0
- package/README.md +867 -0
- package/android/build.gradle +81 -0
- package/android/src/main/AndroidManifest.xml +7 -0
- package/android/src/main/java/expo/modules/docusign/DocuSignError.kt +18 -0
- package/android/src/main/java/expo/modules/docusign/DocuSignManager.kt +321 -0
- package/android/src/main/java/expo/modules/docusign/DocuSignModule.kt +190 -0
- package/app.plugin.js +1 -0
- package/build/DocuSign.types.d.ts +77 -0
- package/build/DocuSign.types.d.ts.map +1 -0
- package/build/DocuSign.types.js +2 -0
- package/build/DocuSign.types.js.map +1 -0
- package/build/DocuSignModule.d.ts +14 -0
- package/build/DocuSignModule.d.ts.map +1 -0
- package/build/DocuSignModule.js +3 -0
- package/build/DocuSignModule.js.map +1 -0
- package/build/api.d.ts +39 -0
- package/build/api.d.ts.map +1 -0
- package/build/api.js +62 -0
- package/build/api.js.map +1 -0
- package/build/index.d.ts +6 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +5 -0
- package/build/index.js.map +1 -0
- package/build/useDocuSignSigning.d.ts +38 -0
- package/build/useDocuSignSigning.d.ts.map +1 -0
- package/build/useDocuSignSigning.js +126 -0
- package/build/useDocuSignSigning.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/DocuSignError.swift +31 -0
- package/ios/DocuSignManager.swift +776 -0
- package/ios/DocuSignModule.swift +169 -0
- package/ios/ReactNativeDocuSign.podspec +29 -0
- package/package.json +60 -0
- package/plugin/build/index.d.ts +8 -0
- package/plugin/build/index.js +235 -0
- package/plugin/build/index.js.map +1 -0
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
import UIKit
|
|
3
|
+
import WebKit
|
|
4
|
+
import DocuSignSDK
|
|
5
|
+
|
|
6
|
+
internal enum DocuSignEnvironment: String {
|
|
7
|
+
case demo
|
|
8
|
+
case production
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
internal struct DocuSignAccountInfo {
|
|
12
|
+
let accountId: String
|
|
13
|
+
let userId: String
|
|
14
|
+
let userName: String
|
|
15
|
+
let email: String
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
internal struct DocuSignSetupOptions {
|
|
19
|
+
let disablePoweredByBranding: Bool
|
|
20
|
+
let disableAppearance: Bool
|
|
21
|
+
let disableLocationPermission: Bool
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
internal final class DocuSignManager: NSObject {
|
|
25
|
+
static let shared = DocuSignManager()
|
|
26
|
+
|
|
27
|
+
private var _isInitialized = false
|
|
28
|
+
private var _hasLoggedIn = false
|
|
29
|
+
private var _integratorKey: String?
|
|
30
|
+
private var _hostURL: URL?
|
|
31
|
+
private var _observersRegistered = false
|
|
32
|
+
private var currentEnvelopeId: String?
|
|
33
|
+
private weak var module: DocuSignModule?
|
|
34
|
+
|
|
35
|
+
private var environment: DocuSignEnvironment = .demo
|
|
36
|
+
private var pendingCompletion: ((Result<SigningOutcome, Error>) -> Void)?
|
|
37
|
+
|
|
38
|
+
private let stateQueue = DispatchQueue(label: "com.rndocusign.state")
|
|
39
|
+
|
|
40
|
+
private var isInitialized: Bool {
|
|
41
|
+
get { stateQueue.sync { _isInitialized } }
|
|
42
|
+
set { stateQueue.sync { _isInitialized = newValue } }
|
|
43
|
+
}
|
|
44
|
+
private var hasLoggedIn: Bool {
|
|
45
|
+
get { stateQueue.sync { _hasLoggedIn } }
|
|
46
|
+
set { stateQueue.sync { _hasLoggedIn = newValue } }
|
|
47
|
+
}
|
|
48
|
+
private var integratorKey: String? {
|
|
49
|
+
get { stateQueue.sync { _integratorKey } }
|
|
50
|
+
set { stateQueue.sync { _integratorKey = newValue } }
|
|
51
|
+
}
|
|
52
|
+
private var hostURL: URL? {
|
|
53
|
+
get { stateQueue.sync { _hostURL } }
|
|
54
|
+
set { stateQueue.sync { _hostURL = newValue } }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private override init() {
|
|
58
|
+
super.init()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
func setModule(_ module: DocuSignModule) {
|
|
62
|
+
self.module = module
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
func initialize(
|
|
66
|
+
integratorKey: String,
|
|
67
|
+
environment: DocuSignEnvironment,
|
|
68
|
+
options: DocuSignSetupOptions
|
|
69
|
+
) throws {
|
|
70
|
+
if isInitialized {
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let host: String
|
|
75
|
+
switch environment {
|
|
76
|
+
case .demo:
|
|
77
|
+
host = "https://demo.docusign.net/restapi"
|
|
78
|
+
case .production:
|
|
79
|
+
host = "https://www.docusign.net/restapi"
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
guard let url = URL(string: host) else {
|
|
83
|
+
throw NotInitializedException()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
self.integratorKey = integratorKey
|
|
87
|
+
self.hostURL = url
|
|
88
|
+
self.environment = environment
|
|
89
|
+
|
|
90
|
+
let dispatchSetup: () -> Void = {
|
|
91
|
+
var configurations = DSMManager.defaultConfigurations() ?? [:]
|
|
92
|
+
if options.disablePoweredByBranding {
|
|
93
|
+
configurations[DSM_SETUP_POWERED_BY_DOCUSIGN_ENABLED] = DSM_SETUP_FALSE_VALUE
|
|
94
|
+
}
|
|
95
|
+
if options.disableAppearance {
|
|
96
|
+
configurations[DSM_SETUP_DISABLE_APPEARANCE] = DSM_SETUP_TRUE_VALUE
|
|
97
|
+
}
|
|
98
|
+
if options.disableLocationPermission {
|
|
99
|
+
configurations[DSM_SETUP_CAPTIVE_SIGNING_DISABLE_LOCATION_PERMISSION] = DSM_SETUP_TRUE_VALUE
|
|
100
|
+
}
|
|
101
|
+
DSMManager.setup(withConfiguration: configurations)
|
|
102
|
+
self.registerNotificationObservers()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if Thread.isMainThread {
|
|
106
|
+
dispatchSetup()
|
|
107
|
+
} else {
|
|
108
|
+
DispatchQueue.main.sync(execute: dispatchSetup)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
isInitialized = true
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
func loginWithAccessToken(
|
|
115
|
+
accessToken: String,
|
|
116
|
+
accountId: String,
|
|
117
|
+
userId: String,
|
|
118
|
+
userName: String,
|
|
119
|
+
email: String,
|
|
120
|
+
host: String,
|
|
121
|
+
expiresIn: Int,
|
|
122
|
+
completion: @escaping (Result<DocuSignAccountInfo, Error>) -> Void
|
|
123
|
+
) throws {
|
|
124
|
+
guard isInitialized, self.integratorKey != nil, self.hostURL != nil else {
|
|
125
|
+
throw NotInitializedException()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
let needsUserInfo = accountId.isEmpty || userId.isEmpty || userName.isEmpty || email.isEmpty || host.isEmpty
|
|
129
|
+
|
|
130
|
+
if !needsUserInfo {
|
|
131
|
+
performLogin(
|
|
132
|
+
accessToken: accessToken,
|
|
133
|
+
accountId: accountId,
|
|
134
|
+
userId: userId,
|
|
135
|
+
userName: userName,
|
|
136
|
+
email: email,
|
|
137
|
+
hostOverride: host,
|
|
138
|
+
expiresIn: expiresIn,
|
|
139
|
+
completion: completion
|
|
140
|
+
)
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
fetchUserInfo(accessToken: accessToken, preferredAccountId: accountId) { [weak self] result in
|
|
145
|
+
guard let self = self else { return }
|
|
146
|
+
switch result {
|
|
147
|
+
case .failure(let error):
|
|
148
|
+
completion(.failure(error))
|
|
149
|
+
case .success(let info):
|
|
150
|
+
self.performLogin(
|
|
151
|
+
accessToken: accessToken,
|
|
152
|
+
accountId: accountId.isEmpty ? info.accountId : accountId,
|
|
153
|
+
userId: userId.isEmpty ? info.userId : userId,
|
|
154
|
+
userName: userName.isEmpty ? info.userName : userName,
|
|
155
|
+
email: email.isEmpty ? info.email : email,
|
|
156
|
+
hostOverride: host.isEmpty ? info.host : host,
|
|
157
|
+
expiresIn: expiresIn,
|
|
158
|
+
completion: completion
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private func performLogin(
|
|
165
|
+
accessToken: String,
|
|
166
|
+
accountId: String,
|
|
167
|
+
userId: String,
|
|
168
|
+
userName: String,
|
|
169
|
+
email: String,
|
|
170
|
+
hostOverride: String,
|
|
171
|
+
expiresIn: Int,
|
|
172
|
+
completion: @escaping (Result<DocuSignAccountInfo, Error>) -> Void
|
|
173
|
+
) {
|
|
174
|
+
guard let integratorKey = self.integratorKey, let fallbackHost = self.hostURL else {
|
|
175
|
+
completion(.failure(NotInitializedException()))
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// DSMManager APIs must run on the main thread. Expo/RN dispatches
|
|
180
|
+
// native module calls on a serial background queue, so hop to main.
|
|
181
|
+
if !Thread.isMainThread {
|
|
182
|
+
DispatchQueue.main.async { [weak self] in
|
|
183
|
+
self?.performLogin(
|
|
184
|
+
accessToken: accessToken,
|
|
185
|
+
accountId: accountId,
|
|
186
|
+
userId: userId,
|
|
187
|
+
userName: userName,
|
|
188
|
+
email: email,
|
|
189
|
+
hostOverride: hostOverride,
|
|
190
|
+
expiresIn: expiresIn,
|
|
191
|
+
completion: completion
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let effectiveHost: URL
|
|
198
|
+
if !hostOverride.isEmpty, let override = URL(string: hostOverride) {
|
|
199
|
+
effectiveHost = override
|
|
200
|
+
} else {
|
|
201
|
+
effectiveHost = fallbackHost
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let expiryDate: Date? = expiresIn > 0
|
|
205
|
+
? Date(timeIntervalSinceNow: TimeInterval(expiresIn))
|
|
206
|
+
: nil
|
|
207
|
+
|
|
208
|
+
// First login: SDK state is fresh, skip the teardown dance entirely.
|
|
209
|
+
// Subsequent login: tear down cookies + session, THEN fire DSMManager.login.
|
|
210
|
+
// The previous implementation called clearAllWebCookies (async) and DSMManager.login
|
|
211
|
+
// back-to-back, which produced a race: the WebView session bootstrapped against
|
|
212
|
+
// half-cleaned state and DSMEnvelopesManager would silently fail to issue
|
|
213
|
+
// settings / consumer_disclosure / recipient calls, leaving the captive signing
|
|
214
|
+
// UI stuck on a spinner with no completion notification.
|
|
215
|
+
if !hasLoggedIn {
|
|
216
|
+
performLoginCall(
|
|
217
|
+
accessToken: accessToken,
|
|
218
|
+
accountId: accountId,
|
|
219
|
+
userId: userId,
|
|
220
|
+
userName: userName,
|
|
221
|
+
email: email,
|
|
222
|
+
effectiveHost: effectiveHost,
|
|
223
|
+
integratorKey: integratorKey,
|
|
224
|
+
expiryDate: expiryDate,
|
|
225
|
+
completion: completion
|
|
226
|
+
)
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
clearWebCookiesAsync { [weak self] in
|
|
231
|
+
guard let self = self else { return }
|
|
232
|
+
_ = DSMManager.logout()
|
|
233
|
+
self.hasLoggedIn = false
|
|
234
|
+
self.performLoginCall(
|
|
235
|
+
accessToken: accessToken,
|
|
236
|
+
accountId: accountId,
|
|
237
|
+
userId: userId,
|
|
238
|
+
userName: userName,
|
|
239
|
+
email: email,
|
|
240
|
+
effectiveHost: effectiveHost,
|
|
241
|
+
integratorKey: integratorKey,
|
|
242
|
+
expiryDate: expiryDate,
|
|
243
|
+
completion: completion
|
|
244
|
+
)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private func performLoginCall(
|
|
249
|
+
accessToken: String,
|
|
250
|
+
accountId: String,
|
|
251
|
+
userId: String,
|
|
252
|
+
userName: String,
|
|
253
|
+
email: String,
|
|
254
|
+
effectiveHost: URL,
|
|
255
|
+
integratorKey: String,
|
|
256
|
+
expiryDate: Date?,
|
|
257
|
+
completion: @escaping (Result<DocuSignAccountInfo, Error>) -> Void
|
|
258
|
+
) {
|
|
259
|
+
let tokenAzp = Self.decodeJWTClaim(accessToken, claim: "azp")
|
|
260
|
+
?? Self.decodeJWTClaim(accessToken, claim: "aud")
|
|
261
|
+
?? "(unknown)"
|
|
262
|
+
#if DEBUG
|
|
263
|
+
NSLog("[DocuSign] Calling DSMManager.login with:")
|
|
264
|
+
NSLog("[DocuSign] integratorKey (init)=\(integratorKey)")
|
|
265
|
+
NSLog("[DocuSign] token azp/aud=\(tokenAzp)")
|
|
266
|
+
NSLog("[DocuSign] host=\(effectiveHost.absoluteString)")
|
|
267
|
+
if tokenAzp != "(unknown)" && tokenAzp != integratorKey {
|
|
268
|
+
NSLog("[DocuSign] ⚠️ MISMATCH: integratorKey != token's azp/aud claim. This is the usual cause of 'Invalid login information'.")
|
|
269
|
+
}
|
|
270
|
+
#endif
|
|
271
|
+
|
|
272
|
+
let diagnostic = "integratorKey=\(integratorKey) tokenAzp=\(tokenAzp) host=\(effectiveHost.absoluteString)"
|
|
273
|
+
|
|
274
|
+
module?.sendEvent("onLoginAttempt", [
|
|
275
|
+
"integratorKey": integratorKey,
|
|
276
|
+
"accountId": accountId,
|
|
277
|
+
"userId": userId,
|
|
278
|
+
"userName": userName,
|
|
279
|
+
"email": email,
|
|
280
|
+
"host": effectiveHost.absoluteString
|
|
281
|
+
])
|
|
282
|
+
|
|
283
|
+
DSMManager.login(
|
|
284
|
+
withAccessToken: accessToken,
|
|
285
|
+
accountId: accountId,
|
|
286
|
+
userId: userId,
|
|
287
|
+
userName: userName,
|
|
288
|
+
email: email,
|
|
289
|
+
host: effectiveHost,
|
|
290
|
+
integratorKey: integratorKey,
|
|
291
|
+
refreshToken: nil,
|
|
292
|
+
expiresIn: expiryDate
|
|
293
|
+
) { [weak self] accountInfo, error in
|
|
294
|
+
if let error = error {
|
|
295
|
+
// Classify failure via /oauth/userinfo pre-flight so we can surface
|
|
296
|
+
// an actionable error instead of opaque "unauthorized".
|
|
297
|
+
self?.classifyLoginFailure(accessToken: accessToken, sdkError: error, diagnostic: diagnostic, integratorKey: integratorKey, completion: completion)
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
self?.hasLoggedIn = true
|
|
301
|
+
let resolved = DocuSignAccountInfo(
|
|
302
|
+
accountId: accountInfo?.accountId ?? accountId,
|
|
303
|
+
userId: accountInfo?.userId ?? userId,
|
|
304
|
+
userName: accountInfo?.userName ?? userName,
|
|
305
|
+
email: accountInfo?.email ?? email
|
|
306
|
+
)
|
|
307
|
+
completion(.success(resolved))
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// Clears DocuSign SDK cookies plus the WKWebsiteDataStore (cookies, session
|
|
312
|
+
/// storage, local storage, IndexedDB) and invokes `completion` on the main
|
|
313
|
+
/// thread once teardown is complete. The DocuSign SDK's `clearAllWebCookies`
|
|
314
|
+
/// has no completion handler, so we layer `WKWebsiteDataStore.removeData`
|
|
315
|
+
/// on top to obtain a real signal that teardown finished before re-logging in.
|
|
316
|
+
private func clearWebCookiesAsync(completion: @escaping () -> Void) {
|
|
317
|
+
DSMManager.clearAllWebCookies()
|
|
318
|
+
let dataStore = WKWebsiteDataStore.default()
|
|
319
|
+
let types: Set<String> = [
|
|
320
|
+
WKWebsiteDataTypeCookies,
|
|
321
|
+
WKWebsiteDataTypeSessionStorage,
|
|
322
|
+
WKWebsiteDataTypeLocalStorage,
|
|
323
|
+
WKWebsiteDataTypeIndexedDBDatabases
|
|
324
|
+
]
|
|
325
|
+
let since = Date(timeIntervalSince1970: 0)
|
|
326
|
+
dataStore.removeData(ofTypes: types, modifiedSince: since) {
|
|
327
|
+
DispatchQueue.main.async { completion() }
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
private func classifyLoginFailure(
|
|
332
|
+
accessToken: String,
|
|
333
|
+
sdkError: Error,
|
|
334
|
+
diagnostic: String,
|
|
335
|
+
integratorKey: String,
|
|
336
|
+
completion: @escaping (Result<DocuSignAccountInfo, Error>) -> Void
|
|
337
|
+
) {
|
|
338
|
+
let sdkMsg = (sdkError as NSError).localizedDescription
|
|
339
|
+
let sdkCode = (sdkError as NSError).code
|
|
340
|
+
|
|
341
|
+
probeUserInfoStatus(accessToken: accessToken) { probe in
|
|
342
|
+
let enrichedMsg: String
|
|
343
|
+
switch probe {
|
|
344
|
+
case .ok:
|
|
345
|
+
enrichedMsg = "SDK rejected a valid token. Likely causes: Mobile SDK not enabled for integration key \(integratorKey), or iOS bundle ID not whitelisted in DocuSign admin. Contact DocuSign support. (SDK: \(sdkMsg)) | \(diagnostic)"
|
|
346
|
+
case .unauthorized:
|
|
347
|
+
enrichedMsg = "Access token rejected by DocuSign /oauth/userinfo. Re-mint via JWT Bearer Grant with scope=signature impersonation. (SDK: \(sdkMsg)) | \(diagnostic)"
|
|
348
|
+
case .network(let netMsg):
|
|
349
|
+
enrichedMsg = "\(sdkMsg) (userinfo probe network error: \(netMsg)) | \(diagnostic)"
|
|
350
|
+
}
|
|
351
|
+
let enriched = NSError(
|
|
352
|
+
domain: "DocuSign",
|
|
353
|
+
code: sdkCode,
|
|
354
|
+
userInfo: [NSLocalizedDescriptionKey: enrichedMsg]
|
|
355
|
+
)
|
|
356
|
+
completion(.failure(enriched))
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private enum UserInfoProbe {
|
|
361
|
+
case ok
|
|
362
|
+
case unauthorized
|
|
363
|
+
case network(String)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private func probeUserInfoStatus(accessToken: String, completion: @escaping (UserInfoProbe) -> Void) {
|
|
367
|
+
guard let base = oauthBaseURL() else {
|
|
368
|
+
completion(.network("no oauth base URL"))
|
|
369
|
+
return
|
|
370
|
+
}
|
|
371
|
+
let url = base.appendingPathComponent("oauth/userinfo")
|
|
372
|
+
var request = URLRequest(url: url)
|
|
373
|
+
request.httpMethod = "GET"
|
|
374
|
+
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
375
|
+
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
|
376
|
+
request.timeoutInterval = 10
|
|
377
|
+
|
|
378
|
+
URLSession.shared.dataTask(with: request) { _, response, error in
|
|
379
|
+
if let error = error {
|
|
380
|
+
completion(.network(error.localizedDescription))
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
guard let http = response as? HTTPURLResponse else {
|
|
384
|
+
completion(.network("no HTTP response"))
|
|
385
|
+
return
|
|
386
|
+
}
|
|
387
|
+
if (200..<300).contains(http.statusCode) {
|
|
388
|
+
completion(.ok)
|
|
389
|
+
} else if http.statusCode == 401 || http.statusCode == 403 {
|
|
390
|
+
completion(.unauthorized)
|
|
391
|
+
} else {
|
|
392
|
+
completion(.network("userinfo HTTP \(http.statusCode)"))
|
|
393
|
+
}
|
|
394
|
+
}.resume()
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
private static func decodeJWTClaim(_ token: String, claim: String) -> String? {
|
|
398
|
+
let parts = token.split(separator: ".")
|
|
399
|
+
guard parts.count >= 2 else { return nil }
|
|
400
|
+
var payload = String(parts[1])
|
|
401
|
+
let padLen = (4 - payload.count % 4) % 4
|
|
402
|
+
payload.append(String(repeating: "=", count: padLen))
|
|
403
|
+
payload = payload.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
|
|
404
|
+
guard let data = Data(base64Encoded: payload) else { return nil }
|
|
405
|
+
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
|
|
406
|
+
if let s = json[claim] as? String { return s }
|
|
407
|
+
if let arr = json[claim] as? [String], let first = arr.first { return first }
|
|
408
|
+
return nil
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private struct ResolvedUserInfo {
|
|
412
|
+
let accountId: String
|
|
413
|
+
let userId: String
|
|
414
|
+
let userName: String
|
|
415
|
+
let email: String
|
|
416
|
+
let host: String
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
private func oauthBaseURL() -> URL? {
|
|
420
|
+
switch environment {
|
|
421
|
+
case .demo:
|
|
422
|
+
return URL(string: "https://account-d.docusign.com")
|
|
423
|
+
case .production:
|
|
424
|
+
return URL(string: "https://account.docusign.com")
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
private func fetchUserInfo(
|
|
429
|
+
accessToken: String,
|
|
430
|
+
preferredAccountId: String,
|
|
431
|
+
completion: @escaping (Result<ResolvedUserInfo, Error>) -> Void
|
|
432
|
+
) {
|
|
433
|
+
guard let base = oauthBaseURL() else {
|
|
434
|
+
completion(.failure(LoginFailedException("Could not derive OAuth base URL")))
|
|
435
|
+
return
|
|
436
|
+
}
|
|
437
|
+
let url = base.appendingPathComponent("oauth/userinfo")
|
|
438
|
+
var request = URLRequest(url: url)
|
|
439
|
+
request.httpMethod = "GET"
|
|
440
|
+
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
|
|
441
|
+
request.setValue("application/json", forHTTPHeaderField: "Accept")
|
|
442
|
+
request.timeoutInterval = 10
|
|
443
|
+
|
|
444
|
+
URLSession.shared.dataTask(with: request) { data, response, error in
|
|
445
|
+
if let error = error {
|
|
446
|
+
completion(.failure(LoginFailedException("userinfo request failed: \(error.localizedDescription)")))
|
|
447
|
+
return
|
|
448
|
+
}
|
|
449
|
+
guard let http = response as? HTTPURLResponse else {
|
|
450
|
+
completion(.failure(LoginFailedException("userinfo: no HTTP response")))
|
|
451
|
+
return
|
|
452
|
+
}
|
|
453
|
+
guard (200..<300).contains(http.statusCode), let data = data else {
|
|
454
|
+
let snippet = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
|
|
455
|
+
completion(.failure(LoginFailedException("userinfo HTTP \(http.statusCode): \(snippet.prefix(200))")))
|
|
456
|
+
return
|
|
457
|
+
}
|
|
458
|
+
do {
|
|
459
|
+
let decoded = try JSONDecoder().decode(UserInfoPayload.self, from: data)
|
|
460
|
+
guard let account = Self.pickAccount(from: decoded.accounts, preferredId: preferredAccountId) else {
|
|
461
|
+
completion(.failure(LoginFailedException("userinfo: no accounts in response")))
|
|
462
|
+
return
|
|
463
|
+
}
|
|
464
|
+
let host = account.base_uri.hasSuffix("/restapi") ? account.base_uri : account.base_uri + "/restapi"
|
|
465
|
+
let resolved = ResolvedUserInfo(
|
|
466
|
+
accountId: account.account_id,
|
|
467
|
+
userId: decoded.sub,
|
|
468
|
+
userName: decoded.name,
|
|
469
|
+
email: decoded.email,
|
|
470
|
+
host: host
|
|
471
|
+
)
|
|
472
|
+
completion(.success(resolved))
|
|
473
|
+
} catch {
|
|
474
|
+
completion(.failure(LoginFailedException("userinfo decode error: \(error.localizedDescription)")))
|
|
475
|
+
}
|
|
476
|
+
}.resume()
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
private static func pickAccount(from accounts: [UserInfoAccount], preferredId: String) -> UserInfoAccount? {
|
|
480
|
+
if !preferredId.isEmpty, let match = accounts.first(where: { $0.account_id == preferredId }) {
|
|
481
|
+
return match
|
|
482
|
+
}
|
|
483
|
+
if let def = accounts.first(where: { $0.is_default == true }) {
|
|
484
|
+
return def
|
|
485
|
+
}
|
|
486
|
+
return accounts.first
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
private struct UserInfoPayload: Decodable {
|
|
490
|
+
let sub: String
|
|
491
|
+
let name: String
|
|
492
|
+
let email: String
|
|
493
|
+
let accounts: [UserInfoAccount]
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
private struct UserInfoAccount: Decodable {
|
|
497
|
+
let account_id: String
|
|
498
|
+
let account_name: String?
|
|
499
|
+
let is_default: Bool?
|
|
500
|
+
let base_uri: String
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
func logout() {
|
|
504
|
+
if Thread.isMainThread {
|
|
505
|
+
_ = DSMManager.logout()
|
|
506
|
+
} else {
|
|
507
|
+
DispatchQueue.main.sync {
|
|
508
|
+
_ = DSMManager.logout()
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
hasLoggedIn = false
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
func isLoggedIn() -> Bool {
|
|
515
|
+
return hasLoggedIn
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/// Tears down any in-flight signing session and the underlying SDK auth
|
|
519
|
+
/// state so the next `loginWithAccessToken` + `presentCaptiveSigning` pair
|
|
520
|
+
/// starts from a clean slate. Safe to call when no session is active.
|
|
521
|
+
///
|
|
522
|
+
/// Consumers should call this between captive signing flows (e.g. inside
|
|
523
|
+
/// the `finally` of their orchestrator hook) to avoid the implicit
|
|
524
|
+
/// teardown path inside `performLogin`. It is also wired into the JS
|
|
525
|
+
/// `useDocuSignSigning` hook's `reset()` so React consumers get this for
|
|
526
|
+
/// free.
|
|
527
|
+
func endSigningSession(completion: @escaping () -> Void) {
|
|
528
|
+
// Resolve any in-flight signing promise so the JS side does not hang.
|
|
529
|
+
var pendingResolved = false
|
|
530
|
+
stateQueue.sync {
|
|
531
|
+
if let pending = pendingCompletion {
|
|
532
|
+
let outcome = SigningOutcome(
|
|
533
|
+
status: "cancelled",
|
|
534
|
+
envelopeId: currentEnvelopeId ?? "",
|
|
535
|
+
errorCode: nil,
|
|
536
|
+
errorMessage: "session_ended"
|
|
537
|
+
)
|
|
538
|
+
pendingCompletion = nil
|
|
539
|
+
currentEnvelopeId = nil
|
|
540
|
+
DispatchQueue.main.async { pending(.success(outcome)) }
|
|
541
|
+
pendingResolved = true
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
_ = pendingResolved // silence unused-warning; kept for future telemetry
|
|
545
|
+
|
|
546
|
+
clearWebCookiesAsync { [weak self] in
|
|
547
|
+
guard let self = self else {
|
|
548
|
+
completion()
|
|
549
|
+
return
|
|
550
|
+
}
|
|
551
|
+
_ = DSMManager.logout()
|
|
552
|
+
self.hasLoggedIn = false
|
|
553
|
+
completion()
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
func presentCaptiveSigning(
|
|
558
|
+
envelopeId: String,
|
|
559
|
+
recipientUserName: String,
|
|
560
|
+
recipientEmail: String,
|
|
561
|
+
recipientClientUserId: String,
|
|
562
|
+
completion: @escaping (Result<SigningOutcome, Error>) -> Void
|
|
563
|
+
) throws {
|
|
564
|
+
guard isInitialized else {
|
|
565
|
+
throw NotInitializedException()
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
guard isLoggedIn() else {
|
|
569
|
+
throw NotLoggedInException()
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
var alreadyInFlight = false
|
|
573
|
+
stateQueue.sync {
|
|
574
|
+
if pendingCompletion != nil {
|
|
575
|
+
alreadyInFlight = true
|
|
576
|
+
} else {
|
|
577
|
+
currentEnvelopeId = envelopeId
|
|
578
|
+
pendingCompletion = completion
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
if alreadyInFlight {
|
|
582
|
+
throw SigningFailedException("A signing session is already in progress")
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
guard let presentingViewController = Self.topmostViewController() else {
|
|
586
|
+
resolvePending(.failure(PresentationException("Could not find a view controller to present from")))
|
|
587
|
+
throw PresentationException("Could not find a view controller to present from")
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
DispatchQueue.main.async {
|
|
591
|
+
let envelopesManager = DSMEnvelopesManager()
|
|
592
|
+
envelopesManager.presentCaptiveSigning(
|
|
593
|
+
withPresenting: presentingViewController,
|
|
594
|
+
envelopeId: envelopeId,
|
|
595
|
+
recipientUserName: recipientUserName,
|
|
596
|
+
recipientEmail: recipientEmail,
|
|
597
|
+
recipientClientUserId: recipientClientUserId,
|
|
598
|
+
animated: true,
|
|
599
|
+
completion: { [weak self] (_: UIViewController?, error: Error?) in
|
|
600
|
+
guard let self = self else { return }
|
|
601
|
+
if let error = error {
|
|
602
|
+
self.resolvePending(.failure(error))
|
|
603
|
+
}
|
|
604
|
+
// Success/cancel path is driven by DSMSigningCompletedNotification / DSMSigningCancelledNotification
|
|
605
|
+
}
|
|
606
|
+
)
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/// Presents captive signing from a pre-minted DocuSign recipient-view URL.
|
|
611
|
+
///
|
|
612
|
+
/// The signing URL itself encodes recipient identity via a short-lived token,
|
|
613
|
+
/// so this path intentionally does NOT require a prior `loginWithAccessToken`.
|
|
614
|
+
/// `initialize` is still required.
|
|
615
|
+
func presentCaptiveSigningWithUrl(
|
|
616
|
+
signingUrl: String,
|
|
617
|
+
envelopeId: String,
|
|
618
|
+
recipientId: String?,
|
|
619
|
+
completion: @escaping (Result<SigningOutcome, Error>) -> Void
|
|
620
|
+
) throws {
|
|
621
|
+
guard isInitialized else {
|
|
622
|
+
throw NotInitializedException()
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
var alreadyInFlight = false
|
|
626
|
+
stateQueue.sync {
|
|
627
|
+
if pendingCompletion != nil {
|
|
628
|
+
alreadyInFlight = true
|
|
629
|
+
} else {
|
|
630
|
+
currentEnvelopeId = envelopeId
|
|
631
|
+
pendingCompletion = completion
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
if alreadyInFlight {
|
|
635
|
+
throw SigningFailedException("A signing session is already in progress")
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
guard let presentingViewController = Self.topmostViewController() else {
|
|
639
|
+
resolvePending(.failure(PresentationException("Could not find a view controller to present from")))
|
|
640
|
+
throw PresentationException("Could not find a view controller to present from")
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
DispatchQueue.main.async {
|
|
644
|
+
let envelopesManager = DSMEnvelopesManager()
|
|
645
|
+
envelopesManager.presentCaptiveSigning(
|
|
646
|
+
withPresenting: presentingViewController,
|
|
647
|
+
signingUrl: signingUrl,
|
|
648
|
+
envelopeId: envelopeId,
|
|
649
|
+
recipientId: recipientId,
|
|
650
|
+
animated: true,
|
|
651
|
+
completion: { [weak self] (_: UIViewController?, error: Error?) in
|
|
652
|
+
guard let self = self else { return }
|
|
653
|
+
if let error = error {
|
|
654
|
+
self.resolvePending(.failure(error))
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
)
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
internal struct SigningOutcome {
|
|
662
|
+
let status: String
|
|
663
|
+
let envelopeId: String
|
|
664
|
+
let errorCode: String?
|
|
665
|
+
let errorMessage: String?
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
private func resolvePending(_ result: Result<SigningOutcome, Error>) {
|
|
669
|
+
var completion: ((Result<SigningOutcome, Error>) -> Void)?
|
|
670
|
+
stateQueue.sync {
|
|
671
|
+
completion = pendingCompletion
|
|
672
|
+
pendingCompletion = nil
|
|
673
|
+
currentEnvelopeId = nil
|
|
674
|
+
}
|
|
675
|
+
completion?(result)
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
private func envelopeId(from notification: Notification) -> String {
|
|
679
|
+
if let id = notification.userInfo?[DSMEnvelopeIdKey] as? String, !id.isEmpty {
|
|
680
|
+
return id
|
|
681
|
+
}
|
|
682
|
+
return currentEnvelopeId ?? ""
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
private func registerNotificationObservers() {
|
|
686
|
+
var alreadyRegistered = false
|
|
687
|
+
stateQueue.sync {
|
|
688
|
+
if _observersRegistered {
|
|
689
|
+
alreadyRegistered = true
|
|
690
|
+
} else {
|
|
691
|
+
_observersRegistered = true
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
if alreadyRegistered { return }
|
|
695
|
+
|
|
696
|
+
let nc = NotificationCenter.default
|
|
697
|
+
nc.addObserver(
|
|
698
|
+
self,
|
|
699
|
+
selector: #selector(handleSigningCompleted(_:)),
|
|
700
|
+
name: .DSMSigningCompleted,
|
|
701
|
+
object: nil
|
|
702
|
+
)
|
|
703
|
+
nc.addObserver(
|
|
704
|
+
self,
|
|
705
|
+
selector: #selector(handleSigningCancelled(_:)),
|
|
706
|
+
name: .DSMSigningCancelled,
|
|
707
|
+
object: nil
|
|
708
|
+
)
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
@objc private func handleSigningCompleted(_ notification: Notification) {
|
|
712
|
+
let envelopeId = envelopeId(from: notification)
|
|
713
|
+
let outcome = SigningOutcome(
|
|
714
|
+
status: "completed",
|
|
715
|
+
envelopeId: envelopeId,
|
|
716
|
+
errorCode: nil,
|
|
717
|
+
errorMessage: nil
|
|
718
|
+
)
|
|
719
|
+
module?.sendEvent("onSigningComplete", ["envelopeId": envelopeId])
|
|
720
|
+
resolvePending(.success(outcome))
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
@objc private func handleSigningCancelled(_ notification: Notification) {
|
|
724
|
+
let envelopeId = envelopeId(from: notification)
|
|
725
|
+
let userInfo = notification.userInfo
|
|
726
|
+
|
|
727
|
+
if let sdkError = userInfo?[DSMErrorKey] as? Error {
|
|
728
|
+
let nsErr = sdkError as NSError
|
|
729
|
+
let errorMessage = nsErr.localizedDescription
|
|
730
|
+
let errorCode = String(nsErr.code)
|
|
731
|
+
let outcome = SigningOutcome(
|
|
732
|
+
status: "error",
|
|
733
|
+
envelopeId: envelopeId,
|
|
734
|
+
errorCode: errorCode,
|
|
735
|
+
errorMessage: errorMessage
|
|
736
|
+
)
|
|
737
|
+
module?.sendEvent("onSigningError", [
|
|
738
|
+
"envelopeId": envelopeId,
|
|
739
|
+
"errorCode": errorCode,
|
|
740
|
+
"errorMessage": errorMessage
|
|
741
|
+
])
|
|
742
|
+
resolvePending(.success(outcome))
|
|
743
|
+
return
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
let reason = userInfo?[DSMSigningExitReasonKey] as? String
|
|
747
|
+
let outcome = SigningOutcome(
|
|
748
|
+
status: "cancelled",
|
|
749
|
+
envelopeId: envelopeId,
|
|
750
|
+
errorCode: nil,
|
|
751
|
+
errorMessage: reason
|
|
752
|
+
)
|
|
753
|
+
var event: [String: Any] = ["envelopeId": envelopeId]
|
|
754
|
+
if let reason = reason { event["reason"] = reason }
|
|
755
|
+
module?.sendEvent("onSigningCancelled", event)
|
|
756
|
+
resolvePending(.success(outcome))
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
private static func topmostViewController(
|
|
760
|
+
base: UIViewController? = UIApplication.shared.connectedScenes
|
|
761
|
+
.compactMap { $0 as? UIWindowScene }
|
|
762
|
+
.flatMap { $0.windows }
|
|
763
|
+
.first(where: { $0.isKeyWindow })?.rootViewController
|
|
764
|
+
) -> UIViewController? {
|
|
765
|
+
if let nav = base as? UINavigationController {
|
|
766
|
+
return topmostViewController(base: nav.visibleViewController)
|
|
767
|
+
}
|
|
768
|
+
if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
|
|
769
|
+
return topmostViewController(base: selected)
|
|
770
|
+
}
|
|
771
|
+
if let presented = base?.presentedViewController {
|
|
772
|
+
return topmostViewController(base: presented)
|
|
773
|
+
}
|
|
774
|
+
return base
|
|
775
|
+
}
|
|
776
|
+
}
|