@signalwire/js 4.0.0-dev-20260826210511 → 4.0.0-dev-20260910191529

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
@@ -2677,15 +2677,57 @@ const RPCEventAckResponse = (id) => makeRPCResponse({
2677
2677
  result: {}
2678
2678
  });
2679
2679
 
2680
+ //#endregion
2681
+ //#region src/utils/authRecovery.ts
2682
+ /**
2683
+ * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
2684
+ * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
2685
+ * underlying signaling error is nested. Bounded by a visited set to guard
2686
+ * against cyclic causes.
2687
+ */
2688
+ function findJSONRPCError(error) {
2689
+ const seen = /* @__PURE__ */ new Set();
2690
+ let current = error;
2691
+ while (current instanceof Error && !seen.has(current)) {
2692
+ seen.add(current);
2693
+ if (current instanceof require_operators.JSONRPCError) return current;
2694
+ current = current.error ?? current.cause;
2695
+ }
2696
+ }
2697
+ /**
2698
+ * Whether an error is a session-recoverable authentication failure
2699
+ * (`-32002` authentication failed or `-32003` requester validation failed)
2700
+ * that a credential re-mint + retry can heal.
2701
+ */
2702
+ function isRecoverableAuthError(error) {
2703
+ const rpcError = findJSONRPCError(error);
2704
+ return rpcError !== void 0 && (rpcError.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
2705
+ }
2706
+ /**
2707
+ * Whether an error is specifically a requester-validation rejection
2708
+ * (`-32003`) — the server refusing the session's credential.
2709
+ *
2710
+ * Narrower than {@link isRecoverableAuthError} on purpose. `-32002` is
2711
+ * overloaded server-side: a rejected reattach arrives as `-32002` with
2712
+ * `cause: INVALID_MSG_UNSPECIFIED` and message `CALL ERROR`, which is a
2713
+ * call-level rejection and says nothing about the credential. Use this where
2714
+ * the decision must not be fooled by that, such as deciding whether retrying
2715
+ * an operation could possibly succeed.
2716
+ */
2717
+ function isRequesterValidationError(error) {
2718
+ return findJSONRPCError(error)?.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED;
2719
+ }
2720
+
2680
2721
  //#endregion
2681
2722
  //#region src/managers/AttachManager.ts
2682
2723
  const logger$24 = require_operators.getLogger();
2683
2724
  var AttachManager = class {
2684
- constructor(storage, deviceController, reconnectCallsTimeout, attachKey) {
2725
+ constructor(storage, deviceController, reconnectCallsTimeout, attachKey, credentialRecovered) {
2685
2726
  this.storage = storage;
2686
2727
  this.deviceController = deviceController;
2687
2728
  this.reconnectCallsTimeout = reconnectCallsTimeout;
2688
2729
  this.attachKey = attachKey;
2730
+ this.credentialRecovered = credentialRecovered;
2689
2731
  this.writeQueue = Promise.resolve();
2690
2732
  }
2691
2733
  async detachAll() {
@@ -2765,8 +2807,14 @@ var AttachManager = class {
2765
2807
  * rejecting. Once that fix is deployed, this will work for both
2766
2808
  * page reloads and WebSocket reconnects.
2767
2809
  *
2768
- * Failed reattach attempts are handled gracefully — the stale call
2769
- * reference is cleaned up from storage.
2810
+ * A failed reattach does NOT generally cost the stored reference. It is
2811
+ * discarded only when the server denied the reattach on a session whose
2812
+ * credential it had already accepted — a verified reauthentication followed
2813
+ * by a refusal is the server saying the call is gone, and that is the one
2814
+ * refusal worth acting on. Until then the credential may be what is being
2815
+ * refused, and the record is the only way a later reload can try again;
2816
+ * keeping it costs nothing, since `detachExpired` reaps it once it is older
2817
+ * than `reconnectCallsTimeout`.
2770
2818
  */
2771
2819
  async reattachCalls() {
2772
2820
  const attached = await this.readAttached();
@@ -2775,6 +2823,7 @@ var AttachManager = class {
2775
2823
  const { destination } = attachment;
2776
2824
  const options = this.buildCallOptions(attachment);
2777
2825
  let succeeded = false;
2826
+ let refusedOnCredentials = false;
2778
2827
  for (let attempt = 1; attempt <= 3; attempt++) try {
2779
2828
  await this.session.createOutboundCall(destination, {
2780
2829
  callId,
@@ -2785,15 +2834,20 @@ var AttachManager = class {
2785
2834
  break;
2786
2835
  } catch (error) {
2787
2836
  logger$24.warn(`[AttachManager] Reattach attempt ${attempt}/3 failed for call ${callId}:`, error);
2837
+ if (isRequesterValidationError(error)) {
2838
+ refusedOnCredentials = true;
2839
+ logger$24.warn(`[AttachManager] Reattach of ${callId} was refused on credentials; not retrying.`);
2840
+ break;
2841
+ }
2788
2842
  if (attempt < 3) await new Promise((r) => setTimeout(r, (attempt + 1) * 1e3));
2789
2843
  }
2790
- if (!succeeded) {
2791
- logger$24.warn(`[AttachManager] Reattach failed after 3 attempts for call ${callId}, removing reference`);
2844
+ if (!succeeded) if (this.credentialRecovered() && !refusedOnCredentials) {
2845
+ logger$24.warn(`[AttachManager] Reattach of ${callId} was denied after a verified reauthentication, removing reference`);
2792
2846
  await this.detach({
2793
2847
  id: callId,
2794
2848
  mediaDirections: attachment.mediaDirections
2795
2849
  });
2796
- }
2850
+ } else logger$24.warn(`[AttachManager] Reattach failed for call ${callId}; keeping the reference (credential refused or never proven good)`);
2797
2851
  }
2798
2852
  }
2799
2853
  /**
@@ -3825,33 +3879,6 @@ function isLayoutChangedPayload(value) {
3825
3879
  return isObject(value) && hasProperty(value, "room_id") && hasProperty(value, "room_session_id") && hasProperty(value, "layout");
3826
3880
  }
3827
3881
 
3828
- //#endregion
3829
- //#region src/utils/unwrapVertoReply.ts
3830
- /**
3831
- * Unwrap a method's own reply from a `webrtc.verto` envelope.
3832
- *
3833
- * A control verb sent in-dialog comes back nested two levels deep:
3834
- *
3835
- * ```
3836
- * { result: { node_id, code, result: { jsonrpc, id, result: <method payload> } } }
3837
- * ```
3838
- *
3839
- * whereas the routed transport resolves the method payload directly under
3840
- * `.result`. Readers want the latter shape, and the difference is silent when it
3841
- * is wrong — `response.result.layouts` simply evaluates to `undefined` against the
3842
- * envelope, so the data arrives, nothing throws, and the caller sees an empty
3843
- * value. That exact failure produced an empty layout dropdown with a successful
3844
- * request behind it.
3845
- *
3846
- * Accepting both shapes here keeps every reader indifferent to which transport
3847
- * produced the response. Anything that is not a nested envelope (a plain ack, or
3848
- * an already-unwrapped reply) passes through untouched.
3849
- */
3850
- function unwrapVertoReply(response) {
3851
- const inner = require_operators.getValueFrom(response, "result.result");
3852
- return inner && typeof inner === "object" && "result" in inner ? inner : response;
3853
- }
3854
-
3855
3882
  //#endregion
3856
3883
  //#region src/managers/CallEventsManager.ts
3857
3884
  const logger$22 = require_operators.getLogger();
@@ -4043,10 +4070,14 @@ var CallEventsManager = class extends Destroyable {
4043
4070
  updateLayouts() {
4044
4071
  if (!this.selfId) return;
4045
4072
  this.webRtcCallSession.executeMethod(this.selfId, "call.layout.list", {}).then((response) => {
4046
- const { result } = unwrapVertoReply(response);
4073
+ const layouts = response.result?.layouts;
4074
+ if (!layouts) {
4075
+ logger$22.warn("[CallEventsManager] Layout list response carried no layouts; keeping current layouts");
4076
+ return;
4077
+ }
4047
4078
  this._sessionState$.next({
4048
4079
  ...this._sessionState$.value,
4049
- layouts: result.layouts
4080
+ layouts
4050
4081
  });
4051
4082
  }).catch((error) => {
4052
4083
  logger$22.error("[CallEventsManager] Error fetching layouts:", error);
@@ -6436,7 +6467,7 @@ var WebRTCVertoManager = class extends VertoManager {
6436
6467
  }
6437
6468
  }));
6438
6469
  const failure = findNestedVertoFailure(response);
6439
- if (failure) throw new require_operators.JSONRPCError(Number.parseInt(failure.code, 10) || 0, failure.message ?? `Call control "${method}" failed (code ${failure.code})`, void 0);
6470
+ if (failure) throw new require_operators.JSONRPCError(Number.parseInt(failure.code, 10) || 0, `Call control "${method}" failed (code ${failure.code})${failure.message ? `: ${failure.message}` : ""}`, void 0);
6440
6471
  return response;
6441
6472
  }
6442
6473
  async executeVerto(message, optionals = {}) {
@@ -7747,6 +7778,33 @@ function mosToQualityLevel(mos) {
7747
7778
  return "critical";
7748
7779
  }
7749
7780
 
7781
+ //#endregion
7782
+ //#region src/utils/unwrapVertoReply.ts
7783
+ /**
7784
+ * Unwrap a method's own reply from a `webrtc.verto` envelope.
7785
+ *
7786
+ * A control verb sent in-dialog comes back nested two levels deep:
7787
+ *
7788
+ * ```
7789
+ * { result: { node_id, code, result: { jsonrpc, id, result: <method payload> } } }
7790
+ * ```
7791
+ *
7792
+ * whereas the routed transport resolves the method payload directly under
7793
+ * `.result`. Readers want the latter shape, and the difference is silent when it
7794
+ * is wrong — `response.result.layouts` simply evaluates to `undefined` against the
7795
+ * envelope, so the data arrives, nothing throws, and the caller sees an empty
7796
+ * value. That exact failure produced an empty layout dropdown with a successful
7797
+ * request behind it.
7798
+ *
7799
+ * Accepting both shapes here keeps every reader indifferent to which transport
7800
+ * produced the response. Anything that is not a nested envelope (a plain ack, or
7801
+ * an already-unwrapped reply) passes through untouched.
7802
+ */
7803
+ function unwrapVertoReply(response) {
7804
+ const inner = require_operators.getValueFrom(response, "result.result");
7805
+ return inner && typeof inner === "object" && "result" in inner ? inner : response;
7806
+ }
7807
+
7750
7808
  //#endregion
7751
7809
  //#region src/core/entities/Call.ts
7752
7810
  const logger$12 = require_operators.getLogger();
@@ -9592,17 +9650,14 @@ var ClientSessionManager = class extends Destroyable {
9592
9650
  const hasStoredState = await (0, rxjs.firstValueFrom)(this.authorizationState$.pipe((0, rxjs.take)(1))) !== void 0;
9593
9651
  if (isRecoverableAuthError$1 && hasStoredState) {
9594
9652
  logger$9.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");
9595
- try {
9596
- await this.cleanupStoredConnectionParams();
9597
- } catch (cleanupError) {
9598
- logger$9.error("Failed to cleanup stored connection params:", cleanupError);
9599
- } finally {
9600
- this.transport.reconnect();
9601
- }
9653
+ await this.discardResumeStateAndReconnect();
9602
9654
  } else this._errors$.next(error);
9603
9655
  }
9604
9656
  /**
9605
- * Clear the resume state (authorization_state + protocol) only.
9657
+ * Clear the resume state (authorization_state + protocol) and ask the
9658
+ * transport to reconnect. The `connected` event re-triggers
9659
+ * `authenticate()`, which now has no stored state and so performs a fresh
9660
+ * connect.
9606
9661
  *
9607
9662
  * This is the stale-auth-state recovery helper used by handleAuthError:
9608
9663
  * the server rejected a reconnect, so the resume state is discarded and a
@@ -9610,9 +9665,24 @@ var ClientSessionManager = class extends Destroyable {
9610
9665
  * session lives on through the reconnect and reattachCalls() needs the
9611
9666
  * stored call references afterwards. Do NOT add detachAll() here.
9612
9667
  *
9668
+ * Connect-time recovery only. A *request* refused on an already
9669
+ * authenticated session is never healed here: dropping the resume state
9670
+ * destroys the association between the socket and the previous session,
9671
+ * which is what reattach depends on. That path mints a fresh credential and
9672
+ * reauthenticates instead (see `SignalWire.recoverAndRetry`).
9673
+ *
9613
9674
  * For public teardown (disconnect/destroy), use {@link teardownSessionState}
9614
9675
  * instead, which clears the attach records as well.
9615
9676
  */
9677
+ async discardResumeStateAndReconnect() {
9678
+ try {
9679
+ await this.cleanupStoredConnectionParams();
9680
+ } catch (cleanupError) {
9681
+ logger$9.error("Failed to cleanup stored connection params:", cleanupError);
9682
+ } finally {
9683
+ this.transport.reconnect();
9684
+ }
9685
+ }
9616
9686
  async cleanupStoredConnectionParams() {
9617
9687
  await this.transport.setProtocol(void 0);
9618
9688
  await this.updateAuthorizationStateInStorage(void 0);
@@ -11179,36 +11249,16 @@ var TransportManager = class extends Destroyable {
11179
11249
  }
11180
11250
  };
11181
11251
 
11182
- //#endregion
11183
- //#region src/utils/authRecovery.ts
11184
- /**
11185
- * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
11186
- * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
11187
- * underlying signaling error is nested. Bounded by a visited set to guard
11188
- * against cyclic causes.
11189
- */
11190
- function findJSONRPCError(error) {
11191
- const seen = /* @__PURE__ */ new Set();
11192
- let current = error;
11193
- while (current instanceof Error && !seen.has(current)) {
11194
- seen.add(current);
11195
- if (current instanceof require_operators.JSONRPCError) return current;
11196
- current = current.error ?? current.cause;
11197
- }
11198
- }
11199
- /**
11200
- * Whether an error is a session-recoverable authentication failure
11201
- * (`-32002` authentication failed or `-32003` requester validation failed)
11202
- * that a credential re-mint + retry can heal.
11203
- */
11204
- function isRecoverableAuthError(error) {
11205
- const rpcError = findJSONRPCError(error);
11206
- return rpcError !== void 0 && (rpcError.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
11207
- }
11208
-
11209
11252
  //#endregion
11210
11253
  //#region src/clients/SignalWire.ts
11211
11254
  const logger$1 = require_operators.getLogger();
11255
+ /**
11256
+ * Storage key for the client-bound marker. The SAT and authorization_state are
11257
+ * both opaque to the SDK, so on a page reload the preflight recovery — which
11258
+ * runs before any session exists — has no other way to know the session was
11259
+ * client-bound. See {@link SignalWire.persistClientBoundMarker}.
11260
+ */
11261
+ const CLIENT_BOUND_STORAGE_KEY = "sw:client_bound";
11212
11262
  const buildOptionsFromDestination = (destination) => {
11213
11263
  if (typeof destination === "string") {
11214
11264
  const queryStartIndex = destination.indexOf("?");
@@ -11252,6 +11302,7 @@ var SignalWire = class extends Destroyable {
11252
11302
  this.preferences = new ClientPreferences();
11253
11303
  this._user$ = this.createBehaviorSubject(void 0);
11254
11304
  this._directory$ = this.createBehaviorSubject(void 0);
11305
+ this._credentialRecovered = false;
11255
11306
  this._isConnected$ = this.createBehaviorSubject(false);
11256
11307
  this._isRegistered$ = this.createBehaviorSubject(false);
11257
11308
  this._errors$ = this.createReplaySubject(1);
@@ -11417,43 +11468,76 @@ var SignalWire = class extends Destroyable {
11417
11468
  }
11418
11469
  }
11419
11470
  /**
11420
- * One-shot recovery for a live session that failed with a recoverable auth
11421
- * error (`-32002`/`-32003`) because its token went stale — e.g. a refresh
11422
- * timer that was throttled while the tab was backgrounded.
11471
+ * Recover a session the server is refusing: mint a fresh credential,
11472
+ * reauthenticate the live session with it, and retry the operation.
11473
+ *
11474
+ * The connection is deliberately kept. A reload authenticates the new socket
11475
+ * against the persisted `authorization_state`, and that handshake is what
11476
+ * associates the socket with the previous session — the association reattach
11477
+ * depends on. `signalwire.reauthenticate` swaps the credential *on that same
11478
+ * session*, so recovery never touches the resume state. Discarding it would
11479
+ * heal the credential by destroying the very thing the caller is trying to
11480
+ * get back to.
11423
11481
  *
11424
- * Two steps, first that succeeds wins:
11425
- * 1. Reauthenticate with the in-memory token (a fresh DPoP proof is
11426
- * generated automatically). Heals a session whose token was already
11427
- * refreshed by the coordinator but never applied to the open socket,
11428
- * and a client-bound session whose server-side auth merely drifted.
11429
- * 2. Re-mint via the developer provider's `refresh()` and reauthenticate.
11430
- * Skipped for client-bound sessions (the DeviceTokenManager owns their
11431
- * refresh; re-minting a base SAT here would drop the DPoP binding).
11482
+ * The operation is still the verdict, never the RPC. Reauthenticating with
11483
+ * the in-memory token is accepted by a resume even while requests stay
11484
+ * refused, because the persisted `authorization_state` short-circuits token
11485
+ * validation — and `signalwire.reauthenticate` with a *freshly minted* token
11486
+ * has also been observed accepted while `subscriber.online` keeps being
11487
+ * refused (staging run 33826974634). Both look like success and are not.
11432
11488
  *
11433
- * @param allowRemint - Whether step 2 (provider re-mint) may run. Callers
11434
- * pass `false` for non-auth failures so a transient network error never
11435
- * escalates to a token re-mint; step 1 (in-memory reauth) always runs.
11436
- * @returns `true` if the session was reauthenticated, `false` otherwise.
11489
+ * @returns the operation's value, or the reason recovery could not deliver
11490
+ * one. `error` is undefined when there was no way to mint at all.
11437
11491
  */
11438
- async recoverStaleCredential(allowRemint = true) {
11439
- const currentToken = this._deps.credential.token;
11440
- if (currentToken) try {
11441
- await this._clientSession.reauthenticate(currentToken);
11442
- return true;
11492
+ async recoverAndRetry(operation) {
11493
+ if (!await this.remintAndReauthenticate()) return { ok: false };
11494
+ try {
11495
+ const value = await operation();
11496
+ this._credentialRecovered = true;
11497
+ return {
11498
+ ok: true,
11499
+ value
11500
+ };
11443
11501
  } catch (error) {
11444
- logger$1.debug("[SignalWire] In-memory reauth failed during recovery:", error);
11502
+ logger$1.warn("[SignalWire] Reauthentication was accepted but the operation is still refused:", error);
11503
+ return {
11504
+ ok: false,
11505
+ error
11506
+ };
11507
+ }
11508
+ }
11509
+ /**
11510
+ * Re-mint a credential and adopt it only if the live session accepts it.
11511
+ *
11512
+ * The mechanism follows the binding: a client-bound session re-mints a bound
11513
+ * base SAT through `authenticate()` with the DPoP fingerprint, because the
11514
+ * developer refresh handler would hand back an unbound token and silently
11515
+ * degrade the session. An unbound session uses the refresh handler. Rotation
11516
+ * cost is not a reason to skip this — the only reason is having no mechanism.
11517
+ *
11518
+ * @returns whether the session is now running on a freshly accepted credential.
11519
+ */
11520
+ async remintAndReauthenticate() {
11521
+ const provider = this._credentialProvider;
11522
+ if (!provider) return false;
11523
+ const { clientBound } = this._clientSession;
11524
+ if (!clientBound && !provider.refresh) {
11525
+ logger$1.debug("[SignalWire] [SW-NO-REFRESH-HANDLER] Unbound session with no refresh handler; cannot re-mint.");
11526
+ return false;
11445
11527
  }
11446
- if (!allowRemint || this._clientSession.clientBound || !this._credentialProvider?.refresh) return false;
11447
11528
  try {
11448
- const newCredentials = await this.remintCredential(this._credentialProvider);
11449
- if (!newCredentials.token) return false;
11529
+ const newCredentials = clientBound ? await provider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0) : await this.remintCredential(provider);
11530
+ if (!newCredentials.token) {
11531
+ logger$1.warn("[SignalWire] Re-minted credential has no token; keeping the current one.");
11532
+ return false;
11533
+ }
11534
+ await this._clientSession.reauthenticate(newCredentials.token);
11450
11535
  this._deps.credential = newCredentials;
11451
11536
  this.persistCredential(newCredentials);
11452
- await this._clientSession.reauthenticate(newCredentials.token);
11453
- if (newCredentials.expiry_at) this._refreshCoordinator?.scheduleDeveloperRefresh(this._credentialProvider, newCredentials.expiry_at);
11537
+ if (newCredentials.expiry_at && provider.refresh) this._refreshCoordinator?.scheduleDeveloperRefresh(provider, newCredentials.expiry_at);
11454
11538
  return true;
11455
11539
  } catch (error) {
11456
- logger$1.error("[SignalWire] Credential recovery failed:", error);
11540
+ logger$1.warn("[SignalWire] Re-mint recovery failed:", error);
11457
11541
  return false;
11458
11542
  }
11459
11543
  }
@@ -11488,10 +11572,9 @@ var SignalWire = class extends Destroyable {
11488
11572
  if (!this._credentialProvider) return;
11489
11573
  try {
11490
11574
  let newCredentials;
11491
- if (this._clientSession.clientBound) {
11492
- const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
11575
+ if (this._clientSession?.clientBound ?? await this.wasClientBound()) {
11493
11576
  logger$1.debug("[SignalWire] Re-minting client-bound base SAT before reconnect");
11494
- newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
11577
+ newCredentials = await this._credentialProvider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0);
11495
11578
  } else if (this._credentialProvider.refresh) {
11496
11579
  logger$1.debug("[SignalWire] Refreshing unbound credential before reconnect");
11497
11580
  newCredentials = await this.remintCredential(this._credentialProvider);
@@ -11519,6 +11602,26 @@ var SignalWire = class extends Destroyable {
11519
11602
  this._deps.storage.setItem("sw:cached_credential", credential);
11520
11603
  if (this._deps.persistSession) this._deps.storage.setItem("sw:cached_credential", credential, "local");
11521
11604
  }
11605
+ /**
11606
+ * Persist whether the session is client-bound, mirroring the credential's
11607
+ * storage scopes so it survives a reload. The preflight recovery reads it
11608
+ * before any session exists to decide whether to re-bind via `authenticate()`
11609
+ * or refresh an unbound token; the marker tracks the latest binding, so an
11610
+ * unbound reconnect clears a stale marker from an earlier client-bound login.
11611
+ */
11612
+ persistClientBoundMarker(bound) {
11613
+ const scopes = this._deps.persistSession ? ["session", "local"] : ["session"];
11614
+ for (const scope of scopes) if (bound) this._deps.storage.setItem(CLIENT_BOUND_STORAGE_KEY, true, scope);
11615
+ else this._deps.storage.removeItem(CLIENT_BOUND_STORAGE_KEY, scope);
11616
+ }
11617
+ /** Read the persisted client-bound marker (see {@link persistClientBoundMarker}). */
11618
+ async wasClientBound() {
11619
+ const scopes = this._deps.persistSession ? ["local", "session"] : ["session"];
11620
+ for (const scope of scopes) try {
11621
+ if (await this._deps.storage.getItem(CLIENT_BOUND_STORAGE_KEY, scope)) return true;
11622
+ } catch {}
11623
+ return false;
11624
+ }
11522
11625
  async init() {
11523
11626
  this._user$.next(new User(this._deps.http));
11524
11627
  if (!this._options.skipConnection) await this.connect();
@@ -11542,6 +11645,42 @@ var SignalWire = class extends Destroyable {
11542
11645
  } catch (error) {
11543
11646
  logger$1.error("[SignalWire] Failed to reattach calls:", error);
11544
11647
  this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
11648
+ } finally {
11649
+ this._credentialRecovered = false;
11650
+ }
11651
+ }
11652
+ /**
11653
+ * Fetch the authenticated user profile, recovering a stale credential.
11654
+ *
11655
+ * On a reload the persisted credential can be expired. Unlike the WS resume —
11656
+ * which the server accepts against the persisted `authorization_state` even
11657
+ * with an expired token — this REST preflight has no such short-circuit and is
11658
+ * refused (401). There is no session yet to reauthenticate, so recovery
11659
+ * re-mints the credential through the provider ({@link refreshCredentialForReconnect})
11660
+ * and retries with a FRESH {@link User}: Fetchable memoizes its result
11661
+ * (shareReplay), so reusing the instance would replay the 401 instead of
11662
+ * re-fetching with the new token. Without the user id the transport/session —
11663
+ * and the reattach a reload is trying to preserve — cannot even be addressed.
11664
+ */
11665
+ async fetchUserOrRecover() {
11666
+ const fetchUser = async (user$1) => {
11667
+ if (!await (0, rxjs.firstValueFrom)(user$1.fetched$)) throw new require_operators.UnexpectedError("Failed to fetch user information - fetched$ emitted false");
11668
+ this._deps.user = user$1;
11669
+ };
11670
+ const user = this._user$.value;
11671
+ if (!user) throw new require_operators.UnexpectedError("User not initialized before connect");
11672
+ try {
11673
+ await fetchUser(user);
11674
+ } catch (firstError) {
11675
+ logger$1.error(`[SignalWire] Failed to fetch user information: ${firstError instanceof Error ? firstError.message : "Unknown error"}. This usually means the user token is invalid or expired. Re-minting the credential and retrying.`);
11676
+ try {
11677
+ await this.refreshCredentialForReconnect();
11678
+ const refetched = new User(this._deps.http);
11679
+ await fetchUser(refetched);
11680
+ this._user$.next(refetched);
11681
+ } catch (retryError) {
11682
+ throw new require_operators.UnexpectedError("Error fetching user information", { cause: retryError });
11683
+ }
11545
11684
  }
11546
11685
  }
11547
11686
  /**
@@ -11583,20 +11722,12 @@ var SignalWire = class extends Destroyable {
11583
11722
  */
11584
11723
  async connect() {
11585
11724
  await this.teardownTransportAndSession();
11586
- try {
11587
- const user = this._user$.value;
11588
- if (!user) throw new require_operators.UnexpectedError("User not initialized before connect");
11589
- if (!await (0, rxjs.firstValueFrom)(user.fetched$)) throw new require_operators.UnexpectedError("Failed to fetch user information - fetched$ emitted false");
11590
- this._deps.user = user;
11591
- } catch (error) {
11592
- logger$1.error(`[SignalWire] Failed to fetch user information: ${error instanceof Error ? error.message : "Unknown error"}. This usually means the user token is invalid or expired.`);
11593
- throw new require_operators.UnexpectedError("Error fetching user information", { cause: error });
11594
- }
11725
+ await this.fetchUserOrRecover();
11595
11726
  const errorHandler = (error) => {
11596
11727
  this._errors$.next(error);
11597
11728
  };
11598
11729
  this._transport = new TransportManager(this._deps.storage, this._deps.protocolKey, this._deps.WebSocket, PreferencesContainer.instance.relayHost ?? this._deps.relayHost, errorHandler);
11599
- this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey);
11730
+ this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey, () => this._credentialRecovered);
11600
11731
  this._clientSession = new ClientSessionManager(() => this._deps.credential, this._transport, this._deps.storage, this._deps.authorizationStateKey, this._deps.deviceController, this._attachManager, this._deps.webRTCApiProvider, this._dpopManager, this._networkMonitor?.networkChange$);
11601
11732
  this._publicSession = new ClientSessionWrapper(this._clientSession);
11602
11733
  this._clientSession.callControl = this._options.callControl ?? "routed";
@@ -11606,6 +11737,7 @@ var SignalWire = class extends Destroyable {
11606
11737
  });
11607
11738
  this.subscribeTo(this._clientSession.authorization$, (authorization) => {
11608
11739
  this._refreshCoordinator?.syncExpiryFromAuthorization(authorization, this._credentialProvider);
11740
+ this.persistClientBoundMarker(Boolean(authorization?.cnf?.jkt));
11609
11741
  });
11610
11742
  await this._clientSession.connect();
11611
11743
  await this._refreshCoordinator?.activate(this._deps.user, this._clientSession);
@@ -11859,19 +11991,18 @@ var SignalWire = class extends Destroyable {
11859
11991
  throw error;
11860
11992
  }
11861
11993
  logger$1.debug("[SignalWire] Failed to register user, attempting credential recovery...");
11862
- let failureCause = error;
11863
- if (await this.recoverStaleCredential(isRecoverableAuthError(error))) try {
11864
- logger$1.debug("[SignalWire] Recovery succeeded, retrying register()");
11994
+ const outcome = await this.recoverAndRetry(async () => {
11865
11995
  await this._transport.execute(RPCExecute({
11866
11996
  method: "subscriber.online",
11867
11997
  params: {}
11868
11998
  }));
11999
+ });
12000
+ if (outcome.ok) {
12001
+ logger$1.debug("[SignalWire] Recovery restored registration");
11869
12002
  this._isRegistered$.next(true);
11870
12003
  return;
11871
- } catch (retryError) {
11872
- logger$1.error("[SignalWire] Register retry after recovery failed:", retryError);
11873
- failureCause = retryError;
11874
12004
  }
12005
+ const failureCause = outcome.error ?? error;
11875
12006
  const registerError = new require_operators.InvalidCredentialsError("Failed to register user, and credential recovery also failed. Please check your credentials.", { cause: failureCause instanceof Error ? failureCause : new Error(String(failureCause), { cause: failureCause }) });
11876
12007
  this._errors$.next(registerError);
11877
12008
  throw registerError;
@@ -11931,10 +12062,13 @@ var SignalWire = class extends Destroyable {
11931
12062
  return await this._clientSession.createOutboundCall(destination, computed_options);
11932
12063
  } catch (error) {
11933
12064
  if (!isRecoverableAuthError(error)) throw error;
11934
- logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering credential and retrying once");
11935
- if (!await this.recoverStaleCredential()) throw error;
11936
- await this.waitAuthentication();
11937
- return this._clientSession.createOutboundCall(destination, computed_options);
12065
+ logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering the session and retrying");
12066
+ const outcome = await this.recoverAndRetry(async () => {
12067
+ await this.waitAuthentication();
12068
+ return this._clientSession.createOutboundCall(destination, computed_options);
12069
+ });
12070
+ if (outcome.ok) return outcome.value;
12071
+ throw outcome.error ?? error;
11938
12072
  }
11939
12073
  }
11940
12074
  /**