@signalwire/js 4.0.0-dev-20260804221355 → 4.0.0-dev-20260908172838

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
  /**
@@ -4016,9 +4070,14 @@ var CallEventsManager = class extends Destroyable {
4016
4070
  updateLayouts() {
4017
4071
  if (!this.selfId) return;
4018
4072
  this.webRtcCallSession.executeMethod(this.selfId, "call.layout.list", {}).then((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
+ }
4019
4078
  this._sessionState$.next({
4020
4079
  ...this._sessionState$.value,
4021
- layouts: response.result.layouts
4080
+ layouts
4022
4081
  });
4023
4082
  }).catch((error) => {
4024
4083
  logger$22.error("[CallEventsManager] Error fetching layouts:", error);
@@ -6018,6 +6077,48 @@ const logger$16 = require_operators.getLogger();
6018
6077
  function resolveInviteNodeId(args) {
6019
6078
  return args.isInvite && !args.reattach && !args.explicitNodeId ? "" : args.currentNodeId ?? "";
6020
6079
  }
6080
+ /**
6081
+ * Surface the real outcome of a `webrtc.verto` reply.
6082
+ *
6083
+ * A webrtc.verto response nests several envelopes, each keyed by a verto-style
6084
+ * string `code` ("200" ok, "400"/etc. fail) rather than a JSON-RPC `error`. An outer
6085
+ * layer reports only whether the frame was delivered; an inner layer carries the op's
6086
+ * own outcome:
6087
+ *
6088
+ * response.result = { code:"200", result:{…} } ← delivery acknowledgement
6089
+ * .result = { jsonrpc, id, result:{…} } ← the reply payload
6090
+ * .result = { code:"400", message:"Bad request" } ← the actual op outcome
6091
+ *
6092
+ * A failure can appear at any layer (delivery refused, or the op itself rejected
6093
+ * deeper down), so walk every nested `.result` object and return the FIRST non-2xx
6094
+ * `code` with its message. Returns null when every `code` seen is 2xx or absent —
6095
+ * i.e. the op succeeded. This is the only way to detect that e.g. a mute/kick was
6096
+ * rejected, since the outer delivery `code` is "200" (delivered) even then.
6097
+ *
6098
+ * Pure function — exported for unit testing.
6099
+ */
6100
+ function findNestedVertoFailure(response) {
6101
+ let node = response;
6102
+ while (node !== null && typeof node === "object") {
6103
+ const obj = node;
6104
+ const err = obj.error;
6105
+ if (err !== null && typeof err === "object") {
6106
+ const e = err;
6107
+ const errCode = typeof e.code === "string" || typeof e.code === "number" ? String(e.code) : void 0;
6108
+ if (errCode !== void 0 && !/^2\d\d$/.test(errCode)) return {
6109
+ code: errCode,
6110
+ message: typeof e.message === "string" ? e.message : void 0
6111
+ };
6112
+ }
6113
+ const code = typeof obj.code === "string" || typeof obj.code === "number" ? String(obj.code) : void 0;
6114
+ if (code !== void 0 && !/^2\d\d$/.test(code)) return {
6115
+ code,
6116
+ message: typeof obj.message === "string" ? obj.message : void 0
6117
+ };
6118
+ node = obj.result !== null && typeof obj.result === "object" ? obj.result : null;
6119
+ }
6120
+ return null;
6121
+ }
6021
6122
  var VertoManager = class extends Destroyable {
6022
6123
  constructor(callSession) {
6023
6124
  super();
@@ -6342,6 +6443,33 @@ var WebRTCVertoManager = class extends VertoManager {
6342
6443
  get vertoPing$() {
6343
6444
  return this.cachedObservable("vertoPing$", () => this.webRtcCallSession.webrtcMessages$.pipe(require_operators.filterAs(isVertoPingInnerParams, "params"), (0, rxjs.takeUntil)(this.destroyed$)));
6344
6445
  }
6446
+ /**
6447
+ * Send a member-control op in-dialog via verto.info.
6448
+ *
6449
+ * The control payload rides in `params.command` — a sibling of `dialogParams`,
6450
+ * at the same level as `dtmf` in {@link sendDigits} — and the inner verto.info
6451
+ * is matched to this call's channel by `dialogParams.callID`, the in-dialog
6452
+ * convention for member-scoped frames. Because it is delivered on the dialog
6453
+ * itself, control lands on the call's own channel with no {node_id,call_id,member_id}
6454
+ * "self" tuple to get wrong. The outer webrtc.verto envelope (added by executeVerto)
6455
+ * still carries the own-leg callID + node_id for session routing.
6456
+ *
6457
+ * Keep `command` OUT of `dialogParams`: it is read at the params level, and
6458
+ * filterVertoParams rewrites/filters dialogParams keys but passes params-level
6459
+ * keys through verbatim.
6460
+ */
6461
+ async sendCallControl(method, params) {
6462
+ const response = await this.executeVerto(VertoInfo({
6463
+ dialogParams: { callID: this.webRtcCallSession.id },
6464
+ command: {
6465
+ method,
6466
+ params
6467
+ }
6468
+ }));
6469
+ const failure = findNestedVertoFailure(response);
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);
6471
+ return response;
6472
+ }
6345
6473
  async executeVerto(message, optionals = {}) {
6346
6474
  const webrtcVertoMessage = WebrtcVerto({
6347
6475
  callID: optionals.callID ?? this.webRtcCallSession.id,
@@ -6350,15 +6478,16 @@ var WebRTCVertoManager = class extends VertoManager {
6350
6478
  subscribe: optionals.subscribe
6351
6479
  });
6352
6480
  const response = await this.webRtcCallSession.execute(webrtcVertoMessage);
6481
+ const nonFatal = message.method === "verto.info" ? { fatal: false } : void 0;
6353
6482
  if (response.error) {
6354
6483
  const error = new require_operators.JSONRPCError(response.error.code, response.error.message, response.error.data);
6355
- this.onError?.(error);
6484
+ this.onError?.(error, nonFatal);
6356
6485
  return response;
6357
6486
  }
6358
6487
  const innerResult = require_operators.getValueFrom(response, "result.result");
6359
6488
  if (innerResult?.error) {
6360
6489
  const error = new require_operators.JSONRPCError(innerResult.error.code, innerResult.error.message, innerResult.error.data);
6361
- this.onError?.(error);
6490
+ this.onError?.(error, nonFatal);
6362
6491
  return response;
6363
6492
  }
6364
6493
  return response;
@@ -7649,6 +7778,33 @@ function mosToQualityLevel(mos) {
7649
7778
  return "critical";
7650
7779
  }
7651
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
+
7652
7808
  //#endregion
7653
7809
  //#region src/core/entities/Call.ts
7654
7810
  const logger$12 = require_operators.getLogger();
@@ -7747,8 +7903,11 @@ var WebRTCCall = class extends Destroyable {
7747
7903
  emitError(callError) {
7748
7904
  if (this._status$.value === "destroyed" || this._status$.value === "failed") return;
7749
7905
  this._errors$.next(callError);
7750
- if (callError.fatal) {
7906
+ if (callError.fatal && this._status$.value !== "disconnecting") {
7751
7907
  this._status$.next("failed");
7908
+ this.vertoManager.bye().catch((error) => {
7909
+ logger$12.debug("[Call] fatal-teardown bye failed (signaling likely already dead):", error);
7910
+ });
7752
7911
  this.destroy();
7753
7912
  }
7754
7913
  }
@@ -7865,6 +8024,7 @@ var WebRTCCall = class extends Destroyable {
7865
8024
  async executeMethod(target, method, args) {
7866
8025
  const self = this.callSelf;
7867
8026
  if (typeof target === "string" && target !== self.member_id) throw new require_operators.InvalidParams(`Target member ID ${target} does not match call's self member ID ${self.member_id}`);
8027
+ if (this.clientSession.callControl === "in-dialog") return this.executeMethodInDialog(target, method, args);
7868
8028
  const params = {
7869
8029
  ...args,
7870
8030
  self,
@@ -7884,6 +8044,81 @@ var WebRTCCall = class extends Destroyable {
7884
8044
  }
7885
8045
  }
7886
8046
  /**
8047
+ * `executeMethod` for a call opened with `callControl: 'in-dialog'`.
8048
+ *
8049
+ * Translates the routed transport's calling convention into the in-dialog one. No
8050
+ * `self` tuple is sent, but a `target` is — the same {call_id, member_id} the routed
8051
+ * transport puts in `target` (minus node_id), for self-ops and cross-member ops alike.
8052
+ *
8053
+ * Target shapes are per-verb and irregular, so they are centralised here rather
8054
+ * than left to callers: most verbs take a singular `target`, `call.member.remove`
8055
+ * takes a plural `targets` array, and `call.member.position.set` takes a flat
8056
+ * `targets` of `{call_id, position}` — the one verb keyed on call_id rather than
8057
+ * member_id, so the member triple `Participant.setPosition` built is unwrapped.
8058
+ */
8059
+ async executeMethodInDialog(target, method, args) {
8060
+ const control = { ...args };
8061
+ if (method === "call.member.position.set") control.targets = (args.targets ?? []).map((entry) => ({
8062
+ call_id: entry.target?.call_id ?? entry.call_id,
8063
+ position: entry.position
8064
+ }));
8065
+ else {
8066
+ const member = typeof target === "object" ? {
8067
+ call_id: target.call_id,
8068
+ member_id: target.member_id
8069
+ } : {
8070
+ call_id: this.id,
8071
+ member_id: target
8072
+ };
8073
+ if (method === "call.member.remove") control.targets = [member];
8074
+ else control.target = member;
8075
+ }
8076
+ return this.sendCommand(method, control);
8077
+ }
8078
+ /**
8079
+ * Sends a `call.*` control verb **in-dialog** via `verto.info`, as an alternative
8080
+ * to the routed {@link executeMethod} transport.
8081
+ *
8082
+ * Why both exist: `executeMethod` addresses the member with an explicit
8083
+ * `{node_id, call_id, member_id}` tuple, which does not resolve for every conference,
8084
+ * so the op can fail. An in-dialog frame carries the verb on the member's own
8085
+ * signaling channel instead, so control works without the client needing to know how
8086
+ * the conference is hosted.
8087
+ *
8088
+ * The trade-off is reach: the in-dialog transport is only accepted for calls that
8089
+ * join a conference over SWML (e.g. an SWML `join_conference`); use the routed
8090
+ * default otherwise.
8091
+ *
8092
+ * `params` are sent verbatim — nothing is built for you, which includes the target.
8093
+ * **A self-directed op still needs one**, or it is refused; name yourself explicitly:
8094
+ *
8095
+ * ```ts
8096
+ * const { call_id, member_id } = call.self.target;
8097
+ * await call.sendCommand('call.mute', { channels: ['audio'], target: { call_id, member_id } });
8098
+ * ```
8099
+ *
8100
+ * Never include `node_id` — only the two ids. The shapes are per-verb: most take a
8101
+ * singular `target`, `call.member.remove` takes a plural `targets` array, and
8102
+ * `call.member.position.set` takes a flat `targets: [{call_id, position}]` (the one
8103
+ * verb keyed on `call_id` rather than `member_id`). Verbs that act on the call as a
8104
+ * whole, or that the SDK does not wrap at all, take no target.
8105
+ *
8106
+ * For the typed alternative that handles all of this, create the client with
8107
+ * `callControl: 'in-dialog'` and use the ordinary `Call`/`Participant` methods.
8108
+ *
8109
+ * @internal Not part of the supported surface while the in-dialog transport is still
8110
+ * rolling out. `WebRTCCall` is exported from the package entry, so without this tag
8111
+ * TypeDoc publishes the method — and the example above — as public API.
8112
+ *
8113
+ * @param method - A `call.*` method name (e.g. `'call.mute'`).
8114
+ * @param params - Method parameters, sent verbatim.
8115
+ * @returns The method's own reply, unwrapped from the `verto.info` envelope.
8116
+ * @throws {JSONRPCError} If the control op fails.
8117
+ */
8118
+ async sendCommand(method, params = {}) {
8119
+ return unwrapVertoReply(await this.vertoManager.sendCallControl(method, params));
8120
+ }
8121
+ /**
7887
8122
  * The local leg's member triple — sent as `self` in every member RPC
7888
8123
  * envelope, and as the `target` of call-scoped self-operations (e.g. lock,
7889
8124
  * layout).
@@ -9210,6 +9445,7 @@ var ClientSessionManager = class extends Destroyable {
9210
9445
  minor: 0,
9211
9446
  revision: 0
9212
9447
  };
9448
+ this.callControl = "routed";
9213
9449
  this._authorization$ = this.createBehaviorSubject(void 0);
9214
9450
  this._errors$ = this.createReplaySubject(1);
9215
9451
  this._authState$ = this.createBehaviorSubject({ kind: "unauthenticated" });
@@ -9414,17 +9650,14 @@ var ClientSessionManager = class extends Destroyable {
9414
9650
  const hasStoredState = await (0, rxjs.firstValueFrom)(this.authorizationState$.pipe((0, rxjs.take)(1))) !== void 0;
9415
9651
  if (isRecoverableAuthError$1 && hasStoredState) {
9416
9652
  logger$9.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");
9417
- try {
9418
- await this.cleanupStoredConnectionParams();
9419
- } catch (cleanupError) {
9420
- logger$9.error("Failed to cleanup stored connection params:", cleanupError);
9421
- } finally {
9422
- this.transport.reconnect();
9423
- }
9653
+ await this.discardResumeStateAndReconnect();
9424
9654
  } else this._errors$.next(error);
9425
9655
  }
9426
9656
  /**
9427
- * 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.
9428
9661
  *
9429
9662
  * This is the stale-auth-state recovery helper used by handleAuthError:
9430
9663
  * the server rejected a reconnect, so the resume state is discarded and a
@@ -9432,9 +9665,24 @@ var ClientSessionManager = class extends Destroyable {
9432
9665
  * session lives on through the reconnect and reattachCalls() needs the
9433
9666
  * stored call references afterwards. Do NOT add detachAll() here.
9434
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
+ *
9435
9674
  * For public teardown (disconnect/destroy), use {@link teardownSessionState}
9436
9675
  * instead, which clears the attach records as well.
9437
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
+ }
9438
9686
  async cleanupStoredConnectionParams() {
9439
9687
  await this.transport.setProtocol(void 0);
9440
9688
  await this.updateAuthorizationStateInStorage(void 0);
@@ -9683,6 +9931,9 @@ var ClientSessionWrapper = class {
9683
9931
  get iceServers() {
9684
9932
  return this.clientSessionManager.iceServers;
9685
9933
  }
9934
+ get callControl() {
9935
+ return this.clientSessionManager.callControl;
9936
+ }
9686
9937
  async execute(request, options) {
9687
9938
  return this.clientSessionManager.execute(request, options);
9688
9939
  }
@@ -9921,7 +10172,7 @@ var DeviceTokenManager = class extends Destroyable {
9921
10172
  method: "POST",
9922
10173
  uri: require_operators.DEVICE_TOKEN_ENDPOINT
9923
10174
  });
9924
- const response = await this.http.request({
10175
+ const response = await this.http().request({
9925
10176
  url: require_operators.DEVICE_TOKEN_ENDPOINT,
9926
10177
  ...POST_PARAMS,
9927
10178
  body: JSON.stringify({
@@ -9948,7 +10199,7 @@ var DeviceTokenManager = class extends Destroyable {
9948
10199
  uri: require_operators.DEVICE_REFRESH_ENDPOINT,
9949
10200
  accessToken: currentToken
9950
10201
  });
9951
- const response = await this.http.request({
10202
+ const response = await this.http().request({
9952
10203
  url: require_operators.DEVICE_REFRESH_ENDPOINT,
9953
10204
  ...POST_PARAMS,
9954
10205
  body: JSON.stringify({
@@ -10998,36 +11249,16 @@ var TransportManager = class extends Destroyable {
10998
11249
  }
10999
11250
  };
11000
11251
 
11001
- //#endregion
11002
- //#region src/utils/authRecovery.ts
11003
- /**
11004
- * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
11005
- * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
11006
- * underlying signaling error is nested. Bounded by a visited set to guard
11007
- * against cyclic causes.
11008
- */
11009
- function findJSONRPCError(error) {
11010
- const seen = /* @__PURE__ */ new Set();
11011
- let current = error;
11012
- while (current instanceof Error && !seen.has(current)) {
11013
- seen.add(current);
11014
- if (current instanceof require_operators.JSONRPCError) return current;
11015
- current = current.error ?? current.cause;
11016
- }
11017
- }
11018
- /**
11019
- * Whether an error is a session-recoverable authentication failure
11020
- * (`-32002` authentication failed or `-32003` requester validation failed)
11021
- * that a credential re-mint + retry can heal.
11022
- */
11023
- function isRecoverableAuthError(error) {
11024
- const rpcError = findJSONRPCError(error);
11025
- return rpcError !== void 0 && (rpcError.code === require_operators.RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === require_operators.RPC_ERROR_AUTHENTICATION_FAILED);
11026
- }
11027
-
11028
11252
  //#endregion
11029
11253
  //#region src/clients/SignalWire.ts
11030
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";
11031
11262
  const buildOptionsFromDestination = (destination) => {
11032
11263
  if (typeof destination === "string") {
11033
11264
  const queryStartIndex = destination.indexOf("?");
@@ -11071,6 +11302,7 @@ var SignalWire = class extends Destroyable {
11071
11302
  this.preferences = new ClientPreferences();
11072
11303
  this._user$ = this.createBehaviorSubject(void 0);
11073
11304
  this._directory$ = this.createBehaviorSubject(void 0);
11305
+ this._credentialRecovered = false;
11074
11306
  this._isConnected$ = this.createBehaviorSubject(false);
11075
11307
  this._isRegistered$ = this.createBehaviorSubject(false);
11076
11308
  this._errors$ = this.createReplaySubject(1);
@@ -11109,6 +11341,16 @@ var SignalWire = class extends Destroyable {
11109
11341
  });
11110
11342
  }
11111
11343
  /**
11344
+ * Build the refresh path's own HTTP controller, against whatever host is current.
11345
+ *
11346
+ * Called on first use rather than up front, so `apiHost` already reflects the
11347
+ * token's `ch` claim. Same credential source as the container's controller — only
11348
+ * the instance, and therefore its observable streams, is separate.
11349
+ */
11350
+ createRefreshHttpController() {
11351
+ return new HTTPRequestController(this._deps.apiHost, () => this._deps.credential);
11352
+ }
11353
+ /**
11112
11354
  * Initializes DPoP if not already set up. Returns the fingerprint on success.
11113
11355
  */
11114
11356
  async initDPoP() {
@@ -11135,7 +11377,14 @@ var SignalWire = class extends Destroyable {
11135
11377
  async resolveCredentials() {
11136
11378
  const fingerprint = await this.initDPoP();
11137
11379
  this._refreshCoordinator = new CredentialRefreshCoordinator(this._dpopManager, {
11138
- http: this._deps.http,
11380
+ http: () => {
11381
+ if (!this._refreshHttp || this._refreshHttpHost !== this._deps.apiHost) {
11382
+ this._refreshHttp?.destroy();
11383
+ this._refreshHttp = this.createRefreshHttpController();
11384
+ this._refreshHttpHost = this._deps.apiHost;
11385
+ }
11386
+ return this._refreshHttp;
11387
+ },
11139
11388
  notifier: {
11140
11389
  onError: (error) => this._errors$.next(error),
11141
11390
  onWarning: (warning) => this._warnings$.next(warning),
@@ -11219,43 +11468,76 @@ var SignalWire = class extends Destroyable {
11219
11468
  }
11220
11469
  }
11221
11470
  /**
11222
- * One-shot recovery for a live session that failed with a recoverable auth
11223
- * error (`-32002`/`-32003`) because its token went stale — e.g. a refresh
11224
- * 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.
11225
11481
  *
11226
- * Two steps, first that succeeds wins:
11227
- * 1. Reauthenticate with the in-memory token (a fresh DPoP proof is
11228
- * generated automatically). Heals a session whose token was already
11229
- * refreshed by the coordinator but never applied to the open socket,
11230
- * and a client-bound session whose server-side auth merely drifted.
11231
- * 2. Re-mint via the developer provider's `refresh()` and reauthenticate.
11232
- * Skipped for client-bound sessions (the DeviceTokenManager owns their
11233
- * 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.
11234
11488
  *
11235
- * @param allowRemint - Whether step 2 (provider re-mint) may run. Callers
11236
- * pass `false` for non-auth failures so a transient network error never
11237
- * escalates to a token re-mint; step 1 (in-memory reauth) always runs.
11238
- * @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.
11239
11491
  */
11240
- async recoverStaleCredential(allowRemint = true) {
11241
- const currentToken = this._deps.credential.token;
11242
- if (currentToken) try {
11243
- await this._clientSession.reauthenticate(currentToken);
11244
- 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
+ };
11245
11501
  } catch (error) {
11246
- 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;
11247
11527
  }
11248
- if (!allowRemint || this._clientSession.clientBound || !this._credentialProvider?.refresh) return false;
11249
11528
  try {
11250
- const newCredentials = await this.remintCredential(this._credentialProvider);
11251
- 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);
11252
11535
  this._deps.credential = newCredentials;
11253
11536
  this.persistCredential(newCredentials);
11254
- await this._clientSession.reauthenticate(newCredentials.token);
11255
- 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);
11256
11538
  return true;
11257
11539
  } catch (error) {
11258
- logger$1.error("[SignalWire] Credential recovery failed:", error);
11540
+ logger$1.warn("[SignalWire] Re-mint recovery failed:", error);
11259
11541
  return false;
11260
11542
  }
11261
11543
  }
@@ -11290,10 +11572,9 @@ var SignalWire = class extends Destroyable {
11290
11572
  if (!this._credentialProvider) return;
11291
11573
  try {
11292
11574
  let newCredentials;
11293
- if (this._clientSession.clientBound) {
11294
- const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
11575
+ if (this._clientSession?.clientBound ?? await this.wasClientBound()) {
11295
11576
  logger$1.debug("[SignalWire] Re-minting client-bound base SAT before reconnect");
11296
- newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
11577
+ newCredentials = await this._credentialProvider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0);
11297
11578
  } else if (this._credentialProvider.refresh) {
11298
11579
  logger$1.debug("[SignalWire] Refreshing unbound credential before reconnect");
11299
11580
  newCredentials = await this.remintCredential(this._credentialProvider);
@@ -11321,6 +11602,26 @@ var SignalWire = class extends Destroyable {
11321
11602
  this._deps.storage.setItem("sw:cached_credential", credential);
11322
11603
  if (this._deps.persistSession) this._deps.storage.setItem("sw:cached_credential", credential, "local");
11323
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
+ }
11324
11625
  async init() {
11325
11626
  this._user$.next(new User(this._deps.http));
11326
11627
  if (!this._options.skipConnection) await this.connect();
@@ -11344,6 +11645,42 @@ var SignalWire = class extends Destroyable {
11344
11645
  } catch (error) {
11345
11646
  logger$1.error("[SignalWire] Failed to reattach calls:", error);
11346
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
+ }
11347
11684
  }
11348
11685
  }
11349
11686
  /**
@@ -11385,28 +11722,22 @@ var SignalWire = class extends Destroyable {
11385
11722
  */
11386
11723
  async connect() {
11387
11724
  await this.teardownTransportAndSession();
11388
- try {
11389
- const user = this._user$.value;
11390
- if (!user) throw new require_operators.UnexpectedError("User not initialized before connect");
11391
- if (!await (0, rxjs.firstValueFrom)(user.fetched$)) throw new require_operators.UnexpectedError("Failed to fetch user information - fetched$ emitted false");
11392
- this._deps.user = user;
11393
- } catch (error) {
11394
- 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.`);
11395
- throw new require_operators.UnexpectedError("Error fetching user information", { cause: error });
11396
- }
11725
+ await this.fetchUserOrRecover();
11397
11726
  const errorHandler = (error) => {
11398
11727
  this._errors$.next(error);
11399
11728
  };
11400
11729
  this._transport = new TransportManager(this._deps.storage, this._deps.protocolKey, this._deps.WebSocket, PreferencesContainer.instance.relayHost ?? this._deps.relayHost, errorHandler);
11401
- 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);
11402
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$);
11403
11732
  this._publicSession = new ClientSessionWrapper(this._clientSession);
11733
+ this._clientSession.callControl = this._options.callControl ?? "routed";
11404
11734
  this._clientSession.onBeforeReconnect = async () => this.refreshCredentialForReconnect();
11405
11735
  this.subscribeTo(this._clientSession.errors$, (error) => {
11406
11736
  this._errors$.next(error);
11407
11737
  });
11408
11738
  this.subscribeTo(this._clientSession.authorization$, (authorization) => {
11409
11739
  this._refreshCoordinator?.syncExpiryFromAuthorization(authorization, this._credentialProvider);
11740
+ this.persistClientBoundMarker(Boolean(authorization?.cnf?.jkt));
11410
11741
  });
11411
11742
  await this._clientSession.connect();
11412
11743
  await this._refreshCoordinator?.activate(this._deps.user, this._clientSession);
@@ -11660,19 +11991,18 @@ var SignalWire = class extends Destroyable {
11660
11991
  throw error;
11661
11992
  }
11662
11993
  logger$1.debug("[SignalWire] Failed to register user, attempting credential recovery...");
11663
- let failureCause = error;
11664
- if (await this.recoverStaleCredential(isRecoverableAuthError(error))) try {
11665
- logger$1.debug("[SignalWire] Recovery succeeded, retrying register()");
11994
+ const outcome = await this.recoverAndRetry(async () => {
11666
11995
  await this._transport.execute(RPCExecute({
11667
11996
  method: "subscriber.online",
11668
11997
  params: {}
11669
11998
  }));
11999
+ });
12000
+ if (outcome.ok) {
12001
+ logger$1.debug("[SignalWire] Recovery restored registration");
11670
12002
  this._isRegistered$.next(true);
11671
12003
  return;
11672
- } catch (retryError) {
11673
- logger$1.error("[SignalWire] Register retry after recovery failed:", retryError);
11674
- failureCause = retryError;
11675
12004
  }
12005
+ const failureCause = outcome.error ?? error;
11676
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 }) });
11677
12007
  this._errors$.next(registerError);
11678
12008
  throw registerError;
@@ -11732,10 +12062,13 @@ var SignalWire = class extends Destroyable {
11732
12062
  return await this._clientSession.createOutboundCall(destination, computed_options);
11733
12063
  } catch (error) {
11734
12064
  if (!isRecoverableAuthError(error)) throw error;
11735
- logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering credential and retrying once");
11736
- if (!await this.recoverStaleCredential()) throw error;
11737
- await this.waitAuthentication();
11738
- 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;
11739
12072
  }
11740
12073
  }
11741
12074
  /**
@@ -12017,6 +12350,8 @@ var SignalWire = class extends Destroyable {
12017
12350
  destroy() {
12018
12351
  this._refreshCoordinator?.destroy();
12019
12352
  this._refreshCoordinator = void 0;
12353
+ this._refreshHttp?.destroy();
12354
+ this._refreshHttp = void 0;
12020
12355
  this._dpopManager?.destroy();
12021
12356
  const session = this._clientSession;
12022
12357
  session?.teardownSessionState();