@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.
@@ -12380,15 +12380,57 @@ const RPCEventAckResponse = (id) => makeRPCResponse({
12380
12380
  result: {}
12381
12381
  });
12382
12382
 
12383
+ //#endregion
12384
+ //#region src/utils/authRecovery.ts
12385
+ /**
12386
+ * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
12387
+ * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
12388
+ * underlying signaling error is nested. Bounded by a visited set to guard
12389
+ * against cyclic causes.
12390
+ */
12391
+ function findJSONRPCError(error) {
12392
+ const seen = /* @__PURE__ */ new Set();
12393
+ let current = error;
12394
+ while (current instanceof Error && !seen.has(current)) {
12395
+ seen.add(current);
12396
+ if (current instanceof JSONRPCError) return current;
12397
+ current = current.error ?? current.cause;
12398
+ }
12399
+ }
12400
+ /**
12401
+ * Whether an error is a session-recoverable authentication failure
12402
+ * (`-32002` authentication failed or `-32003` requester validation failed)
12403
+ * that a credential re-mint + retry can heal.
12404
+ */
12405
+ function isRecoverableAuthError(error) {
12406
+ const rpcError = findJSONRPCError(error);
12407
+ return rpcError !== void 0 && (rpcError.code === RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === RPC_ERROR_AUTHENTICATION_FAILED);
12408
+ }
12409
+ /**
12410
+ * Whether an error is specifically a requester-validation rejection
12411
+ * (`-32003`) — the server refusing the session's credential.
12412
+ *
12413
+ * Narrower than {@link isRecoverableAuthError} on purpose. `-32002` is
12414
+ * overloaded server-side: a rejected reattach arrives as `-32002` with
12415
+ * `cause: INVALID_MSG_UNSPECIFIED` and message `CALL ERROR`, which is a
12416
+ * call-level rejection and says nothing about the credential. Use this where
12417
+ * the decision must not be fooled by that, such as deciding whether retrying
12418
+ * an operation could possibly succeed.
12419
+ */
12420
+ function isRequesterValidationError(error) {
12421
+ return findJSONRPCError(error)?.code === RPC_ERROR_REQUESTER_VALIDATION_FAILED;
12422
+ }
12423
+
12383
12424
  //#endregion
12384
12425
  //#region src/managers/AttachManager.ts
12385
12426
  const logger$25 = getLogger();
12386
12427
  var AttachManager = class {
12387
- constructor(storage, deviceController, reconnectCallsTimeout, attachKey) {
12428
+ constructor(storage, deviceController, reconnectCallsTimeout, attachKey, credentialRecovered) {
12388
12429
  this.storage = storage;
12389
12430
  this.deviceController = deviceController;
12390
12431
  this.reconnectCallsTimeout = reconnectCallsTimeout;
12391
12432
  this.attachKey = attachKey;
12433
+ this.credentialRecovered = credentialRecovered;
12392
12434
  this.writeQueue = Promise.resolve();
12393
12435
  }
12394
12436
  async detachAll() {
@@ -12468,8 +12510,14 @@ var AttachManager = class {
12468
12510
  * rejecting. Once that fix is deployed, this will work for both
12469
12511
  * page reloads and WebSocket reconnects.
12470
12512
  *
12471
- * Failed reattach attempts are handled gracefully — the stale call
12472
- * reference is cleaned up from storage.
12513
+ * A failed reattach does NOT generally cost the stored reference. It is
12514
+ * discarded only when the server denied the reattach on a session whose
12515
+ * credential it had already accepted — a verified reauthentication followed
12516
+ * by a refusal is the server saying the call is gone, and that is the one
12517
+ * refusal worth acting on. Until then the credential may be what is being
12518
+ * refused, and the record is the only way a later reload can try again;
12519
+ * keeping it costs nothing, since `detachExpired` reaps it once it is older
12520
+ * than `reconnectCallsTimeout`.
12473
12521
  */
12474
12522
  async reattachCalls() {
12475
12523
  const attached = await this.readAttached();
@@ -12478,6 +12526,7 @@ var AttachManager = class {
12478
12526
  const { destination } = attachment;
12479
12527
  const options = this.buildCallOptions(attachment);
12480
12528
  let succeeded = false;
12529
+ let refusedOnCredentials = false;
12481
12530
  for (let attempt = 1; attempt <= 3; attempt++) try {
12482
12531
  await this.session.createOutboundCall(destination, {
12483
12532
  callId,
@@ -12488,15 +12537,20 @@ var AttachManager = class {
12488
12537
  break;
12489
12538
  } catch (error) {
12490
12539
  logger$25.warn(`[AttachManager] Reattach attempt ${attempt}/3 failed for call ${callId}:`, error);
12540
+ if (isRequesterValidationError(error)) {
12541
+ refusedOnCredentials = true;
12542
+ logger$25.warn(`[AttachManager] Reattach of ${callId} was refused on credentials; not retrying.`);
12543
+ break;
12544
+ }
12491
12545
  if (attempt < 3) await new Promise((r) => setTimeout(r, (attempt + 1) * 1e3));
12492
12546
  }
12493
- if (!succeeded) {
12494
- logger$25.warn(`[AttachManager] Reattach failed after 3 attempts for call ${callId}, removing reference`);
12547
+ if (!succeeded) if (this.credentialRecovered() && !refusedOnCredentials) {
12548
+ logger$25.warn(`[AttachManager] Reattach of ${callId} was denied after a verified reauthentication, removing reference`);
12495
12549
  await this.detach({
12496
12550
  id: callId,
12497
12551
  mediaDirections: attachment.mediaDirections
12498
12552
  });
12499
- }
12553
+ } else logger$25.warn(`[AttachManager] Reattach failed for call ${callId}; keeping the reference (credential refused or never proven good)`);
12500
12554
  }
12501
12555
  }
12502
12556
  /**
@@ -14514,33 +14568,6 @@ function throwOnRPCError() {
14514
14568
  });
14515
14569
  }
14516
14570
 
14517
- //#endregion
14518
- //#region src/utils/unwrapVertoReply.ts
14519
- /**
14520
- * Unwrap a method's own reply from a `webrtc.verto` envelope.
14521
- *
14522
- * A control verb sent in-dialog comes back nested two levels deep:
14523
- *
14524
- * ```
14525
- * { result: { node_id, code, result: { jsonrpc, id, result: <method payload> } } }
14526
- * ```
14527
- *
14528
- * whereas the routed transport resolves the method payload directly under
14529
- * `.result`. Readers want the latter shape, and the difference is silent when it
14530
- * is wrong — `response.result.layouts` simply evaluates to `undefined` against the
14531
- * envelope, so the data arrives, nothing throws, and the caller sees an empty
14532
- * value. That exact failure produced an empty layout dropdown with a successful
14533
- * request behind it.
14534
- *
14535
- * Accepting both shapes here keeps every reader indifferent to which transport
14536
- * produced the response. Anything that is not a nested envelope (a plain ack, or
14537
- * an already-unwrapped reply) passes through untouched.
14538
- */
14539
- function unwrapVertoReply(response) {
14540
- const inner = getValueFrom(response, "result.result");
14541
- return inner && typeof inner === "object" && "result" in inner ? inner : response;
14542
- }
14543
-
14544
14571
  //#endregion
14545
14572
  //#region src/managers/CallEventsManager.ts
14546
14573
  var import_cjs$20 = require_cjs();
@@ -14733,10 +14760,14 @@ var CallEventsManager = class extends Destroyable {
14733
14760
  updateLayouts() {
14734
14761
  if (!this.selfId) return;
14735
14762
  this.webRtcCallSession.executeMethod(this.selfId, "call.layout.list", {}).then((response) => {
14736
- const { result } = unwrapVertoReply(response);
14763
+ const layouts = response.result?.layouts;
14764
+ if (!layouts) {
14765
+ logger$22.warn("[CallEventsManager] Layout list response carried no layouts; keeping current layouts");
14766
+ return;
14767
+ }
14737
14768
  this._sessionState$.next({
14738
14769
  ...this._sessionState$.value,
14739
- layouts: result.layouts
14770
+ layouts
14740
14771
  });
14741
14772
  }).catch((error) => {
14742
14773
  logger$22.error("[CallEventsManager] Error fetching layouts:", error);
@@ -17131,7 +17162,7 @@ var WebRTCVertoManager = class extends VertoManager {
17131
17162
  }
17132
17163
  }));
17133
17164
  const failure = findNestedVertoFailure(response);
17134
- if (failure) throw new JSONRPCError(Number.parseInt(failure.code, 10) || 0, failure.message ?? `Call control "${method}" failed (code ${failure.code})`, void 0);
17165
+ if (failure) throw new JSONRPCError(Number.parseInt(failure.code, 10) || 0, `Call control "${method}" failed (code ${failure.code})${failure.message ? `: ${failure.message}` : ""}`, void 0);
17135
17166
  return response;
17136
17167
  }
17137
17168
  async executeVerto(message, optionals = {}) {
@@ -18439,6 +18470,33 @@ function mosToQualityLevel(mos) {
18439
18470
  return "critical";
18440
18471
  }
18441
18472
 
18473
+ //#endregion
18474
+ //#region src/utils/unwrapVertoReply.ts
18475
+ /**
18476
+ * Unwrap a method's own reply from a `webrtc.verto` envelope.
18477
+ *
18478
+ * A control verb sent in-dialog comes back nested two levels deep:
18479
+ *
18480
+ * ```
18481
+ * { result: { node_id, code, result: { jsonrpc, id, result: <method payload> } } }
18482
+ * ```
18483
+ *
18484
+ * whereas the routed transport resolves the method payload directly under
18485
+ * `.result`. Readers want the latter shape, and the difference is silent when it
18486
+ * is wrong — `response.result.layouts` simply evaluates to `undefined` against the
18487
+ * envelope, so the data arrives, nothing throws, and the caller sees an empty
18488
+ * value. That exact failure produced an empty layout dropdown with a successful
18489
+ * request behind it.
18490
+ *
18491
+ * Accepting both shapes here keeps every reader indifferent to which transport
18492
+ * produced the response. Anything that is not a nested envelope (a plain ack, or
18493
+ * an already-unwrapped reply) passes through untouched.
18494
+ */
18495
+ function unwrapVertoReply(response) {
18496
+ const inner = getValueFrom(response, "result.result");
18497
+ return inner && typeof inner === "object" && "result" in inner ? inner : response;
18498
+ }
18499
+
18442
18500
  //#endregion
18443
18501
  //#region src/core/entities/Call.ts
18444
18502
  var import_cjs$11 = require_cjs();
@@ -20289,17 +20347,14 @@ var ClientSessionManager = class extends Destroyable {
20289
20347
  const hasStoredState = await (0, import_cjs$7.firstValueFrom)(this.authorizationState$.pipe((0, import_cjs$7.take)(1))) !== void 0;
20290
20348
  if (isRecoverableAuthError$1 && hasStoredState) {
20291
20349
  logger$9.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");
20292
- try {
20293
- await this.cleanupStoredConnectionParams();
20294
- } catch (cleanupError) {
20295
- logger$9.error("Failed to cleanup stored connection params:", cleanupError);
20296
- } finally {
20297
- this.transport.reconnect();
20298
- }
20350
+ await this.discardResumeStateAndReconnect();
20299
20351
  } else this._errors$.next(error);
20300
20352
  }
20301
20353
  /**
20302
- * Clear the resume state (authorization_state + protocol) only.
20354
+ * Clear the resume state (authorization_state + protocol) and ask the
20355
+ * transport to reconnect. The `connected` event re-triggers
20356
+ * `authenticate()`, which now has no stored state and so performs a fresh
20357
+ * connect.
20303
20358
  *
20304
20359
  * This is the stale-auth-state recovery helper used by handleAuthError:
20305
20360
  * the server rejected a reconnect, so the resume state is discarded and a
@@ -20307,9 +20362,24 @@ var ClientSessionManager = class extends Destroyable {
20307
20362
  * session lives on through the reconnect and reattachCalls() needs the
20308
20363
  * stored call references afterwards. Do NOT add detachAll() here.
20309
20364
  *
20365
+ * Connect-time recovery only. A *request* refused on an already
20366
+ * authenticated session is never healed here: dropping the resume state
20367
+ * destroys the association between the socket and the previous session,
20368
+ * which is what reattach depends on. That path mints a fresh credential and
20369
+ * reauthenticates instead (see `SignalWire.recoverAndRetry`).
20370
+ *
20310
20371
  * For public teardown (disconnect/destroy), use {@link teardownSessionState}
20311
20372
  * instead, which clears the attach records as well.
20312
20373
  */
20374
+ async discardResumeStateAndReconnect() {
20375
+ try {
20376
+ await this.cleanupStoredConnectionParams();
20377
+ } catch (cleanupError) {
20378
+ logger$9.error("Failed to cleanup stored connection params:", cleanupError);
20379
+ } finally {
20380
+ this.transport.reconnect();
20381
+ }
20382
+ }
20313
20383
  async cleanupStoredConnectionParams() {
20314
20384
  await this.transport.setProtocol(void 0);
20315
20385
  await this.updateAuthorizationStateInStorage(void 0);
@@ -21881,37 +21951,17 @@ var TransportManager = class extends Destroyable {
21881
21951
  }
21882
21952
  };
21883
21953
 
21884
- //#endregion
21885
- //#region src/utils/authRecovery.ts
21886
- /**
21887
- * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
21888
- * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
21889
- * underlying signaling error is nested. Bounded by a visited set to guard
21890
- * against cyclic causes.
21891
- */
21892
- function findJSONRPCError(error) {
21893
- const seen = /* @__PURE__ */ new Set();
21894
- let current = error;
21895
- while (current instanceof Error && !seen.has(current)) {
21896
- seen.add(current);
21897
- if (current instanceof JSONRPCError) return current;
21898
- current = current.error ?? current.cause;
21899
- }
21900
- }
21901
- /**
21902
- * Whether an error is a session-recoverable authentication failure
21903
- * (`-32002` authentication failed or `-32003` requester validation failed)
21904
- * that a credential re-mint + retry can heal.
21905
- */
21906
- function isRecoverableAuthError(error) {
21907
- const rpcError = findJSONRPCError(error);
21908
- return rpcError !== void 0 && (rpcError.code === RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === RPC_ERROR_AUTHENTICATION_FAILED);
21909
- }
21910
-
21911
21954
  //#endregion
21912
21955
  //#region src/clients/SignalWire.ts
21913
21956
  var import_cjs$1 = require_cjs();
21914
21957
  const logger$1 = getLogger();
21958
+ /**
21959
+ * Storage key for the client-bound marker. The SAT and authorization_state are
21960
+ * both opaque to the SDK, so on a page reload the preflight recovery — which
21961
+ * runs before any session exists — has no other way to know the session was
21962
+ * client-bound. See {@link SignalWire.persistClientBoundMarker}.
21963
+ */
21964
+ const CLIENT_BOUND_STORAGE_KEY = "sw:client_bound";
21915
21965
  const buildOptionsFromDestination = (destination) => {
21916
21966
  if (typeof destination === "string") {
21917
21967
  const queryStartIndex = destination.indexOf("?");
@@ -21955,6 +22005,7 @@ var SignalWire = class extends Destroyable {
21955
22005
  this.preferences = new ClientPreferences();
21956
22006
  this._user$ = this.createBehaviorSubject(void 0);
21957
22007
  this._directory$ = this.createBehaviorSubject(void 0);
22008
+ this._credentialRecovered = false;
21958
22009
  this._isConnected$ = this.createBehaviorSubject(false);
21959
22010
  this._isRegistered$ = this.createBehaviorSubject(false);
21960
22011
  this._errors$ = this.createReplaySubject(1);
@@ -22120,43 +22171,76 @@ var SignalWire = class extends Destroyable {
22120
22171
  }
22121
22172
  }
22122
22173
  /**
22123
- * One-shot recovery for a live session that failed with a recoverable auth
22124
- * error (`-32002`/`-32003`) because its token went stale — e.g. a refresh
22125
- * timer that was throttled while the tab was backgrounded.
22174
+ * Recover a session the server is refusing: mint a fresh credential,
22175
+ * reauthenticate the live session with it, and retry the operation.
22126
22176
  *
22127
- * Two steps, first that succeeds wins:
22128
- * 1. Reauthenticate with the in-memory token (a fresh DPoP proof is
22129
- * generated automatically). Heals a session whose token was already
22130
- * refreshed by the coordinator but never applied to the open socket,
22131
- * and a client-bound session whose server-side auth merely drifted.
22132
- * 2. Re-mint via the developer provider's `refresh()` and reauthenticate.
22133
- * Skipped for client-bound sessions (the DeviceTokenManager owns their
22134
- * refresh; re-minting a base SAT here would drop the DPoP binding).
22177
+ * The connection is deliberately kept. A reload authenticates the new socket
22178
+ * against the persisted `authorization_state`, and that handshake is what
22179
+ * associates the socket with the previous session — the association reattach
22180
+ * depends on. `signalwire.reauthenticate` swaps the credential *on that same
22181
+ * session*, so recovery never touches the resume state. Discarding it would
22182
+ * heal the credential by destroying the very thing the caller is trying to
22183
+ * get back to.
22135
22184
  *
22136
- * @param allowRemint - Whether step 2 (provider re-mint) may run. Callers
22137
- * pass `false` for non-auth failures so a transient network error never
22138
- * escalates to a token re-mint; step 1 (in-memory reauth) always runs.
22139
- * @returns `true` if the session was reauthenticated, `false` otherwise.
22185
+ * The operation is still the verdict, never the RPC. Reauthenticating with
22186
+ * the in-memory token is accepted by a resume even while requests stay
22187
+ * refused, because the persisted `authorization_state` short-circuits token
22188
+ * validation — and `signalwire.reauthenticate` with a *freshly minted* token
22189
+ * has also been observed accepted while `subscriber.online` keeps being
22190
+ * refused (staging run 33826974634). Both look like success and are not.
22191
+ *
22192
+ * @returns the operation's value, or the reason recovery could not deliver
22193
+ * one. `error` is undefined when there was no way to mint at all.
22140
22194
  */
22141
- async recoverStaleCredential(allowRemint = true) {
22142
- const currentToken = this._deps.credential.token;
22143
- if (currentToken) try {
22144
- await this._clientSession.reauthenticate(currentToken);
22145
- return true;
22195
+ async recoverAndRetry(operation) {
22196
+ if (!await this.remintAndReauthenticate()) return { ok: false };
22197
+ try {
22198
+ const value = await operation();
22199
+ this._credentialRecovered = true;
22200
+ return {
22201
+ ok: true,
22202
+ value
22203
+ };
22146
22204
  } catch (error) {
22147
- logger$1.debug("[SignalWire] In-memory reauth failed during recovery:", error);
22205
+ logger$1.warn("[SignalWire] Reauthentication was accepted but the operation is still refused:", error);
22206
+ return {
22207
+ ok: false,
22208
+ error
22209
+ };
22210
+ }
22211
+ }
22212
+ /**
22213
+ * Re-mint a credential and adopt it only if the live session accepts it.
22214
+ *
22215
+ * The mechanism follows the binding: a client-bound session re-mints a bound
22216
+ * base SAT through `authenticate()` with the DPoP fingerprint, because the
22217
+ * developer refresh handler would hand back an unbound token and silently
22218
+ * degrade the session. An unbound session uses the refresh handler. Rotation
22219
+ * cost is not a reason to skip this — the only reason is having no mechanism.
22220
+ *
22221
+ * @returns whether the session is now running on a freshly accepted credential.
22222
+ */
22223
+ async remintAndReauthenticate() {
22224
+ const provider = this._credentialProvider;
22225
+ if (!provider) return false;
22226
+ const { clientBound } = this._clientSession;
22227
+ if (!clientBound && !provider.refresh) {
22228
+ logger$1.debug("[SignalWire] [SW-NO-REFRESH-HANDLER] Unbound session with no refresh handler; cannot re-mint.");
22229
+ return false;
22148
22230
  }
22149
- if (!allowRemint || this._clientSession.clientBound || !this._credentialProvider?.refresh) return false;
22150
22231
  try {
22151
- const newCredentials = await this.remintCredential(this._credentialProvider);
22152
- if (!newCredentials.token) return false;
22232
+ const newCredentials = clientBound ? await provider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0) : await this.remintCredential(provider);
22233
+ if (!newCredentials.token) {
22234
+ logger$1.warn("[SignalWire] Re-minted credential has no token; keeping the current one.");
22235
+ return false;
22236
+ }
22237
+ await this._clientSession.reauthenticate(newCredentials.token);
22153
22238
  this._deps.credential = newCredentials;
22154
22239
  this.persistCredential(newCredentials);
22155
- await this._clientSession.reauthenticate(newCredentials.token);
22156
- if (newCredentials.expiry_at) this._refreshCoordinator?.scheduleDeveloperRefresh(this._credentialProvider, newCredentials.expiry_at);
22240
+ if (newCredentials.expiry_at && provider.refresh) this._refreshCoordinator?.scheduleDeveloperRefresh(provider, newCredentials.expiry_at);
22157
22241
  return true;
22158
22242
  } catch (error) {
22159
- logger$1.error("[SignalWire] Credential recovery failed:", error);
22243
+ logger$1.warn("[SignalWire] Re-mint recovery failed:", error);
22160
22244
  return false;
22161
22245
  }
22162
22246
  }
@@ -22191,10 +22275,9 @@ var SignalWire = class extends Destroyable {
22191
22275
  if (!this._credentialProvider) return;
22192
22276
  try {
22193
22277
  let newCredentials;
22194
- if (this._clientSession.clientBound) {
22195
- const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
22278
+ if (this._clientSession?.clientBound ?? await this.wasClientBound()) {
22196
22279
  logger$1.debug("[SignalWire] Re-minting client-bound base SAT before reconnect");
22197
- newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
22280
+ newCredentials = await this._credentialProvider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0);
22198
22281
  } else if (this._credentialProvider.refresh) {
22199
22282
  logger$1.debug("[SignalWire] Refreshing unbound credential before reconnect");
22200
22283
  newCredentials = await this.remintCredential(this._credentialProvider);
@@ -22222,6 +22305,26 @@ var SignalWire = class extends Destroyable {
22222
22305
  this._deps.storage.setItem("sw:cached_credential", credential);
22223
22306
  if (this._deps.persistSession) this._deps.storage.setItem("sw:cached_credential", credential, "local");
22224
22307
  }
22308
+ /**
22309
+ * Persist whether the session is client-bound, mirroring the credential's
22310
+ * storage scopes so it survives a reload. The preflight recovery reads it
22311
+ * before any session exists to decide whether to re-bind via `authenticate()`
22312
+ * or refresh an unbound token; the marker tracks the latest binding, so an
22313
+ * unbound reconnect clears a stale marker from an earlier client-bound login.
22314
+ */
22315
+ persistClientBoundMarker(bound) {
22316
+ const scopes = this._deps.persistSession ? ["session", "local"] : ["session"];
22317
+ for (const scope of scopes) if (bound) this._deps.storage.setItem(CLIENT_BOUND_STORAGE_KEY, true, scope);
22318
+ else this._deps.storage.removeItem(CLIENT_BOUND_STORAGE_KEY, scope);
22319
+ }
22320
+ /** Read the persisted client-bound marker (see {@link persistClientBoundMarker}). */
22321
+ async wasClientBound() {
22322
+ const scopes = this._deps.persistSession ? ["local", "session"] : ["session"];
22323
+ for (const scope of scopes) try {
22324
+ if (await this._deps.storage.getItem(CLIENT_BOUND_STORAGE_KEY, scope)) return true;
22325
+ } catch {}
22326
+ return false;
22327
+ }
22225
22328
  async init() {
22226
22329
  this._user$.next(new User(this._deps.http));
22227
22330
  if (!this._options.skipConnection) await this.connect();
@@ -22245,6 +22348,42 @@ var SignalWire = class extends Destroyable {
22245
22348
  } catch (error) {
22246
22349
  logger$1.error("[SignalWire] Failed to reattach calls:", error);
22247
22350
  this._errors$.next(error instanceof Error ? error : new Error(String(error), { cause: error }));
22351
+ } finally {
22352
+ this._credentialRecovered = false;
22353
+ }
22354
+ }
22355
+ /**
22356
+ * Fetch the authenticated user profile, recovering a stale credential.
22357
+ *
22358
+ * On a reload the persisted credential can be expired. Unlike the WS resume —
22359
+ * which the server accepts against the persisted `authorization_state` even
22360
+ * with an expired token — this REST preflight has no such short-circuit and is
22361
+ * refused (401). There is no session yet to reauthenticate, so recovery
22362
+ * re-mints the credential through the provider ({@link refreshCredentialForReconnect})
22363
+ * and retries with a FRESH {@link User}: Fetchable memoizes its result
22364
+ * (shareReplay), so reusing the instance would replay the 401 instead of
22365
+ * re-fetching with the new token. Without the user id the transport/session —
22366
+ * and the reattach a reload is trying to preserve — cannot even be addressed.
22367
+ */
22368
+ async fetchUserOrRecover() {
22369
+ const fetchUser = async (user$1) => {
22370
+ if (!await (0, import_cjs$1.firstValueFrom)(user$1.fetched$)) throw new UnexpectedError("Failed to fetch user information - fetched$ emitted false");
22371
+ this._deps.user = user$1;
22372
+ };
22373
+ const user = this._user$.value;
22374
+ if (!user) throw new UnexpectedError("User not initialized before connect");
22375
+ try {
22376
+ await fetchUser(user);
22377
+ } catch (firstError) {
22378
+ 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.`);
22379
+ try {
22380
+ await this.refreshCredentialForReconnect();
22381
+ const refetched = new User(this._deps.http);
22382
+ await fetchUser(refetched);
22383
+ this._user$.next(refetched);
22384
+ } catch (retryError) {
22385
+ throw new UnexpectedError("Error fetching user information", { cause: retryError });
22386
+ }
22248
22387
  }
22249
22388
  }
22250
22389
  /**
@@ -22286,20 +22425,12 @@ var SignalWire = class extends Destroyable {
22286
22425
  */
22287
22426
  async connect() {
22288
22427
  await this.teardownTransportAndSession();
22289
- try {
22290
- const user = this._user$.value;
22291
- if (!user) throw new UnexpectedError("User not initialized before connect");
22292
- if (!await (0, import_cjs$1.firstValueFrom)(user.fetched$)) throw new UnexpectedError("Failed to fetch user information - fetched$ emitted false");
22293
- this._deps.user = user;
22294
- } catch (error) {
22295
- 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.`);
22296
- throw new UnexpectedError("Error fetching user information", { cause: error });
22297
- }
22428
+ await this.fetchUserOrRecover();
22298
22429
  const errorHandler = (error) => {
22299
22430
  this._errors$.next(error);
22300
22431
  };
22301
22432
  this._transport = new TransportManager(this._deps.storage, this._deps.protocolKey, this._deps.WebSocket, PreferencesContainer.instance.relayHost ?? this._deps.relayHost, errorHandler);
22302
- this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey);
22433
+ this._attachManager = new AttachManager(this._deps.storage, this._deps.deviceController, PreferencesContainer.instance.reconnectCallsTimeout, this._deps.attachedCallsKey, () => this._credentialRecovered);
22303
22434
  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$);
22304
22435
  this._publicSession = new ClientSessionWrapper(this._clientSession);
22305
22436
  this._clientSession.callControl = this._options.callControl ?? "routed";
@@ -22309,6 +22440,7 @@ var SignalWire = class extends Destroyable {
22309
22440
  });
22310
22441
  this.subscribeTo(this._clientSession.authorization$, (authorization) => {
22311
22442
  this._refreshCoordinator?.syncExpiryFromAuthorization(authorization, this._credentialProvider);
22443
+ this.persistClientBoundMarker(Boolean(authorization?.cnf?.jkt));
22312
22444
  });
22313
22445
  await this._clientSession.connect();
22314
22446
  await this._refreshCoordinator?.activate(this._deps.user, this._clientSession);
@@ -22562,19 +22694,18 @@ var SignalWire = class extends Destroyable {
22562
22694
  throw error;
22563
22695
  }
22564
22696
  logger$1.debug("[SignalWire] Failed to register user, attempting credential recovery...");
22565
- let failureCause = error;
22566
- if (await this.recoverStaleCredential(isRecoverableAuthError(error))) try {
22567
- logger$1.debug("[SignalWire] Recovery succeeded, retrying register()");
22697
+ const outcome = await this.recoverAndRetry(async () => {
22568
22698
  await this._transport.execute(RPCExecute({
22569
22699
  method: "subscriber.online",
22570
22700
  params: {}
22571
22701
  }));
22702
+ });
22703
+ if (outcome.ok) {
22704
+ logger$1.debug("[SignalWire] Recovery restored registration");
22572
22705
  this._isRegistered$.next(true);
22573
22706
  return;
22574
- } catch (retryError) {
22575
- logger$1.error("[SignalWire] Register retry after recovery failed:", retryError);
22576
- failureCause = retryError;
22577
22707
  }
22708
+ const failureCause = outcome.error ?? error;
22578
22709
  const registerError = new 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 }) });
22579
22710
  this._errors$.next(registerError);
22580
22711
  throw registerError;
@@ -22634,10 +22765,13 @@ var SignalWire = class extends Destroyable {
22634
22765
  return await this._clientSession.createOutboundCall(destination, computed_options);
22635
22766
  } catch (error) {
22636
22767
  if (!isRecoverableAuthError(error)) throw error;
22637
- logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering credential and retrying once");
22638
- if (!await this.recoverStaleCredential()) throw error;
22639
- await this.waitAuthentication();
22640
- return this._clientSession.createOutboundCall(destination, computed_options);
22768
+ logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering the session and retrying");
22769
+ const outcome = await this.recoverAndRetry(async () => {
22770
+ await this.waitAuthentication();
22771
+ return this._clientSession.createOutboundCall(destination, computed_options);
22772
+ });
22773
+ if (outcome.ok) return outcome.value;
22774
+ throw outcome.error ?? error;
22641
22775
  }
22642
22776
  }
22643
22777
  /**