@abraca/dabra 2.93.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.
@@ -1237,6 +1237,7 @@ var AbracadabraWS = class extends EventEmitter {
1237
1237
  this.offlineListener = null;
1238
1238
  this.receivedOnOpenPayload = void 0;
1239
1239
  this.closeTries = 0;
1240
+ this.lastRefreshToken = null;
1240
1241
  this.setConfiguration(configuration);
1241
1242
  this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
1242
1243
  this.on("open", this.configuration.onOpen);
@@ -1500,6 +1501,42 @@ var AbracadabraWS = class extends EventEmitter {
1500
1501
  if (this.webSocket?.readyState === WsReadyStates.Open) this.webSocket.send(message);
1501
1502
  else this.messageQueue.push(message);
1502
1503
  }
1504
+ /**
1505
+ * Re-arm this CONNECTION with a freshly minted JWT, in place.
1506
+ *
1507
+ * The server tracks a connection's expiry as one shared value
1508
+ * (`SyncSession`'s `jwt_exp`, an `Arc<AtomicI64>` every session on the socket
1509
+ * points at) and rejects every non-stateless frame once it passes — dropping
1510
+ * the whole socket for an ordinary session. `auth:refresh {"token":…}` moves
1511
+ * that value, and it rides `MSG_STATELESS` precisely because stateless is the
1512
+ * one frame kind an expired session may still send.
1513
+ *
1514
+ * So ONE frame, through any authenticated document, re-arms everything
1515
+ * multiplexed here. Sending it per attached provider would be N identical
1516
+ * frames on a shared socket carrying sixty documents; `lastRefreshToken` is
1517
+ * what keeps it at one.
1518
+ *
1519
+ * Verified against a live server with a 45-second token TTL, on an ORDINARY
1520
+ * (non-elevated) account, refreshing before the lapse so the socket is never
1521
+ * dropped and never re-handshaken: without the frame the socket is closed
1522
+ * past the original expiry, with it `close` never fires at all.
1523
+ *
1524
+ * Returns whether a frame actually went out. `false` means there was nobody
1525
+ * to send it through — harmless, because the next handshake carries the new
1526
+ * token anyway (see the provider's token closure).
1527
+ */
1528
+ refreshAuth(token) {
1529
+ if (!token || token === this.lastRefreshToken) return false;
1530
+ if (this.status !== WebSocketStatus.Connected) return false;
1531
+ const payload = `auth:refresh ${JSON.stringify({ token })}`;
1532
+ for (const provider of this.configuration.providerMap.values()) {
1533
+ if (!provider.isAuthenticated) continue;
1534
+ provider.sendStateless(payload);
1535
+ this.lastRefreshToken = token;
1536
+ return true;
1537
+ }
1538
+ return false;
1539
+ }
1503
1540
  onClose({ event }) {
1504
1541
  this.closeTries = 0;
1505
1542
  this.cleanupWebSocket();
@@ -3133,7 +3170,10 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3133
3170
  if (client) {
3134
3171
  const r = resolved;
3135
3172
  if (!r.url && !r.websocketProvider) r.url = client.wsUrl;
3136
- if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = () => client.token ?? "";
3173
+ if (resolved.token === void 0 && !configuration.cryptoIdentity) resolved.token = async () => {
3174
+ await client.ensureFreshToken().catch(() => false);
3175
+ return client.token ?? "";
3176
+ };
3137
3177
  }
3138
3178
  super(resolved);
3139
3179
  this.effectiveRole = null;
@@ -3143,6 +3183,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3143
3183
  this.childAccessTimes = /* @__PURE__ */ new Map();
3144
3184
  this.pinnedChildren = /* @__PURE__ */ new Set();
3145
3185
  this.transientChildren = /* @__PURE__ */ new Set();
3186
+ this.unsubscribeToken = null;
3146
3187
  this.boundHandleYSubdocsChange = this.handleYSubdocsChange.bind(this);
3147
3188
  this.hasCachedContent = false;
3148
3189
  this._client = client;
@@ -3154,6 +3195,11 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3154
3195
  this.on("subdocRegistered", configuration.onSubdocRegistered ?? (() => null));
3155
3196
  this.on("subdocLoaded", configuration.onSubdocLoaded ?? (() => null));
3156
3197
  this.document.on("subdocs", this.boundHandleYSubdocsChange);
3198
+ this.unsubscribeToken = client?.onTokenChanged?.((token) => {
3199
+ try {
3200
+ this.configuration.websocketProvider?.refreshAuth?.(token);
3201
+ } catch {}
3202
+ }) ?? null;
3157
3203
  this.on("synced", () => this.flushPendingUpdates());
3158
3204
  this.restorePermissionSnapshot();
3159
3205
  this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => setTimeout(resolve, 5e3))]).catch((err) => {
@@ -3558,6 +3604,8 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3558
3604
  return this.configuration.websocketProvider.status === "connected";
3559
3605
  }
3560
3606
  destroy() {
3607
+ this.unsubscribeToken?.();
3608
+ this.unsubscribeToken = null;
3561
3609
  this.document.off("subdocs", this.boundHandleYSubdocsChange);
3562
3610
  const childIds = [...this.childProviders.keys()];
3563
3611
  for (const provider of this.childProviders.values()) provider.destroy();
@@ -10800,28 +10848,70 @@ function decodeBase64UrlToString(b64url) {
10800
10848
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
10801
10849
  return new TextDecoder().decode(bytes);
10802
10850
  }
10851
+ /**
10852
+ * Read a JWT's `exp` / `iat` claims, in ms. `0` for anything unreadable.
10853
+ *
10854
+ * Deliberately tolerant: a token this cannot parse is treated as expiring now,
10855
+ * which costs one extra handshake and never costs a dead session.
10856
+ */
10857
+ function readJwtTimes(token) {
10858
+ if (!token) return {
10859
+ exp: 0,
10860
+ iat: 0
10861
+ };
10862
+ const payload = token.split(".")[1];
10863
+ if (!payload) return {
10864
+ exp: 0,
10865
+ iat: 0
10866
+ };
10867
+ try {
10868
+ const claims = JSON.parse(decodeBase64UrlToString(payload));
10869
+ return {
10870
+ exp: typeof claims.exp === "number" ? claims.exp * 1e3 : 0,
10871
+ iat: typeof claims.iat === "number" ? claims.iat * 1e3 : 0
10872
+ };
10873
+ } catch {
10874
+ return {
10875
+ exp: 0,
10876
+ iat: 0
10877
+ };
10878
+ }
10879
+ }
10803
10880
  var AbracadabraClient = class {
10804
10881
  constructor(config) {
10805
10882
  this.rootListInflight = /* @__PURE__ */ new Map();
10806
10883
  this.streamTokens = /* @__PURE__ */ new Map();
10807
10884
  this.streamTokenInflight = /* @__PURE__ */ new Map();
10885
+ this._renew = null;
10886
+ this._renewing = null;
10887
+ this._renewTimer = null;
10888
+ this._tokenListeners = /* @__PURE__ */ new Set();
10808
10889
  this.baseUrl = config.url.replace(/\/+$/, "");
10809
10890
  this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
10810
10891
  this.storageKey = config.storageKey ?? "abracadabra:auth";
10811
10892
  this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
10812
10893
  this.cache = config.cache ?? null;
10813
10894
  this._onAuthFailed = config.onAuthFailed ?? null;
10895
+ this.renewMarginMs = config.tokenRenewMarginMs ?? 20 * 6e4;
10896
+ this.renewCheckMs = config.tokenRenewCheckMs ?? 6e4;
10814
10897
  this._token = config.token ?? this.loadPersistedToken() ?? null;
10815
10898
  }
10816
10899
  get token() {
10817
10900
  return this._token;
10818
10901
  }
10819
10902
  set token(value) {
10903
+ const changed = value !== this._token;
10820
10904
  this._token = value;
10821
10905
  this.streamTokens.clear();
10822
10906
  this.streamTokenInflight.clear();
10823
10907
  if (this.persistAuth) if (value) this.persistToken(value);
10824
10908
  else this.clearPersistedToken();
10909
+ if (changed && value) {
10910
+ this.scheduleSessionRenewal();
10911
+ for (const listener of this._tokenListeners) try {
10912
+ listener(value);
10913
+ } catch {}
10914
+ }
10825
10915
  }
10826
10916
  get isAuthenticated() {
10827
10917
  return this._token !== null;
@@ -10837,6 +10927,117 @@ var AbracadabraClient = class {
10837
10927
  return false;
10838
10928
  }
10839
10929
  }
10930
+ /** When the current token stops validating, in ms. `0` when unknown. */
10931
+ get tokenExpiresAt() {
10932
+ return readJwtTimes(this._token).exp;
10933
+ }
10934
+ /**
10935
+ * Install the way this client re-authenticates itself, or `null` to stop.
10936
+ *
10937
+ * {@link loginWithKey} installs one for you, so a key-authenticated client
10938
+ * — every Node runner, and every browser session on a crypto identity —
10939
+ * renews without its consumer doing anything. Install one by hand for a
10940
+ * password session or any other flow that can mint a fresh token.
10941
+ *
10942
+ * The function must return the new JWT; adopting it (and notifying open
10943
+ * sockets) is this client's job.
10944
+ */
10945
+ setSessionRenewer(renew) {
10946
+ this._renew = renew;
10947
+ if (renew) this.scheduleSessionRenewal();
10948
+ else this.stopSessionRenewal();
10949
+ }
10950
+ /** Whether this client knows how to re-authenticate itself. */
10951
+ get canRenewSession() {
10952
+ return this._renew !== null;
10953
+ }
10954
+ /**
10955
+ * Called whenever the session token changes — a login, a renewal, a device
10956
+ * refresh, a key revocation. Providers use this to re-arm sockets that are
10957
+ * already open. Returns an unsubscribe function.
10958
+ */
10959
+ onTokenChanged(listener) {
10960
+ this._tokenListeners.add(listener);
10961
+ return () => this._tokenListeners.delete(listener);
10962
+ }
10963
+ /**
10964
+ * Make sure the token has life left in it, re-minting if it does not.
10965
+ *
10966
+ * Cheap when the token is fresh — one subtraction — so callers need not
10967
+ * reason about when the last renewal was, and concurrent callers share one
10968
+ * handshake. Returns whether the session is believed good; `false` is not
10969
+ * fatal, and the caller's own failure is still the authority.
10970
+ */
10971
+ async ensureFreshToken(marginMs) {
10972
+ if (!this._renew) return this.isTokenValid();
10973
+ if (this._renewing) return this._renewing;
10974
+ const { exp } = readJwtTimes(this._token);
10975
+ if (exp > 0 && exp - Date.now() > this.renewMargin(marginMs)) return true;
10976
+ const mint = this._renew;
10977
+ const renew = (async () => {
10978
+ try {
10979
+ const token = await mint();
10980
+ if (token && token !== this._token) this.token = token;
10981
+ return true;
10982
+ } catch {
10983
+ return false;
10984
+ } finally {
10985
+ this._renewing = null;
10986
+ }
10987
+ })();
10988
+ this._renewing = renew;
10989
+ return renew;
10990
+ }
10991
+ /**
10992
+ * How long before `exp` this session is re-minted.
10993
+ *
10994
+ * Capped at a third of the token's own lifetime, so a server configured
10995
+ * with short-lived tokens is not re-authenticated on every check — without
10996
+ * the cap a 45-second token against a 20-minute margin would mint a new
10997
+ * session every time anything asked.
10998
+ */
10999
+ renewMargin(marginMs) {
11000
+ const { exp, iat } = readJwtTimes(this._token);
11001
+ const lifetime = exp > iat && iat > 0 ? exp - iat : Number.POSITIVE_INFINITY;
11002
+ return Math.min(marginMs ?? this.renewMarginMs, lifetime / 3);
11003
+ }
11004
+ /**
11005
+ * Arm a single timer for the moment this token needs replacing.
11006
+ *
11007
+ * Scheduled from the token's OWN expiry rather than on a fixed interval,
11008
+ * and that is not tidiness. A poll can outrun the margin: measured against
11009
+ * a server issuing 45-second tokens, a 60-second poll first fired fifteen
11010
+ * seconds AFTER the token had already lapsed — long enough for the
11011
+ * awareness heartbeat to hit an expired session and have the socket dropped
11012
+ * under it. A deadline cannot be outrun by the thing it is a deadline for.
11013
+ *
11014
+ * Re-armed on every token change, so a renewal schedules the next one.
11015
+ */
11016
+ scheduleSessionRenewal() {
11017
+ this.stopSessionRenewal();
11018
+ if (!this._renew || this.renewCheckMs <= 0) return;
11019
+ const { exp } = readJwtTimes(this._token);
11020
+ const delay = exp > 0 ? Math.max(1e3, exp - Date.now() - this.renewMargin()) : this.renewCheckMs;
11021
+ this._renewTimer = setTimeout(() => {
11022
+ this.ensureFreshToken().catch(() => false).finally(() => this.scheduleSessionRenewal());
11023
+ }, Math.min(delay, 720 * 6e4));
11024
+ this._renewTimer.unref?.();
11025
+ }
11026
+ stopSessionRenewal() {
11027
+ if (!this._renewTimer) return;
11028
+ clearTimeout(this._renewTimer);
11029
+ this._renewTimer = null;
11030
+ }
11031
+ /**
11032
+ * Stop renewing and drop every listener. Call when a client is discarded —
11033
+ * a long-lived consumer that builds one client per connection would
11034
+ * otherwise leave a timer per discarded client.
11035
+ */
11036
+ destroy() {
11037
+ this.stopSessionRenewal();
11038
+ this._renew = null;
11039
+ this._tokenListeners.clear();
11040
+ }
10840
11041
  /** Derives ws:// or wss:// URL from the http(s) base URL. */
10841
11042
  get wsUrl() {
10842
11043
  return this.baseUrl.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://") + "/ws";
@@ -10899,11 +11100,13 @@ var AbracadabraClient = class {
10899
11100
  async loginWithKey(publicKey, signChallenge) {
10900
11101
  const { challenge } = await this.challenge(publicKey);
10901
11102
  const signature = await signChallenge(challenge);
10902
- return this.verify({
11103
+ const token = await this.verify({
10903
11104
  publicKey,
10904
11105
  signature,
10905
11106
  challenge
10906
11107
  });
11108
+ this.setSessionRenewer(() => this.loginWithKey(publicKey, signChallenge));
11109
+ return token;
10907
11110
  }
10908
11111
  /** Add a new Ed25519 public key to the current user (multi-device). */
10909
11112
  async addKey(opts) {