@abraca/dabra 2.92.0 → 2.95.0

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.
@@ -1207,6 +1207,7 @@ var AbracadabraWS = class extends EventEmitter {
1207
1207
  this.offlineListener = null;
1208
1208
  this.receivedOnOpenPayload = void 0;
1209
1209
  this.closeTries = 0;
1210
+ this.lastRefreshToken = null;
1210
1211
  this.setConfiguration(configuration);
1211
1212
  this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
1212
1213
  this.on("open", this.configuration.onOpen);
@@ -1470,6 +1471,42 @@ var AbracadabraWS = class extends EventEmitter {
1470
1471
  if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
1471
1472
  else this.messageQueue.push(message);
1472
1473
  }
1474
+ /**
1475
+ * Re-arm this CONNECTION with a freshly minted JWT, in place.
1476
+ *
1477
+ * The server tracks a connection's expiry as one shared value
1478
+ * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket
1479
+ * points at) and rejects every non-stateless frame once it passes — dropping
1480
+ * the whole socket for an ordinary session. `auth:refresh {"token":…}` moves
1481
+ * that value, and it rides `MSG_STATELESS` precisely because stateless is the
1482
+ * one frame kind an expired session may still send.
1483
+ *
1484
+ * So ONE frame, through any authenticated document, re-arms everything
1485
+ * multiplexed here. Sending it per attached provider would be N identical
1486
+ * frames on a shared socket carrying sixty documents; `lastRefreshToken` is
1487
+ * what keeps it at one.
1488
+ *
1489
+ * Verified against a live server with a 45-second token TTL, on an ORDINARY
1490
+ * (non-elevated) account, refreshing before the lapse so the socket is never
1491
+ * dropped and never re-handshaken: without the frame the socket is closed
1492
+ * past the original expiry, with it `close` never fires at all.
1493
+ *
1494
+ * Returns whether a frame actually went out. `false` means there was nobody
1495
+ * to send it through — harmless, because the next handshake carries the new
1496
+ * token anyway (see the provider's token closure).
1497
+ */
1498
+ refreshAuth(token) {
1499
+ if (!token || token === this.lastRefreshToken) return false;
1500
+ if (this.status !== WebSocketStatus.Connected) return false;
1501
+ const payload = `auth:refresh ${JSON.stringify({ token })}`;
1502
+ for (const provider of this.configuration.providerMap.values()) {
1503
+ if (!provider.isAuthenticated) continue;
1504
+ provider.sendStateless(payload);
1505
+ this.lastRefreshToken = token;
1506
+ return true;
1507
+ }
1508
+ return false;
1509
+ }
1473
1510
  onClose({ event }) {
1474
1511
  this.closeTries = 0;
1475
1512
  this.cleanupWebSocket();
@@ -3103,7 +3140,10 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3103
3140
  if (client) {
3104
3141
  const r = resolved;
3105
3142
  if (!r.url && !r.websocketProvider) r.url = client.wsUrl;
3106
- if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = () => client.token ?? "";
3143
+ if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = async () => {
3144
+ await client.ensureFreshToken().catch(() => false);
3145
+ return client.token ?? "";
3146
+ };
3107
3147
  }
3108
3148
  super(resolved);
3109
3149
  this.effectiveRole = null;
@@ -3113,6 +3153,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3113
3153
  this.childAccessTimes = /* @__PURE__ */ new Map();
3114
3154
  this.pinnedChildren = /* @__PURE__ */ new Set();
3115
3155
  this.transientChildren = /* @__PURE__ */ new Set();
3156
+ this.unsubscribeToken = null;
3116
3157
  this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
3117
3158
  this.hasCachedContent = false;
3118
3159
  this._client = client;
@@ -3124,6 +3165,11 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3124
3165
  this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
3125
3166
  this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
3126
3167
  this.document.on("subdocs", this.boundHandleYSubdocsChange);
3168
+ this.unsubscribeToken = client?.onTokenChanged?.((token) => {
3169
+ try {
3170
+ this.configuration.websocketProvider?.refreshAuth?.(token);
3171
+ } catch {}
3172
+ }) ?? null;
3127
3173
  this.on("synced", () => this.flushPendingUpdates());
3128
3174
  this.restorePermissionSnapshot();
3129
3175
  this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => setTimeout(resolve, 5e3))]).catch((err) => {
@@ -3528,6 +3574,8 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3528
3574
  return this.configuration.websocketProvider.status === "connected";
3529
3575
  }
3530
3576
  destroy() {
3577
+ this.unsubscribeToken?.();
3578
+ this.unsubscribeToken = null;
3531
3579
  this.document.off("subdocs", this.boundHandleYSubdocsChange);
3532
3580
  const childIds = [...this.childProviders.keys()];
3533
3581
  for (const provider of this.childProviders.values()) provider.destroy();
@@ -10770,28 +10818,70 @@ function decodeBase64UrlToString(b64url) {
10770
10818
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
10771
10819
  return new TextDecoder().decode(bytes);
10772
10820
  }
10821
+ /**
10822
+ * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.
10823
+ *
10824
+ * Deliberately tolerant: a token this cannot parse is treated as expiring now,
10825
+ * which costs one extra handshake and never costs a dead session.
10826
+ */
10827
+ function readJwtTimes(token) {
10828
+ if (!token) return {
10829
+ exp: 0,
10830
+ iat: 0
10831
+ };
10832
+ const payload = token.split(".")[1];
10833
+ if (!payload) return {
10834
+ exp: 0,
10835
+ iat: 0
10836
+ };
10837
+ try {
10838
+ const claims = JSON.parse(decodeBase64UrlToString(payload));
10839
+ return {
10840
+ exp: typeof claims.exp === "number" ? claims.exp * 1e3 : 0,
10841
+ iat: typeof claims.iat === "number" ? claims.iat * 1e3 : 0
10842
+ };
10843
+ } catch {
10844
+ return {
10845
+ exp: 0,
10846
+ iat: 0
10847
+ };
10848
+ }
10849
+ }
10773
10850
  var AbracadabraClient = class {
10774
10851
  constructor(config) {
10775
10852
  this.rootListInflight = /* @__PURE__ */ new Map();
10776
10853
  this.streamTokens = /* @__PURE__ */ new Map();
10777
10854
  this.streamTokenInflight = /* @__PURE__ */ new Map();
10855
+ this._renew = null;
10856
+ this._renewing = null;
10857
+ this._renewTimer = null;
10858
+ this._tokenListeners = /* @__PURE__ */ new Set();
10778
10859
  this.baseUrl = config.url.replace(/\/+$/, "");
10779
10860
  this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
10780
10861
  this.storageKey = config.storageKey ?? "abracadabra:auth";
10781
10862
  this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
10782
10863
  this.cache = config.cache ?? null;
10783
10864
  this._onAuthFailed = config.onAuthFailed ?? null;
10865
+ this.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 6e4;
10866
+ this.renewCheckMs = config.tokenRenewCheckMs ?? 6e4;
10784
10867
  this._token = config.token ?? this.loadPersistedToken() ?? null;
10785
10868
  }
10786
10869
  get token() {
10787
10870
  return this._token;
10788
10871
  }
10789
10872
  set token(value) {
10873
+ const changed = value !== this._token;
10790
10874
  this._token = value;
10791
10875
  this.streamTokens.clear();
10792
10876
  this.streamTokenInflight.clear();
10793
10877
  if (this.persistAuth) if (value) this.persistToken(value);
10794
10878
  else this.clearPersistedToken();
10879
+ if (changed && value) {
10880
+ this.scheduleSessionRenewal();
10881
+ for (const listener of this._tokenListeners) try {
10882
+ listener(value);
10883
+ } catch {}
10884
+ }
10795
10885
  }
10796
10886
  get isAuthenticated() {
10797
10887
  return this._token !== null;
@@ -10807,6 +10897,117 @@ var AbracadabraClient = class {
10807
10897
  return false;
10808
10898
  }
10809
10899
  }
10900
+ /** When the current token stops validating, in ms. `0` when unknown. */
10901
+ get tokenExpiresAt() {
10902
+ return readJwtTimes(this._token).exp;
10903
+ }
10904
+ /**
10905
+ * Install the way this client re-authenticates itself, or `null` to stop.
10906
+ *
10907
+ * {@link loginWithKey} installs one for you, so a key-authenticated client
10908
+ * — every Node runner, and every browser session on a crypto identity —
10909
+ * renews without its consumer doing anything. Install one by hand for a
10910
+ * password session or any other flow that can mint a fresh token.
10911
+ *
10912
+ * The function must return the new JWT; adopting it (and notifying open
10913
+ * sockets) is this client's job.
10914
+ */
10915
+ setSessionRenewer(renew) {
10916
+ this._renew = renew;
10917
+ if (renew) this.scheduleSessionRenewal();
10918
+ else this.stopSessionRenewal();
10919
+ }
10920
+ /** Whether this client knows how to re-authenticate itself. */
10921
+ get canRenewSession() {
10922
+ return this._renew !== null;
10923
+ }
10924
+ /**
10925
+ * Called whenever the session token changes — a login, a renewal, a device
10926
+ * refresh, a key revocation. Providers use this to re-arm sockets that are
10927
+ * already open. Returns an unsubscribe function.
10928
+ */
10929
+ onTokenChanged(listener) {
10930
+ this._tokenListeners.add(listener);
10931
+ return () => this._tokenListeners.delete(listener);
10932
+ }
10933
+ /**
10934
+ * Make sure the token has life left in it, re-minting if it does not.
10935
+ *
10936
+ * Cheap when the token is fresh — one subtraction — so callers need not
10937
+ * reason about when the last renewal was, and concurrent callers share one
10938
+ * handshake. Returns whether the session is believed good; `false` is not
10939
+ * fatal, and the caller's own failure is still the authority.
10940
+ */
10941
+ async ensureFreshToken(marginMs) {
10942
+ if (!this._renew) return this.isTokenValid();
10943
+ if (this._renewing) return this._renewing;
10944
+ const { exp } = readJwtTimes(this._token);
10945
+ if (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;
10946
+ const mint = this._renew;
10947
+ const renew = (async () => {
10948
+ try {
10949
+ const token = await mint();
10950
+ if (token && token !== this._token) this.token = token;
10951
+ return true;
10952
+ } catch {
10953
+ return false;
10954
+ } finally {
10955
+ this._renewing = null;
10956
+ }
10957
+ })();
10958
+ this._renewing = renew;
10959
+ return renew;
10960
+ }
10961
+ /**
10962
+ * How long before `exp` this session is re-minted.
10963
+ *
10964
+ * Capped at a third of the token's own lifetime, so a server configured
10965
+ * with short-lived tokens is not re-authenticated on every check — without
10966
+ * the cap a 45-second token against a 20-minute margin would mint a new
10967
+ * session every time anything asked.
10968
+ */
10969
+ renewMargin(marginMs) {
10970
+ const { exp, iat } = readJwtTimes(this._token);
10971
+ const lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;
10972
+ return Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);
10973
+ }
10974
+ /**
10975
+ * Arm a single timer for the moment this token needs replacing.
10976
+ *
10977
+ * Scheduled from the token's OWN expiry rather than on a fixed interval,
10978
+ * and that is not tidiness. A poll can outrun the margin: measured against
10979
+ * a server issuing 45-second tokens, a 60-second poll first fired fifteen
10980
+ * seconds AFTER the token had already lapsed — long enough for the
10981
+ * awareness heartbeat to hit an expired session and have the socket dropped
10982
+ * under it. A deadline cannot be outrun by the thing it is a deadline for.
10983
+ *
10984
+ * Re-armed on every token change, so a renewal schedules the next one.
10985
+ */
10986
+ scheduleSessionRenewal() {
10987
+ this.stopSessionRenewal();
10988
+ if (!this._renew || this.renewCheckMs <= 0) return;
10989
+ const { exp } = readJwtTimes(this._token);
10990
+ const delay = exp > 0 ? Math.max(1e3, exp - Date.now() - this.renewMargin()) : this.renewCheckMs;
10991
+ this._renewTimer = setTimeout(() => {
10992
+ this.ensureFreshToken().catch(() => false).finally(() => this.scheduleSessionRenewal());
10993
+ }, Math.min(delay, 720 * 6e4));
10994
+ this._renewTimer.unref?.();
10995
+ }
10996
+ stopSessionRenewal() {
10997
+ if (!this._renewTimer) return;
10998
+ clearTimeout(this._renewTimer);
10999
+ this._renewTimer = null;
11000
+ }
11001
+ /**
11002
+ * Stop renewing and drop every listener. Call when a client is discarded —
11003
+ * a long-lived consumer that builds one client per connection would
11004
+ * otherwise leave a timer per discarded client.
11005
+ */
11006
+ destroy() {
11007
+ this.stopSessionRenewal();
11008
+ this._renew = null;
11009
+ this._tokenListeners.clear();
11010
+ }
10810
11011
  /** Derives ws:// or wss:// URL from the http(s) base URL. */
10811
11012
  get wsUrl() {
10812
11013
  return this.baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://") + "/ws";
@@ -10869,11 +11070,13 @@ var AbracadabraClient = class {
10869
11070
  async loginWithKey(publicKey, signChallenge) {
10870
11071
  const { challenge } = await this.challenge(publicKey);
10871
11072
  const signature = await signChallenge(challenge);
10872
- return this.verify({
11073
+ const token = await this.verify({
10873
11074
  publicKey,
10874
11075
  signature,
10875
11076
  challenge
10876
11077
  });
11078
+ this.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));
11079
+ return token;
10877
11080
  }
10878
11081
  /** Add a new Ed25519 public key to the current user (multi-device). */
10879
11082
  async addKey(opts) {