@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.cjs CHANGED
@@ -7137,12 +7137,12 @@ class OriginNotAllowedView {
7137
7137
  const title = document.createElement('h2');
7138
7138
  title.className = 'sv-not-activated-title';
7139
7139
  title.id = 'sv-modal-title';
7140
- title.textContent = 'This domain isn’t allowed';
7140
+ title.textContent = 'This domain isn\'t allowed';
7141
7141
  container.appendChild(title);
7142
7142
  const message = document.createElement('p');
7143
7143
  message.className = 'sv-not-activated-message';
7144
7144
  message.textContent =
7145
- 'Sign-in is blocked because this website’s domain is not on the SparkVault Identity allowlist for this account.';
7145
+ 'Sign-in is blocked because this website\'s domain is not on the SparkVault Identity allowlist for this account.';
7146
7146
  container.appendChild(message);
7147
7147
  const ownerCard = div('sv-not-activated-owner');
7148
7148
  const ownerLabel = document.createElement('span');
@@ -7154,7 +7154,7 @@ class OriginNotAllowedView {
7154
7154
  // trust it into the DOM as markup.
7155
7155
  ownerHint.textContent = this.props.origin
7156
7156
  ? `Add ${this.props.origin} to your verified domains in SparkVault, then reload this page.`
7157
- : 'Add this website’s domain to your verified domains in SparkVault, then reload this page.';
7157
+ : 'Add this website\'s domain to your verified domains in SparkVault, then reload this page.';
7158
7158
  ownerCard.appendChild(ownerLabel);
7159
7159
  ownerCard.appendChild(ownerHint);
7160
7160
  container.appendChild(ownerCard);
@@ -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`, {
@@ -18794,14 +18906,18 @@ function injectHelpDeskFormStyles() {
18794
18906
  * offsets it reported along the way. A transfer whose bytes all arrived
18795
18907
  * while the vault was still saving (`received`: the SDK throws
18796
18908
  * RECEIVED_STILL_SAVING from ./transfer-retry.js for it) shows the file
18797
- * stored and the check still to come. Both clients attach such a file as it
18798
- * is, and the server, which alone learns when the file is stored, refuses a
18799
- * message sent before then in its own words.
18909
+ * stored and the check still to come. The server refuses a message naming
18910
+ * such a file, so neither client attaches it until a check of its upload
18911
+ * confirms it stored, and both hold the message meanwhile in one sentence
18912
+ * (STORING_HOLD_COPY).
18800
18913
  *
18801
18914
  * BROWSER-SAFE: pure data, no Node built-ins.
18802
18915
  */
18803
18916
 
18804
18917
 
18918
+ /** What holds a message back while one of its files is received and not yet confirmed stored. */
18919
+ const STORING_HOLD_COPY = 'A file is still being stored. Check its upload in a moment, or remove it.';
18920
+
18805
18921
  /** A step's state. */
18806
18922
  const CEREMONY_STEP_STATUS = Object.freeze({ PENDING: 'pending', ACTIVE: 'active', COMPLETE: 'complete' });
18807
18923
 
@@ -19914,7 +20030,7 @@ const ACCEPTED_KINDS_COPY = `You can attach ${ACCEPTED_ATTACHMENTS_COPY}.`;
19914
20030
  /** What a message's files still need before it can be sent, from the most pressing. */
19915
20031
  const HOLD_COPY = Object.freeze({
19916
20032
  uploading: 'Your files are still uploading.',
19917
- storing: 'A file is still being stored. Check its upload in a moment, or remove it.',
20033
+ storing: STORING_HOLD_COPY,
19918
20034
  retryable: "Remove the files that couldn't be attached, or try them again.",
19919
20035
  refused: "Remove the files that can't be attached."
19920
20036
  });
@@ -21727,6 +21843,7 @@ function mountHelpDeskForm(client, options) {
21727
21843
  }
21728
21844
  const ownGeneration = generation;
21729
21845
  let ticketAttempted = false;
21846
+ let installed = false;
21730
21847
  pending = true;
21731
21848
  disable(true);
21732
21849
  message('');
@@ -21755,8 +21872,10 @@ function mountHelpDeskForm(client, options) {
21755
21872
  sessionChanged();
21756
21873
  return;
21757
21874
  }
21758
- if (session)
21875
+ if (session) {
21759
21876
  client.setSession(session);
21877
+ installed = true;
21878
+ }
21760
21879
  token = await client.getSessionToken();
21761
21880
  sessionToken = token;
21762
21881
  sessionKnown = true;
@@ -21953,6 +22072,15 @@ function mountHelpDeskForm(client, options) {
21953
22072
  notify$1(options.onError, error);
21954
22073
  }
21955
22074
  finally {
22075
+ // A session the secure window redeemed that this form did not install
22076
+ // (it left, or the customer changed meanwhile) is revoked: no one else
22077
+ // holds its bearer.
22078
+ if (widgetSignIn && !installed) {
22079
+ void widgetSignIn.then((session) => client.discardSession(session), () => undefined).catch((failure) => {
22080
+ if (!destroyed)
22081
+ notify$1(options.onError, failure instanceof Error ? failure : new Error('The unused sign-in could not be ended.'));
22082
+ });
22083
+ }
21956
22084
  if (alive(ownGeneration)) {
21957
22085
  authenticating = false;
21958
22086
  pending = false;
@@ -25850,6 +25978,7 @@ class SupportView {
25850
25978
  }
25851
25979
  }
25852
25980
 
25981
+ const STILL_LOADING = 'Support is still loading. Please try again.';
25853
25982
  function notify(callback, value) {
25854
25983
  try {
25855
25984
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -25882,9 +26011,22 @@ function createHelpDeskSupport(config, options) {
25882
26011
  // to a signed-out form, a Switch account or Use website account to the
25883
26012
  // account arrived at.
25884
26013
  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.
26014
+ // Another account's session, or the website's, is taking the old one's
26015
+ // place: the host hears the session arrived at, never the signed-out moment
26016
+ // between the two.
25887
26017
  let replacingSession = false;
26018
+ // A Use website account that a ticket gate held up: the website's identity
26019
+ // is asked, and the host told where support arrived, at support's next
26020
+ // session lookup (`lookUpSession`). It concerns the client's session, not
26021
+ // the journey, so only another account change ends it.
26022
+ let websiteArrivalDue = false;
26023
+ // The session lookups in flight (`lookUpSession`), and whether the client
26024
+ // said a clear aloud meanwhile. The clear is held rather than told at once,
26025
+ // and the first lookup to settle takes it, so the host hears it once: that
26026
+ // lookup's caller tells the host where support arrived, which may be a
26027
+ // session put in its place.
26028
+ let lookupsInFlight = 0;
26029
+ let heldClear = false;
25888
26030
  // The issue, as written, that the held composition (the mounted form, the one
25889
26031
  // a re-authorized form will take, or the one saved before a reload) was last
25890
26032
  // filled from: '' for one filled from none. A form taking that composition is
@@ -25996,13 +26138,17 @@ function createHelpDeskSupport(config, options) {
25996
26138
  }
25997
26139
  async function connect() {
25998
26140
  if (!connected)
25999
- connected = HelpDeskClient.connect(config, options).then((answer) => {
26141
+ connected = HelpDeskClient.connect(config, { ...options, onDiscardError: reportLostRevocation }).then((answer) => {
26000
26142
  if (destroyed)
26001
26143
  throw new Error('Support is closed.');
26002
26144
  client = answer;
26003
26145
  stopSession = answer.subscribeSession((change) => {
26004
- if (change.source === 'clear' && !replacingSession)
26146
+ if (change.source !== 'clear' || replacingSession)
26147
+ return;
26148
+ if (lookupsInFlight === 0)
26005
26149
  notify(options.onSession, null);
26150
+ else
26151
+ heldClear = true;
26006
26152
  });
26007
26153
  kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
26008
26154
  analytics = createSupportAnalytics({
@@ -26033,7 +26179,9 @@ function createHelpDeskSupport(config, options) {
26033
26179
  }
26034
26180
  if (!options.persist || destroyed || state.stage !== 'issue')
26035
26181
  return;
26036
- const token = await active.getSessionToken();
26182
+ const { token, arrival } = await lookUpSession(active);
26183
+ if (arrival !== undefined)
26184
+ tellHost(arrival);
26037
26185
  if (destroyed)
26038
26186
  return;
26039
26187
  anonymous = !token;
@@ -26143,7 +26291,7 @@ function createHelpDeskSupport(config, options) {
26143
26291
  }
26144
26292
  function signIn(input = {}) {
26145
26293
  if (!client)
26146
- return Promise.reject(new Error('Support is still loading. Please try again.'));
26294
+ return Promise.reject(new Error(STILL_LOADING));
26147
26295
  nativeIdentity?.abort();
26148
26296
  const operation = new AbortController();
26149
26297
  nativeIdentity = operation;
@@ -26160,6 +26308,81 @@ function createHelpDeskSupport(config, options) {
26160
26308
  }
26161
26309
  });
26162
26310
  }
26311
+ /**
26312
+ * Revoke a session a sign-in redeemed that support will not install, through
26313
+ * the client the sign-in started on (support's own is gone once destroyed):
26314
+ * nobody else holds its bearer.
26315
+ */
26316
+ function discard(active, session) {
26317
+ void active.discardSession(session).catch(reportLostRevocation);
26318
+ }
26319
+ /**
26320
+ * A refused or lost revocation, of a session support let go of or one its
26321
+ * client let go of unused (`onDiscardError`), reaches the host while
26322
+ * support is open; the customer's journey goes on all the same.
26323
+ */
26324
+ function reportLostRevocation(value) {
26325
+ if (!destroyed)
26326
+ notify(options.onError, failure(value));
26327
+ }
26328
+ /**
26329
+ * Tell the host the session Use website account brought support to, or null
26330
+ * for none. Only the website's identity signs support in to a session the
26331
+ * host does not hold: a host that lends one (getSessionToken) is never told
26332
+ * of it, as on mount, since a null would make it drop the very session
26333
+ * support goes back to; one lending back the switched-to session it kept
26334
+ * hears from the client that it ended.
26335
+ */
26336
+ function reportWebsiteArrival(active, session) {
26337
+ if (active.hasIdentityProvider)
26338
+ tellHost(session);
26339
+ }
26340
+ function tellHost(session) {
26341
+ if (!destroyed)
26342
+ notify(options.onSession, session);
26343
+ }
26344
+ /**
26345
+ * Support's session lookup, with where support arrived (`arrival`) when the
26346
+ * host has that to hear, for the caller to tell it once (`tellHost`), or to
26347
+ * tell it of the session it puts in place instead. The first lookup after a
26348
+ * Use website account that a ticket gate held up (contact's, once the gate
26349
+ * opens, or a reopened support's) is where the website's identity signs
26350
+ * support back in, as the return itself does ungated; any other lookup's
26351
+ * arrival is the null of a clear the client said aloud meanwhile, such as
26352
+ * its refusal of a lent bearer it let go of, so that the host drops it.
26353
+ */
26354
+ async function lookUpSession(active) {
26355
+ if (websiteArrivalDue) {
26356
+ websiteArrivalDue = false;
26357
+ let arrived;
26358
+ try {
26359
+ arrived = await active.authenticate();
26360
+ }
26361
+ catch (value) {
26362
+ tellHost(null);
26363
+ throw value;
26364
+ }
26365
+ return { token: arrived?.token ?? null, arrival: arrived };
26366
+ }
26367
+ lookupsInFlight += 1;
26368
+ try {
26369
+ const token = await active.getSessionToken();
26370
+ return takeHeldClear() ? { token, arrival: null } : { token };
26371
+ }
26372
+ catch (value) {
26373
+ if (takeHeldClear())
26374
+ tellHost(null);
26375
+ throw value;
26376
+ }
26377
+ finally {
26378
+ lookupsInFlight -= 1;
26379
+ }
26380
+ }
26381
+ function takeHeldClear() {
26382
+ const cleared = heldClear;
26383
+ heldClear = false;
26384
+ return cleared;
26385
+ }
26163
26386
  function startAttempt(available, releaseId, resultCount) {
26164
26387
  if (!analytics)
26165
26388
  return Promise.resolve(null);
@@ -26222,11 +26445,19 @@ function createHelpDeskSupport(config, options) {
26222
26445
  if (password !== undefined)
26223
26446
  await kb.unlock({ password });
26224
26447
  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.');
26448
+ // A platform grant proves employee access independently of the host's
26449
+ // ticket identity, so the support session the sign-in also opens is
26450
+ // never installed.
26451
+ const active = client;
26452
+ if (!active)
26453
+ throw new Error(STILL_LOADING);
26228
26454
  const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
26229
- await kb.unlock({ identity_grant: session.identity_grant.token });
26455
+ try {
26456
+ await kb.unlock({ identity_grant: session.identity_grant.token });
26457
+ }
26458
+ finally {
26459
+ discard(active, session);
26460
+ }
26230
26461
  }
26231
26462
  if (destroyed || ownSequence !== sequence)
26232
26463
  return;
@@ -26406,7 +26637,12 @@ function createHelpDeskSupport(config, options) {
26406
26637
  clearSupportIssue(client.desk.desk_id);
26407
26638
  update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
26408
26639
  }
26409
- async function showContact(reason) {
26640
+ /**
26641
+ * Open the contact step for `reason`. `carried` is the message of the failure
26642
+ * that led here, which stays in view until the customer's next action; an
26643
+ * error from any earlier step is cleared.
26644
+ */
26645
+ async function showContact(reason, carried) {
26410
26646
  if (destroyed || contactOpening === sequence)
26411
26647
  return;
26412
26648
  if (reason === 'article_not_answered' && state.article) {
@@ -26425,7 +26661,7 @@ function createHelpDeskSupport(config, options) {
26425
26661
  }
26426
26662
  if (reason !== 'direct')
26427
26663
  void attempt?.then((active) => active?.contactRequested(reason));
26428
- update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
26664
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: carried });
26429
26665
  const ownSequence = ++sequence;
26430
26666
  contactOpening = ownSequence;
26431
26667
  try {
@@ -26445,7 +26681,9 @@ function createHelpDeskSupport(config, options) {
26445
26681
  view.focusContact();
26446
26682
  return;
26447
26683
  }
26448
- const token = await active.getSessionToken();
26684
+ const { token, arrival } = await lookUpSession(active);
26685
+ if (arrival !== undefined)
26686
+ tellHost(arrival);
26449
26687
  const customer = token ? await active.getMe() : null;
26450
26688
  if (destroyed || ownSequence !== sequence)
26451
26689
  return;
@@ -26491,11 +26729,25 @@ function createHelpDeskSupport(config, options) {
26491
26729
  notify(options.onTicketAccess, await active.unlockTicketAccess({ password }));
26492
26730
  else if (identity) {
26493
26731
  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);
26732
+ let installed = false;
26733
+ try {
26734
+ notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26735
+ // A customer session already in place keeps it, the sign-in serving
26736
+ // its employee grant alone; a closed support signs no one in. The
26737
+ // host hears once where support arrives: the employee session put
26738
+ // in place of none, or the lookup's own arrival.
26739
+ const { token, arrival } = await lookUpSession(active);
26740
+ if (!token && !destroyed) {
26741
+ active.setSession(session);
26742
+ installed = true;
26743
+ }
26744
+ const arrived = installed ? session : arrival;
26745
+ if (arrived !== undefined)
26746
+ tellHost(arrived);
26747
+ }
26748
+ finally {
26749
+ if (!installed)
26750
+ discard(active, session);
26499
26751
  }
26500
26752
  }
26501
26753
  else
@@ -26532,6 +26784,7 @@ function createHelpDeskSupport(config, options) {
26532
26784
  pendingComposition = composition ? { subject: composition.subject, body: composition.body } : { subject: '', body: '' };
26533
26785
  pendingRecovery = null;
26534
26786
  pendingArrival = null;
26787
+ websiteArrivalDue = false;
26535
26788
  kb?.clearAccess();
26536
26789
  kbConfig = null;
26537
26790
  results = [];
@@ -26547,13 +26800,20 @@ function createHelpDeskSupport(config, options) {
26547
26800
  */
26548
26801
  function switchAccount(composition) {
26549
26802
  const form = contact;
26550
- const policy = client?.ticketAccessPolicy;
26803
+ const active = client;
26804
+ if (!active)
26805
+ return Promise.reject(new Error(STILL_LOADING));
26806
+ const policy = active.ticketAccessPolicy;
26551
26807
  // Open synchronously in the Switch account gesture, before anything is awaited.
26552
26808
  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)
26809
+ // Support was destroyed while the chooser was open (the form stays
26810
+ // locked meanwhile, so no other change replaces it): nothing waits on
26811
+ // this account, so its session ends here.
26812
+ if (destroyed || contact !== form) {
26813
+ discard(active, session);
26555
26814
  return;
26556
- return replaceAccount(client, session, composition);
26815
+ }
26816
+ return replaceAccount(active, session, composition);
26557
26817
  });
26558
26818
  }
26559
26819
  /**
@@ -26573,22 +26833,26 @@ function createHelpDeskSupport(config, options) {
26573
26833
  const released = active.switchSupportAccount();
26574
26834
  replacingSession = false;
26575
26835
  // A refused or lost revocation leaves the chosen account in place.
26576
- void released.catch((value) => notify(options.onError, failure(value)));
26836
+ void released.catch(reportLostRevocation);
26577
26837
  active.setSession(session);
26578
26838
  notify(options.onSession, session);
26839
+ let refusal;
26579
26840
  if (active.ticketAccessPolicy?.mode === 'identity') {
26580
- // Without this grant, contact's access check shows the employee gate for the chosen account.
26841
+ // Without this grant, contact's access check shows the employee gate
26842
+ // for the chosen account, which then says why it was refused.
26581
26843
  try {
26582
26844
  notify(options.onTicketAccess, await active.unlockTicketAccess({ identityGrant: session.identity_grant.token }));
26583
26845
  }
26584
26846
  catch (value) {
26847
+ const error = failure(value);
26848
+ refusal = error.message;
26585
26849
  if (!destroyed && ownSequence === sequence)
26586
- notify(options.onError, failure(value));
26850
+ notify(options.onError, error);
26587
26851
  }
26588
26852
  }
26589
26853
  if (destroyed || ownSequence !== sequence)
26590
26854
  return;
26591
- await showContact('direct');
26855
+ await showContact('direct', refusal);
26592
26856
  }
26593
26857
  /**
26594
26858
  * Sign out of support from the contact form, without a window: the session
@@ -26606,31 +26870,44 @@ function createHelpDeskSupport(config, options) {
26606
26870
  update({ error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26607
26871
  // The session ends here at once, and the host hears so; a refused or lost
26608
26872
  // revocation leaves this browser signed out all the same.
26609
- void active.signOutSupport().catch((value) => notify(options.onError, failure(value)));
26873
+ void active.signOutSupport().catch(reportLostRevocation);
26610
26874
  // A host that keeps the session cleans up after it as its own sign-out does.
26611
26875
  const host = options.hostKeepsSession;
26612
26876
  notify(host ? () => host.onSignOut() : undefined, undefined);
26613
26877
  void showContact('direct');
26614
26878
  }
26879
+ /**
26880
+ * Use website account from the contact form: the session switched to is
26881
+ * released and the website's identity resumed, and the host hears once which
26882
+ * session support arrived at, never the signed-out moment between.
26883
+ */
26615
26884
  async function useWebsiteAccount(composition, recovering = false) {
26616
26885
  if (!client || destroyed || state.navigationLocked)
26617
26886
  return;
26887
+ const active = client;
26618
26888
  const ownSequence = ++sequence;
26619
26889
  leaveCustomer(composition);
26620
26890
  pendingRecovery = recovering ? { websiteSignedOut: true } : null;
26621
26891
  update({ busy: true, error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
26892
+ // The release clears the switched-to session at once, before the website
26893
+ // is asked; its revocation goes behind, as a switch's does.
26894
+ replacingSession = true;
26895
+ const { released, resumed } = active.returnToWebsiteAccount();
26896
+ replacingSession = false;
26897
+ // The return decides at once whether a ticket gate stands (its release
26898
+ // ends a password's or an employee proof's access): a standing gate asks
26899
+ // the website nothing yet, so the arrival waits for support's next
26900
+ // session lookup (`lookUpSession`).
26901
+ const gated = !active.hasTicketAccess;
26902
+ websiteArrivalDue = gated && active.hasIdentityProvider;
26903
+ void released.catch(reportLostRevocation);
26904
+ let arrived;
26622
26905
  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');
26906
+ arrived = await resumed;
26632
26907
  }
26633
26908
  catch (value) {
26909
+ if (!gated)
26910
+ reportWebsiteArrival(active, null);
26634
26911
  if (destroyed || ownSequence !== sequence)
26635
26912
  return;
26636
26913
  const error = failure(value);
@@ -26638,13 +26915,24 @@ function createHelpDeskSupport(config, options) {
26638
26915
  // The website was not reached, so it is not known to have no account.
26639
26916
  if (pendingRecovery)
26640
26917
  pendingRecovery = { websiteSignedOut: false };
26641
- if (client.hasTicketAccess) {
26918
+ if (active.hasTicketAccess) {
26642
26919
  mountContact(pendingComposition, null);
26643
26920
  pendingComposition = null;
26644
26921
  }
26645
26922
  else
26646
- await showContact('direct');
26923
+ await showContact('direct', error.message);
26924
+ return;
26647
26925
  }
26926
+ if (!gated)
26927
+ reportWebsiteArrival(active, arrived);
26928
+ if (destroyed || ownSequence !== sequence)
26929
+ return;
26930
+ switchedAccount = false;
26931
+ // The website account the form arrives at says so, as a switch does; one
26932
+ // the website does not give back gets none (`mountContact`).
26933
+ pendingArrival = { from: 'switch', droppedFiles: composition?.hadFiles === true };
26934
+ update({ busy: false });
26935
+ await showContact('direct');
26648
26936
  }
26649
26937
  function receipt(ticket) {
26650
26938
  const customer = contactCustomer;
@@ -26717,23 +27005,35 @@ class HelpDeskModule {
26717
27005
  * enables it. A custom onAuthRequired callback may supply a server-issued
26718
27006
  * help desk session. Destroy the returned handle on unmount/account change.
26719
27007
  */
26720
- async mountForm(options) {
26721
- const client = await this.connect(options);
26722
- return mountHelpDeskForm(client, options);
27008
+ mountForm(options) {
27009
+ return this.connectForm(options, (client) => mountHelpDeskForm(client, options));
26723
27010
  }
26724
27011
  /** Inject a form over an already-connected client that the host also drives headlessly. */
26725
27012
  mountClientForm(client, options) {
26726
27013
  return mountHelpDeskForm(client, options);
26727
27014
  }
26728
27015
  /** 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);
27016
+ openForm(options) {
27017
+ return this.connectForm(options, (client) => this.openClientForm(client, options));
26732
27018
  }
26733
27019
  /** Open a modal over a client whose company session the host also drives headlessly. */
26734
27020
  openClientForm(client, options = {}) {
26735
27021
  return openHelpDeskForm(client, { ...options, backdropBlur: this.config.backdropBlur });
26736
27022
  }
27023
+ /**
27024
+ * Connect the client one of this module's own forms opens over: a lost
27025
+ * revocation of a session the client let go of unused reaches the form's
27026
+ * `onError` while the form stands, as the form reports its own.
27027
+ */
27028
+ async connectForm(options, open) {
27029
+ let form = null;
27030
+ const client = await this.connect({ ...options, onDiscardError: (error) => {
27031
+ if (form && form.getState() !== 'destroyed')
27032
+ void Promise.resolve(options.onError?.(error)).catch(() => undefined);
27033
+ } });
27034
+ form = open(client);
27035
+ return form;
27036
+ }
26737
27037
  /** Bind existing support buttons, including ones added later. Cleanup closes this binding's form. */
26738
27038
  attach(selector, options) {
26739
27039
  let disposed = false;
@@ -31452,7 +31752,7 @@ class SparkVault {
31452
31752
  }
31453
31753
  /** Get the SDK version */
31454
31754
  static get version() {
31455
- return '16.12.1';
31755
+ return '17.0.1';
31456
31756
  }
31457
31757
  }
31458
31758
  if (typeof window !== 'undefined') {