@sparkvault/sdk-js 16.12.1 → 17.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.
package/dist/index.cjs CHANGED
@@ -17977,8 +17977,12 @@ function closedBeforeReady(firstCheck) {
17977
17977
  return new PopupSeveredError(SEVERED_MESSAGE);
17978
17978
  return new SparkVaultError('Support sign-in did not start. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_INTERRUPTED');
17979
17979
  }
17980
- /** Open synchronously inside the user's gesture, before preparing the server challenge. */
17981
- function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17980
+ /**
17981
+ * Open synchronously inside the user's gesture, before preparing the server
17982
+ * challenge. A session redeemed after the sign-in already ended (cancelled,
17983
+ * expired, its window gone) reaches no caller, so it goes to `discard`.
17984
+ */
17985
+ function openWidgetIdentity(options, prepare, ready, redeem, discard, deskId) {
17982
17986
  if (!isHelpDeskId(deskId))
17983
17987
  return Promise.reject(new ValidationError('Support sign-in requires a valid desk.'));
17984
17988
  if (typeof window === 'undefined')
@@ -18026,12 +18030,18 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
18026
18030
  if (!challenge || settled || checking)
18027
18031
  return;
18028
18032
  checking = true;
18033
+ let session;
18029
18034
  try {
18030
- finish(null, await redeem(challenge, code));
18035
+ session = await redeem(challenge, code);
18031
18036
  }
18032
18037
  catch (error) {
18033
18038
  finish(error instanceof Error ? error : new Error(String(error)));
18039
+ return;
18034
18040
  }
18041
+ if (settled)
18042
+ discard(session);
18043
+ else
18044
+ finish(null, session);
18035
18045
  };
18036
18046
  const receive = (event) => {
18037
18047
  if (!challenge || event.source !== popup || event.origin !== firstPartyOrigin)
@@ -18199,7 +18209,7 @@ function sessionChanged() {
18199
18209
  * provider. A provider must supply an hdt_ token, not a website identity JWT.
18200
18210
  */
18201
18211
  class HelpDeskClient {
18202
- constructor(desk, http, transfers, provider, assertionProvider) {
18212
+ constructor(desk, http, transfers, provider, assertionProvider, onDiscardError) {
18203
18213
  this.authentication = null;
18204
18214
  this.verifiedRequesterId = null;
18205
18215
  this.provedSession = false;
@@ -18218,16 +18228,32 @@ class HelpDeskClient {
18218
18228
  this.ticketAccess = null;
18219
18229
  /** Only this client's own sign-in ceremonies create credentials it may revoke on account switch. */
18220
18230
  this.issuedSessions = new WeakMap();
18231
+ /**
18232
+ * Every bearer this client revoked or discarded, each with whether a host
18233
+ * lending it back has heard it ends. It grows by one bearer per release
18234
+ * (Switch account, Sign out, Use website account, logout) or discarded
18235
+ * session over one client's life. A host that keeps the session `onSession`
18236
+ * reports may lend one back through `getSessionToken`: it lends none then,
18237
+ * and the first such answer per bearer is cleared aloud so that the host
18238
+ * drops it. None of them is ever installed again.
18239
+ */
18240
+ this.releasedTokens = new Map();
18221
18241
  this.ownsSession = false;
18242
+ // Frozen copies of the records this client reads, so a page changing the desk it handed in (`HelpDeskConnectOptions.desk`) changes nothing here.
18222
18243
  this.desk = Object.freeze({ ...desk, branding: Object.freeze({ ...desk.branding }), identity: desk.identity ? Object.freeze({ ...desk.identity }) : null,
18223
- external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined });
18244
+ external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined,
18245
+ ticket_access_control: desk.ticket_access_control ? Object.freeze({ ...desk.ticket_access_control }) : undefined });
18224
18246
  this.http = http;
18225
18247
  this.transfers = transfers;
18226
18248
  this.provider = provider;
18227
18249
  this.assertionProvider = assertionProvider;
18228
- this.currentTicketPolicy = desk.ticket_access_control;
18250
+ this.onDiscardError = onDiscardError;
18251
+ this.currentTicketPolicy = this.desk.ticket_access_control;
18229
18252
  }
18230
- /** Discover a desk by its configured host, before any customer credentials are sent. */
18253
+ /**
18254
+ * Discover a desk by its configured host, before any customer credentials
18255
+ * are sent, or take the lookup's answer the page already holds (`desk`).
18256
+ */
18231
18257
  static async connect(config, options) {
18232
18258
  const host = hostname(options?.host);
18233
18259
  if (options.deskId !== undefined && !isHelpDeskId(options.deskId)) {
@@ -18239,6 +18265,9 @@ class HelpDeskClient {
18239
18265
  if (options.getIdentityAssertion !== undefined && typeof options.getIdentityAssertion !== 'function') {
18240
18266
  throw new ValidationError('getIdentityAssertion must be a function', { field: 'getIdentityAssertion' });
18241
18267
  }
18268
+ if (options.onDiscardError !== undefined && typeof options.onDiscardError !== 'function') {
18269
+ throw new ValidationError('onDiscardError must be a function', { field: 'onDiscardError' });
18270
+ }
18242
18271
  if (options.getIdentityAssertion && options.identityEndpoint)
18243
18272
  throw new ValidationError('Choose getIdentityAssertion or identityEndpoint, not both');
18244
18273
  const assertionProvider = options.getIdentityAssertion ?? (options.identityEndpoint ? endpointProvider(identityEndpoint(options.identityEndpoint), config.timeout) : undefined);
@@ -18246,9 +18275,10 @@ class HelpDeskClient {
18246
18275
  throw new ValidationError('Choose company identity or a customer-token provider, not both');
18247
18276
  const customerConfig = { ...config, accessToken: undefined, getAccessToken: undefined, apiKey: undefined };
18248
18277
  const http = new HttpClient(customerConfig);
18249
- const { data } = await http.request(apiPath `/v1/hd/desks`, {
18250
- query: { host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
18251
- });
18278
+ const data = options.desk !== undefined ? options.desk
18279
+ : (await http.request(apiPath `/v1/hd/desks`, {
18280
+ query: { host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
18281
+ })).data;
18252
18282
  if (data?.kind === 'moved') {
18253
18283
  throw new SparkVaultError('This help desk has moved. Connect using its current host.', 'HELP_DESK_MOVED', 409, { movedTo: data.moved_to });
18254
18284
  }
@@ -18260,7 +18290,7 @@ class HelpDeskClient {
18260
18290
  throw new SparkVaultError('The help desk lookup did not identify this account\'s desk.', 'HELP_DESK_INVALID_RESPONSE');
18261
18291
  }
18262
18292
  hostname(data.canonical_host);
18263
- return new HelpDeskClient(data, http, new IngotsModule(customerConfig, http), options.getSessionToken, assertionProvider);
18293
+ return new HelpDeskClient(data, http, new IngotsModule(customerConfig, http), options.getSessionToken, assertionProvider, options.onDiscardError);
18264
18294
  }
18265
18295
  /**
18266
18296
  * Install a customer session answer the host holds, such as one restored
@@ -18268,9 +18298,12 @@ class HelpDeskClient {
18268
18298
  * no deadline of its own: it lasts until Core answers 401, which clears it.
18269
18299
  * A company provider verifies restored sessions again before use. Null
18270
18300
  * stays signed out until refreshSession() or authenticate() explicitly
18271
- * resumes the provider.
18301
+ * resumes the provider. A session this client sent for revocation is
18302
+ * refused: its bearer is ended, or will be.
18272
18303
  */
18273
18304
  setSession(session) {
18305
+ if (session && this.releasedTokens.has(session.token))
18306
+ throw new ValidationError('This session has ended; sign in again', { field: 'session' });
18274
18307
  if (session?.customer.assurance === 'identity' && ['external_sso', 'external_unavailable'].includes(this.desk.auth_mode))
18275
18308
  this.websiteAccountSuppressed = true;
18276
18309
  this.installSession(session, null);
@@ -18383,6 +18416,13 @@ class HelpDeskClient {
18383
18416
  if (token !== null && !validToken(token)) {
18384
18417
  throw new ValidationError('getSessionToken must return an hdt_ customer bearer or null', { field: 'getSessionToken' });
18385
18418
  }
18419
+ const released = token === null ? undefined : this.releasedTokens.get(token);
18420
+ if (released) {
18421
+ const report = !released.reported;
18422
+ released.reported = true;
18423
+ this.rememberToken(null, report ? 'clear' : 'provider', report);
18424
+ return null;
18425
+ }
18386
18426
  this.rememberToken(token, 'provider');
18387
18427
  return token;
18388
18428
  }
@@ -18442,14 +18482,20 @@ class HelpDeskClient {
18442
18482
  async establish(path, body) {
18443
18483
  const revision = this.revision;
18444
18484
  const session = await this.send('POST', path, body, undefined, false);
18445
- if (revision !== this.revision)
18485
+ if (revision !== this.revision) {
18486
+ this.discardMinted(session);
18446
18487
  throw new AuthenticationError('The help desk session changed during sign-in. Try again.');
18447
- if (!validLifetime(session?.ttl_seconds))
18488
+ }
18489
+ if (!validToken(session?.token) || !Number.isFinite(session.expires_at) || !validLifetime(session.ttl_seconds)) {
18490
+ this.discardMinted(session);
18448
18491
  throw new SparkVaultError('The help desk returned an invalid session.', 'HELP_DESK_INVALID_RESPONSE');
18492
+ }
18449
18493
  this.issuedSessions.set(session, session.token);
18450
18494
  const installed = this.installSession(session, landedDeadline(session));
18451
- if (this.session !== installed || this.token !== session.token)
18495
+ if (this.session !== installed || this.token !== session.token) {
18496
+ this.discardMinted(session);
18452
18497
  throw sessionChanged();
18498
+ }
18453
18499
  this.provedSession = true;
18454
18500
  return session;
18455
18501
  }
@@ -18475,8 +18521,10 @@ class HelpDeskClient {
18475
18521
  }
18476
18522
  const revision = this.revision;
18477
18523
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/external/complete`, options, undefined, false);
18478
- if (revision !== this.revision)
18524
+ if (revision !== this.revision) {
18525
+ this.discardMinted(result);
18479
18526
  throw sessionChanged();
18527
+ }
18480
18528
  this.acceptExternalSession(result, automatic);
18481
18529
  return result;
18482
18530
  }
@@ -18519,6 +18567,7 @@ class HelpDeskClient {
18519
18567
  acceptExternalSession(session, automatic = false) {
18520
18568
  if (!validToken(session?.token) || !Number.isFinite(session.expires_at) || !validLifetime(session.ttl_seconds) ||
18521
18569
  !isResourceIdOf('requester', session.customer?.requester_id)) {
18570
+ this.discardMinted(session);
18522
18571
  throw new SparkVaultError('The help desk returned an invalid company session.', 'HELP_DESK_INVALID_RESPONSE');
18523
18572
  }
18524
18573
  const deadline = landedDeadline(session);
@@ -18538,8 +18587,10 @@ class HelpDeskClient {
18538
18587
  });
18539
18588
  // Session observers may synchronously clear/replace the account. Never
18540
18589
  // return that former customer's proof or add token aliases to the new one.
18541
- if (this.session !== installed || this.token !== session.token || this.verifiedRequesterId !== session.customer.requester_id)
18590
+ if (this.session !== installed || this.token !== session.token || this.verifiedRequesterId !== session.customer.requester_id) {
18591
+ this.discardMinted(session);
18542
18592
  throw sessionChanged();
18593
+ }
18543
18594
  if (sameCustomer) {
18544
18595
  this.renewedTokens.add(session.token);
18545
18596
  while (this.renewedTokens.size > 8)
@@ -18556,8 +18607,10 @@ class HelpDeskClient {
18556
18607
  async redeemExternal(options) {
18557
18608
  const revision = this.revision;
18558
18609
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/external/redeem`, options, undefined, false);
18559
- if (revision !== this.revision)
18610
+ if (revision !== this.revision) {
18611
+ this.discardMinted(result);
18560
18612
  throw sessionChanged();
18613
+ }
18561
18614
  this.acceptExternalSession(result);
18562
18615
  return result;
18563
18616
  }
@@ -18591,19 +18644,60 @@ class HelpDeskClient {
18591
18644
  const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/redeem`, {
18592
18645
  challenge_id: challenge.challenge_id, verifier: challenge.verifier, ...(code && { code }),
18593
18646
  }, undefined, false);
18594
- if (revision !== this.revision)
18595
- throw sessionChanged();
18596
18647
  // A native sign-in opens a session at the desk's issuer: an email sign-in's customer is linked to
18597
18648
  // its Secure Identity (`identity`); a sign-in by the organization's own identity provider carries
18598
18649
  // the `federated` mark and the `federated` assurance together, never one without the other.
18599
18650
  const customer = result?.customer;
18600
18651
  const nativeIdentity = customer?.federated === true ? customer.assurance === 'federated' : customer?.assurance === 'identity';
18601
18652
  if (!validToken(result?.token) || !Number.isFinite(result.expires_at) || !nativeIdentity || !/^hdwip_[A-Za-z0-9_-]{43}$/.test(result.identity_grant?.token)) {
18653
+ this.discardMinted(result);
18602
18654
  throw new SparkVaultError('The help desk returned an invalid support identity.', 'HELP_DESK_INVALID_RESPONSE');
18603
18655
  }
18604
18656
  this.issuedSessions.set(result, result.token);
18657
+ if (revision !== this.revision) {
18658
+ this.discardMinted(result);
18659
+ throw sessionChanged();
18660
+ }
18605
18661
  return result;
18606
- }, this.desk.desk_id);
18662
+ }, (session) => this.discardMinted(session), this.desk.desk_id);
18663
+ }
18664
+ /**
18665
+ * End a session Core minted for this client that reaches no one: its answer
18666
+ * was invalid, the customer changed while it was minted, or the sign-in
18667
+ * that asked for it had ended. Nobody else holds its bearer, so a refused or
18668
+ * lost revocation goes to `onDiscardError`, without which that bearer lasts
18669
+ * out its lifetime. The installed session, and one already sent for
18670
+ * revocation, are left as they are.
18671
+ */
18672
+ discardMinted(answer) {
18673
+ const token = answer?.token;
18674
+ if (!validToken(token) || token === this.token || this.releasedTokens.has(token))
18675
+ return;
18676
+ void this.revoke(token, undefined).catch((value) => {
18677
+ try {
18678
+ this.onDiscardError?.(value instanceof Error ? value : new Error(String(value)));
18679
+ }
18680
+ catch {
18681
+ // The callback belongs to the host; it has no part in the sign-in's outcome.
18682
+ }
18683
+ });
18684
+ }
18685
+ /**
18686
+ * Revoke a session this client's own sign-in redeemed that its caller will
18687
+ * not install: the form that asked for it has gone, or it served only for
18688
+ * its `identity_grant`. An installed session ends through `signOutSupport`
18689
+ * or `logout`; one this client did not issue belongs to whoever lent it and
18690
+ * is never revoked here. One already sent for revocation is not sent again.
18691
+ */
18692
+ async discardSession(session) {
18693
+ if (!session || this.issuedSessions.get(session) !== session.token) {
18694
+ throw new ValidationError('Only a session this client signed in can be discarded', { field: 'session' });
18695
+ }
18696
+ if (session.token === this.token)
18697
+ throw new ValidationError('The installed session ends through signOutSupport or logout', { field: 'session' });
18698
+ if (this.releasedTokens.has(session.token))
18699
+ return;
18700
+ await this.revoke(session.token, undefined);
18607
18701
  }
18608
18702
  /** Choose a different support identity without logging out or changing the host website. */
18609
18703
  switchSupportAccount() {
@@ -18613,16 +18707,28 @@ class HelpDeskClient {
18613
18707
  /**
18614
18708
  * Sign the customer out of support in this browser: revoke the session, one
18615
18709
  * a provider lent included, and keep the website's identity from signing
18616
- * them back in until `useWebsiteAccount`. The session is gone here before
18710
+ * them back in until `returnToWebsiteAccount`. The session is gone here before
18617
18711
  * the revocation is answered; the host website's own sign-in is untouched.
18618
18712
  */
18619
18713
  signOutSupport() {
18620
18714
  this.websiteAccountSuppressed = true;
18621
18715
  return this.releaseSession(true);
18622
18716
  }
18623
- /** The only operation that resumes the website's configured identity provider after an explicit switch. */
18624
- async useWebsiteAccount() {
18625
- await this.releaseSession(false);
18717
+ /**
18718
+ * Go back to the website's identity after an explicit switch, releasing as
18719
+ * `switchSupportAccount` releases: the session in use is gone here at once,
18720
+ * a lent one never revoked, and `released` settles with its revocation,
18721
+ * which never holds up the return. `resumed` settles with the session the
18722
+ * website's identity signed support in with, or null for none, for a
18723
+ * session the host lends, or, the website not yet asked, while a ticket
18724
+ * gate stands (`HelpDeskWebsiteAccountReturn`). The only operation that
18725
+ * resumes the website's configured identity provider after a switch.
18726
+ */
18727
+ returnToWebsiteAccount() {
18728
+ const released = this.releaseSession(false);
18729
+ return { released, resumed: this.resumeWebsiteAccount() };
18730
+ }
18731
+ async resumeWebsiteAccount() {
18626
18732
  this.websiteAccountSuppressed = false;
18627
18733
  this.resetProviderSession();
18628
18734
  if (!this.hasTicketAccess)
@@ -18701,6 +18807,12 @@ class HelpDeskClient {
18701
18807
  const accessToken = this.ticketAccess?.token;
18702
18808
  this.clearSession();
18703
18809
  this.clearTicketAccess();
18810
+ await this.revoke(token, accessToken);
18811
+ }
18812
+ /** End `token`'s session and `accessToken`'s ticket access at the desk; each credential sent can revoke only itself. */
18813
+ async revoke(token, accessToken) {
18814
+ if (token)
18815
+ this.releasedTokens.set(token, { reported: false });
18704
18816
  if (!token && !accessToken)
18705
18817
  return;
18706
18818
  await this.http.request(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/logout`, {
@@ -21727,6 +21839,7 @@ function mountHelpDeskForm(client, options) {
21727
21839
  }
21728
21840
  const ownGeneration = generation;
21729
21841
  let ticketAttempted = false;
21842
+ let installed = false;
21730
21843
  pending = true;
21731
21844
  disable(true);
21732
21845
  message('');
@@ -21755,8 +21868,10 @@ function mountHelpDeskForm(client, options) {
21755
21868
  sessionChanged();
21756
21869
  return;
21757
21870
  }
21758
- if (session)
21871
+ if (session) {
21759
21872
  client.setSession(session);
21873
+ installed = true;
21874
+ }
21760
21875
  token = await client.getSessionToken();
21761
21876
  sessionToken = token;
21762
21877
  sessionKnown = true;
@@ -21953,6 +22068,15 @@ function mountHelpDeskForm(client, options) {
21953
22068
  notify$1(options.onError, error);
21954
22069
  }
21955
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
+ }
21956
22080
  if (alive(ownGeneration)) {
21957
22081
  authenticating = false;
21958
22082
  pending = false;
@@ -25850,6 +25974,7 @@ class SupportView {
25850
25974
  }
25851
25975
  }
25852
25976
 
25977
+ const STILL_LOADING = 'Support is still loading. Please try again.';
25853
25978
  function notify(callback, value) {
25854
25979
  try {
25855
25980
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -25882,9 +26007,22 @@ function createHelpDeskSupport(config, options) {
25882
26007
  // to a signed-out form, a Switch account or Use website account to the
25883
26008
  // account arrived at.
25884
26009
  let pendingArrival = null;
25885
- // A chosen account's session is taking the old one's place: the host hears
25886
- // 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.
25887
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;
25888
26026
  // The issue, as written, that the held composition (the mounted form, the one
25889
26027
  // a re-authorized form will take, or the one saved before a reload) was last
25890
26028
  // filled from: '' for one filled from none. A form taking that composition is
@@ -25996,13 +26134,17 @@ function createHelpDeskSupport(config, options) {
25996
26134
  }
25997
26135
  async function connect() {
25998
26136
  if (!connected)
25999
- connected = HelpDeskClient.connect(config, options).then((answer) => {
26137
+ connected = HelpDeskClient.connect(config, { ...options, onDiscardError: reportLostRevocation }).then((answer) => {
26000
26138
  if (destroyed)
26001
26139
  throw new Error('Support is closed.');
26002
26140
  client = answer;
26003
26141
  stopSession = answer.subscribeSession((change) => {
26004
- if (change.source === 'clear' && !replacingSession)
26142
+ if (change.source !== 'clear' || replacingSession)
26143
+ return;
26144
+ if (lookupsInFlight === 0)
26005
26145
  notify(options.onSession, null);
26146
+ else
26147
+ heldClear = true;
26006
26148
  });
26007
26149
  kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
26008
26150
  analytics = createSupportAnalytics({
@@ -26033,7 +26175,9 @@ function createHelpDeskSupport(config, options) {
26033
26175
  }
26034
26176
  if (!options.persist || destroyed || state.stage !== 'issue')
26035
26177
  return;
26036
- const token = await active.getSessionToken();
26178
+ const { token, arrival } = await lookUpSession(active);
26179
+ if (arrival !== undefined)
26180
+ tellHost(arrival);
26037
26181
  if (destroyed)
26038
26182
  return;
26039
26183
  anonymous = !token;
@@ -26143,7 +26287,7 @@ function createHelpDeskSupport(config, options) {
26143
26287
  }
26144
26288
  function signIn(input = {}) {
26145
26289
  if (!client)
26146
- return Promise.reject(new Error('Support is still loading. Please try again.'));
26290
+ return Promise.reject(new Error(STILL_LOADING));
26147
26291
  nativeIdentity?.abort();
26148
26292
  const operation = new AbortController();
26149
26293
  nativeIdentity = operation;
@@ -26160,6 +26304,81 @@ function createHelpDeskSupport(config, options) {
26160
26304
  }
26161
26305
  });
26162
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
+ }
26163
26382
  function startAttempt(available, releaseId, resultCount) {
26164
26383
  if (!analytics)
26165
26384
  return Promise.resolve(null);
@@ -26222,11 +26441,19 @@ function createHelpDeskSupport(config, options) {
26222
26441
  if (password !== undefined)
26223
26442
  await kb.unlock({ password });
26224
26443
  else {
26225
- // A platform grant proves employee access independently of the host's ticket identity.
26226
- if (!client)
26227
- 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);
26228
26450
  const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
26229
- 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
+ }
26230
26457
  }
26231
26458
  if (destroyed || ownSequence !== sequence)
26232
26459
  return;
@@ -26406,7 +26633,12 @@ function createHelpDeskSupport(config, options) {
26406
26633
  clearSupportIssue(client.desk.desk_id);
26407
26634
  update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
26408
26635
  }
26409
- 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) {
26410
26642
  if (destroyed || contactOpening === sequence)
26411
26643
  return;
26412
26644
  if (reason === 'article_not_answered' && state.article) {
@@ -26425,7 +26657,7 @@ function createHelpDeskSupport(config, options) {
26425
26657
  }
26426
26658
  if (reason !== 'direct')
26427
26659
  void attempt?.then((active) => active?.contactRequested(reason));
26428
- update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
26660
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: carried });
26429
26661
  const ownSequence = ++sequence;
26430
26662
  contactOpening = ownSequence;
26431
26663
  try {
@@ -26445,7 +26677,9 @@ function createHelpDeskSupport(config, options) {
26445
26677
  view.focusContact();
26446
26678
  return;
26447
26679
  }
26448
- const token = await active.getSessionToken();
26680
+ const { token, arrival } = await lookUpSession(active);
26681
+ if (arrival !== undefined)
26682
+ tellHost(arrival);
26449
26683
  const customer = token ? await active.getMe() : null;
26450
26684
  if (destroyed || ownSequence !== sequence)
26451
26685
  return;
@@ -26491,11 +26725,25 @@ function createHelpDeskSupport(config, options) {
26491
26725
  notify(options.onTicketAccess, await active.unlockTicketAccess({ password }));
26492
26726
  else if (identity) {
26493
26727
  const session = await identity;
26494
- notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26495
- const hostToken = await active.getSessionToken();
26496
- if (!hostToken) {
26497
- active.setSession(session);
26498
- 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);
26499
26747
  }
26500
26748
  }
26501
26749
  else
@@ -26532,6 +26780,7 @@ function createHelpDeskSupport(config, options) {
26532
26780
  pendingComposition = composition ? { subject: composition.subject, body: composition.body } : { subject: '', body: '' };
26533
26781
  pendingRecovery = null;
26534
26782
  pendingArrival = null;
26783
+ websiteArrivalDue = false;
26535
26784
  kb?.clearAccess();
26536
26785
  kbConfig = null;
26537
26786
  results = [];
@@ -26547,13 +26796,20 @@ function createHelpDeskSupport(config, options) {
26547
26796
  */
26548
26797
  function switchAccount(composition) {
26549
26798
  const form = contact;
26550
- const policy = client?.ticketAccessPolicy;
26799
+ const active = client;
26800
+ if (!active)
26801
+ return Promise.reject(new Error(STILL_LOADING));
26802
+ const policy = active.ticketAccessPolicy;
26551
26803
  // Open synchronously in the Switch account gesture, before anything is awaited.
26552
26804
  return signIn({ selectAccount: true, employeeCompanyId: policy?.mode === 'identity' ? policy.company_id : undefined }).then((session) => {
26553
- // The form that asked has left (support destroyed or the journey reset): nothing waits on this account.
26554
- 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);
26555
26810
  return;
26556
- return replaceAccount(client, session, composition);
26811
+ }
26812
+ return replaceAccount(active, session, composition);
26557
26813
  });
26558
26814
  }
26559
26815
  /**
@@ -26573,22 +26829,26 @@ function createHelpDeskSupport(config, options) {
26573
26829
  const released = active.switchSupportAccount();
26574
26830
  replacingSession = false;
26575
26831
  // A refused or lost revocation leaves the chosen account in place.
26576
- void released.catch((value) => notify(options.onError, failure(value)));
26832
+ void released.catch(reportLostRevocation);
26577
26833
  active.setSession(session);
26578
26834
  notify(options.onSession, session);
26835
+ let refusal;
26579
26836
  if (active.ticketAccessPolicy?.mode === 'identity') {
26580
- // 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.
26581
26839
  try {
26582
26840
  notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26583
26841
  }
26584
26842
  catch (value) {
26843
+ const error = failure(value);
26844
+ refusal = error.message;
26585
26845
  if (!destroyed && ownSequence === sequence)
26586
- notify(options.onError, failure(value));
26846
+ notify(options.onError, error);
26587
26847
  }
26588
26848
  }
26589
26849
  if (destroyed || ownSequence !== sequence)
26590
26850
  return;
26591
- await showContact('direct');
26851
+ await showContact('direct', refusal);
26592
26852
  }
26593
26853
  /**
26594
26854
  * Sign out of support from the contact form, without a window: the session
@@ -26606,31 +26866,44 @@ function createHelpDeskSupport(config, options) {
26606
26866
  update({ error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26607
26867
  // The session ends here at once, and the host hears so; a refused or lost
26608
26868
  // revocation leaves this browser signed out all the same.
26609
- void active.signOutSupport().catch((value) => notify(options.onError, failure(value)));
26869
+ void active.signOutSupport().catch(reportLostRevocation);
26610
26870
  // A host that keeps the session cleans up after it as its own sign-out does.
26611
26871
  const host = options.hostKeepsSession;
26612
26872
  notify(host ? () => host.onSignOut() : undefined, undefined);
26613
26873
  void showContact('direct');
26614
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
+ */
26615
26880
  async function useWebsiteAccount(composition, recovering = false) {
26616
26881
  if (!client || destroyed || state.navigationLocked)
26617
26882
  return;
26883
+ const active = client;
26618
26884
  const ownSequence = ++sequence;
26619
26885
  leaveCustomer(composition);
26620
26886
  pendingRecovery = recovering ? { websiteSignedOut: true } : null;
26621
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;
26622
26901
  try {
26623
- await client.useWebsiteAccount();
26624
- if (destroyed || ownSequence !== sequence)
26625
- return;
26626
- switchedAccount = false;
26627
- // The website account the form arrives at says so, as a switch does; one
26628
- // the website does not give back gets none (`mountContact`).
26629
- pendingArrival = { from: 'switch', droppedFiles: composition?.hadFiles === true };
26630
- update({ busy: false });
26631
- await showContact('direct');
26902
+ arrived = await resumed;
26632
26903
  }
26633
26904
  catch (value) {
26905
+ if (!gated)
26906
+ reportWebsiteArrival(active, null);
26634
26907
  if (destroyed || ownSequence !== sequence)
26635
26908
  return;
26636
26909
  const error = failure(value);
@@ -26638,13 +26911,24 @@ function createHelpDeskSupport(config, options) {
26638
26911
  // The website was not reached, so it is not known to have no account.
26639
26912
  if (pendingRecovery)
26640
26913
  pendingRecovery = { websiteSignedOut: false };
26641
- if (client.hasTicketAccess) {
26914
+ if (active.hasTicketAccess) {
26642
26915
  mountContact(pendingComposition, null);
26643
26916
  pendingComposition = null;
26644
26917
  }
26645
26918
  else
26646
- await showContact('direct');
26919
+ await showContact('direct', error.message);
26920
+ return;
26647
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');
26648
26932
  }
26649
26933
  function receipt(ticket) {
26650
26934
  const customer = contactCustomer;
@@ -26717,23 +27001,35 @@ class HelpDeskModule {
26717
27001
  * enables it. A custom onAuthRequired callback may supply a server-issued
26718
27002
  * help desk session. Destroy the returned handle on unmount/account change.
26719
27003
  */
26720
- async mountForm(options) {
26721
- const client = await this.connect(options);
26722
- return mountHelpDeskForm(client, options);
27004
+ mountForm(options) {
27005
+ return this.connectForm(options, (client) => mountHelpDeskForm(client, options));
26723
27006
  }
26724
27007
  /** Inject a form over an already-connected client that the host also drives headlessly. */
26725
27008
  mountClientForm(client, options) {
26726
27009
  return mountHelpDeskForm(client, options);
26727
27010
  }
26728
27011
  /** Open a ticket form in the SDK's accessible modal. */
26729
- async openForm(options) {
26730
- const client = await this.connect(options);
26731
- return this.openClientForm(client, options);
27012
+ openForm(options) {
27013
+ return this.connectForm(options, (client) => this.openClientForm(client, options));
26732
27014
  }
26733
27015
  /** Open a modal over a client whose company session the host also drives headlessly. */
26734
27016
  openClientForm(client, options = {}) {
26735
27017
  return openHelpDeskForm(client, { ...options, backdropBlur: this.config.backdropBlur });
26736
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
+ }
26737
27033
  /** Bind existing support buttons, including ones added later. Cleanup closes this binding's form. */
26738
27034
  attach(selector, options) {
26739
27035
  let disposed = false;
@@ -31452,7 +31748,7 @@ class SparkVault {
31452
31748
  }
31453
31749
  /** Get the SDK version */
31454
31750
  static get version() {
31455
- return '16.12.1';
31751
+ return '17.0.0';
31456
31752
  }
31457
31753
  }
31458
31754
  if (typeof window !== 'undefined') {