react-native-docusign 1.0.5 → 2.0.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 (36) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +181 -70
  3. package/android/build.gradle +5 -5
  4. package/android/src/main/java/expo/modules/docusign/DocuSignError.kt +30 -10
  5. package/android/src/main/java/expo/modules/docusign/DocuSignFailure.kt +145 -0
  6. package/android/src/main/java/expo/modules/docusign/DocuSignManager.kt +407 -58
  7. package/android/src/main/java/expo/modules/docusign/DocuSignModule.kt +61 -42
  8. package/build/DocuSign.types.d.ts +39 -0
  9. package/build/DocuSign.types.d.ts.map +1 -1
  10. package/build/DocuSignError.d.ts +86 -0
  11. package/build/DocuSignError.d.ts.map +1 -0
  12. package/build/DocuSignError.js +210 -0
  13. package/build/DocuSignError.js.map +1 -0
  14. package/build/DocuSignModule.d.ts +24 -5
  15. package/build/DocuSignModule.d.ts.map +1 -1
  16. package/build/DocuSignModule.js.map +1 -1
  17. package/build/api.d.ts +24 -6
  18. package/build/api.d.ts.map +1 -1
  19. package/build/api.js +84 -17
  20. package/build/api.js.map +1 -1
  21. package/build/index.d.ts +2 -0
  22. package/build/index.d.ts.map +1 -1
  23. package/build/index.js +1 -0
  24. package/build/index.js.map +1 -1
  25. package/build/useDocuSignSigning.d.ts +2 -1
  26. package/build/useDocuSignSigning.d.ts.map +1 -1
  27. package/build/useDocuSignSigning.js +20 -6
  28. package/build/useDocuSignSigning.js.map +1 -1
  29. package/ios/DocuSignError.swift +45 -10
  30. package/ios/DocuSignFailure.swift +104 -0
  31. package/ios/DocuSignManager.swift +162 -106
  32. package/ios/DocuSignModule.swift +37 -37
  33. package/ios/ReactNativeDocuSign.podspec +1 -1
  34. package/package.json +12 -3
  35. package/plugin/build/index.js +21 -41
  36. package/plugin/build/index.js.map +1 -1
@@ -11,10 +11,12 @@ import com.docusign.androidsdk.listeners.DSAuthenticationListener
11
11
  import com.docusign.androidsdk.listeners.DSCaptiveSigningListener
12
12
  import com.docusign.androidsdk.listeners.DSLogoutListener
13
13
  import com.docusign.androidsdk.util.DSMode
14
+ import java.io.IOException
14
15
  import java.net.HttpURLConnection
15
16
  import java.net.URL
16
17
  import java.util.concurrent.atomic.AtomicReference
17
18
  import kotlin.concurrent.thread
19
+ import org.json.JSONObject
18
20
 
19
21
  internal enum class DocuSignEnvironment(val value: String) {
20
22
  DEMO("demo"),
@@ -26,12 +28,65 @@ internal enum class DocuSignEnvironment(val value: String) {
26
28
  }
27
29
  }
28
30
 
31
+ internal enum class CaptiveSigningLaunchStrategy(val value: String) {
32
+ FETCH("fetch"),
33
+ SIGNING_URL("signingUrl");
34
+
35
+ companion object {
36
+ fun fromString(value: String): CaptiveSigningLaunchStrategy =
37
+ values().firstOrNull { it.value == value }
38
+ ?: FETCH.also {
39
+ if (value.isNotEmpty()) {
40
+ android.util.Log.w("DocuSign", "unknown launchStrategy '$value', falling back to fetch")
41
+ }
42
+ }
43
+ }
44
+ }
45
+
46
+ /** Credentials the signing-URL strategy needs to mint a recipient view. */
47
+ internal data class DocuSignSession(
48
+ val accessToken: String,
49
+ val accountId: String,
50
+ val host: String
51
+ )
52
+
53
+ /**
54
+ * Normalises a DocuSign `host` into a REST API root.
55
+ *
56
+ * Consumers pass whatever their backend hands them, and the three shapes seen in the wild all have
57
+ * to reach the same place:
58
+ *
59
+ * https://demo.docusign.net -> https://demo.docusign.net/restapi/v2.1
60
+ * https://demo.docusign.net/restapi -> https://demo.docusign.net/restapi/v2.1
61
+ * https://demo.docusign.net/restapi/v2.1 -> unchanged, an explicit version wins
62
+ *
63
+ * Pulled out of the request builder so the branching is readable and can be exercised on its own.
64
+ * Ordering is load-bearing: the versioned check has to come first, or an already-versioned host
65
+ * would fall through and get a second `/restapi/v2.1` appended.
66
+ */
67
+ internal fun restApiRoot(host: String): String {
68
+ val base = host.trimEnd('/')
69
+ return when {
70
+ Regex("/restapi/v[0-9.]+$", RegexOption.IGNORE_CASE).containsMatchIn(base) -> base
71
+ base.endsWith("/restapi", ignoreCase = true) -> "$base/v2.1"
72
+ else -> "$base/restapi/v2.1"
73
+ }
74
+ }
75
+
29
76
  internal data class SigningOutcome(
30
77
  val status: String,
31
78
  val envelopeId: String,
32
79
  val errorCode: String? = null,
33
80
  val errorMessage: String? = null
34
- )
81
+ ) {
82
+ fun toPayload(): Map<String, Any> =
83
+ listOfNotNull<Pair<String, Any>>(
84
+ "status" to status,
85
+ "envelopeId" to envelopeId,
86
+ errorCode?.let { "errorCode" to it },
87
+ errorMessage?.let { "errorMessage" to it }
88
+ ).toMap()
89
+ }
35
90
 
36
91
  internal data class DocuSignAccountInfo(
37
92
  val accountId: String,
@@ -48,9 +103,16 @@ internal object DocuSignManager {
48
103
  @Volatile private var integratorKey: String = ""
49
104
  @Volatile private var environment: DocuSignEnvironment = DocuSignEnvironment.DEMO
50
105
  @Volatile private var currentEnvelopeId: String? = null
106
+ // One reference, not three fields: a login racing an in-flight mint would otherwise tear the
107
+ // triple and build a request with one session's token and another's account id.
108
+ @Volatile private var session: DocuSignSession? = null
51
109
  private val pendingCompletion = AtomicReference<((Result<SigningOutcome>) -> Unit)?>(null)
52
110
 
53
- private enum class UserInfoProbe { OK, UNAUTHORIZED, NETWORK }
111
+ private sealed class UserInfoProbe {
112
+ /** `error` carries DocuSign's error body for a non-2xx status, and is null otherwise. */
113
+ data class Response(val status: Int, val error: DocuSignHttpException?) : UserInfoProbe()
114
+ data class TransportFailed(val error: Throwable) : UserInfoProbe()
115
+ }
54
116
 
55
117
  fun setModule(module: DocuSignModule) {
56
118
  this.module = module
@@ -96,6 +158,8 @@ internal object DocuSignManager {
96
158
  return
97
159
  }
98
160
 
161
+ session = DocuSignSession(accessToken = accessToken, accountId = accountId, host = host)
162
+
99
163
  try {
100
164
  DocuSign.getInstance().getAuthenticationDelegate().login(
101
165
  accessToken,
@@ -115,34 +179,57 @@ internal object DocuSignManager {
115
179
  }
116
180
 
117
181
  override fun onError(exception: DSAuthenticationException) {
118
- val sdkMsg = exception.message ?: "Unknown error"
119
- classifyLoginFailure(accessToken, sdkMsg) { enrichedMsg ->
120
- completion(Result.failure(LoginFailedException(enrichedMsg)))
182
+ classifyLoginFailure(accessToken, exception) { failure ->
183
+ completion(Result.failure(failure))
121
184
  }
122
185
  }
123
186
  }
124
187
  )
125
188
  } catch (e: Exception) {
126
- completion(Result.failure(LoginFailedException(e.message ?: "Unknown error")))
189
+ completion(
190
+ Result.failure(
191
+ DocuSignFailure(
192
+ code = "login_failed",
193
+ message = "DocuSign login could not start: ${e.message ?: e.javaClass.simpleName}",
194
+ details = FailureDetails.from(e)
195
+ )
196
+ )
197
+ )
127
198
  }
128
199
  }
129
200
 
201
+ /**
202
+ * The SDK's login error rarely says why. A second call to `/oauth/userinfo` with the same token
203
+ * separates an expired or wrongly scoped token (401 or 403) from a valid token the SDK still
204
+ * refuses, which points at DocuSign admin configuration rather than the backend.
205
+ */
130
206
  private fun classifyLoginFailure(
131
207
  accessToken: String,
132
- sdkMsg: String,
133
- completion: (String) -> Unit
208
+ sdkError: Throwable,
209
+ completion: (DocuSignFailure) -> Unit
134
210
  ) {
135
211
  probeUserInfoStatus(accessToken) { probe ->
136
212
  val diagnostic = "integratorKey=$integratorKey environment=${environment.value}"
137
- val enriched = when (probe) {
138
- UserInfoProbe.OK ->
139
- "SDK rejected a valid token. Likely causes: Mobile SDK not enabled for integration key $integratorKey, or Android package name not whitelisted in DocuSign admin. Contact DocuSign support. (SDK: $sdkMsg) | $diagnostic"
140
- UserInfoProbe.UNAUTHORIZED ->
141
- "Access token rejected by DocuSign /oauth/userinfo. Re-mint via JWT Bearer Grant with scope=signature impersonation. (SDK: $sdkMsg) | $diagnostic"
142
- UserInfoProbe.NETWORK ->
143
- "$sdkMsg | $diagnostic"
213
+ val sdkDetails = FailureDetails.from(sdkError)
214
+ val (summary, details) = when (probe) {
215
+ is UserInfoProbe.Response -> {
216
+ val withStatus = probe.error?.let { sdkDetails.withHttp(it) }
217
+ ?: sdkDetails.copy(httpStatus = probe.status)
218
+ val summary = when (probe.status) {
219
+ in 200..299 ->
220
+ "DocuSign rejected a valid access token. The Mobile SDK may not be enabled for integration key $integratorKey, or the Android package name is not allowed in DocuSign admin."
221
+ 401, 403 ->
222
+ "DocuSign rejected the access token. Mint a new token with the signature and impersonation scopes."
223
+ else ->
224
+ "DocuSign login failed, and the userinfo check returned HTTP ${probe.status}."
225
+ }
226
+ summary to withStatus
227
+ }
228
+ is UserInfoProbe.TransportFailed ->
229
+ "DocuSign login failed, and the userinfo check could not reach DocuSign." to
230
+ sdkDetails.withUnderlyingIfAbsent(probe.error)
144
231
  }
145
- completion(enriched)
232
+ completion(DocuSignFailure(code = "login_failed", message = "$summary ($diagnostic)", details = details))
146
233
  }
147
234
  }
148
235
 
@@ -161,17 +248,17 @@ internal object DocuSignManager {
161
248
  setRequestProperty("Authorization", "Bearer $accessToken")
162
249
  setRequestProperty("Accept", "application/json")
163
250
  }
164
- when (val code = connection.responseCode) {
165
- in 200..299 -> UserInfoProbe.OK
166
- 401, 403 -> UserInfoProbe.UNAUTHORIZED
167
- else -> {
168
- android.util.Log.w("DocuSign", "userinfo probe HTTP $code")
169
- UserInfoProbe.NETWORK
170
- }
251
+ val status = connection.responseCode
252
+ if (status in 200..299) {
253
+ UserInfoProbe.Response(status, null)
254
+ } else {
255
+ // Only the error body is read. A successful response is the user's profile, which the
256
+ // failure has no use for.
257
+ val body = connection.errorStream?.bufferedReader()?.use { it.readText() } ?: ""
258
+ UserInfoProbe.Response(status, DocuSignHttpException.from(status, body))
171
259
  }
172
260
  } catch (e: Exception) {
173
- android.util.Log.w("DocuSign", "userinfo probe error: ${e.message}")
174
- UserInfoProbe.NETWORK
261
+ UserInfoProbe.TransportFailed(e)
175
262
  } finally {
176
263
  connection?.disconnect()
177
264
  }
@@ -183,6 +270,10 @@ internal object DocuSignManager {
183
270
  val ctx = appContext
184
271
  if (!isInitialized || ctx == null) return
185
272
  hasLoggedIn = false
273
+ // The signing-URL strategy holds these between login and present, which is longer than this
274
+ // object retained a token for before. Drop them on the way out so a signed-out process is not
275
+ // sitting on a bearer token; the next login repopulates them.
276
+ session = null
186
277
  try {
187
278
  DocuSign.getInstance().getAuthenticationDelegate().logout(
188
279
  ctx,
@@ -257,6 +348,7 @@ internal object DocuSignManager {
257
348
  recipientUserName: String,
258
349
  recipientEmail: String,
259
350
  recipientClientUserId: String,
351
+ launchStrategy: CaptiveSigningLaunchStrategy,
260
352
  completion: (Result<SigningOutcome>) -> Unit
261
353
  ) {
262
354
  if (!isInitialized) {
@@ -270,56 +362,313 @@ internal object DocuSignManager {
270
362
  }
271
363
 
272
364
  if (!pendingCompletion.compareAndSet(null, completion)) {
273
- completion(Result.failure(SigningFailedException("A signing session is already in progress")))
365
+ completion(Result.failure(SigningInProgressException()))
274
366
  return
275
367
  }
276
368
  currentEnvelopeId = envelopeId
277
369
 
370
+ val listener = captiveSigningListener()
371
+
372
+ when (launchStrategy) {
373
+ CaptiveSigningLaunchStrategy.FETCH ->
374
+ launchViaEnvelopeFetch(activity, envelopeId, recipientClientUserId, listener)
375
+ CaptiveSigningLaunchStrategy.SIGNING_URL ->
376
+ launchViaSigningUrl(
377
+ activity,
378
+ envelopeId,
379
+ recipientUserName,
380
+ recipientEmail,
381
+ recipientClientUserId,
382
+ listener,
383
+ completion
384
+ )
385
+ }
386
+ }
387
+
388
+ /**
389
+ * One listener for every launch path. Both entrypoints previously built their own copy, so a fix
390
+ * to any callback had to be made twice and the copies could drift.
391
+ *
392
+ * `mintFailure` is set when the signing-URL strategy fell back to fetch, so a fetch failure still
393
+ * carries what the mint learned.
394
+ */
395
+ private fun captiveSigningListener(mintFailure: Throwable? = null) = object : DSCaptiveSigningListener {
396
+ override fun onStart(envelopeId: String) {}
397
+
398
+ override fun onSuccess(envelopeId: String) {
399
+ handleSigningCompleted(envelopeId)
400
+ }
401
+
402
+ override fun onCancel(envelopeId: String, recipientId: String) {
403
+ handleSigningCancelled(envelopeId, null)
404
+ }
405
+
406
+ override fun onError(envelopeId: String?, exception: DSSigningException) {
407
+ handleSigningError(
408
+ signingFailure(envelopeId, exception, mintFailure, "DocuSign signing failed")
409
+ )
410
+ }
411
+
412
+ override fun onRecipientSigningSuccess(envelopeId: String, recipientId: String) {}
413
+
414
+ override fun onRecipientSigningError(
415
+ envelopeId: String,
416
+ recipientId: String,
417
+ exception: DSSigningException
418
+ ) {
419
+ handleSigningError(
420
+ signingFailure(envelopeId, exception, mintFailure, "DocuSign reported a recipient signing error")
421
+ )
422
+ }
423
+ }
424
+
425
+ /**
426
+ * A mint rejected with DocuSign's own error code, such as a recipient that does not match the
427
+ * envelope, names the real problem where the fetch path's error usually does not, so it is folded
428
+ * into the failure the caller finally receives.
429
+ */
430
+ private fun signingFailure(
431
+ envelopeId: String?,
432
+ error: Throwable,
433
+ mintFailure: Throwable?,
434
+ summary: String
435
+ ): DocuSignFailure {
436
+ val sdkDetails = FailureDetails.from(error)
437
+ val details = when (mintFailure) {
438
+ null -> sdkDetails
439
+ is DocuSignHttpException -> sdkDetails.withHttp(mintFailure)
440
+ else -> sdkDetails.withUnderlyingIfAbsent(mintFailure)
441
+ }
442
+ return DocuSignFailure(
443
+ code = "signing_failed",
444
+ message = "$summary: ${error.message ?: error.javaClass.simpleName}",
445
+ details = details,
446
+ envelopeId = envelopeId
447
+ )
448
+ }
449
+
450
+ /**
451
+ * Guards every URL this object hands to the SDK or sends credentials to.
452
+ *
453
+ * The SDK's URL overload validates nothing and calls `startActivity` unconditionally, so a blank
454
+ * or non-https signing URL would open an empty signing activity that never calls the listener
455
+ * back, leaving the promise unsettled. The recipient-view request needs the same check for a
456
+ * different reason: it carries the session bearer token, and `host` arrives unvalidated from JS.
457
+ */
458
+ private fun isHttpsUrl(url: String): Boolean {
459
+ val uri = android.net.Uri.parse(url)
460
+ return uri.scheme.equals("https", ignoreCase = true) && !uri.host.isNullOrBlank()
461
+ }
462
+
463
+ private fun launchViaEnvelopeFetch(
464
+ activity: Activity,
465
+ envelopeId: String,
466
+ recipientClientUserId: String,
467
+ listener: DSCaptiveSigningListener,
468
+ mintFailure: Throwable? = null
469
+ ) {
278
470
  try {
279
471
  DocuSign.getInstance().getCustomSettingsDelegate()
280
472
  .disableNativeComponentsInOnlineSigning(activity, true)
281
-
282
473
  DocuSign.getInstance().getSigningDelegate().launchCaptiveSigning(
283
474
  activity,
284
475
  envelopeId,
285
476
  recipientClientUserId,
286
- object : DSCaptiveSigningListener {
287
- override fun onStart(envelopeId: String) {}
477
+ listener
478
+ )
479
+ } catch (e: Exception) {
480
+ currentEnvelopeId = null
481
+ val pending = pendingCompletion.getAndSet(null)
482
+ pending?.invoke(
483
+ Result.failure(
484
+ signingFailure(envelopeId, e, mintFailure, "DocuSign could not open the signing ceremony")
485
+ )
486
+ )
487
+ }
488
+ }
288
489
 
289
- override fun onSuccess(envelopeId: String) {
290
- handleSigningCompleted(envelopeId)
291
- }
490
+ /**
491
+ * Presents captive signing from a pre-minted DocuSign recipient-view URL.
492
+ * The URL is the signing credential, so SDK initialization is required but
493
+ * a prior `loginWithAccessToken` call is not.
494
+ */
495
+ fun presentCaptiveSigningWithUrl(
496
+ activity: Activity,
497
+ signingUrl: String,
498
+ envelopeId: String,
499
+ recipientId: String?,
500
+ completion: (Result<SigningOutcome>) -> Unit
501
+ ) {
502
+ if (!isInitialized) {
503
+ completion(Result.failure(NotInitializedException()))
504
+ return
505
+ }
292
506
 
293
- override fun onCancel(envelopeId: String, recipientId: String) {
294
- handleSigningCancelled(envelopeId, null)
295
- }
507
+ // Ahead of the compareAndSet on purpose: a rejected URL must not claim the pending slot, or a
508
+ // later valid call would be refused as "already in progress".
509
+ if (!isHttpsUrl(signingUrl)) {
510
+ completion(Result.failure(InvalidSigningUrlException()))
511
+ return
512
+ }
296
513
 
297
- override fun onError(envelopeId: String?, exception: DSSigningException) {
298
- handleSigningError(
299
- envelopeId,
300
- "signing_failed",
301
- exception.message ?: "Unknown error"
302
- )
303
- }
514
+ if (!pendingCompletion.compareAndSet(null, completion)) {
515
+ completion(Result.failure(SigningInProgressException()))
516
+ return
517
+ }
518
+ currentEnvelopeId = envelopeId
304
519
 
305
- override fun onRecipientSigningSuccess(envelopeId: String, recipientId: String) {}
306
-
307
- override fun onRecipientSigningError(
308
- envelopeId: String,
309
- recipientId: String,
310
- exception: DSSigningException
311
- ) {
312
- handleSigningError(
313
- envelopeId,
314
- "recipient_signing_failed",
315
- exception.message ?: "Unknown error"
316
- )
520
+ launchWithSigningUrl(activity, signingUrl, envelopeId, recipientId, captiveSigningListener())
521
+ }
522
+
523
+ /**
524
+ * Mints a recipient view and launches the SDK's signing-URL overload.
525
+ *
526
+ * The fetch-based overload downloads the envelope with `include=documents` on a size-derived
527
+ * read timeout that floors at 15s when nothing is cached, and that download is what times out
528
+ * on large envelopes. The signing-URL overload skips it and points the WebView straight at a
529
+ * recipient-view URL, which needs nothing beyond the recipient details passed here and the
530
+ * session credentials already held, so the timing-out call never runs.
531
+ */
532
+ private fun launchViaSigningUrl(
533
+ activity: Activity,
534
+ envelopeId: String,
535
+ recipientUserName: String,
536
+ recipientEmail: String,
537
+ recipientClientUserId: String,
538
+ listener: DSCaptiveSigningListener,
539
+ completion: (Result<SigningOutcome>) -> Unit
540
+ ) {
541
+ thread(start = true, isDaemon = true) {
542
+ val url = try {
543
+ mintRecipientViewUrl(envelopeId, recipientUserName, recipientEmail, recipientClientUserId)
544
+ .also {
545
+ // Same guard the public URL entrypoint applies. A malformed mint response would
546
+ // otherwise open an empty signing activity that never calls the listener back.
547
+ if (!isHttpsUrl(it)) throw IOException("recipient view returned an invalid URL")
317
548
  }
549
+ } catch (e: Exception) {
550
+ // A mint failure must not be worse than not offering the strategy at all. Falling back to
551
+ // the fetch path restores the default behaviour exactly, so this can only add a way to
552
+ // succeed. The mint's failure rides along so a fetch failure still names it.
553
+ activity.runOnUiThread {
554
+ if (!canLaunchOn(activity, envelopeId, completion)) return@runOnUiThread
555
+ launchViaEnvelopeFetch(
556
+ activity,
557
+ envelopeId,
558
+ recipientClientUserId,
559
+ captiveSigningListener(mintFailure = e),
560
+ mintFailure = e
561
+ )
318
562
  }
563
+ return@thread
564
+ }
565
+ activity.runOnUiThread {
566
+ if (!canLaunchOn(activity, envelopeId, completion)) return@runOnUiThread
567
+ launchWithSigningUrl(activity, url, envelopeId, recipientClientUserId, listener)
568
+ }
569
+ }
570
+ }
571
+
572
+ private fun launchWithSigningUrl(
573
+ activity: Activity,
574
+ url: String,
575
+ envelopeId: String,
576
+ recipientId: String?,
577
+ listener: DSCaptiveSigningListener
578
+ ) {
579
+ try {
580
+ DocuSign.getInstance().getCustomSettingsDelegate()
581
+ .disableNativeComponentsInOnlineSigning(activity, true)
582
+ DocuSign.getInstance().getSigningDelegate().launchCaptiveSigning(
583
+ activity,
584
+ url,
585
+ envelopeId,
586
+ recipientId,
587
+ listener
319
588
  )
320
589
  } catch (e: Exception) {
590
+ currentEnvelopeId = null
321
591
  val pending = pendingCompletion.getAndSet(null)
322
- pending?.invoke(Result.failure(SigningFailedException(e.message ?: "Unknown error")))
592
+ pending?.invoke(
593
+ Result.failure(
594
+ signingFailure(envelopeId, e, null, "DocuSign could not open the signing ceremony")
595
+ )
596
+ )
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Minting puts a network round trip between capturing the Activity and using it, which the fetch
602
+ * path never did because it launched on the same stack frame. `runOnUiThread` posts to the main
603
+ * looper regardless of Activity state, so by the time this runs the screen may be gone or the
604
+ * session already resolved by `reset` or `endSigningSession`. Launching the SDK against either is
605
+ * how a dead-window crash or an orphaned signing screen happens.
606
+ *
607
+ * The check is on identity, not nullness. `reset` and `endSigningSession` clear the slot, and a
608
+ * fresh `presentCaptiveSigning` can claim it before a stale mint lands. A nullness check would
609
+ * pass in that window and launch this envelope wired to the new session's promise, resolving it
610
+ * with the wrong outcome. On a mismatch, do nothing at all: the slot is not this call's to
611
+ * resolve, and its own completion was already settled by whoever cleared it.
612
+ */
613
+ private fun canLaunchOn(
614
+ activity: Activity,
615
+ envelopeId: String,
616
+ completion: (Result<SigningOutcome>) -> Unit
617
+ ): Boolean {
618
+ if (pendingCompletion.get() !== completion) return false
619
+ if (activity.isFinishing || activity.isDestroyed) {
620
+ handleSigningCancelled(envelopeId, "activity_unavailable")
621
+ return false
622
+ }
623
+ return true
624
+ }
625
+
626
+ private fun mintRecipientViewUrl(
627
+ envelopeId: String,
628
+ recipientUserName: String,
629
+ recipientEmail: String,
630
+ recipientClientUserId: String
631
+ ): String {
632
+ val active = session ?: throw IllegalStateException("no active DocuSign session")
633
+ val endpoint =
634
+ "${restApiRoot(active.host)}/accounts/${active.accountId}/envelopes/$envelopeId/views/recipient"
635
+ // `host` arrives from JS unvalidated, and this request carries the session bearer token. Refuse
636
+ // to send it anywhere that is not https rather than leaking it in cleartext. Throwing here
637
+ // routes to the fetch fallback, so a misconfigured host degrades instead of failing outright.
638
+ if (!isHttpsUrl(endpoint)) {
639
+ throw IOException("DocuSign host must be an https URL to mint a recipient view")
640
+ }
641
+ val body = JSONObject()
642
+ .put("clientUserId", recipientClientUserId)
643
+ .put("userName", recipientUserName)
644
+ .put("email", recipientEmail)
645
+ .put("authenticationMethod", "none")
646
+ .put("returnUrl", "https://docusign/")
647
+ .toString()
648
+ var connection: HttpURLConnection? = null
649
+ return try {
650
+ connection = (URL(endpoint).openConnection() as HttpURLConnection).apply {
651
+ requestMethod = "POST"
652
+ // Deliberately tighter than the envelope download this replaces. A recipient view is a
653
+ // small JSON POST, and the thread holds the Activity for the whole round trip, so a long
654
+ // ceiling would just delay the fallback and pin the view tree while it waited.
655
+ connectTimeout = 15_000
656
+ readTimeout = 15_000
657
+ doOutput = true
658
+ setRequestProperty("Authorization", "Bearer ${active.accessToken}")
659
+ setRequestProperty("Content-Type", "application/json")
660
+ setRequestProperty("Accept", "application/json")
661
+ }
662
+ connection.outputStream.use { it.write(body.toByteArray()) }
663
+ val code = connection.responseCode
664
+ val stream = if (code in 200..299) connection.inputStream else connection.errorStream
665
+ val text = stream?.bufferedReader()?.use { it.readText() } ?: ""
666
+ if (code !in 200..299) {
667
+ throw DocuSignHttpException.from(code, text)
668
+ }
669
+ JSONObject(text).getString("url")
670
+ } finally {
671
+ connection?.disconnect()
323
672
  }
324
673
  }
325
674
 
@@ -341,9 +690,9 @@ internal object DocuSignManager {
341
690
  pendingCompletion.getAndSet(null)?.invoke(Result.success(outcome))
342
691
  }
343
692
 
344
- fun handleSigningError(envelopeId: String?, errorCode: String, errorMessage: String) {
345
- module?.emitSigningError(envelopeId, errorCode, errorMessage)
693
+ /** The module emits onSigningError when it settles the failure, so this does not. */
694
+ fun handleSigningError(failure: DocuSignFailure) {
346
695
  currentEnvelopeId = null
347
- pendingCompletion.getAndSet(null)?.invoke(Result.failure(SigningFailedException(errorMessage)))
696
+ pendingCompletion.getAndSet(null)?.invoke(Result.failure(failure))
348
697
  }
349
698
  }