@spacelr/sdk 0.19.5 → 0.19.7

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.mjs CHANGED
@@ -443,6 +443,7 @@ var TokenManager = class {
443
443
  constructor(storage, refreshBufferSeconds = 60, refreshLockName = "spacelr_token_refresh") {
444
444
  this.refreshCallback = null;
445
445
  this.reauthCallback = null;
446
+ this.reauthGeneration = 0;
446
447
  this.refreshPromise = null;
447
448
  this.tokenRefreshedListeners = /* @__PURE__ */ new Set();
448
449
  this.authLostListeners = /* @__PURE__ */ new Set();
@@ -468,6 +469,16 @@ var TokenManager = class {
468
469
  */
469
470
  setReauthCallback(callback) {
470
471
  this.reauthCallback = callback;
472
+ this.reauthGeneration += 1;
473
+ }
474
+ /**
475
+ * #1090: changes whenever the re-authentication callback is set, replaced or
476
+ * dropped. Lets a caller tell whether "its" API-token session is still the
477
+ * current one without keeping a reference to the callback (whose closure
478
+ * holds the API token).
479
+ */
480
+ getReauthGeneration() {
481
+ return this.reauthGeneration;
471
482
  }
472
483
  /** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
473
484
  async canRenew() {
@@ -492,11 +503,13 @@ var TokenManager = class {
492
503
  const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
493
504
  const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
494
505
  this.reauthCallback = null;
506
+ this.reauthGeneration += 1;
495
507
  await this.storage.setTokens(normalised);
496
508
  this.authLostEmitted = false;
497
509
  }
498
510
  async clearTokens() {
499
511
  this.reauthCallback = null;
512
+ this.reauthGeneration += 1;
500
513
  await this.storage.clearTokens();
501
514
  this.refreshPromise = null;
502
515
  this.authLostEmitted = false;
@@ -579,6 +592,7 @@ var TokenManager = class {
579
592
  if (this.authLostEmitted) return;
580
593
  this.authLostEmitted = true;
581
594
  this.reauthCallback = null;
595
+ this.reauthGeneration += 1;
582
596
  this.pendingClear = this.storage.clearTokens().catch(() => {
583
597
  });
584
598
  await this.pendingClear;
@@ -796,6 +810,22 @@ async function generatePKCEChallenge() {
796
810
  // libs/sdk/src/core/realtime.ts
797
811
  import { io } from "socket.io-client";
798
812
  var REBUILD_RETRY_DELAY_MS = 5e3;
813
+ var SOCKET_TOKEN_REFRESH_LEAD_MS = 45e3;
814
+ var SOCKET_TOKEN_REFRESH_JITTER_MS = 15e3;
815
+ var SOCKET_TOKEN_REFRESH_RETRY_MS = 5e3;
816
+ var SOCKET_TOKEN_REFRESH_RETRY_MAX_MS = 3e4;
817
+ var SERVER_DISCONNECT_REBUILD_DELAY_MS = 1e3;
818
+ function jwtExpiryMs(token) {
819
+ const payload = token.split(".")[1];
820
+ if (!payload) return null;
821
+ try {
822
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
823
+ const exp = JSON.parse(json).exp;
824
+ return typeof exp === "number" ? exp * 1e3 : null;
825
+ } catch {
826
+ return null;
827
+ }
828
+ }
799
829
  var PERMANENT_STREAM_ACK_ERRORS = /* @__PURE__ */ new Set([
800
830
  "not-stream-collection",
801
831
  "Collection not found",
@@ -986,6 +1016,18 @@ var RealtimeClient = class {
986
1016
  // Scheduled retry after a failed `rebuildSocket()`; cleared when it fires
987
1017
  // or when `disconnect()` tears down.
988
1018
  this.rebuildRetryTimer = null;
1019
+ // #1078 — the access token the open socket was last authenticated with, and
1020
+ // the timer that replaces it before it expires.
1021
+ this.socketToken = null;
1022
+ this.socketTokenTimer = null;
1023
+ this.socketTokenRetries = 0;
1024
+ // The token of a socket the server closed. If the next connect would use the
1025
+ // same token again, it is renewed first (once).
1026
+ this.serverClosedToken = null;
1027
+ // `reauthenticate` messages whose `authenticated` reply is still due. Such a
1028
+ // reply confirms a token swap on a live socket, not a new connection, so the
1029
+ // subscriptions must not be sent again for it.
1030
+ this.pendingReauthReplies = 0;
989
1031
  this.connectionState = "disconnected";
990
1032
  this.connectionStateListeners = /* @__PURE__ */ new Set();
991
1033
  this.streamSubscriptions = /* @__PURE__ */ new Map();
@@ -1229,6 +1271,7 @@ var RealtimeClient = class {
1229
1271
  clearTimeout(this.rebuildRetryTimer);
1230
1272
  this.rebuildRetryTimer = null;
1231
1273
  }
1274
+ this.clearSocketTokenTimer();
1232
1275
  if (this.unsubscribeFromTokenRefreshed) {
1233
1276
  this.unsubscribeFromTokenRefreshed();
1234
1277
  this.unsubscribeFromTokenRefreshed = null;
@@ -1356,10 +1399,16 @@ var RealtimeClient = class {
1356
1399
  this.socket = null;
1357
1400
  previous.disconnect();
1358
1401
  }
1359
- const token = await this.config.getToken();
1402
+ let token = await this.config.getToken();
1403
+ if (token && token === this.serverClosedToken) {
1404
+ this.serverClosedToken = null;
1405
+ await this.config.refreshToken?.().catch(() => null);
1406
+ token = await this.config.getToken();
1407
+ }
1360
1408
  if (!token) {
1361
1409
  throw new Error("No authentication token available");
1362
1410
  }
1411
+ this.socketToken = token;
1363
1412
  const wsUrl = this.config.baseUrl.replace(/\/api\/v\d+\/?$/, "");
1364
1413
  return new Promise((resolve, reject) => {
1365
1414
  let initialConnect = true;
@@ -1368,6 +1417,7 @@ var RealtimeClient = class {
1368
1417
  auth: async (cb) => {
1369
1418
  try {
1370
1419
  const freshToken = await this.config.getToken();
1420
+ if (freshToken) this.socketToken = freshToken;
1371
1421
  cb({ token: freshToken });
1372
1422
  } catch {
1373
1423
  cb({ token: null });
@@ -1397,6 +1447,7 @@ var RealtimeClient = class {
1397
1447
  if (this.disposed) return;
1398
1448
  if (this.socket !== socket) return;
1399
1449
  this.setConnectionState("connected");
1450
+ this.scheduleSocketTokenRefresh();
1400
1451
  if (initialConnect) {
1401
1452
  initialConnect = false;
1402
1453
  if (this.socket) {
@@ -1429,14 +1480,14 @@ var RealtimeClient = class {
1429
1480
  }
1430
1481
  if (this.config.onTokenRefreshed && !this.unsubscribeFromTokenRefreshed) {
1431
1482
  this.unsubscribeFromTokenRefreshed = this.config.onTokenRefreshed(
1432
- (accessToken) => {
1433
- this.socket?.emit("reauthenticate", { token: accessToken });
1434
- }
1483
+ (accessToken) => this.reauthenticateSocket(accessToken)
1435
1484
  );
1436
1485
  }
1437
1486
  if (this.subscriptions.size > 0) this.resubscribeAll();
1438
1487
  if (this.streamSubscriptions.size > 0) void this.resubscribeAllStreams();
1439
1488
  resolve();
1489
+ } else if (this.pendingReauthReplies > 0) {
1490
+ this.pendingReauthReplies -= 1;
1440
1491
  } else {
1441
1492
  this.resubscribeAll();
1442
1493
  void this.resubscribeAllStreams();
@@ -1516,11 +1567,17 @@ var RealtimeClient = class {
1516
1567
  }
1517
1568
  }
1518
1569
  });
1519
- socket.on("disconnect", () => {
1570
+ socket.on("disconnect", (reason) => {
1571
+ if (this.socket === socket) this.pendingReauthReplies = 0;
1520
1572
  if (this.disposed) return;
1521
1573
  if (initialConnect) return;
1522
1574
  if (this.socket !== socket) return;
1523
1575
  this.setConnectionState("reconnecting");
1576
+ if (reason === "io server disconnect") {
1577
+ this.serverClosedToken = this.socketToken;
1578
+ this.clearSocketTokenTimer();
1579
+ this.scheduleRebuildRetry(SERVER_DISCONNECT_REBUILD_DELAY_MS);
1580
+ }
1524
1581
  });
1525
1582
  });
1526
1583
  }
@@ -1582,7 +1639,72 @@ var RealtimeClient = class {
1582
1639
  } catch {
1583
1640
  }
1584
1641
  }
1585
- scheduleRebuildRetry() {
1642
+ /** #1078: send a new access token to the open socket, once per token. */
1643
+ reauthenticateSocket(accessToken) {
1644
+ if (accessToken === this.socketToken) return;
1645
+ if (!this.socket?.connected) return;
1646
+ this.socketToken = accessToken;
1647
+ this.pendingReauthReplies += 1;
1648
+ this.socket.emit("reauthenticate", { token: accessToken });
1649
+ this.scheduleSocketTokenRefresh();
1650
+ }
1651
+ clearSocketTokenTimer() {
1652
+ if (this.socketTokenTimer) {
1653
+ clearTimeout(this.socketTokenTimer);
1654
+ this.socketTokenTimer = null;
1655
+ }
1656
+ }
1657
+ /**
1658
+ * #1078: keep the open socket's token fresh. A subscriber that only listens
1659
+ * makes no requests, so nothing else would refresh its token before the
1660
+ * gateway closes the socket at expiry. Shortly before expiry this asks the
1661
+ * token manager for a token (which refreshes it) and re-authenticates the
1662
+ * socket with the result. Tokens without a readable `exp` are left alone.
1663
+ */
1664
+ scheduleSocketTokenRefresh(retryMs) {
1665
+ this.clearSocketTokenTimer();
1666
+ if (retryMs === void 0) this.socketTokenRetries = 0;
1667
+ if (this.disposed || !this.socketToken) return;
1668
+ const expiresAt = jwtExpiryMs(this.socketToken);
1669
+ if (expiresAt === null) return;
1670
+ const remaining = expiresAt - Date.now();
1671
+ const lead = Math.min(
1672
+ SOCKET_TOKEN_REFRESH_LEAD_MS + Math.random() * SOCKET_TOKEN_REFRESH_JITTER_MS,
1673
+ remaining / 2
1674
+ );
1675
+ const delay = retryMs ?? Math.max(1e3, remaining - lead);
1676
+ this.socketTokenTimer = setTimeout(() => {
1677
+ this.socketTokenTimer = null;
1678
+ void this.refreshSocketToken(expiresAt);
1679
+ }, delay);
1680
+ this.socketTokenTimer.unref?.();
1681
+ }
1682
+ async refreshSocketToken(expiresAt) {
1683
+ if (this.disposed || !this.socket) return;
1684
+ const previous = this.socketToken;
1685
+ let token = null;
1686
+ try {
1687
+ token = await this.config.getToken();
1688
+ } catch {
1689
+ }
1690
+ if (this.disposed || !this.socket) return;
1691
+ if (this.socketToken !== previous) return;
1692
+ if (token && token !== previous) {
1693
+ this.reauthenticateSocket(token);
1694
+ return;
1695
+ }
1696
+ const remaining = expiresAt - Date.now();
1697
+ if (remaining <= 0) return;
1698
+ const backoff = Math.min(
1699
+ SOCKET_TOKEN_REFRESH_RETRY_MS * 2 ** this.socketTokenRetries,
1700
+ SOCKET_TOKEN_REFRESH_RETRY_MAX_MS
1701
+ );
1702
+ this.socketTokenRetries += 1;
1703
+ this.scheduleSocketTokenRefresh(
1704
+ Math.min(backoff, Math.max(SOCKET_TOKEN_REFRESH_RETRY_MS, remaining / 2))
1705
+ );
1706
+ }
1707
+ scheduleRebuildRetry(delayMs = REBUILD_RETRY_DELAY_MS) {
1586
1708
  if (this.disposed || this.rebuildRetryTimer) return;
1587
1709
  this.rebuildRetryTimer = setTimeout(() => {
1588
1710
  this.rebuildRetryTimer = null;
@@ -1592,7 +1714,7 @@ var RealtimeClient = class {
1592
1714
  }
1593
1715
  if (this.socket?.connected) return;
1594
1716
  void this.rebuildSocket();
1595
- }, REBUILD_RETRY_DELAY_MS);
1717
+ }, delayMs);
1596
1718
  this.rebuildRetryTimer.unref?.();
1597
1719
  }
1598
1720
  ensureWakeListeners() {
@@ -1992,10 +2114,22 @@ function mapProfile(u) {
1992
2114
  roles: u.roles ?? []
1993
2115
  };
1994
2116
  }
2117
+ var DAY_MS = 24 * 60 * 60 * 1e3;
2118
+ var API_TOKEN_EXPIRY_DEFAULT_DAYS = 14;
2119
+ var API_TOKEN_EXPIRY_REMINDER_MS = DAY_MS;
1995
2120
  var AuthModule = class _AuthModule {
1996
2121
  constructor(http, tokenManager, config, hooks = {}) {
1997
2122
  this.stateListeners = /* @__PURE__ */ new Set();
1998
2123
  this.lastEmittedState = null;
2124
+ // #1090: expiry of the API token behind the current machine-user session, as
2125
+ // last reported by the token endpoint, and who wants to hear about it.
2126
+ this.apiTokenExpiresAt = null;
2127
+ // The token manager's re-auth generation of the API-token sign-in this
2128
+ // expiry belongs to. The expiry counts only while that generation is current:
2129
+ // any other sign-in, setTokens, clearTokens or auth loss moves it on. A number
2130
+ // on purpose, not the exchange callback, whose closure holds the API token.
2131
+ this.apiTokenGeneration = null;
2132
+ this.apiTokenExpiryListeners = /* @__PURE__ */ new Set();
1999
2133
  this.http = http;
2000
2134
  this.tokenManager = tokenManager;
2001
2135
  this.config = config;
@@ -2010,9 +2144,10 @@ var AuthModule = class _AuthModule {
2010
2144
  expiresAt
2011
2145
  };
2012
2146
  });
2013
- this.unsubscribeAuthLost = this.tokenManager.onAuthLost(
2014
- () => this.emitState("unauthenticated")
2015
- );
2147
+ this.unsubscribeAuthLost = this.tokenManager.onAuthLost(() => {
2148
+ this.setApiTokenExpiry(void 0);
2149
+ this.emitState("unauthenticated");
2150
+ });
2016
2151
  }
2017
2152
  /**
2018
2153
  * Returns true if a non-expired access token is currently in storage.
@@ -2073,6 +2208,7 @@ var AuthModule = class _AuthModule {
2073
2208
  this.unsubscribeAuthLost = () => {
2074
2209
  };
2075
2210
  this.stateListeners.clear();
2211
+ this.apiTokenExpiryListeners.clear();
2076
2212
  this.lastEmittedState = null;
2077
2213
  this.beforeLogout = void 0;
2078
2214
  this.afterSignIn = void 0;
@@ -2088,8 +2224,64 @@ var AuthModule = class _AuthModule {
2088
2224
  await this.beforeLogout().catch(() => void 0);
2089
2225
  }
2090
2226
  await this.tokenManager.setTokens(tokens);
2227
+ this.setApiTokenExpiry(void 0);
2091
2228
  this.emitState("authenticated");
2092
2229
  }
2230
+ /** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
2231
+ setApiTokenExpiry(expiresAt) {
2232
+ const parsed = expiresAt ? new Date(expiresAt) : null;
2233
+ const next = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null;
2234
+ if (next?.getTime() !== this.apiTokenExpiresAt?.getTime()) {
2235
+ for (const entry of this.apiTokenExpiryListeners) entry.lastNotifiedAt = 0;
2236
+ }
2237
+ this.apiTokenExpiresAt = next;
2238
+ for (const entry of this.apiTokenExpiryListeners) this.notifyApiTokenExpiry(entry);
2239
+ }
2240
+ apiTokenSessionLive() {
2241
+ return this.apiTokenGeneration !== null && this.apiTokenGeneration === this.tokenManager.getReauthGeneration();
2242
+ }
2243
+ notifyApiTokenExpiry(entry) {
2244
+ const expiresAt = this.apiTokenExpiresAt;
2245
+ if (!expiresAt || !this.apiTokenSessionLive()) return;
2246
+ const now = Date.now();
2247
+ if (expiresAt.getTime() - now > entry.withinMs) return;
2248
+ if (now - entry.lastNotifiedAt < API_TOKEN_EXPIRY_REMINDER_MS) return;
2249
+ entry.lastNotifiedAt = now;
2250
+ try {
2251
+ void Promise.resolve(entry.listener({ expiresAt: new Date(expiresAt) })).catch(() => void 0);
2252
+ } catch {
2253
+ }
2254
+ }
2255
+ /**
2256
+ * #1090: expiry of the project API token behind the current machine-user
2257
+ * session, or null when it is unknown (no API-token session, a token without
2258
+ * an expiry, or a server that does not report it yet).
2259
+ */
2260
+ getApiTokenExpiry() {
2261
+ return this.apiTokenExpiresAt && this.apiTokenSessionLive() ? new Date(this.apiTokenExpiresAt) : null;
2262
+ }
2263
+ /**
2264
+ * #1090: be told when the project API token of this session expires within
2265
+ * `withinDays` (default 14), so a new token can be issued before the agent is
2266
+ * signed out. Checked at sign-in, on every re-exchange (at least every 15
2267
+ * minutes while the session is in use) and when the listener is added; a
2268
+ * listener hears about the same token at most once a day. Returns an
2269
+ * unsubscribe function.
2270
+ */
2271
+ onApiTokenExpiring(listener, options = {}) {
2272
+ const requested = options.withinDays;
2273
+ const withinDays = typeof requested === "number" && Number.isFinite(requested) && requested >= 0 ? requested : API_TOKEN_EXPIRY_DEFAULT_DAYS;
2274
+ const entry = {
2275
+ listener,
2276
+ withinMs: withinDays * DAY_MS,
2277
+ lastNotifiedAt: 0
2278
+ };
2279
+ this.apiTokenExpiryListeners.add(entry);
2280
+ this.notifyApiTokenExpiry(entry);
2281
+ return () => {
2282
+ this.apiTokenExpiryListeners.delete(entry);
2283
+ };
2284
+ }
2093
2285
  emitState(state) {
2094
2286
  if (state === "authenticated") {
2095
2287
  this.afterSignIn?.().catch(() => void 0);
@@ -2157,6 +2349,7 @@ var AuthModule = class _AuthModule {
2157
2349
  } catch {
2158
2350
  }
2159
2351
  await this.tokenManager.clearTokens();
2352
+ this.setApiTokenExpiry(void 0);
2160
2353
  this.emitState("unauthenticated");
2161
2354
  }
2162
2355
  /**
@@ -2219,6 +2412,8 @@ var AuthModule = class _AuthModule {
2219
2412
  * browser: an API token is a long-lived secret.
2220
2413
  */
2221
2414
  async loginWithApiToken(apiToken) {
2415
+ let reportedExpiry;
2416
+ let generation = null;
2222
2417
  const exchange = async () => {
2223
2418
  const response = await this.http.request({
2224
2419
  method: "POST",
@@ -2226,6 +2421,10 @@ var AuthModule = class _AuthModule {
2226
2421
  body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
2227
2422
  skipAuthRefresh: true
2228
2423
  });
2424
+ reportedExpiry = response.api_token_expires_at;
2425
+ if (generation !== null && generation === this.tokenManager.getReauthGeneration()) {
2426
+ this.setApiTokenExpiry(reportedExpiry ?? this.apiTokenExpiresAt?.toISOString());
2427
+ }
2229
2428
  return {
2230
2429
  accessToken: response.access_token,
2231
2430
  expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
@@ -2234,6 +2433,9 @@ var AuthModule = class _AuthModule {
2234
2433
  const tokens = await exchange();
2235
2434
  await this.installSession(tokens);
2236
2435
  this.tokenManager.setReauthCallback(exchange);
2436
+ generation = this.tokenManager.getReauthGeneration();
2437
+ this.apiTokenGeneration = generation;
2438
+ this.setApiTokenExpiry(reportedExpiry);
2237
2439
  }
2238
2440
  async exchangeCode(params) {
2239
2441
  const body = {
@@ -4673,6 +4875,7 @@ function createClient(config) {
4673
4875
  const realtime = new RealtimeClient({
4674
4876
  baseUrl: config.apiUrl,
4675
4877
  getToken: () => tokenManager.getAccessToken(),
4878
+ refreshToken: () => tokenManager.forceRefresh(),
4676
4879
  onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
4677
4880
  });
4678
4881
  const notifications = new NotificationsModule(httpClient, {