@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.
@@ -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
  /**
@@ -14706,9 +14760,14 @@ var CallEventsManager = class extends Destroyable {
14706
14760
  updateLayouts() {
14707
14761
  if (!this.selfId) return;
14708
14762
  this.webRtcCallSession.executeMethod(this.selfId, "call.layout.list", {}).then((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
+ }
14709
14768
  this._sessionState$.next({
14710
14769
  ...this._sessionState$.value,
14711
- layouts: response.result.layouts
14770
+ layouts
14712
14771
  });
14713
14772
  }).catch((error) => {
14714
14773
  logger$22.error("[CallEventsManager] Error fetching layouts:", error);
@@ -16713,6 +16772,48 @@ const logger$16 = getLogger();
16713
16772
  function resolveInviteNodeId(args) {
16714
16773
  return args.isInvite && !args.reattach && !args.explicitNodeId ? "" : args.currentNodeId ?? "";
16715
16774
  }
16775
+ /**
16776
+ * Surface the real outcome of a `webrtc.verto` reply.
16777
+ *
16778
+ * A webrtc.verto response nests several envelopes, each keyed by a verto-style
16779
+ * string `code` ("200" ok, "400"/etc. fail) rather than a JSON-RPC `error`. An outer
16780
+ * layer reports only whether the frame was delivered; an inner layer carries the op's
16781
+ * own outcome:
16782
+ *
16783
+ * response.result = { code:"200", result:{…} } ← delivery acknowledgement
16784
+ * .result = { jsonrpc, id, result:{…} } ← the reply payload
16785
+ * .result = { code:"400", message:"Bad request" } ← the actual op outcome
16786
+ *
16787
+ * A failure can appear at any layer (delivery refused, or the op itself rejected
16788
+ * deeper down), so walk every nested `.result` object and return the FIRST non-2xx
16789
+ * `code` with its message. Returns null when every `code` seen is 2xx or absent —
16790
+ * i.e. the op succeeded. This is the only way to detect that e.g. a mute/kick was
16791
+ * rejected, since the outer delivery `code` is "200" (delivered) even then.
16792
+ *
16793
+ * Pure function — exported for unit testing.
16794
+ */
16795
+ function findNestedVertoFailure(response) {
16796
+ let node = response;
16797
+ while (node !== null && typeof node === "object") {
16798
+ const obj = node;
16799
+ const err = obj.error;
16800
+ if (err !== null && typeof err === "object") {
16801
+ const e = err;
16802
+ const errCode = typeof e.code === "string" || typeof e.code === "number" ? String(e.code) : void 0;
16803
+ if (errCode !== void 0 && !/^2\d\d$/.test(errCode)) return {
16804
+ code: errCode,
16805
+ message: typeof e.message === "string" ? e.message : void 0
16806
+ };
16807
+ }
16808
+ const code = typeof obj.code === "string" || typeof obj.code === "number" ? String(obj.code) : void 0;
16809
+ if (code !== void 0 && !/^2\d\d$/.test(code)) return {
16810
+ code,
16811
+ message: typeof obj.message === "string" ? obj.message : void 0
16812
+ };
16813
+ node = obj.result !== null && typeof obj.result === "object" ? obj.result : null;
16814
+ }
16815
+ return null;
16816
+ }
16716
16817
  var VertoManager = class extends Destroyable {
16717
16818
  constructor(callSession) {
16718
16819
  super();
@@ -17037,6 +17138,33 @@ var WebRTCVertoManager = class extends VertoManager {
17037
17138
  get vertoPing$() {
17038
17139
  return this.cachedObservable("vertoPing$", () => this.webRtcCallSession.webrtcMessages$.pipe(filterAs(isVertoPingInnerParams, "params"), (0, import_cjs$15.takeUntil)(this.destroyed$)));
17039
17140
  }
17141
+ /**
17142
+ * Send a member-control op in-dialog via verto.info.
17143
+ *
17144
+ * The control payload rides in `params.command` — a sibling of `dialogParams`,
17145
+ * at the same level as `dtmf` in {@link sendDigits} — and the inner verto.info
17146
+ * is matched to this call's channel by `dialogParams.callID`, the in-dialog
17147
+ * convention for member-scoped frames. Because it is delivered on the dialog
17148
+ * itself, control lands on the call's own channel with no {node_id,call_id,member_id}
17149
+ * "self" tuple to get wrong. The outer webrtc.verto envelope (added by executeVerto)
17150
+ * still carries the own-leg callID + node_id for session routing.
17151
+ *
17152
+ * Keep `command` OUT of `dialogParams`: it is read at the params level, and
17153
+ * filterVertoParams rewrites/filters dialogParams keys but passes params-level
17154
+ * keys through verbatim.
17155
+ */
17156
+ async sendCallControl(method, params) {
17157
+ const response = await this.executeVerto(VertoInfo({
17158
+ dialogParams: { callID: this.webRtcCallSession.id },
17159
+ command: {
17160
+ method,
17161
+ params
17162
+ }
17163
+ }));
17164
+ const failure = findNestedVertoFailure(response);
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);
17166
+ return response;
17167
+ }
17040
17168
  async executeVerto(message, optionals = {}) {
17041
17169
  const webrtcVertoMessage = WebrtcVerto({
17042
17170
  callID: optionals.callID ?? this.webRtcCallSession.id,
@@ -17045,15 +17173,16 @@ var WebRTCVertoManager = class extends VertoManager {
17045
17173
  subscribe: optionals.subscribe
17046
17174
  });
17047
17175
  const response = await this.webRtcCallSession.execute(webrtcVertoMessage);
17176
+ const nonFatal = message.method === "verto.info" ? { fatal: false } : void 0;
17048
17177
  if (response.error) {
17049
17178
  const error = new JSONRPCError(response.error.code, response.error.message, response.error.data);
17050
- this.onError?.(error);
17179
+ this.onError?.(error, nonFatal);
17051
17180
  return response;
17052
17181
  }
17053
17182
  const innerResult = getValueFrom(response, "result.result");
17054
17183
  if (innerResult?.error) {
17055
17184
  const error = new JSONRPCError(innerResult.error.code, innerResult.error.message, innerResult.error.data);
17056
- this.onError?.(error);
17185
+ this.onError?.(error, nonFatal);
17057
17186
  return response;
17058
17187
  }
17059
17188
  return response;
@@ -18341,6 +18470,33 @@ function mosToQualityLevel(mos) {
18341
18470
  return "critical";
18342
18471
  }
18343
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
+
18344
18500
  //#endregion
18345
18501
  //#region src/core/entities/Call.ts
18346
18502
  var import_cjs$11 = require_cjs();
@@ -18440,8 +18596,11 @@ var WebRTCCall = class extends Destroyable {
18440
18596
  emitError(callError) {
18441
18597
  if (this._status$.value === "destroyed" || this._status$.value === "failed") return;
18442
18598
  this._errors$.next(callError);
18443
- if (callError.fatal) {
18599
+ if (callError.fatal && this._status$.value !== "disconnecting") {
18444
18600
  this._status$.next("failed");
18601
+ this.vertoManager.bye().catch((error) => {
18602
+ logger$12.debug("[Call] fatal-teardown bye failed (signaling likely already dead):", error);
18603
+ });
18445
18604
  this.destroy();
18446
18605
  }
18447
18606
  }
@@ -18558,6 +18717,7 @@ var WebRTCCall = class extends Destroyable {
18558
18717
  async executeMethod(target, method, args) {
18559
18718
  const self = this.callSelf;
18560
18719
  if (typeof target === "string" && target !== self.member_id) throw new InvalidParams(`Target member ID ${target} does not match call's self member ID ${self.member_id}`);
18720
+ if (this.clientSession.callControl === "in-dialog") return this.executeMethodInDialog(target, method, args);
18561
18721
  const params = {
18562
18722
  ...args,
18563
18723
  self,
@@ -18577,6 +18737,81 @@ var WebRTCCall = class extends Destroyable {
18577
18737
  }
18578
18738
  }
18579
18739
  /**
18740
+ * `executeMethod` for a call opened with `callControl: 'in-dialog'`.
18741
+ *
18742
+ * Translates the routed transport's calling convention into the in-dialog one. No
18743
+ * `self` tuple is sent, but a `target` is — the same {call_id, member_id} the routed
18744
+ * transport puts in `target` (minus node_id), for self-ops and cross-member ops alike.
18745
+ *
18746
+ * Target shapes are per-verb and irregular, so they are centralised here rather
18747
+ * than left to callers: most verbs take a singular `target`, `call.member.remove`
18748
+ * takes a plural `targets` array, and `call.member.position.set` takes a flat
18749
+ * `targets` of `{call_id, position}` — the one verb keyed on call_id rather than
18750
+ * member_id, so the member triple `Participant.setPosition` built is unwrapped.
18751
+ */
18752
+ async executeMethodInDialog(target, method, args) {
18753
+ const control = { ...args };
18754
+ if (method === "call.member.position.set") control.targets = (args.targets ?? []).map((entry) => ({
18755
+ call_id: entry.target?.call_id ?? entry.call_id,
18756
+ position: entry.position
18757
+ }));
18758
+ else {
18759
+ const member = typeof target === "object" ? {
18760
+ call_id: target.call_id,
18761
+ member_id: target.member_id
18762
+ } : {
18763
+ call_id: this.id,
18764
+ member_id: target
18765
+ };
18766
+ if (method === "call.member.remove") control.targets = [member];
18767
+ else control.target = member;
18768
+ }
18769
+ return this.sendCommand(method, control);
18770
+ }
18771
+ /**
18772
+ * Sends a `call.*` control verb **in-dialog** via `verto.info`, as an alternative
18773
+ * to the routed {@link executeMethod} transport.
18774
+ *
18775
+ * Why both exist: `executeMethod` addresses the member with an explicit
18776
+ * `{node_id, call_id, member_id}` tuple, which does not resolve for every conference,
18777
+ * so the op can fail. An in-dialog frame carries the verb on the member's own
18778
+ * signaling channel instead, so control works without the client needing to know how
18779
+ * the conference is hosted.
18780
+ *
18781
+ * The trade-off is reach: the in-dialog transport is only accepted for calls that
18782
+ * join a conference over SWML (e.g. an SWML `join_conference`); use the routed
18783
+ * default otherwise.
18784
+ *
18785
+ * `params` are sent verbatim — nothing is built for you, which includes the target.
18786
+ * **A self-directed op still needs one**, or it is refused; name yourself explicitly:
18787
+ *
18788
+ * ```ts
18789
+ * const { call_id, member_id } = call.self.target;
18790
+ * await call.sendCommand('call.mute', { channels: ['audio'], target: { call_id, member_id } });
18791
+ * ```
18792
+ *
18793
+ * Never include `node_id` — only the two ids. The shapes are per-verb: most take a
18794
+ * singular `target`, `call.member.remove` takes a plural `targets` array, and
18795
+ * `call.member.position.set` takes a flat `targets: [{call_id, position}]` (the one
18796
+ * verb keyed on `call_id` rather than `member_id`). Verbs that act on the call as a
18797
+ * whole, or that the SDK does not wrap at all, take no target.
18798
+ *
18799
+ * For the typed alternative that handles all of this, create the client with
18800
+ * `callControl: 'in-dialog'` and use the ordinary `Call`/`Participant` methods.
18801
+ *
18802
+ * @internal Not part of the supported surface while the in-dialog transport is still
18803
+ * rolling out. `WebRTCCall` is exported from the package entry, so without this tag
18804
+ * TypeDoc publishes the method — and the example above — as public API.
18805
+ *
18806
+ * @param method - A `call.*` method name (e.g. `'call.mute'`).
18807
+ * @param params - Method parameters, sent verbatim.
18808
+ * @returns The method's own reply, unwrapped from the `verto.info` envelope.
18809
+ * @throws {JSONRPCError} If the control op fails.
18810
+ */
18811
+ async sendCommand(method, params = {}) {
18812
+ return unwrapVertoReply(await this.vertoManager.sendCallControl(method, params));
18813
+ }
18814
+ /**
18580
18815
  * The local leg's member triple — sent as `self` in every member RPC
18581
18816
  * envelope, and as the `target` of call-scoped self-operations (e.g. lock,
18582
18817
  * layout).
@@ -19907,6 +20142,7 @@ var ClientSessionManager = class extends Destroyable {
19907
20142
  minor: 0,
19908
20143
  revision: 0
19909
20144
  };
20145
+ this.callControl = "routed";
19910
20146
  this._authorization$ = this.createBehaviorSubject(void 0);
19911
20147
  this._errors$ = this.createReplaySubject(1);
19912
20148
  this._authState$ = this.createBehaviorSubject({ kind: "unauthenticated" });
@@ -20111,17 +20347,14 @@ var ClientSessionManager = class extends Destroyable {
20111
20347
  const hasStoredState = await (0, import_cjs$7.firstValueFrom)(this.authorizationState$.pipe((0, import_cjs$7.take)(1))) !== void 0;
20112
20348
  if (isRecoverableAuthError$1 && hasStoredState) {
20113
20349
  logger$9.debug("[Session] Recoverable auth error — cleaning up stored state and reconnecting fresh");
20114
- try {
20115
- await this.cleanupStoredConnectionParams();
20116
- } catch (cleanupError) {
20117
- logger$9.error("Failed to cleanup stored connection params:", cleanupError);
20118
- } finally {
20119
- this.transport.reconnect();
20120
- }
20350
+ await this.discardResumeStateAndReconnect();
20121
20351
  } else this._errors$.next(error);
20122
20352
  }
20123
20353
  /**
20124
- * 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.
20125
20358
  *
20126
20359
  * This is the stale-auth-state recovery helper used by handleAuthError:
20127
20360
  * the server rejected a reconnect, so the resume state is discarded and a
@@ -20129,9 +20362,24 @@ var ClientSessionManager = class extends Destroyable {
20129
20362
  * session lives on through the reconnect and reattachCalls() needs the
20130
20363
  * stored call references afterwards. Do NOT add detachAll() here.
20131
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
+ *
20132
20371
  * For public teardown (disconnect/destroy), use {@link teardownSessionState}
20133
20372
  * instead, which clears the attach records as well.
20134
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
+ }
20135
20383
  async cleanupStoredConnectionParams() {
20136
20384
  await this.transport.setProtocol(void 0);
20137
20385
  await this.updateAuthorizationStateInStorage(void 0);
@@ -20380,6 +20628,9 @@ var ClientSessionWrapper = class {
20380
20628
  get iceServers() {
20381
20629
  return this.clientSessionManager.iceServers;
20382
20630
  }
20631
+ get callControl() {
20632
+ return this.clientSessionManager.callControl;
20633
+ }
20383
20634
  async execute(request, options) {
20384
20635
  return this.clientSessionManager.execute(request, options);
20385
20636
  }
@@ -20620,7 +20871,7 @@ var DeviceTokenManager = class extends Destroyable {
20620
20871
  method: "POST",
20621
20872
  uri: DEVICE_TOKEN_ENDPOINT
20622
20873
  });
20623
- const response = await this.http.request({
20874
+ const response = await this.http().request({
20624
20875
  url: DEVICE_TOKEN_ENDPOINT,
20625
20876
  ...POST_PARAMS,
20626
20877
  body: JSON.stringify({
@@ -20647,7 +20898,7 @@ var DeviceTokenManager = class extends Destroyable {
20647
20898
  uri: DEVICE_REFRESH_ENDPOINT,
20648
20899
  accessToken: currentToken
20649
20900
  });
20650
- const response = await this.http.request({
20901
+ const response = await this.http().request({
20651
20902
  url: DEVICE_REFRESH_ENDPOINT,
20652
20903
  ...POST_PARAMS,
20653
20904
  body: JSON.stringify({
@@ -21700,37 +21951,17 @@ var TransportManager = class extends Destroyable {
21700
21951
  }
21701
21952
  };
21702
21953
 
21703
- //#endregion
21704
- //#region src/utils/authRecovery.ts
21705
- /**
21706
- * Walk an error's `error`/`cause` chain looking for a {@link JSONRPCError}.
21707
- * Errors thrown by call creation are wrapped (e.g. `CallCreateError`), so the
21708
- * underlying signaling error is nested. Bounded by a visited set to guard
21709
- * against cyclic causes.
21710
- */
21711
- function findJSONRPCError(error) {
21712
- const seen = /* @__PURE__ */ new Set();
21713
- let current = error;
21714
- while (current instanceof Error && !seen.has(current)) {
21715
- seen.add(current);
21716
- if (current instanceof JSONRPCError) return current;
21717
- current = current.error ?? current.cause;
21718
- }
21719
- }
21720
- /**
21721
- * Whether an error is a session-recoverable authentication failure
21722
- * (`-32002` authentication failed or `-32003` requester validation failed)
21723
- * that a credential re-mint + retry can heal.
21724
- */
21725
- function isRecoverableAuthError(error) {
21726
- const rpcError = findJSONRPCError(error);
21727
- return rpcError !== void 0 && (rpcError.code === RPC_ERROR_REQUESTER_VALIDATION_FAILED || rpcError.code === RPC_ERROR_AUTHENTICATION_FAILED);
21728
- }
21729
-
21730
21954
  //#endregion
21731
21955
  //#region src/clients/SignalWire.ts
21732
21956
  var import_cjs$1 = require_cjs();
21733
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";
21734
21965
  const buildOptionsFromDestination = (destination) => {
21735
21966
  if (typeof destination === "string") {
21736
21967
  const queryStartIndex = destination.indexOf("?");
@@ -21774,6 +22005,7 @@ var SignalWire = class extends Destroyable {
21774
22005
  this.preferences = new ClientPreferences();
21775
22006
  this._user$ = this.createBehaviorSubject(void 0);
21776
22007
  this._directory$ = this.createBehaviorSubject(void 0);
22008
+ this._credentialRecovered = false;
21777
22009
  this._isConnected$ = this.createBehaviorSubject(false);
21778
22010
  this._isRegistered$ = this.createBehaviorSubject(false);
21779
22011
  this._errors$ = this.createReplaySubject(1);
@@ -21812,6 +22044,16 @@ var SignalWire = class extends Destroyable {
21812
22044
  });
21813
22045
  }
21814
22046
  /**
22047
+ * Build the refresh path's own HTTP controller, against whatever host is current.
22048
+ *
22049
+ * Called on first use rather than up front, so `apiHost` already reflects the
22050
+ * token's `ch` claim. Same credential source as the container's controller — only
22051
+ * the instance, and therefore its observable streams, is separate.
22052
+ */
22053
+ createRefreshHttpController() {
22054
+ return new HTTPRequestController(this._deps.apiHost, () => this._deps.credential);
22055
+ }
22056
+ /**
21815
22057
  * Initializes DPoP if not already set up. Returns the fingerprint on success.
21816
22058
  */
21817
22059
  async initDPoP() {
@@ -21838,7 +22080,14 @@ var SignalWire = class extends Destroyable {
21838
22080
  async resolveCredentials() {
21839
22081
  const fingerprint = await this.initDPoP();
21840
22082
  this._refreshCoordinator = new CredentialRefreshCoordinator(this._dpopManager, {
21841
- http: this._deps.http,
22083
+ http: () => {
22084
+ if (!this._refreshHttp || this._refreshHttpHost !== this._deps.apiHost) {
22085
+ this._refreshHttp?.destroy();
22086
+ this._refreshHttp = this.createRefreshHttpController();
22087
+ this._refreshHttpHost = this._deps.apiHost;
22088
+ }
22089
+ return this._refreshHttp;
22090
+ },
21842
22091
  notifier: {
21843
22092
  onError: (error) => this._errors$.next(error),
21844
22093
  onWarning: (warning) => this._warnings$.next(warning),
@@ -21922,43 +22171,76 @@ var SignalWire = class extends Destroyable {
21922
22171
  }
21923
22172
  }
21924
22173
  /**
21925
- * One-shot recovery for a live session that failed with a recoverable auth
21926
- * error (`-32002`/`-32003`) because its token went stale — e.g. a refresh
21927
- * 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.
21928
22176
  *
21929
- * Two steps, first that succeeds wins:
21930
- * 1. Reauthenticate with the in-memory token (a fresh DPoP proof is
21931
- * generated automatically). Heals a session whose token was already
21932
- * refreshed by the coordinator but never applied to the open socket,
21933
- * and a client-bound session whose server-side auth merely drifted.
21934
- * 2. Re-mint via the developer provider's `refresh()` and reauthenticate.
21935
- * Skipped for client-bound sessions (the DeviceTokenManager owns their
21936
- * 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.
21937
22184
  *
21938
- * @param allowRemint - Whether step 2 (provider re-mint) may run. Callers
21939
- * pass `false` for non-auth failures so a transient network error never
21940
- * escalates to a token re-mint; step 1 (in-memory reauth) always runs.
21941
- * @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.
21942
22194
  */
21943
- async recoverStaleCredential(allowRemint = true) {
21944
- const currentToken = this._deps.credential.token;
21945
- if (currentToken) try {
21946
- await this._clientSession.reauthenticate(currentToken);
21947
- 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
+ };
21948
22204
  } catch (error) {
21949
- 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;
21950
22230
  }
21951
- if (!allowRemint || this._clientSession.clientBound || !this._credentialProvider?.refresh) return false;
21952
22231
  try {
21953
- const newCredentials = await this.remintCredential(this._credentialProvider);
21954
- 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);
21955
22238
  this._deps.credential = newCredentials;
21956
22239
  this.persistCredential(newCredentials);
21957
- await this._clientSession.reauthenticate(newCredentials.token);
21958
- 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);
21959
22241
  return true;
21960
22242
  } catch (error) {
21961
- logger$1.error("[SignalWire] Credential recovery failed:", error);
22243
+ logger$1.warn("[SignalWire] Re-mint recovery failed:", error);
21962
22244
  return false;
21963
22245
  }
21964
22246
  }
@@ -21993,10 +22275,9 @@ var SignalWire = class extends Destroyable {
21993
22275
  if (!this._credentialProvider) return;
21994
22276
  try {
21995
22277
  let newCredentials;
21996
- if (this._clientSession.clientBound) {
21997
- const fingerprint = this._dpopManager?.initialized ? this._dpopManager.fingerprint : void 0;
22278
+ if (this._clientSession?.clientBound ?? await this.wasClientBound()) {
21998
22279
  logger$1.debug("[SignalWire] Re-minting client-bound base SAT before reconnect");
21999
- newCredentials = await this._credentialProvider.authenticate(fingerprint ? { fingerprint } : void 0);
22280
+ newCredentials = await this._credentialProvider.authenticate(this._dpopManager?.initialized ? { fingerprint: this._dpopManager.fingerprint } : void 0);
22000
22281
  } else if (this._credentialProvider.refresh) {
22001
22282
  logger$1.debug("[SignalWire] Refreshing unbound credential before reconnect");
22002
22283
  newCredentials = await this.remintCredential(this._credentialProvider);
@@ -22024,6 +22305,26 @@ var SignalWire = class extends Destroyable {
22024
22305
  this._deps.storage.setItem("sw:cached_credential", credential);
22025
22306
  if (this._deps.persistSession) this._deps.storage.setItem("sw:cached_credential", credential, "local");
22026
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
+ }
22027
22328
  async init() {
22028
22329
  this._user$.next(new User(this._deps.http));
22029
22330
  if (!this._options.skipConnection) await this.connect();
@@ -22047,6 +22348,42 @@ var SignalWire = class extends Destroyable {
22047
22348
  } catch (error) {
22048
22349
  logger$1.error("[SignalWire] Failed to reattach calls:", error);
22049
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
+ }
22050
22387
  }
22051
22388
  }
22052
22389
  /**
@@ -22088,28 +22425,22 @@ var SignalWire = class extends Destroyable {
22088
22425
  */
22089
22426
  async connect() {
22090
22427
  await this.teardownTransportAndSession();
22091
- try {
22092
- const user = this._user$.value;
22093
- if (!user) throw new UnexpectedError("User not initialized before connect");
22094
- if (!await (0, import_cjs$1.firstValueFrom)(user.fetched$)) throw new UnexpectedError("Failed to fetch user information - fetched$ emitted false");
22095
- this._deps.user = user;
22096
- } catch (error) {
22097
- 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.`);
22098
- throw new UnexpectedError("Error fetching user information", { cause: error });
22099
- }
22428
+ await this.fetchUserOrRecover();
22100
22429
  const errorHandler = (error) => {
22101
22430
  this._errors$.next(error);
22102
22431
  };
22103
22432
  this._transport = new TransportManager(this._deps.storage, this._deps.protocolKey, this._deps.WebSocket, PreferencesContainer.instance.relayHost ?? this._deps.relayHost, errorHandler);
22104
- 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);
22105
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$);
22106
22435
  this._publicSession = new ClientSessionWrapper(this._clientSession);
22436
+ this._clientSession.callControl = this._options.callControl ?? "routed";
22107
22437
  this._clientSession.onBeforeReconnect = async () => this.refreshCredentialForReconnect();
22108
22438
  this.subscribeTo(this._clientSession.errors$, (error) => {
22109
22439
  this._errors$.next(error);
22110
22440
  });
22111
22441
  this.subscribeTo(this._clientSession.authorization$, (authorization) => {
22112
22442
  this._refreshCoordinator?.syncExpiryFromAuthorization(authorization, this._credentialProvider);
22443
+ this.persistClientBoundMarker(Boolean(authorization?.cnf?.jkt));
22113
22444
  });
22114
22445
  await this._clientSession.connect();
22115
22446
  await this._refreshCoordinator?.activate(this._deps.user, this._clientSession);
@@ -22363,19 +22694,18 @@ var SignalWire = class extends Destroyable {
22363
22694
  throw error;
22364
22695
  }
22365
22696
  logger$1.debug("[SignalWire] Failed to register user, attempting credential recovery...");
22366
- let failureCause = error;
22367
- if (await this.recoverStaleCredential(isRecoverableAuthError(error))) try {
22368
- logger$1.debug("[SignalWire] Recovery succeeded, retrying register()");
22697
+ const outcome = await this.recoverAndRetry(async () => {
22369
22698
  await this._transport.execute(RPCExecute({
22370
22699
  method: "subscriber.online",
22371
22700
  params: {}
22372
22701
  }));
22702
+ });
22703
+ if (outcome.ok) {
22704
+ logger$1.debug("[SignalWire] Recovery restored registration");
22373
22705
  this._isRegistered$.next(true);
22374
22706
  return;
22375
- } catch (retryError) {
22376
- logger$1.error("[SignalWire] Register retry after recovery failed:", retryError);
22377
- failureCause = retryError;
22378
22707
  }
22708
+ const failureCause = outcome.error ?? error;
22379
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 }) });
22380
22710
  this._errors$.next(registerError);
22381
22711
  throw registerError;
@@ -22435,10 +22765,13 @@ var SignalWire = class extends Destroyable {
22435
22765
  return await this._clientSession.createOutboundCall(destination, computed_options);
22436
22766
  } catch (error) {
22437
22767
  if (!isRecoverableAuthError(error)) throw error;
22438
- logger$1.debug("[SignalWire] Dial hit a recoverable auth error; recovering credential and retrying once");
22439
- if (!await this.recoverStaleCredential()) throw error;
22440
- await this.waitAuthentication();
22441
- 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;
22442
22775
  }
22443
22776
  }
22444
22777
  /**
@@ -22720,6 +23053,8 @@ var SignalWire = class extends Destroyable {
22720
23053
  destroy() {
22721
23054
  this._refreshCoordinator?.destroy();
22722
23055
  this._refreshCoordinator = void 0;
23056
+ this._refreshHttp?.destroy();
23057
+ this._refreshHttp = void 0;
22723
23058
  this._dpopManager?.destroy();
22724
23059
  const session = this._clientSession;
22725
23060
  session?.teardownSessionState();