@sparkvault/sdk-js 16.12.0 → 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.mjs CHANGED
@@ -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`, {
@@ -21723,6 +21835,7 @@ function mountHelpDeskForm(client, options) {
21723
21835
  }
21724
21836
  const ownGeneration = generation;
21725
21837
  let ticketAttempted = false;
21838
+ let installed = false;
21726
21839
  pending = true;
21727
21840
  disable(true);
21728
21841
  message('');
@@ -21751,8 +21864,10 @@ function mountHelpDeskForm(client, options) {
21751
21864
  sessionChanged();
21752
21865
  return;
21753
21866
  }
21754
- if (session)
21867
+ if (session) {
21755
21868
  client.setSession(session);
21869
+ installed = true;
21870
+ }
21756
21871
  token = await client.getSessionToken();
21757
21872
  sessionToken = token;
21758
21873
  sessionKnown = true;
@@ -21949,6 +22064,15 @@ function mountHelpDeskForm(client, options) {
21949
22064
  notify$1(options.onError, error);
21950
22065
  }
21951
22066
  finally {
22067
+ // A session the secure window redeemed that this form did not install
22068
+ // (it left, or the customer changed meanwhile) is revoked: no one else
22069
+ // holds its bearer.
22070
+ if (widgetSignIn && !installed) {
22071
+ void widgetSignIn.then((session) => client.discardSession(session), () => undefined).catch((failure) => {
22072
+ if (!destroyed)
22073
+ notify$1(options.onError, failure instanceof Error ? failure : new Error('The unused sign-in could not be ended.'));
22074
+ });
22075
+ }
21952
22076
  if (alive(ownGeneration)) {
21953
22077
  authenticating = false;
21954
22078
  pending = false;
@@ -25846,6 +25970,7 @@ class SupportView {
25846
25970
  }
25847
25971
  }
25848
25972
 
25973
+ const STILL_LOADING = 'Support is still loading. Please try again.';
25849
25974
  function notify(callback, value) {
25850
25975
  try {
25851
25976
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -25878,9 +26003,22 @@ function createHelpDeskSupport(config, options) {
25878
26003
  // to a signed-out form, a Switch account or Use website account to the
25879
26004
  // account arrived at.
25880
26005
  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.
26006
+ // Another account's session, or the website's, is taking the old one's
26007
+ // place: the host hears the session arrived at, never the signed-out moment
26008
+ // between the two.
25883
26009
  let replacingSession = false;
26010
+ // A Use website account that a ticket gate held up: the website's identity
26011
+ // is asked, and the host told where support arrived, at support's next
26012
+ // session lookup (`lookUpSession`). It concerns the client's session, not
26013
+ // the journey, so only another account change ends it.
26014
+ let websiteArrivalDue = false;
26015
+ // The session lookups in flight (`lookUpSession`), and whether the client
26016
+ // said a clear aloud meanwhile. The clear is held rather than told at once,
26017
+ // and the first lookup to settle takes it, so the host hears it once: that
26018
+ // lookup's caller tells the host where support arrived, which may be a
26019
+ // session put in its place.
26020
+ let lookupsInFlight = 0;
26021
+ let heldClear = false;
25884
26022
  // The issue, as written, that the held composition (the mounted form, the one
25885
26023
  // a re-authorized form will take, or the one saved before a reload) was last
25886
26024
  // filled from: '' for one filled from none. A form taking that composition is
@@ -25992,13 +26130,17 @@ function createHelpDeskSupport(config, options) {
25992
26130
  }
25993
26131
  async function connect() {
25994
26132
  if (!connected)
25995
- connected = HelpDeskClient.connect(config, options).then((answer) => {
26133
+ connected = HelpDeskClient.connect(config, { ...options, onDiscardError: reportLostRevocation }).then((answer) => {
25996
26134
  if (destroyed)
25997
26135
  throw new Error('Support is closed.');
25998
26136
  client = answer;
25999
26137
  stopSession = answer.subscribeSession((change) => {
26000
- if (change.source === 'clear' && !replacingSession)
26138
+ if (change.source !== 'clear' || replacingSession)
26139
+ return;
26140
+ if (lookupsInFlight === 0)
26001
26141
  notify(options.onSession, null);
26142
+ else
26143
+ heldClear = true;
26002
26144
  });
26003
26145
  kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
26004
26146
  analytics = createSupportAnalytics({
@@ -26029,7 +26171,9 @@ function createHelpDeskSupport(config, options) {
26029
26171
  }
26030
26172
  if (!options.persist || destroyed || state.stage !== 'issue')
26031
26173
  return;
26032
- const token = await active.getSessionToken();
26174
+ const { token, arrival } = await lookUpSession(active);
26175
+ if (arrival !== undefined)
26176
+ tellHost(arrival);
26033
26177
  if (destroyed)
26034
26178
  return;
26035
26179
  anonymous = !token;
@@ -26139,7 +26283,7 @@ function createHelpDeskSupport(config, options) {
26139
26283
  }
26140
26284
  function signIn(input = {}) {
26141
26285
  if (!client)
26142
- return Promise.reject(new Error('Support is still loading. Please try again.'));
26286
+ return Promise.reject(new Error(STILL_LOADING));
26143
26287
  nativeIdentity?.abort();
26144
26288
  const operation = new AbortController();
26145
26289
  nativeIdentity = operation;
@@ -26156,6 +26300,81 @@ function createHelpDeskSupport(config, options) {
26156
26300
  }
26157
26301
  });
26158
26302
  }
26303
+ /**
26304
+ * Revoke a session a sign-in redeemed that support will not install, through
26305
+ * the client the sign-in started on (support's own is gone once destroyed):
26306
+ * nobody else holds its bearer.
26307
+ */
26308
+ function discard(active, session) {
26309
+ void active.discardSession(session).catch(reportLostRevocation);
26310
+ }
26311
+ /**
26312
+ * A refused or lost revocation, of a session support let go of or one its
26313
+ * client let go of unused (`onDiscardError`), reaches the host while
26314
+ * support is open; the customer's journey goes on all the same.
26315
+ */
26316
+ function reportLostRevocation(value) {
26317
+ if (!destroyed)
26318
+ notify(options.onError, failure(value));
26319
+ }
26320
+ /**
26321
+ * Tell the host the session Use website account brought support to, or null
26322
+ * for none. Only the website's identity signs support in to a session the
26323
+ * host does not hold: a host that lends one (getSessionToken) is never told
26324
+ * of it, as on mount, since a null would make it drop the very session
26325
+ * support goes back to; one lending back the switched-to session it kept
26326
+ * hears from the client that it ended.
26327
+ */
26328
+ function reportWebsiteArrival(active, session) {
26329
+ if (active.hasIdentityProvider)
26330
+ tellHost(session);
26331
+ }
26332
+ function tellHost(session) {
26333
+ if (!destroyed)
26334
+ notify(options.onSession, session);
26335
+ }
26336
+ /**
26337
+ * Support's session lookup, with where support arrived (`arrival`) when the
26338
+ * host has that to hear, for the caller to tell it once (`tellHost`), or to
26339
+ * tell it of the session it puts in place instead. The first lookup after a
26340
+ * Use website account that a ticket gate held up (contact's, once the gate
26341
+ * opens, or a reopened support's) is where the website's identity signs
26342
+ * support back in, as the return itself does ungated; any other lookup's
26343
+ * arrival is the null of a clear the client said aloud meanwhile, such as
26344
+ * its refusal of a lent bearer it let go of, so that the host drops it.
26345
+ */
26346
+ async function lookUpSession(active) {
26347
+ if (websiteArrivalDue) {
26348
+ websiteArrivalDue = false;
26349
+ let arrived;
26350
+ try {
26351
+ arrived = await active.authenticate();
26352
+ }
26353
+ catch (value) {
26354
+ tellHost(null);
26355
+ throw value;
26356
+ }
26357
+ return { token: arrived?.token ?? null, arrival: arrived };
26358
+ }
26359
+ lookupsInFlight += 1;
26360
+ try {
26361
+ const token = await active.getSessionToken();
26362
+ return takeHeldClear() ? { token, arrival: null } : { token };
26363
+ }
26364
+ catch (value) {
26365
+ if (takeHeldClear())
26366
+ tellHost(null);
26367
+ throw value;
26368
+ }
26369
+ finally {
26370
+ lookupsInFlight -= 1;
26371
+ }
26372
+ }
26373
+ function takeHeldClear() {
26374
+ const cleared = heldClear;
26375
+ heldClear = false;
26376
+ return cleared;
26377
+ }
26159
26378
  function startAttempt(available, releaseId, resultCount) {
26160
26379
  if (!analytics)
26161
26380
  return Promise.resolve(null);
@@ -26218,11 +26437,19 @@ function createHelpDeskSupport(config, options) {
26218
26437
  if (password !== undefined)
26219
26438
  await kb.unlock({ password });
26220
26439
  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.');
26440
+ // A platform grant proves employee access independently of the host's
26441
+ // ticket identity, so the support session the sign-in also opens is
26442
+ // never installed.
26443
+ const active = client;
26444
+ if (!active)
26445
+ throw new Error(STILL_LOADING);
26224
26446
  const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
26225
- await kb.unlock({ identity_grant: session.identity_grant.token });
26447
+ try {
26448
+ await kb.unlock({ identity_grant: session.identity_grant.token });
26449
+ }
26450
+ finally {
26451
+ discard(active, session);
26452
+ }
26226
26453
  }
26227
26454
  if (destroyed || ownSequence !== sequence)
26228
26455
  return;
@@ -26402,7 +26629,12 @@ function createHelpDeskSupport(config, options) {
26402
26629
  clearSupportIssue(client.desk.desk_id);
26403
26630
  update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
26404
26631
  }
26405
- async function showContact(reason) {
26632
+ /**
26633
+ * Open the contact step for `reason`. `carried` is the message of the failure
26634
+ * that led here, which stays in view until the customer's next action; an
26635
+ * error from any earlier step is cleared.
26636
+ */
26637
+ async function showContact(reason, carried) {
26406
26638
  if (destroyed || contactOpening === sequence)
26407
26639
  return;
26408
26640
  if (reason === 'article_not_answered' && state.article) {
@@ -26421,7 +26653,7 @@ function createHelpDeskSupport(config, options) {
26421
26653
  }
26422
26654
  if (reason !== 'direct')
26423
26655
  void attempt?.then((active) => active?.contactRequested(reason));
26424
- update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
26656
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: carried });
26425
26657
  const ownSequence = ++sequence;
26426
26658
  contactOpening = ownSequence;
26427
26659
  try {
@@ -26441,7 +26673,9 @@ function createHelpDeskSupport(config, options) {
26441
26673
  view.focusContact();
26442
26674
  return;
26443
26675
  }
26444
- const token = await active.getSessionToken();
26676
+ const { token, arrival } = await lookUpSession(active);
26677
+ if (arrival !== undefined)
26678
+ tellHost(arrival);
26445
26679
  const customer = token ? await active.getMe() : null;
26446
26680
  if (destroyed || ownSequence !== sequence)
26447
26681
  return;
@@ -26487,11 +26721,25 @@ function createHelpDeskSupport(config, options) {
26487
26721
  notify(options.onTicketAccess, await active.unlockTicketAccess({ password }));
26488
26722
  else if (identity) {
26489
26723
  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);
26724
+ let installed = false;
26725
+ try {
26726
+ notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26727
+ // A customer session already in place keeps it, the sign-in serving
26728
+ // its employee grant alone; a closed support signs no one in. The
26729
+ // host hears once where support arrives: the employee session put
26730
+ // in place of none, or the lookup's own arrival.
26731
+ const { token, arrival } = await lookUpSession(active);
26732
+ if (!token && !destroyed) {
26733
+ active.setSession(session);
26734
+ installed = true;
26735
+ }
26736
+ const arrived = installed ? session : arrival;
26737
+ if (arrived !== undefined)
26738
+ tellHost(arrived);
26739
+ }
26740
+ finally {
26741
+ if (!installed)
26742
+ discard(active, session);
26495
26743
  }
26496
26744
  }
26497
26745
  else
@@ -26528,6 +26776,7 @@ function createHelpDeskSupport(config, options) {
26528
26776
  pendingComposition = composition ? { subject: composition.subject, body: composition.body } : { subject: '', body: '' };
26529
26777
  pendingRecovery = null;
26530
26778
  pendingArrival = null;
26779
+ websiteArrivalDue = false;
26531
26780
  kb?.clearAccess();
26532
26781
  kbConfig = null;
26533
26782
  results = [];
@@ -26543,13 +26792,20 @@ function createHelpDeskSupport(config, options) {
26543
26792
  */
26544
26793
  function switchAccount(composition) {
26545
26794
  const form = contact;
26546
- const policy = client?.ticketAccessPolicy;
26795
+ const active = client;
26796
+ if (!active)
26797
+ return Promise.reject(new Error(STILL_LOADING));
26798
+ const policy = active.ticketAccessPolicy;
26547
26799
  // Open synchronously in the Switch account gesture, before anything is awaited.
26548
26800
  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)
26801
+ // Support was destroyed while the chooser was open (the form stays
26802
+ // locked meanwhile, so no other change replaces it): nothing waits on
26803
+ // this account, so its session ends here.
26804
+ if (destroyed || contact !== form) {
26805
+ discard(active, session);
26551
26806
  return;
26552
- return replaceAccount(client, session, composition);
26807
+ }
26808
+ return replaceAccount(active, session, composition);
26553
26809
  });
26554
26810
  }
26555
26811
  /**
@@ -26569,22 +26825,26 @@ function createHelpDeskSupport(config, options) {
26569
26825
  const released = active.switchSupportAccount();
26570
26826
  replacingSession = false;
26571
26827
  // A refused or lost revocation leaves the chosen account in place.
26572
- void released.catch((value) => notify(options.onError, failure(value)));
26828
+ void released.catch(reportLostRevocation);
26573
26829
  active.setSession(session);
26574
26830
  notify(options.onSession, session);
26831
+ let refusal;
26575
26832
  if (active.ticketAccessPolicy?.mode === 'identity') {
26576
- // Without this grant, contact's access check shows the employee gate for the chosen account.
26833
+ // Without this grant, contact's access check shows the employee gate
26834
+ // for the chosen account, which then says why it was refused.
26577
26835
  try {
26578
26836
  notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26579
26837
  }
26580
26838
  catch (value) {
26839
+ const error = failure(value);
26840
+ refusal = error.message;
26581
26841
  if (!destroyed && ownSequence === sequence)
26582
- notify(options.onError, failure(value));
26842
+ notify(options.onError, error);
26583
26843
  }
26584
26844
  }
26585
26845
  if (destroyed || ownSequence !== sequence)
26586
26846
  return;
26587
- await showContact('direct');
26847
+ await showContact('direct', refusal);
26588
26848
  }
26589
26849
  /**
26590
26850
  * Sign out of support from the contact form, without a window: the session
@@ -26602,31 +26862,44 @@ function createHelpDeskSupport(config, options) {
26602
26862
  update({ error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26603
26863
  // The session ends here at once, and the host hears so; a refused or lost
26604
26864
  // revocation leaves this browser signed out all the same.
26605
- void active.signOutSupport().catch((value) => notify(options.onError, failure(value)));
26865
+ void active.signOutSupport().catch(reportLostRevocation);
26606
26866
  // A host that keeps the session cleans up after it as its own sign-out does.
26607
26867
  const host = options.hostKeepsSession;
26608
26868
  notify(host ? () => host.onSignOut() : undefined, undefined);
26609
26869
  void showContact('direct');
26610
26870
  }
26871
+ /**
26872
+ * Use website account from the contact form: the session switched to is
26873
+ * released and the website's identity resumed, and the host hears once which
26874
+ * session support arrived at, never the signed-out moment between.
26875
+ */
26611
26876
  async function useWebsiteAccount(composition, recovering = false) {
26612
26877
  if (!client || destroyed || state.navigationLocked)
26613
26878
  return;
26879
+ const active = client;
26614
26880
  const ownSequence = ++sequence;
26615
26881
  leaveCustomer(composition);
26616
26882
  pendingRecovery = recovering ? { websiteSignedOut: true } : null;
26617
26883
  update({ busy: true, error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26884
+ // The release clears the switched-to session at once, before the website
26885
+ // is asked; its revocation goes behind, as a switch's does.
26886
+ replacingSession = true;
26887
+ const { released, resumed } = active.returnToWebsiteAccount();
26888
+ replacingSession = false;
26889
+ // The return decides at once whether a ticket gate stands (its release
26890
+ // ends a password's or an employee proof's access): a standing gate asks
26891
+ // the website nothing yet, so the arrival waits for support's next
26892
+ // session lookup (`lookUpSession`).
26893
+ const gated = !active.hasTicketAccess;
26894
+ websiteArrivalDue = gated && active.hasIdentityProvider;
26895
+ void released.catch(reportLostRevocation);
26896
+ let arrived;
26618
26897
  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');
26898
+ arrived = await resumed;
26628
26899
  }
26629
26900
  catch (value) {
26901
+ if (!gated)
26902
+ reportWebsiteArrival(active, null);
26630
26903
  if (destroyed || ownSequence !== sequence)
26631
26904
  return;
26632
26905
  const error = failure(value);
@@ -26634,13 +26907,24 @@ function createHelpDeskSupport(config, options) {
26634
26907
  // The website was not reached, so it is not known to have no account.
26635
26908
  if (pendingRecovery)
26636
26909
  pendingRecovery = { websiteSignedOut: false };
26637
- if (client.hasTicketAccess) {
26910
+ if (active.hasTicketAccess) {
26638
26911
  mountContact(pendingComposition, null);
26639
26912
  pendingComposition = null;
26640
26913
  }
26641
26914
  else
26642
- await showContact('direct');
26915
+ await showContact('direct', error.message);
26916
+ return;
26643
26917
  }
26918
+ if (!gated)
26919
+ reportWebsiteArrival(active, arrived);
26920
+ if (destroyed || ownSequence !== sequence)
26921
+ return;
26922
+ switchedAccount = false;
26923
+ // The website account the form arrives at says so, as a switch does; one
26924
+ // the website does not give back gets none (`mountContact`).
26925
+ pendingArrival = { from: 'switch', droppedFiles: composition?.hadFiles === true };
26926
+ update({ busy: false });
26927
+ await showContact('direct');
26644
26928
  }
26645
26929
  function receipt(ticket) {
26646
26930
  const customer = contactCustomer;
@@ -26713,23 +26997,35 @@ class HelpDeskModule {
26713
26997
  * enables it. A custom onAuthRequired callback may supply a server-issued
26714
26998
  * help desk session. Destroy the returned handle on unmount/account change.
26715
26999
  */
26716
- async mountForm(options) {
26717
- const client = await this.connect(options);
26718
- return mountHelpDeskForm(client, options);
27000
+ mountForm(options) {
27001
+ return this.connectForm(options, (client) => mountHelpDeskForm(client, options));
26719
27002
  }
26720
27003
  /** Inject a form over an already-connected client that the host also drives headlessly. */
26721
27004
  mountClientForm(client, options) {
26722
27005
  return mountHelpDeskForm(client, options);
26723
27006
  }
26724
27007
  /** 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);
27008
+ openForm(options) {
27009
+ return this.connectForm(options, (client) => this.openClientForm(client, options));
26728
27010
  }
26729
27011
  /** Open a modal over a client whose company session the host also drives headlessly. */
26730
27012
  openClientForm(client, options = {}) {
26731
27013
  return openHelpDeskForm(client, { ...options, backdropBlur: this.config.backdropBlur });
26732
27014
  }
27015
+ /**
27016
+ * Connect the client one of this module's own forms opens over: a lost
27017
+ * revocation of a session the client let go of unused reaches the form's
27018
+ * `onError` while the form stands, as the form reports its own.
27019
+ */
27020
+ async connectForm(options, open) {
27021
+ let form = null;
27022
+ const client = await this.connect({ ...options, onDiscardError: (error) => {
27023
+ if (form && form.getState() !== 'destroyed')
27024
+ void Promise.resolve(options.onError?.(error)).catch(() => undefined);
27025
+ } });
27026
+ form = open(client);
27027
+ return form;
27028
+ }
26733
27029
  /** Bind existing support buttons, including ones added later. Cleanup closes this binding's form. */
26734
27030
  attach(selector, options) {
26735
27031
  let disposed = false;
@@ -31448,7 +31744,7 @@ class SparkVault {
31448
31744
  }
31449
31745
  /** Get the SDK version */
31450
31746
  static get version() {
31451
- return '16.12.0';
31747
+ return '17.0.0';
31452
31748
  }
31453
31749
  }
31454
31750
  if (typeof window !== 'undefined') {