@sparkvault/sdk-js 16.12.1 → 17.0.1

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/dist/index.mjs CHANGED
@@ -7133,12 +7133,12 @@ class OriginNotAllowedView {
7133
7133
  const title = document.createElement('h2');
7134
7134
  title.className = 'sv-not-activated-title';
7135
7135
  title.id = 'sv-modal-title';
7136
- title.textContent = 'This domain isn’t allowed';
7136
+ title.textContent = 'This domain isn\'t allowed';
7137
7137
  container.appendChild(title);
7138
7138
  const message = document.createElement('p');
7139
7139
  message.className = 'sv-not-activated-message';
7140
7140
  message.textContent =
7141
- 'Sign-in is blocked because this website’s domain is not on the SparkVault Identity allowlist for this account.';
7141
+ 'Sign-in is blocked because this website\'s domain is not on the SparkVault Identity allowlist for this account.';
7142
7142
  container.appendChild(message);
7143
7143
  const ownerCard = div('sv-not-activated-owner');
7144
7144
  const ownerLabel = document.createElement('span');
@@ -7150,7 +7150,7 @@ class OriginNotAllowedView {
7150
7150
  // trust it into the DOM as markup.
7151
7151
  ownerHint.textContent = this.props.origin
7152
7152
  ? `Add ${this.props.origin} to your verified domains in SparkVault, then reload this page.`
7153
- : 'Add this website’s domain to your verified domains in SparkVault, then reload this page.';
7153
+ : 'Add this website\'s domain to your verified domains in SparkVault, then reload this page.';
7154
7154
  ownerCard.appendChild(ownerLabel);
7155
7155
  ownerCard.appendChild(ownerHint);
7156
7156
  container.appendChild(ownerCard);
@@ -17973,8 +17973,12 @@ function closedBeforeReady(firstCheck) {
17973
17973
  return new PopupSeveredError(SEVERED_MESSAGE);
17974
17974
  return new SparkVaultError('Support sign-in did not start. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_INTERRUPTED');
17975
17975
  }
17976
- /** Open synchronously inside the user's gesture, before preparing the server challenge. */
17977
- function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17976
+ /**
17977
+ * Open synchronously inside the user's gesture, before preparing the server
17978
+ * challenge. A session redeemed after the sign-in already ended (cancelled,
17979
+ * expired, its window gone) reaches no caller, so it goes to `discard`.
17980
+ */
17981
+ function openWidgetIdentity(options, prepare, ready, redeem, discard, deskId) {
17978
17982
  if (!isHelpDeskId(deskId))
17979
17983
  return Promise.reject(new ValidationError('Support sign-in requires a valid desk.'));
17980
17984
  if (typeof window === 'undefined')
@@ -18022,12 +18026,18 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
18022
18026
  if (!challenge || settled || checking)
18023
18027
  return;
18024
18028
  checking = true;
18029
+ let session;
18025
18030
  try {
18026
- finish(null, await redeem(challenge, code));
18031
+ session = await redeem(challenge, code);
18027
18032
  }
18028
18033
  catch (error) {
18029
18034
  finish(error instanceof Error ? error : new Error(String(error)));
18035
+ return;
18030
18036
  }
18037
+ if (settled)
18038
+ discard(session);
18039
+ else
18040
+ finish(null, session);
18031
18041
  };
18032
18042
  const receive = (event) => {
18033
18043
  if (!challenge || event.source !== popup || event.origin !== firstPartyOrigin)
@@ -18195,7 +18205,7 @@ function sessionChanged() {
18195
18205
  * provider. A provider must supply an hdt_ token, not a website identity JWT.
18196
18206
  */
18197
18207
  class HelpDeskClient {
18198
- constructor(desk, http, transfers, provider, assertionProvider) {
18208
+ constructor(desk, http, transfers, provider, assertionProvider, onDiscardError) {
18199
18209
  this.authentication = null;
18200
18210
  this.verifiedRequesterId = null;
18201
18211
  this.provedSession = false;
@@ -18214,16 +18224,32 @@ class HelpDeskClient {
18214
18224
  this.ticketAccess = null;
18215
18225
  /** Only this client's own sign-in ceremonies create credentials it may revoke on account switch. */
18216
18226
  this.issuedSessions = new WeakMap();
18227
+ /**
18228
+ * Every bearer this client revoked or discarded, each with whether a host
18229
+ * lending it back has heard it ends. It grows by one bearer per release
18230
+ * (Switch account, Sign out, Use website account, logout) or discarded
18231
+ * session over one client's life. A host that keeps the session `onSession`
18232
+ * reports may lend one back through `getSessionToken`: it lends none then,
18233
+ * and the first such answer per bearer is cleared aloud so that the host
18234
+ * drops it. None of them is ever installed again.
18235
+ */
18236
+ this.releasedTokens = new Map();
18217
18237
  this.ownsSession = false;
18238
+ // Frozen copies of the records this client reads, so a page changing the desk it handed in (`HelpDeskConnectOptions.desk`) changes nothing here.
18218
18239
  this.desk = Object.freeze({ ...desk, branding: Object.freeze({ ...desk.branding }), identity: desk.identity ? Object.freeze({ ...desk.identity }) : null,
18219
- external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined });
18240
+ external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined,
18241
+ ticket_access_control: desk.ticket_access_control ? Object.freeze({ ...desk.ticket_access_control }) : undefined });
18220
18242
  this.http = http;
18221
18243
  this.transfers = transfers;
18222
18244
  this.provider = provider;
18223
18245
  this.assertionProvider = assertionProvider;
18224
- this.currentTicketPolicy = desk.ticket_access_control;
18246
+ this.onDiscardError = onDiscardError;
18247
+ this.currentTicketPolicy = this.desk.ticket_access_control;
18225
18248
  }
18226
- /** Discover a desk by its configured host, before any customer credentials are sent. */
18249
+ /**
18250
+ * Discover a desk by its configured host, before any customer credentials
18251
+ * are sent, or take the lookup's answer the page already holds (`desk`).
18252
+ */
18227
18253
  static async connect(config, options) {
18228
18254
  const host = hostname(options?.host);
18229
18255
  if (options.deskId !== undefined && !isHelpDeskId(options.deskId)) {
@@ -18235,6 +18261,9 @@ class HelpDeskClient {
18235
18261
  if (options.getIdentityAssertion !== undefined && typeof options.getIdentityAssertion !== 'function') {
18236
18262
  throw new ValidationError('getIdentityAssertion must be a function', { field: 'getIdentityAssertion' });
18237
18263
  }
18264
+ if (options.onDiscardError !== undefined && typeof options.onDiscardError !== 'function') {
18265
+ throw new ValidationError('onDiscardError must be a function', { field: 'onDiscardError' });
18266
+ }
18238
18267
  if (options.getIdentityAssertion && options.identityEndpoint)
18239
18268
  throw new ValidationError('Choose getIdentityAssertion or identityEndpoint, not both');
18240
18269
  const assertionProvider = options.getIdentityAssertion ?? (options.identityEndpoint ? endpointProvider(identityEndpoint(options.identityEndpoint), config.timeout) : undefined);
@@ -18242,9 +18271,10 @@ class HelpDeskClient {
18242
18271
  throw new ValidationError('Choose company identity or a customer-token provider, not both');
18243
18272
  const customerConfig = { ...config, accessToken: undefined, getAccessToken: undefined, apiKey: undefined };
18244
18273
  const http = new HttpClient(customerConfig);
18245
- const { data } = await http.request(apiPath `/v1/hd/desks`, {
18246
- query: { host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
18247
- });
18274
+ const data = options.desk !== undefined ? options.desk
18275
+ : (await http.request(apiPath `/v1/hd/desks`, {
18276
+ query: { host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
18277
+ })).data;
18248
18278
  if (data?.kind === 'moved') {
18249
18279
  throw new SparkVaultError('This help desk has moved. Connect using its current host.', 'HELP_DESK_MOVED', 409, { movedTo: data.moved_to });
18250
18280
  }
@@ -18256,7 +18286,7 @@ class HelpDeskClient {
18256
18286
  throw new SparkVaultError('The help desk lookup did not identify this account\'s desk.', 'HELP_DESK_INVALID_RESPONSE');
18257
18287
  }
18258
18288
  hostname(data.canonical_host);
18259
- return new HelpDeskClient(data, http, new IngotsModule(customerConfig, http), options.getSessionToken, assertionProvider);
18289
+ return new HelpDeskClient(data, http, new IngotsModule(customerConfig, http), options.getSessionToken, assertionProvider, options.onDiscardError);
18260
18290
  }
18261
18291
  /**
18262
18292
  * Install a customer session answer the host holds, such as one restored
@@ -18264,9 +18294,12 @@ class HelpDeskClient {
18264
18294
  * no deadline of its own: it lasts until Core answers 401, which clears it.
18265
18295
  * A company provider verifies restored sessions again before use. Null
18266
18296
  * stays signed out until refreshSession() or authenticate() explicitly
18267
- * resumes the provider.
18297
+ * resumes the provider. A session this client sent for revocation is
18298
+ * refused: its bearer is ended, or will be.
18268
18299
  */
18269
18300
  setSession(session) {
18301
+ if (session && this.releasedTokens.has(session.token))
18302
+ throw new ValidationError('This session has ended; sign in again', { field: 'session' });
18270
18303
  if (session?.customer.assurance === 'identity' && ['external_sso', 'external_unavailable'].includes(this.desk.auth_mode))
18271
18304
  this.websiteAccountSuppressed = true;
18272
18305
  this.installSession(session, null);
@@ -18379,6 +18412,13 @@ class HelpDeskClient {
18379
18412
  if (token !== null && !validToken(token)) {
18380
18413
  throw new ValidationError('getSessionToken must return an hdt_ customer bearer or null', { field: 'getSessionToken' });
18381
18414
  }
18415
+ const released = token === null ? undefined : this.releasedTokens.get(token);
18416
+ if (released) {
18417
+ const report = !released.reported;
18418
+ released.reported = true;
18419
+ this.rememberToken(null, report ? 'clear' : 'provider', report);
18420
+ return null;
18421
+ }
18382
18422
  this.rememberToken(token, 'provider');
18383
18423
  return token;
18384
18424
  }
@@ -18438,14 +18478,20 @@ class HelpDeskClient {
18438
18478
  async establish(path, body) {
18439
18479
  const revision = this.revision;
18440
18480
  const session = await this.send('POST', path, body, undefined, false);
18441
- if (revision !== this.revision)
18481
+ if (revision !== this.revision) {
18482
+ this.discardMinted(session);
18442
18483
  throw new AuthenticationError('The help desk session changed during sign-in. Try again.');
18443
- if (!validLifetime(session?.ttl_seconds))
18484
+ }
18485
+ if (!validToken(session?.token) || !Number.isFinite(session.expires_at) || !validLifetime(session.ttl_seconds)) {
18486
+ this.discardMinted(session);
18444
18487
  throw new SparkVaultError('The help desk returned an invalid session.', 'HELP_DESK_INVALID_RESPONSE');
18488
+ }
18445
18489
  this.issuedSessions.set(session, session.token);
18446
18490
  const installed = this.installSession(session, landedDeadline(session));
18447
- if (this.session !== installed || this.token !== session.token)
18491
+ if (this.session !== installed || this.token !== session.token) {
18492
+ this.discardMinted(session);
18448
18493
  throw sessionChanged();
18494
+ }
18449
18495
  this.provedSession = true;
18450
18496
  return session;
18451
18497
  }
@@ -18471,8 +18517,10 @@ class HelpDeskClient {
18471
18517
  }
18472
18518
  const revision = this.revision;
18473
18519
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/external/complete`, options, undefined, false);
18474
- if (revision !== this.revision)
18520
+ if (revision !== this.revision) {
18521
+ this.discardMinted(result);
18475
18522
  throw sessionChanged();
18523
+ }
18476
18524
  this.acceptExternalSession(result, automatic);
18477
18525
  return result;
18478
18526
  }
@@ -18515,6 +18563,7 @@ class HelpDeskClient {
18515
18563
  acceptExternalSession(session, automatic = false) {
18516
18564
  if (!validToken(session?.token) || !Number.isFinite(session.expires_at) || !validLifetime(session.ttl_seconds) ||
18517
18565
  !isResourceIdOf('requester', session.customer?.requester_id)) {
18566
+ this.discardMinted(session);
18518
18567
  throw new SparkVaultError('The help desk returned an invalid company session.', 'HELP_DESK_INVALID_RESPONSE');
18519
18568
  }
18520
18569
  const deadline = landedDeadline(session);
@@ -18534,8 +18583,10 @@ class HelpDeskClient {
18534
18583
  });
18535
18584
  // Session observers may synchronously clear/replace the account. Never
18536
18585
  // return that former customer's proof or add token aliases to the new one.
18537
- if (this.session !== installed || this.token !== session.token || this.verifiedRequesterId !== session.customer.requester_id)
18586
+ if (this.session !== installed || this.token !== session.token || this.verifiedRequesterId !== session.customer.requester_id) {
18587
+ this.discardMinted(session);
18538
18588
  throw sessionChanged();
18589
+ }
18539
18590
  if (sameCustomer) {
18540
18591
  this.renewedTokens.add(session.token);
18541
18592
  while (this.renewedTokens.size > 8)
@@ -18552,8 +18603,10 @@ class HelpDeskClient {
18552
18603
  async redeemExternal(options) {
18553
18604
  const revision = this.revision;
18554
18605
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/external/redeem`, options, undefined, false);
18555
- if (revision !== this.revision)
18606
+ if (revision !== this.revision) {
18607
+ this.discardMinted(result);
18556
18608
  throw sessionChanged();
18609
+ }
18557
18610
  this.acceptExternalSession(result);
18558
18611
  return result;
18559
18612
  }
@@ -18587,19 +18640,60 @@ class HelpDeskClient {
18587
18640
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/redeem`, {
18588
18641
  challenge_id: challenge.challenge_id, verifier: challenge.verifier, ...(code && { code }),
18589
18642
  }, undefined, false);
18590
- if (revision !== this.revision)
18591
- throw sessionChanged();
18592
18643
  // A native sign-in opens a session at the desk's issuer: an email sign-in's customer is linked to
18593
18644
  // its Secure Identity (`identity`); a sign-in by the organization's own identity provider carries
18594
18645
  // the `federated` mark and the `federated` assurance together, never one without the other.
18595
18646
  const customer = result?.customer;
18596
18647
  const nativeIdentity = customer?.federated === true ? customer.assurance === 'federated' : customer?.assurance === 'identity';
18597
18648
  if (!validToken(result?.token) || !Number.isFinite(result.expires_at) || !nativeIdentity || !/^hdwip_[A-Za-z0-9_-]{43}$/.test(result.identity_grant?.token)) {
18649
+ this.discardMinted(result);
18598
18650
  throw new SparkVaultError('The help desk returned an invalid support identity.', 'HELP_DESK_INVALID_RESPONSE');
18599
18651
  }
18600
18652
  this.issuedSessions.set(result, result.token);
18653
+ if (revision !== this.revision) {
18654
+ this.discardMinted(result);
18655
+ throw sessionChanged();
18656
+ }
18601
18657
  return result;
18602
- }, this.desk.desk_id);
18658
+ }, (session) => this.discardMinted(session), this.desk.desk_id);
18659
+ }
18660
+ /**
18661
+ * End a session Core minted for this client that reaches no one: its answer
18662
+ * was invalid, the customer changed while it was minted, or the sign-in
18663
+ * that asked for it had ended. Nobody else holds its bearer, so a refused or
18664
+ * lost revocation goes to `onDiscardError`, without which that bearer lasts
18665
+ * out its lifetime. The installed session, and one already sent for
18666
+ * revocation, are left as they are.
18667
+ */
18668
+ discardMinted(answer) {
18669
+ const token = answer?.token;
18670
+ if (!validToken(token) || token === this.token || this.releasedTokens.has(token))
18671
+ return;
18672
+ void this.revoke(token, undefined).catch((value) => {
18673
+ try {
18674
+ this.onDiscardError?.(value instanceof Error ? value : new Error(String(value)));
18675
+ }
18676
+ catch {
18677
+ // The callback belongs to the host; it has no part in the sign-in's outcome.
18678
+ }
18679
+ });
18680
+ }
18681
+ /**
18682
+ * Revoke a session this client's own sign-in redeemed that its caller will
18683
+ * not install: the form that asked for it has gone, or it served only for
18684
+ * its `identity_grant`. An installed session ends through `signOutSupport`
18685
+ * or `logout`; one this client did not issue belongs to whoever lent it and
18686
+ * is never revoked here. One already sent for revocation is not sent again.
18687
+ */
18688
+ async discardSession(session) {
18689
+ if (!session || this.issuedSessions.get(session) !== session.token) {
18690
+ throw new ValidationError('Only a session this client signed in can be discarded', { field: 'session' });
18691
+ }
18692
+ if (session.token === this.token)
18693
+ throw new ValidationError('The installed session ends through signOutSupport or logout', { field: 'session' });
18694
+ if (this.releasedTokens.has(session.token))
18695
+ return;
18696
+ await this.revoke(session.token, undefined);
18603
18697
  }
18604
18698
  /** Choose a different support identity without logging out or changing the host website. */
18605
18699
  switchSupportAccount() {
@@ -18609,16 +18703,28 @@ class HelpDeskClient {
18609
18703
  /**
18610
18704
  * Sign the customer out of support in this browser: revoke the session, one
18611
18705
  * a provider lent included, and keep the website's identity from signing
18612
- * them back in until `useWebsiteAccount`. The session is gone here before
18706
+ * them back in until `returnToWebsiteAccount`. The session is gone here before
18613
18707
  * the revocation is answered; the host website's own sign-in is untouched.
18614
18708
  */
18615
18709
  signOutSupport() {
18616
18710
  this.websiteAccountSuppressed = true;
18617
18711
  return this.releaseSession(true);
18618
18712
  }
18619
- /** The only operation that resumes the website's configured identity provider after an explicit switch. */
18620
- async useWebsiteAccount() {
18621
- await this.releaseSession(false);
18713
+ /**
18714
+ * Go back to the website's identity after an explicit switch, releasing as
18715
+ * `switchSupportAccount` releases: the session in use is gone here at once,
18716
+ * a lent one never revoked, and `released` settles with its revocation,
18717
+ * which never holds up the return. `resumed` settles with the session the
18718
+ * website's identity signed support in with, or null for none, for a
18719
+ * session the host lends, or, the website not yet asked, while a ticket
18720
+ * gate stands (`HelpDeskWebsiteAccountReturn`). The only operation that
18721
+ * resumes the website's configured identity provider after a switch.
18722
+ */
18723
+ returnToWebsiteAccount() {
18724
+ const released = this.releaseSession(false);
18725
+ return { released, resumed: this.resumeWebsiteAccount() };
18726
+ }
18727
+ async resumeWebsiteAccount() {
18622
18728
  this.websiteAccountSuppressed = false;
18623
18729
  this.resetProviderSession();
18624
18730
  if (!this.hasTicketAccess)
@@ -18697,6 +18803,12 @@ class HelpDeskClient {
18697
18803
  const accessToken = this.ticketAccess?.token;
18698
18804
  this.clearSession();
18699
18805
  this.clearTicketAccess();
18806
+ await this.revoke(token, accessToken);
18807
+ }
18808
+ /** End `token`'s session and `accessToken`'s ticket access at the desk; each credential sent can revoke only itself. */
18809
+ async revoke(token, accessToken) {
18810
+ if (token)
18811
+ this.releasedTokens.set(token, { reported: false });
18700
18812
  if (!token && !accessToken)
18701
18813
  return;
18702
18814
  await this.http.request(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/logout`, {
@@ -18790,14 +18902,18 @@ function injectHelpDeskFormStyles() {
18790
18902
  * offsets it reported along the way. A transfer whose bytes all arrived
18791
18903
  * while the vault was still saving (`received`: the SDK throws
18792
18904
  * RECEIVED_STILL_SAVING from ./transfer-retry.js for it) shows the file
18793
- * stored and the check still to come. Both clients attach such a file as it
18794
- * is, and the server, which alone learns when the file is stored, refuses a
18795
- * message sent before then in its own words.
18905
+ * stored and the check still to come. The server refuses a message naming
18906
+ * such a file, so neither client attaches it until a check of its upload
18907
+ * confirms it stored, and both hold the message meanwhile in one sentence
18908
+ * (STORING_HOLD_COPY).
18796
18909
  *
18797
18910
  * BROWSER-SAFE: pure data, no Node built-ins.
18798
18911
  */
18799
18912
 
18800
18913
 
18914
+ /** What holds a message back while one of its files is received and not yet confirmed stored. */
18915
+ const STORING_HOLD_COPY = 'A file is still being stored. Check its upload in a moment, or remove it.';
18916
+
18801
18917
  /** A step's state. */
18802
18918
  const CEREMONY_STEP_STATUS = Object.freeze({ PENDING: 'pending', ACTIVE: 'active', COMPLETE: 'complete' });
18803
18919
 
@@ -19910,7 +20026,7 @@ const ACCEPTED_KINDS_COPY = `You can attach ${ACCEPTED_ATTACHMENTS_COPY}.`;
19910
20026
  /** What a message's files still need before it can be sent, from the most pressing. */
19911
20027
  const HOLD_COPY = Object.freeze({
19912
20028
  uploading: 'Your files are still uploading.',
19913
- storing: 'A file is still being stored. Check its upload in a moment, or remove it.',
20029
+ storing: STORING_HOLD_COPY,
19914
20030
  retryable: "Remove the files that couldn't be attached, or try them again.",
19915
20031
  refused: "Remove the files that can't be attached."
19916
20032
  });
@@ -21723,6 +21839,7 @@ function mountHelpDeskForm(client, options) {
21723
21839
  }
21724
21840
  const ownGeneration = generation;
21725
21841
  let ticketAttempted = false;
21842
+ let installed = false;
21726
21843
  pending = true;
21727
21844
  disable(true);
21728
21845
  message('');
@@ -21751,8 +21868,10 @@ function mountHelpDeskForm(client, options) {
21751
21868
  sessionChanged();
21752
21869
  return;
21753
21870
  }
21754
- if (session)
21871
+ if (session) {
21755
21872
  client.setSession(session);
21873
+ installed = true;
21874
+ }
21756
21875
  token = await client.getSessionToken();
21757
21876
  sessionToken = token;
21758
21877
  sessionKnown = true;
@@ -21949,6 +22068,15 @@ function mountHelpDeskForm(client, options) {
21949
22068
  notify$1(options.onError, error);
21950
22069
  }
21951
22070
  finally {
22071
+ // A session the secure window redeemed that this form did not install
22072
+ // (it left, or the customer changed meanwhile) is revoked: no one else
22073
+ // holds its bearer.
22074
+ if (widgetSignIn && !installed) {
22075
+ void widgetSignIn.then((session) => client.discardSession(session), () => undefined).catch((failure) => {
22076
+ if (!destroyed)
22077
+ notify$1(options.onError, failure instanceof Error ? failure : new Error('The unused sign-in could not be ended.'));
22078
+ });
22079
+ }
21952
22080
  if (alive(ownGeneration)) {
21953
22081
  authenticating = false;
21954
22082
  pending = false;
@@ -25846,6 +25974,7 @@ class SupportView {
25846
25974
  }
25847
25975
  }
25848
25976
 
25977
+ const STILL_LOADING = 'Support is still loading. Please try again.';
25849
25978
  function notify(callback, value) {
25850
25979
  try {
25851
25980
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -25878,9 +26007,22 @@ function createHelpDeskSupport(config, options) {
25878
26007
  // to a signed-out form, a Switch account or Use website account to the
25879
26008
  // account arrived at.
25880
26009
  let pendingArrival = null;
25881
- // A chosen account's session is taking the old one's place: the host hears
25882
- // the new session, never the signed-out moment between the two.
26010
+ // Another account's session, or the website's, is taking the old one's
26011
+ // place: the host hears the session arrived at, never the signed-out moment
26012
+ // between the two.
25883
26013
  let replacingSession = false;
26014
+ // A Use website account that a ticket gate held up: the website's identity
26015
+ // is asked, and the host told where support arrived, at support's next
26016
+ // session lookup (`lookUpSession`). It concerns the client's session, not
26017
+ // the journey, so only another account change ends it.
26018
+ let websiteArrivalDue = false;
26019
+ // The session lookups in flight (`lookUpSession`), and whether the client
26020
+ // said a clear aloud meanwhile. The clear is held rather than told at once,
26021
+ // and the first lookup to settle takes it, so the host hears it once: that
26022
+ // lookup's caller tells the host where support arrived, which may be a
26023
+ // session put in its place.
26024
+ let lookupsInFlight = 0;
26025
+ let heldClear = false;
25884
26026
  // The issue, as written, that the held composition (the mounted form, the one
25885
26027
  // a re-authorized form will take, or the one saved before a reload) was last
25886
26028
  // filled from: '' for one filled from none. A form taking that composition is
@@ -25992,13 +26134,17 @@ function createHelpDeskSupport(config, options) {
25992
26134
  }
25993
26135
  async function connect() {
25994
26136
  if (!connected)
25995
- connected = HelpDeskClient.connect(config, options).then((answer) => {
26137
+ connected = HelpDeskClient.connect(config, { ...options, onDiscardError: reportLostRevocation }).then((answer) => {
25996
26138
  if (destroyed)
25997
26139
  throw new Error('Support is closed.');
25998
26140
  client = answer;
25999
26141
  stopSession = answer.subscribeSession((change) => {
26000
- if (change.source === 'clear' && !replacingSession)
26142
+ if (change.source !== 'clear' || replacingSession)
26143
+ return;
26144
+ if (lookupsInFlight === 0)
26001
26145
  notify(options.onSession, null);
26146
+ else
26147
+ heldClear = true;
26002
26148
  });
26003
26149
  kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
26004
26150
  analytics = createSupportAnalytics({
@@ -26029,7 +26175,9 @@ function createHelpDeskSupport(config, options) {
26029
26175
  }
26030
26176
  if (!options.persist || destroyed || state.stage !== 'issue')
26031
26177
  return;
26032
- const token = await active.getSessionToken();
26178
+ const { token, arrival } = await lookUpSession(active);
26179
+ if (arrival !== undefined)
26180
+ tellHost(arrival);
26033
26181
  if (destroyed)
26034
26182
  return;
26035
26183
  anonymous = !token;
@@ -26139,7 +26287,7 @@ function createHelpDeskSupport(config, options) {
26139
26287
  }
26140
26288
  function signIn(input = {}) {
26141
26289
  if (!client)
26142
- return Promise.reject(new Error('Support is still loading. Please try again.'));
26290
+ return Promise.reject(new Error(STILL_LOADING));
26143
26291
  nativeIdentity?.abort();
26144
26292
  const operation = new AbortController();
26145
26293
  nativeIdentity = operation;
@@ -26156,6 +26304,81 @@ function createHelpDeskSupport(config, options) {
26156
26304
  }
26157
26305
  });
26158
26306
  }
26307
+ /**
26308
+ * Revoke a session a sign-in redeemed that support will not install, through
26309
+ * the client the sign-in started on (support's own is gone once destroyed):
26310
+ * nobody else holds its bearer.
26311
+ */
26312
+ function discard(active, session) {
26313
+ void active.discardSession(session).catch(reportLostRevocation);
26314
+ }
26315
+ /**
26316
+ * A refused or lost revocation, of a session support let go of or one its
26317
+ * client let go of unused (`onDiscardError`), reaches the host while
26318
+ * support is open; the customer's journey goes on all the same.
26319
+ */
26320
+ function reportLostRevocation(value) {
26321
+ if (!destroyed)
26322
+ notify(options.onError, failure(value));
26323
+ }
26324
+ /**
26325
+ * Tell the host the session Use website account brought support to, or null
26326
+ * for none. Only the website's identity signs support in to a session the
26327
+ * host does not hold: a host that lends one (getSessionToken) is never told
26328
+ * of it, as on mount, since a null would make it drop the very session
26329
+ * support goes back to; one lending back the switched-to session it kept
26330
+ * hears from the client that it ended.
26331
+ */
26332
+ function reportWebsiteArrival(active, session) {
26333
+ if (active.hasIdentityProvider)
26334
+ tellHost(session);
26335
+ }
26336
+ function tellHost(session) {
26337
+ if (!destroyed)
26338
+ notify(options.onSession, session);
26339
+ }
26340
+ /**
26341
+ * Support's session lookup, with where support arrived (`arrival`) when the
26342
+ * host has that to hear, for the caller to tell it once (`tellHost`), or to
26343
+ * tell it of the session it puts in place instead. The first lookup after a
26344
+ * Use website account that a ticket gate held up (contact's, once the gate
26345
+ * opens, or a reopened support's) is where the website's identity signs
26346
+ * support back in, as the return itself does ungated; any other lookup's
26347
+ * arrival is the null of a clear the client said aloud meanwhile, such as
26348
+ * its refusal of a lent bearer it let go of, so that the host drops it.
26349
+ */
26350
+ async function lookUpSession(active) {
26351
+ if (websiteArrivalDue) {
26352
+ websiteArrivalDue = false;
26353
+ let arrived;
26354
+ try {
26355
+ arrived = await active.authenticate();
26356
+ }
26357
+ catch (value) {
26358
+ tellHost(null);
26359
+ throw value;
26360
+ }
26361
+ return { token: arrived?.token ?? null, arrival: arrived };
26362
+ }
26363
+ lookupsInFlight += 1;
26364
+ try {
26365
+ const token = await active.getSessionToken();
26366
+ return takeHeldClear() ? { token, arrival: null } : { token };
26367
+ }
26368
+ catch (value) {
26369
+ if (takeHeldClear())
26370
+ tellHost(null);
26371
+ throw value;
26372
+ }
26373
+ finally {
26374
+ lookupsInFlight -= 1;
26375
+ }
26376
+ }
26377
+ function takeHeldClear() {
26378
+ const cleared = heldClear;
26379
+ heldClear = false;
26380
+ return cleared;
26381
+ }
26159
26382
  function startAttempt(available, releaseId, resultCount) {
26160
26383
  if (!analytics)
26161
26384
  return Promise.resolve(null);
@@ -26218,11 +26441,19 @@ function createHelpDeskSupport(config, options) {
26218
26441
  if (password !== undefined)
26219
26442
  await kb.unlock({ password });
26220
26443
  else {
26221
- // A platform grant proves employee access independently of the host's ticket identity.
26222
- if (!client)
26223
- throw new Error('Support is still loading. Please try again.');
26444
+ // A platform grant proves employee access independently of the host's
26445
+ // ticket identity, so the support session the sign-in also opens is
26446
+ // never installed.
26447
+ const active = client;
26448
+ if (!active)
26449
+ throw new Error(STILL_LOADING);
26224
26450
  const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
26225
- await kb.unlock({ identity_grant: session.identity_grant.token });
26451
+ try {
26452
+ await kb.unlock({ identity_grant: session.identity_grant.token });
26453
+ }
26454
+ finally {
26455
+ discard(active, session);
26456
+ }
26226
26457
  }
26227
26458
  if (destroyed || ownSequence !== sequence)
26228
26459
  return;
@@ -26402,7 +26633,12 @@ function createHelpDeskSupport(config, options) {
26402
26633
  clearSupportIssue(client.desk.desk_id);
26403
26634
  update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
26404
26635
  }
26405
- async function showContact(reason) {
26636
+ /**
26637
+ * Open the contact step for `reason`. `carried` is the message of the failure
26638
+ * that led here, which stays in view until the customer's next action; an
26639
+ * error from any earlier step is cleared.
26640
+ */
26641
+ async function showContact(reason, carried) {
26406
26642
  if (destroyed || contactOpening === sequence)
26407
26643
  return;
26408
26644
  if (reason === 'article_not_answered' && state.article) {
@@ -26421,7 +26657,7 @@ function createHelpDeskSupport(config, options) {
26421
26657
  }
26422
26658
  if (reason !== 'direct')
26423
26659
  void attempt?.then((active) => active?.contactRequested(reason));
26424
- update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
26660
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: carried });
26425
26661
  const ownSequence = ++sequence;
26426
26662
  contactOpening = ownSequence;
26427
26663
  try {
@@ -26441,7 +26677,9 @@ function createHelpDeskSupport(config, options) {
26441
26677
  view.focusContact();
26442
26678
  return;
26443
26679
  }
26444
- const token = await active.getSessionToken();
26680
+ const { token, arrival } = await lookUpSession(active);
26681
+ if (arrival !== undefined)
26682
+ tellHost(arrival);
26445
26683
  const customer = token ? await active.getMe() : null;
26446
26684
  if (destroyed || ownSequence !== sequence)
26447
26685
  return;
@@ -26487,11 +26725,25 @@ function createHelpDeskSupport(config, options) {
26487
26725
  notify(options.onTicketAccess, await active.unlockTicketAccess({ password }));
26488
26726
  else if (identity) {
26489
26727
  const session = await identity;
26490
- notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26491
- const hostToken = await active.getSessionToken();
26492
- if (!hostToken) {
26493
- active.setSession(session);
26494
- notify(options.onSession, session);
26728
+ let installed = false;
26729
+ try {
26730
+ notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26731
+ // A customer session already in place keeps it, the sign-in serving
26732
+ // its employee grant alone; a closed support signs no one in. The
26733
+ // host hears once where support arrives: the employee session put
26734
+ // in place of none, or the lookup's own arrival.
26735
+ const { token, arrival } = await lookUpSession(active);
26736
+ if (!token && !destroyed) {
26737
+ active.setSession(session);
26738
+ installed = true;
26739
+ }
26740
+ const arrived = installed ? session : arrival;
26741
+ if (arrived !== undefined)
26742
+ tellHost(arrived);
26743
+ }
26744
+ finally {
26745
+ if (!installed)
26746
+ discard(active, session);
26495
26747
  }
26496
26748
  }
26497
26749
  else
@@ -26528,6 +26780,7 @@ function createHelpDeskSupport(config, options) {
26528
26780
  pendingComposition = composition ? { subject: composition.subject, body: composition.body } : { subject: '', body: '' };
26529
26781
  pendingRecovery = null;
26530
26782
  pendingArrival = null;
26783
+ websiteArrivalDue = false;
26531
26784
  kb?.clearAccess();
26532
26785
  kbConfig = null;
26533
26786
  results = [];
@@ -26543,13 +26796,20 @@ function createHelpDeskSupport(config, options) {
26543
26796
  */
26544
26797
  function switchAccount(composition) {
26545
26798
  const form = contact;
26546
- const policy = client?.ticketAccessPolicy;
26799
+ const active = client;
26800
+ if (!active)
26801
+ return Promise.reject(new Error(STILL_LOADING));
26802
+ const policy = active.ticketAccessPolicy;
26547
26803
  // Open synchronously in the Switch account gesture, before anything is awaited.
26548
26804
  return signIn({ selectAccount: true, employeeCompanyId: policy?.mode === 'identity' ? policy.company_id : undefined }).then((session) => {
26549
- // The form that asked has left (support destroyed or the journey reset): nothing waits on this account.
26550
- if (destroyed || !client || contact !== form)
26805
+ // Support was destroyed while the chooser was open (the form stays
26806
+ // locked meanwhile, so no other change replaces it): nothing waits on
26807
+ // this account, so its session ends here.
26808
+ if (destroyed || contact !== form) {
26809
+ discard(active, session);
26551
26810
  return;
26552
- return replaceAccount(client, session, composition);
26811
+ }
26812
+ return replaceAccount(active, session, composition);
26553
26813
  });
26554
26814
  }
26555
26815
  /**
@@ -26569,22 +26829,26 @@ function createHelpDeskSupport(config, options) {
26569
26829
  const released = active.switchSupportAccount();
26570
26830
  replacingSession = false;
26571
26831
  // A refused or lost revocation leaves the chosen account in place.
26572
- void released.catch((value) => notify(options.onError, failure(value)));
26832
+ void released.catch(reportLostRevocation);
26573
26833
  active.setSession(session);
26574
26834
  notify(options.onSession, session);
26835
+ let refusal;
26575
26836
  if (active.ticketAccessPolicy?.mode === 'identity') {
26576
- // Without this grant, contact's access check shows the employee gate for the chosen account.
26837
+ // Without this grant, contact's access check shows the employee gate
26838
+ // for the chosen account, which then says why it was refused.
26577
26839
  try {
26578
26840
  notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26579
26841
  }
26580
26842
  catch (value) {
26843
+ const error = failure(value);
26844
+ refusal = error.message;
26581
26845
  if (!destroyed && ownSequence === sequence)
26582
- notify(options.onError, failure(value));
26846
+ notify(options.onError, error);
26583
26847
  }
26584
26848
  }
26585
26849
  if (destroyed || ownSequence !== sequence)
26586
26850
  return;
26587
- await showContact('direct');
26851
+ await showContact('direct', refusal);
26588
26852
  }
26589
26853
  /**
26590
26854
  * Sign out of support from the contact form, without a window: the session
@@ -26602,31 +26866,44 @@ function createHelpDeskSupport(config, options) {
26602
26866
  update({ error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26603
26867
  // The session ends here at once, and the host hears so; a refused or lost
26604
26868
  // revocation leaves this browser signed out all the same.
26605
- void active.signOutSupport().catch((value) => notify(options.onError, failure(value)));
26869
+ void active.signOutSupport().catch(reportLostRevocation);
26606
26870
  // A host that keeps the session cleans up after it as its own sign-out does.
26607
26871
  const host = options.hostKeepsSession;
26608
26872
  notify(host ? () => host.onSignOut() : undefined, undefined);
26609
26873
  void showContact('direct');
26610
26874
  }
26875
+ /**
26876
+ * Use website account from the contact form: the session switched to is
26877
+ * released and the website's identity resumed, and the host hears once which
26878
+ * session support arrived at, never the signed-out moment between.
26879
+ */
26611
26880
  async function useWebsiteAccount(composition, recovering = false) {
26612
26881
  if (!client || destroyed || state.navigationLocked)
26613
26882
  return;
26883
+ const active = client;
26614
26884
  const ownSequence = ++sequence;
26615
26885
  leaveCustomer(composition);
26616
26886
  pendingRecovery = recovering ? { websiteSignedOut: true } : null;
26617
26887
  update({ busy: true, error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26888
+ // The release clears the switched-to session at once, before the website
26889
+ // is asked; its revocation goes behind, as a switch's does.
26890
+ replacingSession = true;
26891
+ const { released, resumed } = active.returnToWebsiteAccount();
26892
+ replacingSession = false;
26893
+ // The return decides at once whether a ticket gate stands (its release
26894
+ // ends a password's or an employee proof's access): a standing gate asks
26895
+ // the website nothing yet, so the arrival waits for support's next
26896
+ // session lookup (`lookUpSession`).
26897
+ const gated = !active.hasTicketAccess;
26898
+ websiteArrivalDue = gated && active.hasIdentityProvider;
26899
+ void released.catch(reportLostRevocation);
26900
+ let arrived;
26618
26901
  try {
26619
- await client.useWebsiteAccount();
26620
- if (destroyed || ownSequence !== sequence)
26621
- return;
26622
- switchedAccount = false;
26623
- // The website account the form arrives at says so, as a switch does; one
26624
- // the website does not give back gets none (`mountContact`).
26625
- pendingArrival = { from: 'switch', droppedFiles: composition?.hadFiles === true };
26626
- update({ busy: false });
26627
- await showContact('direct');
26902
+ arrived = await resumed;
26628
26903
  }
26629
26904
  catch (value) {
26905
+ if (!gated)
26906
+ reportWebsiteArrival(active, null);
26630
26907
  if (destroyed || ownSequence !== sequence)
26631
26908
  return;
26632
26909
  const error = failure(value);
@@ -26634,13 +26911,24 @@ function createHelpDeskSupport(config, options) {
26634
26911
  // The website was not reached, so it is not known to have no account.
26635
26912
  if (pendingRecovery)
26636
26913
  pendingRecovery = { websiteSignedOut: false };
26637
- if (client.hasTicketAccess) {
26914
+ if (active.hasTicketAccess) {
26638
26915
  mountContact(pendingComposition, null);
26639
26916
  pendingComposition = null;
26640
26917
  }
26641
26918
  else
26642
- await showContact('direct');
26919
+ await showContact('direct', error.message);
26920
+ return;
26643
26921
  }
26922
+ if (!gated)
26923
+ reportWebsiteArrival(active, arrived);
26924
+ if (destroyed || ownSequence !== sequence)
26925
+ return;
26926
+ switchedAccount = false;
26927
+ // The website account the form arrives at says so, as a switch does; one
26928
+ // the website does not give back gets none (`mountContact`).
26929
+ pendingArrival = { from: 'switch', droppedFiles: composition?.hadFiles === true };
26930
+ update({ busy: false });
26931
+ await showContact('direct');
26644
26932
  }
26645
26933
  function receipt(ticket) {
26646
26934
  const customer = contactCustomer;
@@ -26713,23 +27001,35 @@ class HelpDeskModule {
26713
27001
  * enables it. A custom onAuthRequired callback may supply a server-issued
26714
27002
  * help desk session. Destroy the returned handle on unmount/account change.
26715
27003
  */
26716
- async mountForm(options) {
26717
- const client = await this.connect(options);
26718
- return mountHelpDeskForm(client, options);
27004
+ mountForm(options) {
27005
+ return this.connectForm(options, (client) => mountHelpDeskForm(client, options));
26719
27006
  }
26720
27007
  /** Inject a form over an already-connected client that the host also drives headlessly. */
26721
27008
  mountClientForm(client, options) {
26722
27009
  return mountHelpDeskForm(client, options);
26723
27010
  }
26724
27011
  /** Open a ticket form in the SDK's accessible modal. */
26725
- async openForm(options) {
26726
- const client = await this.connect(options);
26727
- return this.openClientForm(client, options);
27012
+ openForm(options) {
27013
+ return this.connectForm(options, (client) => this.openClientForm(client, options));
26728
27014
  }
26729
27015
  /** Open a modal over a client whose company session the host also drives headlessly. */
26730
27016
  openClientForm(client, options = {}) {
26731
27017
  return openHelpDeskForm(client, { ...options, backdropBlur: this.config.backdropBlur });
26732
27018
  }
27019
+ /**
27020
+ * Connect the client one of this module's own forms opens over: a lost
27021
+ * revocation of a session the client let go of unused reaches the form's
27022
+ * `onError` while the form stands, as the form reports its own.
27023
+ */
27024
+ async connectForm(options, open) {
27025
+ let form = null;
27026
+ const client = await this.connect({ ...options, onDiscardError: (error) => {
27027
+ if (form && form.getState() !== 'destroyed')
27028
+ void Promise.resolve(options.onError?.(error)).catch(() => undefined);
27029
+ } });
27030
+ form = open(client);
27031
+ return form;
27032
+ }
26733
27033
  /** Bind existing support buttons, including ones added later. Cleanup closes this binding's form. */
26734
27034
  attach(selector, options) {
26735
27035
  let disposed = false;
@@ -31448,7 +31748,7 @@ class SparkVault {
31448
31748
  }
31449
31749
  /** Get the SDK version */
31450
31750
  static get version() {
31451
- return '16.12.1';
31751
+ return '17.0.1';
31452
31752
  }
31453
31753
  }
31454
31754
  if (typeof window !== 'undefined') {