@spacelr/sdk 0.19.6 → 0.19.8

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;
@@ -2100,10 +2114,22 @@ function mapProfile(u) {
2100
2114
  roles: u.roles ?? []
2101
2115
  };
2102
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;
2103
2120
  var AuthModule = class _AuthModule {
2104
2121
  constructor(http, tokenManager, config, hooks = {}) {
2105
2122
  this.stateListeners = /* @__PURE__ */ new Set();
2106
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();
2107
2133
  this.http = http;
2108
2134
  this.tokenManager = tokenManager;
2109
2135
  this.config = config;
@@ -2118,9 +2144,10 @@ var AuthModule = class _AuthModule {
2118
2144
  expiresAt
2119
2145
  };
2120
2146
  });
2121
- this.unsubscribeAuthLost = this.tokenManager.onAuthLost(
2122
- () => this.emitState("unauthenticated")
2123
- );
2147
+ this.unsubscribeAuthLost = this.tokenManager.onAuthLost(() => {
2148
+ this.setApiTokenExpiry(void 0);
2149
+ this.emitState("unauthenticated");
2150
+ });
2124
2151
  }
2125
2152
  /**
2126
2153
  * Returns true if a non-expired access token is currently in storage.
@@ -2181,6 +2208,7 @@ var AuthModule = class _AuthModule {
2181
2208
  this.unsubscribeAuthLost = () => {
2182
2209
  };
2183
2210
  this.stateListeners.clear();
2211
+ this.apiTokenExpiryListeners.clear();
2184
2212
  this.lastEmittedState = null;
2185
2213
  this.beforeLogout = void 0;
2186
2214
  this.afterSignIn = void 0;
@@ -2196,8 +2224,64 @@ var AuthModule = class _AuthModule {
2196
2224
  await this.beforeLogout().catch(() => void 0);
2197
2225
  }
2198
2226
  await this.tokenManager.setTokens(tokens);
2227
+ this.setApiTokenExpiry(void 0);
2199
2228
  this.emitState("authenticated");
2200
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
+ }
2201
2285
  emitState(state) {
2202
2286
  if (state === "authenticated") {
2203
2287
  this.afterSignIn?.().catch(() => void 0);
@@ -2265,6 +2349,7 @@ var AuthModule = class _AuthModule {
2265
2349
  } catch {
2266
2350
  }
2267
2351
  await this.tokenManager.clearTokens();
2352
+ this.setApiTokenExpiry(void 0);
2268
2353
  this.emitState("unauthenticated");
2269
2354
  }
2270
2355
  /**
@@ -2327,6 +2412,8 @@ var AuthModule = class _AuthModule {
2327
2412
  * browser: an API token is a long-lived secret.
2328
2413
  */
2329
2414
  async loginWithApiToken(apiToken) {
2415
+ let reportedExpiry;
2416
+ let generation = null;
2330
2417
  const exchange = async () => {
2331
2418
  const response = await this.http.request({
2332
2419
  method: "POST",
@@ -2334,6 +2421,10 @@ var AuthModule = class _AuthModule {
2334
2421
  body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
2335
2422
  skipAuthRefresh: true
2336
2423
  });
2424
+ reportedExpiry = response.api_token_expires_at;
2425
+ if (generation !== null && generation === this.tokenManager.getReauthGeneration()) {
2426
+ this.setApiTokenExpiry(reportedExpiry ?? this.apiTokenExpiresAt?.toISOString());
2427
+ }
2337
2428
  return {
2338
2429
  accessToken: response.access_token,
2339
2430
  expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
@@ -2342,6 +2433,9 @@ var AuthModule = class _AuthModule {
2342
2433
  const tokens = await exchange();
2343
2434
  await this.installSession(tokens);
2344
2435
  this.tokenManager.setReauthCallback(exchange);
2436
+ generation = this.tokenManager.getReauthGeneration();
2437
+ this.apiTokenGeneration = generation;
2438
+ this.setApiTokenExpiry(reportedExpiry);
2345
2439
  }
2346
2440
  async exchangeCode(params) {
2347
2441
  const body = {