@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.d.mts CHANGED
@@ -37,6 +37,12 @@ interface RegisterParams {
37
37
  firstName?: string;
38
38
  lastName?: string;
39
39
  displayName?: string;
40
+ /**
41
+ * Registration invite, for a project that only accepts registrations by
42
+ * invitation. The app's registration page usually receives it in the URL
43
+ * fragment of the invitation link (`#registrationToken=…`).
44
+ */
45
+ registrationToken?: string;
40
46
  }
41
47
  interface LoginResponse {
42
48
  user: {
@@ -76,6 +82,8 @@ interface TokenResponse {
76
82
  expires_in: number;
77
83
  refresh_token?: string;
78
84
  scope?: string;
85
+ /** #1090: expiry (ISO 8601) of the project API token; API-token sign-in only. */
86
+ api_token_expires_at?: string;
79
87
  }
80
88
  interface UserInfo {
81
89
  sub: string;
@@ -484,6 +492,7 @@ declare class TokenManager {
484
492
  private refreshLockName;
485
493
  private refreshCallback;
486
494
  private reauthCallback;
495
+ private reauthGeneration;
487
496
  private refreshPromise;
488
497
  private tokenRefreshedListeners;
489
498
  private authLostListeners;
@@ -496,6 +505,13 @@ declare class TokenManager {
496
505
  * re-authenticating through this callback instead. `null` removes it.
497
506
  */
498
507
  setReauthCallback(callback: ReauthCallback | null): void;
508
+ /**
509
+ * #1090: changes whenever the re-authentication callback is set, replaced or
510
+ * dropped. Lets a caller tell whether "its" API-token session is still the
511
+ * current one without keeping a reference to the callback (whose closure
512
+ * holds the API token).
513
+ */
514
+ getReauthGeneration(): number;
499
515
  /** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
500
516
  canRenew(): Promise<boolean>;
501
517
  getAccessToken(): Promise<string | null>;
@@ -1131,6 +1147,9 @@ declare class AuthModule {
1131
1147
  private lastEmittedState;
1132
1148
  private beforeLogout?;
1133
1149
  private afterSignIn?;
1150
+ private apiTokenExpiresAt;
1151
+ private apiTokenGeneration;
1152
+ private apiTokenExpiryListeners;
1134
1153
  constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
1135
1154
  /**
1136
1155
  * Wired by `createClient`. `beforeLogout` runs while the session is still
@@ -1190,6 +1209,29 @@ declare class AuthModule {
1190
1209
  * the previous user before it is re-registered for the new one.
1191
1210
  */
1192
1211
  private installSession;
1212
+ /** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
1213
+ private setApiTokenExpiry;
1214
+ private apiTokenSessionLive;
1215
+ private notifyApiTokenExpiry;
1216
+ /**
1217
+ * #1090: expiry of the project API token behind the current machine-user
1218
+ * session, or null when it is unknown (no API-token session, a token without
1219
+ * an expiry, or a server that does not report it yet).
1220
+ */
1221
+ getApiTokenExpiry(): Date | null;
1222
+ /**
1223
+ * #1090: be told when the project API token of this session expires within
1224
+ * `withinDays` (default 14), so a new token can be issued before the agent is
1225
+ * signed out. Checked at sign-in, on every re-exchange (at least every 15
1226
+ * minutes while the session is in use) and when the listener is added; a
1227
+ * listener hears about the same token at most once a day. Returns an
1228
+ * unsubscribe function.
1229
+ */
1230
+ onApiTokenExpiring(listener: (info: {
1231
+ expiresAt: Date;
1232
+ }) => void | Promise<void>, options?: {
1233
+ withinDays?: number;
1234
+ }): () => void;
1193
1235
  private emitState;
1194
1236
  login(params: LoginParams): Promise<LoginResponse>;
1195
1237
  register(params: RegisterParams): Promise<RegisterResponse>;
package/dist/index.d.ts CHANGED
@@ -37,6 +37,12 @@ interface RegisterParams {
37
37
  firstName?: string;
38
38
  lastName?: string;
39
39
  displayName?: string;
40
+ /**
41
+ * Registration invite, for a project that only accepts registrations by
42
+ * invitation. The app's registration page usually receives it in the URL
43
+ * fragment of the invitation link (`#registrationToken=…`).
44
+ */
45
+ registrationToken?: string;
40
46
  }
41
47
  interface LoginResponse {
42
48
  user: {
@@ -76,6 +82,8 @@ interface TokenResponse {
76
82
  expires_in: number;
77
83
  refresh_token?: string;
78
84
  scope?: string;
85
+ /** #1090: expiry (ISO 8601) of the project API token; API-token sign-in only. */
86
+ api_token_expires_at?: string;
79
87
  }
80
88
  interface UserInfo {
81
89
  sub: string;
@@ -484,6 +492,7 @@ declare class TokenManager {
484
492
  private refreshLockName;
485
493
  private refreshCallback;
486
494
  private reauthCallback;
495
+ private reauthGeneration;
487
496
  private refreshPromise;
488
497
  private tokenRefreshedListeners;
489
498
  private authLostListeners;
@@ -496,6 +505,13 @@ declare class TokenManager {
496
505
  * re-authenticating through this callback instead. `null` removes it.
497
506
  */
498
507
  setReauthCallback(callback: ReauthCallback | null): void;
508
+ /**
509
+ * #1090: changes whenever the re-authentication callback is set, replaced or
510
+ * dropped. Lets a caller tell whether "its" API-token session is still the
511
+ * current one without keeping a reference to the callback (whose closure
512
+ * holds the API token).
513
+ */
514
+ getReauthGeneration(): number;
499
515
  /** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
500
516
  canRenew(): Promise<boolean>;
501
517
  getAccessToken(): Promise<string | null>;
@@ -1131,6 +1147,9 @@ declare class AuthModule {
1131
1147
  private lastEmittedState;
1132
1148
  private beforeLogout?;
1133
1149
  private afterSignIn?;
1150
+ private apiTokenExpiresAt;
1151
+ private apiTokenGeneration;
1152
+ private apiTokenExpiryListeners;
1134
1153
  constructor(http: HttpClient, tokenManager: TokenManager, config: SpacelrClientConfig,
1135
1154
  /**
1136
1155
  * Wired by `createClient`. `beforeLogout` runs while the session is still
@@ -1190,6 +1209,29 @@ declare class AuthModule {
1190
1209
  * the previous user before it is re-registered for the new one.
1191
1210
  */
1192
1211
  private installSession;
1212
+ /** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
1213
+ private setApiTokenExpiry;
1214
+ private apiTokenSessionLive;
1215
+ private notifyApiTokenExpiry;
1216
+ /**
1217
+ * #1090: expiry of the project API token behind the current machine-user
1218
+ * session, or null when it is unknown (no API-token session, a token without
1219
+ * an expiry, or a server that does not report it yet).
1220
+ */
1221
+ getApiTokenExpiry(): Date | null;
1222
+ /**
1223
+ * #1090: be told when the project API token of this session expires within
1224
+ * `withinDays` (default 14), so a new token can be issued before the agent is
1225
+ * signed out. Checked at sign-in, on every re-exchange (at least every 15
1226
+ * minutes while the session is in use) and when the listener is added; a
1227
+ * listener hears about the same token at most once a day. Returns an
1228
+ * unsubscribe function.
1229
+ */
1230
+ onApiTokenExpiring(listener: (info: {
1231
+ expiresAt: Date;
1232
+ }) => void | Promise<void>, options?: {
1233
+ withinDays?: number;
1234
+ }): () => void;
1193
1235
  private emitState;
1194
1236
  login(params: LoginParams): Promise<LoginResponse>;
1195
1237
  register(params: RegisterParams): Promise<RegisterResponse>;
package/dist/index.js CHANGED
@@ -490,6 +490,7 @@ var TokenManager = class {
490
490
  constructor(storage, refreshBufferSeconds = 60, refreshLockName = "spacelr_token_refresh") {
491
491
  this.refreshCallback = null;
492
492
  this.reauthCallback = null;
493
+ this.reauthGeneration = 0;
493
494
  this.refreshPromise = null;
494
495
  this.tokenRefreshedListeners = /* @__PURE__ */ new Set();
495
496
  this.authLostListeners = /* @__PURE__ */ new Set();
@@ -515,6 +516,16 @@ var TokenManager = class {
515
516
  */
516
517
  setReauthCallback(callback) {
517
518
  this.reauthCallback = callback;
519
+ this.reauthGeneration += 1;
520
+ }
521
+ /**
522
+ * #1090: changes whenever the re-authentication callback is set, replaced or
523
+ * dropped. Lets a caller tell whether "its" API-token session is still the
524
+ * current one without keeping a reference to the callback (whose closure
525
+ * holds the API token).
526
+ */
527
+ getReauthGeneration() {
528
+ return this.reauthGeneration;
518
529
  }
519
530
  /** True when an expired or rejected access token can be renewed (refresh token or re-auth). */
520
531
  async canRenew() {
@@ -539,11 +550,13 @@ var TokenManager = class {
539
550
  const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
540
551
  const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
541
552
  this.reauthCallback = null;
553
+ this.reauthGeneration += 1;
542
554
  await this.storage.setTokens(normalised);
543
555
  this.authLostEmitted = false;
544
556
  }
545
557
  async clearTokens() {
546
558
  this.reauthCallback = null;
559
+ this.reauthGeneration += 1;
547
560
  await this.storage.clearTokens();
548
561
  this.refreshPromise = null;
549
562
  this.authLostEmitted = false;
@@ -626,6 +639,7 @@ var TokenManager = class {
626
639
  if (this.authLostEmitted) return;
627
640
  this.authLostEmitted = true;
628
641
  this.reauthCallback = null;
642
+ this.reauthGeneration += 1;
629
643
  this.pendingClear = this.storage.clearTokens().catch(() => {
630
644
  });
631
645
  await this.pendingClear;
@@ -2147,10 +2161,22 @@ function mapProfile(u) {
2147
2161
  roles: u.roles ?? []
2148
2162
  };
2149
2163
  }
2164
+ var DAY_MS = 24 * 60 * 60 * 1e3;
2165
+ var API_TOKEN_EXPIRY_DEFAULT_DAYS = 14;
2166
+ var API_TOKEN_EXPIRY_REMINDER_MS = DAY_MS;
2150
2167
  var AuthModule = class _AuthModule {
2151
2168
  constructor(http, tokenManager, config, hooks = {}) {
2152
2169
  this.stateListeners = /* @__PURE__ */ new Set();
2153
2170
  this.lastEmittedState = null;
2171
+ // #1090: expiry of the API token behind the current machine-user session, as
2172
+ // last reported by the token endpoint, and who wants to hear about it.
2173
+ this.apiTokenExpiresAt = null;
2174
+ // The token manager's re-auth generation of the API-token sign-in this
2175
+ // expiry belongs to. The expiry counts only while that generation is current:
2176
+ // any other sign-in, setTokens, clearTokens or auth loss moves it on. A number
2177
+ // on purpose, not the exchange callback, whose closure holds the API token.
2178
+ this.apiTokenGeneration = null;
2179
+ this.apiTokenExpiryListeners = /* @__PURE__ */ new Set();
2154
2180
  this.http = http;
2155
2181
  this.tokenManager = tokenManager;
2156
2182
  this.config = config;
@@ -2165,9 +2191,10 @@ var AuthModule = class _AuthModule {
2165
2191
  expiresAt
2166
2192
  };
2167
2193
  });
2168
- this.unsubscribeAuthLost = this.tokenManager.onAuthLost(
2169
- () => this.emitState("unauthenticated")
2170
- );
2194
+ this.unsubscribeAuthLost = this.tokenManager.onAuthLost(() => {
2195
+ this.setApiTokenExpiry(void 0);
2196
+ this.emitState("unauthenticated");
2197
+ });
2171
2198
  }
2172
2199
  /**
2173
2200
  * Returns true if a non-expired access token is currently in storage.
@@ -2228,6 +2255,7 @@ var AuthModule = class _AuthModule {
2228
2255
  this.unsubscribeAuthLost = () => {
2229
2256
  };
2230
2257
  this.stateListeners.clear();
2258
+ this.apiTokenExpiryListeners.clear();
2231
2259
  this.lastEmittedState = null;
2232
2260
  this.beforeLogout = void 0;
2233
2261
  this.afterSignIn = void 0;
@@ -2243,8 +2271,64 @@ var AuthModule = class _AuthModule {
2243
2271
  await this.beforeLogout().catch(() => void 0);
2244
2272
  }
2245
2273
  await this.tokenManager.setTokens(tokens);
2274
+ this.setApiTokenExpiry(void 0);
2246
2275
  this.emitState("authenticated");
2247
2276
  }
2277
+ /** #1090: remember the API token's expiry (or forget it) and tell the listeners. */
2278
+ setApiTokenExpiry(expiresAt) {
2279
+ const parsed = expiresAt ? new Date(expiresAt) : null;
2280
+ const next = parsed && !Number.isNaN(parsed.getTime()) ? parsed : null;
2281
+ if (next?.getTime() !== this.apiTokenExpiresAt?.getTime()) {
2282
+ for (const entry of this.apiTokenExpiryListeners) entry.lastNotifiedAt = 0;
2283
+ }
2284
+ this.apiTokenExpiresAt = next;
2285
+ for (const entry of this.apiTokenExpiryListeners) this.notifyApiTokenExpiry(entry);
2286
+ }
2287
+ apiTokenSessionLive() {
2288
+ return this.apiTokenGeneration !== null && this.apiTokenGeneration === this.tokenManager.getReauthGeneration();
2289
+ }
2290
+ notifyApiTokenExpiry(entry) {
2291
+ const expiresAt = this.apiTokenExpiresAt;
2292
+ if (!expiresAt || !this.apiTokenSessionLive()) return;
2293
+ const now = Date.now();
2294
+ if (expiresAt.getTime() - now > entry.withinMs) return;
2295
+ if (now - entry.lastNotifiedAt < API_TOKEN_EXPIRY_REMINDER_MS) return;
2296
+ entry.lastNotifiedAt = now;
2297
+ try {
2298
+ void Promise.resolve(entry.listener({ expiresAt: new Date(expiresAt) })).catch(() => void 0);
2299
+ } catch {
2300
+ }
2301
+ }
2302
+ /**
2303
+ * #1090: expiry of the project API token behind the current machine-user
2304
+ * session, or null when it is unknown (no API-token session, a token without
2305
+ * an expiry, or a server that does not report it yet).
2306
+ */
2307
+ getApiTokenExpiry() {
2308
+ return this.apiTokenExpiresAt && this.apiTokenSessionLive() ? new Date(this.apiTokenExpiresAt) : null;
2309
+ }
2310
+ /**
2311
+ * #1090: be told when the project API token of this session expires within
2312
+ * `withinDays` (default 14), so a new token can be issued before the agent is
2313
+ * signed out. Checked at sign-in, on every re-exchange (at least every 15
2314
+ * minutes while the session is in use) and when the listener is added; a
2315
+ * listener hears about the same token at most once a day. Returns an
2316
+ * unsubscribe function.
2317
+ */
2318
+ onApiTokenExpiring(listener, options = {}) {
2319
+ const requested = options.withinDays;
2320
+ const withinDays = typeof requested === "number" && Number.isFinite(requested) && requested >= 0 ? requested : API_TOKEN_EXPIRY_DEFAULT_DAYS;
2321
+ const entry = {
2322
+ listener,
2323
+ withinMs: withinDays * DAY_MS,
2324
+ lastNotifiedAt: 0
2325
+ };
2326
+ this.apiTokenExpiryListeners.add(entry);
2327
+ this.notifyApiTokenExpiry(entry);
2328
+ return () => {
2329
+ this.apiTokenExpiryListeners.delete(entry);
2330
+ };
2331
+ }
2248
2332
  emitState(state) {
2249
2333
  if (state === "authenticated") {
2250
2334
  this.afterSignIn?.().catch(() => void 0);
@@ -2312,6 +2396,7 @@ var AuthModule = class _AuthModule {
2312
2396
  } catch {
2313
2397
  }
2314
2398
  await this.tokenManager.clearTokens();
2399
+ this.setApiTokenExpiry(void 0);
2315
2400
  this.emitState("unauthenticated");
2316
2401
  }
2317
2402
  /**
@@ -2374,6 +2459,8 @@ var AuthModule = class _AuthModule {
2374
2459
  * browser: an API token is a long-lived secret.
2375
2460
  */
2376
2461
  async loginWithApiToken(apiToken) {
2462
+ let reportedExpiry;
2463
+ let generation = null;
2377
2464
  const exchange = async () => {
2378
2465
  const response = await this.http.request({
2379
2466
  method: "POST",
@@ -2381,6 +2468,10 @@ var AuthModule = class _AuthModule {
2381
2468
  body: { grant_type: API_TOKEN_GRANT, client_id: this.config.clientId, api_token: apiToken },
2382
2469
  skipAuthRefresh: true
2383
2470
  });
2471
+ reportedExpiry = response.api_token_expires_at;
2472
+ if (generation !== null && generation === this.tokenManager.getReauthGeneration()) {
2473
+ this.setApiTokenExpiry(reportedExpiry ?? this.apiTokenExpiresAt?.toISOString());
2474
+ }
2384
2475
  return {
2385
2476
  accessToken: response.access_token,
2386
2477
  expiresAt: response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0
@@ -2389,6 +2480,9 @@ var AuthModule = class _AuthModule {
2389
2480
  const tokens = await exchange();
2390
2481
  await this.installSession(tokens);
2391
2482
  this.tokenManager.setReauthCallback(exchange);
2483
+ generation = this.tokenManager.getReauthGeneration();
2484
+ this.apiTokenGeneration = generation;
2485
+ this.setApiTokenExpiry(reportedExpiry);
2392
2486
  }
2393
2487
  async exchangeCode(params) {
2394
2488
  const body = {