@mitralab.io/platform-sdk 1.4.1 → 1.5.0-beta.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.5.0-beta.0
6
+
7
+ - Expose `auth.allTokens` for apps enabled server-side, with the three families IAM returns at
8
+ login: `platform` and `b2bToken` session pairs and the `mitraSpace` token. It is `null` for every
9
+ other app, and a malformed part reads as `null` without failing the login.
10
+ - Persist the field with the session. An app refresh replaces `platform` and keeps `mitraSpace` and
11
+ `b2bToken` from login, and a refresh without the field clears it; a new login, `setSession`,
12
+ `setToken` or a legacy login resets it, the legacy SDK's silent refresh keeps it, and `signOut()`
13
+ clears it.
14
+ - Export `AllTokens`, `PlatformSessionTokens` and `MitraSpaceToken`, with `readonly` fields; the
15
+ instances the SDK returns are frozen.
16
+ - Keep the field on the legacy SDK's silent refresh only when the renewed token has the same `sub`
17
+ as the current one; a late refresh for another person, or a token without a readable `sub`,
18
+ resets it.
19
+
5
20
  ## 1.4.1
6
21
 
7
22
  Stable release of the 1.4.1-beta.0 line, already on the `beta` tag. It pins
package/README.md CHANGED
@@ -160,6 +160,28 @@ const mitra = createClient({
160
160
  })
161
161
  ```
162
162
 
163
+ ### Tokens beyond the app session
164
+
165
+ An app enabled server-side receives an extra `allTokens` field when someone signs in with Google, Microsoft, or email. `mitra.auth.allTokens` is `null` whenever IAM did not send it, which is the case for every other app, and a malformed field never fails the login: a part that does not have the expected shape reads as `null`. When all three parts are `null`, the field reads as `null` as well, the same as for an app outside the flag.
166
+
167
+ ```typescript
168
+ const platformAccessToken = mitra.auth.allTokens?.platform?.accessToken
169
+ const mitraSpaceToken = mitra.auth.allTokens?.mitraSpace?.token
170
+ const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken
171
+ ```
172
+
173
+ There are three families, each one `null` when IAM could not issue it:
174
+
175
+ - `platform`: an IAM session pair (`accessToken`, `refreshToken`, `tokenType`) in the workspace IAM chose for the person.
176
+ - `mitraSpace`: a mitraSpace token (`token`, `tokenType`). It lasts for decades and has no refresh flow.
177
+ - `b2bToken`: an IAM session pair for the same person in the IAM of another environment, with the same shape as `platform`.
178
+
179
+ `platform` and `b2bToken` are sessions of one hour. The SDK refreshes only the app token: each app refresh brings a new `platform`, while `b2bToken` comes from login alone, so the app renews it itself with `POST {iam of that environment}/api/v1/auth/refresh-token`, sending only its `refreshToken`. The SDK does not store what that call returns. On an app refresh, `platform` is replaced by what IAM sent, `null` included; `mitraSpace` and `b2bToken`, which IAM sends as `null` there on purpose, keep the values issued at login; a refresh without the field clears it, because IAM omits it whenever the app is not entitled to these tokens and a stored one-hour pair would expire unnoticed. A new login, `setSession`, `setToken`, or a legacy login replaces the session and resets the field; the silent token refresh of the legacy SDK keeps it when the renewed token belongs to the same person, and resets it otherwise. Auth-state listeners are not notified when only these tokens change, so read them right before use. The returned objects are frozen: keep a renewed `b2bToken` in your own state instead of writing it back. After a reload, the `b2bToken` pair available is the one issued at login: the SDK neither renews nor expires it, so a `401` from the peer means the person has to sign in again. `platform` is renewed only by this SDK's app refresh; the silent rotation through the legacy bridge keeps whatever was stored when the renewed token belongs to the same person.
180
+
181
+ These tokens are not checked against `appId`: they are issued for other scopes and stay validated by the server that receives them.
182
+
183
+ **Security note.** These tokens reach more than the app session: `platform` and `b2bToken` act as the person on IAM endpoints the app token cannot reach, and the mitraSpace token lives for decades. `b2bToken` carries the widest exposure: it is the person's session in another environment, the production of the Mitra brand, kept on the origin of an app that runs in a different environment. All three are stored with the rest of the session in `localStorage` under `mitra_auth_{appId}`, so any script running on the application origin can read them. They are persisted, instead of held in memory, because IAM issues `mitraSpace` and `b2bToken` only at login, and `platform` only at login and on refresh: without persistence, a reload would leave `platform` `null` until the next refresh and the other two until the next sign-in. The SDK only carries what IAM sent: the flag is turned on per app in IAM, so whoever enables it there decides which app origins hold these sessions. `signOut()` removes them.
184
+
163
185
  ### Signing in with email
164
186
 
165
187
  Email sign-in needs neither a password nor an SSO account, and the application
package/dist/index.cjs CHANGED
@@ -327,6 +327,9 @@ function resolveAuthPageUrl(apiUrl, configuredAuthPageUrl, browserWindow = globa
327
327
  function stripBearer(token) {
328
328
  return token.replace(/^\s*(?:bearer\s+)+/i, "").trim();
329
329
  }
330
+ function toSessionTokens(session) {
331
+ return { token: stripBearer(session.token), refreshToken: session.refreshToken ?? null };
332
+ }
330
333
  var LegacySessionBridge = class {
331
334
  auth;
332
335
  appId;
@@ -371,7 +374,7 @@ var LegacySessionBridge = class {
371
374
  authUrl: this.legacyUrl,
372
375
  authPageUrl,
373
376
  projectId: this.appId,
374
- onTokenRefresh: (session2) => this.adopt(session2),
377
+ onTokenRefresh: (session2) => this.rotate(session2),
375
378
  ...session.token ? { token: session.token } : {},
376
379
  ...session.refreshToken ? { refreshToken: session.refreshToken } : {}
377
380
  });
@@ -382,16 +385,24 @@ var LegacySessionBridge = class {
382
385
  }
383
386
  }
384
387
  /**
385
- * Stores a session produced by the legacy SDK. The AuthModule subscription
388
+ * Stores a session produced by a legacy login. The AuthModule subscription
386
389
  * then writes that session back to the process-wide legacy config and
387
390
  * reinstates the refresh hook removed by legacy login.
388
391
  */
389
392
  adopt(session) {
390
- const adopted = this.auth.adoptSession({
391
- token: stripBearer(session.token),
392
- refreshToken: session.refreshToken ?? null
393
- });
394
- if (!adopted) this.syncToLegacy(this.auth.readSessionTokens());
393
+ if (!this.auth.adoptSession(toSessionTokens(session))) {
394
+ this.syncToLegacy(this.auth.readSessionTokens());
395
+ }
396
+ }
397
+ /**
398
+ * Stores tokens the legacy SDK silently refreshed for the session already in
399
+ * place. Unlike a legacy login, it keeps the extra login tokens of the client
400
+ * when the renewed token belongs to the same person.
401
+ */
402
+ rotate(session) {
403
+ if (!this.auth.rotateSession(toSessionTokens(session))) {
404
+ this.syncToLegacy(this.auth.readSessionTokens());
405
+ }
395
406
  }
396
407
  };
397
408
  var activeBridge = null;
@@ -474,6 +485,34 @@ var PROVIDERS = {
474
485
  var POPUP_WIDTH = 480;
475
486
  var POPUP_HEIGHT = 600;
476
487
  var POPUP_CLOSED_POLL_MS = 500;
488
+ function isPlainObject(value) {
489
+ return typeof value === "object" && value !== null && !Array.isArray(value);
490
+ }
491
+ function isNonEmptyString(value) {
492
+ return typeof value === "string" && value.trim() !== "";
493
+ }
494
+ function readSessionPair(value) {
495
+ if (!isPlainObject(value)) return null;
496
+ const { accessToken, refreshToken, tokenType } = value;
497
+ if (!isNonEmptyString(accessToken) || !isNonEmptyString(refreshToken) || !isNonEmptyString(tokenType)) {
498
+ return null;
499
+ }
500
+ return Object.freeze({ accessToken, refreshToken, tokenType });
501
+ }
502
+ function readMitraSpaceToken(value) {
503
+ if (!isPlainObject(value)) return null;
504
+ const { token, tokenType } = value;
505
+ if (!isNonEmptyString(token) || !isNonEmptyString(tokenType)) return null;
506
+ return Object.freeze({ token, tokenType });
507
+ }
508
+ function normalizeAllTokens(value) {
509
+ if (!isPlainObject(value)) return void 0;
510
+ return Object.freeze({
511
+ platform: readSessionPair(value.platform),
512
+ mitraSpace: readMitraSpaceToken(value.mitraSpace),
513
+ b2bToken: readSessionPair(value.b2bToken)
514
+ });
515
+ }
477
516
  function expectAuthTokenResponse(value) {
478
517
  const response = (0, import_sdk_core2.expectObject)(
479
518
  value,
@@ -481,16 +520,18 @@ function expectAuthTokenResponse(value) {
481
520
  coreErrors
482
521
  );
483
522
  for (const field of ["accessToken", "refreshToken", "tokenType"]) {
484
- if (typeof response[field] !== "string" || !response[field].trim()) {
523
+ if (!isNonEmptyString(response[field])) {
485
524
  throw coreErrors.invalidResponse(
486
525
  `Authentication token response has an invalid ${field} field`
487
526
  );
488
527
  }
489
528
  }
529
+ const allTokens = normalizeAllTokens(response.allTokens);
490
530
  return {
491
531
  accessToken: response.accessToken,
492
532
  refreshToken: response.refreshToken,
493
- tokenType: response.tokenType
533
+ tokenType: response.tokenType,
534
+ ...allTokens ? { allTokens } : {}
494
535
  };
495
536
  }
496
537
  var AuthPageFlow = class {
@@ -1075,11 +1116,27 @@ function belongsToApp(token, appId) {
1075
1116
  if (!payload) return true;
1076
1117
  return payload.app_id === appId;
1077
1118
  }
1119
+ function subjectOf(token) {
1120
+ const sub = decodeJwtPayload(token)?.sub;
1121
+ return typeof sub === "string" && sub !== "" ? sub : null;
1122
+ }
1078
1123
  function isTokenExpiring(token, minValidityMs) {
1079
1124
  const exp = decodeJwtPayload(token)?.exp;
1080
1125
  if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
1081
1126
  return exp * 1e3 - Date.now() < minValidityMs;
1082
1127
  }
1128
+ function discardEmptyAllTokens(tokens) {
1129
+ if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken) return null;
1130
+ return tokens;
1131
+ }
1132
+ function mergeAllTokens(current, incoming) {
1133
+ if (!incoming) return null;
1134
+ return discardEmptyAllTokens(Object.freeze({
1135
+ platform: incoming.platform,
1136
+ mitraSpace: incoming.mitraSpace ?? current?.mitraSpace ?? null,
1137
+ b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null
1138
+ }));
1139
+ }
1083
1140
  function isDefinitiveRefreshFailure(error) {
1084
1141
  return error instanceof MitraApiError && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 429;
1085
1142
  }
@@ -1089,6 +1146,7 @@ var AuthModule = class {
1089
1146
  _currentUser = null;
1090
1147
  #accessToken = null;
1091
1148
  #refreshToken = null;
1149
+ #allTokens = null;
1092
1150
  sessionGeneration = 0;
1093
1151
  refreshFlight = null;
1094
1152
  transientRefreshFailureGeneration = null;
@@ -1154,7 +1212,8 @@ var AuthModule = class {
1154
1212
  handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
1155
1213
  readSessionTokens: () => this.readSessionTokens(),
1156
1214
  onSessionChange: (callback) => this.onSessionChange(callback),
1157
- adoptSession: (session) => this.adoptSession(session)
1215
+ adoptSession: (session) => this.adoptSession(session),
1216
+ rotateSession: (session) => this.rotateSession(session)
1158
1217
  });
1159
1218
  }
1160
1219
  /** The currently authenticated user, or null. */
@@ -1165,16 +1224,32 @@ var AuthModule = class {
1165
1224
  get accessToken() {
1166
1225
  return this.#accessToken;
1167
1226
  }
1227
+ /**
1228
+ * Extra tokens IAM issues at login for apps enabled server-side, or `null`
1229
+ * when IAM did not send them. They are reset by every new session and updated
1230
+ * on each app refresh, and these changes are not announced to auth-state
1231
+ * listeners, so read them here right before use instead of caching them.
1232
+ *
1233
+ * @example
1234
+ * ```typescript
1235
+ * const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
1236
+ * ```
1237
+ */
1238
+ get allTokens() {
1239
+ return this.#allTokens;
1240
+ }
1168
1241
  /** Whether a user is currently authenticated (local check, not server-validated). */
1169
1242
  get isAuthenticated() {
1170
1243
  return this._currentUser !== null && this.#accessToken !== null;
1171
1244
  }
1172
1245
  /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
1173
- async signIn(_credentials) {
1174
- throw new MitraApiError(
1175
- "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1176
- 0,
1177
- "UNSUPPORTED_AUTH_METHOD"
1246
+ signIn(_credentials) {
1247
+ return Promise.reject(
1248
+ new MitraApiError(
1249
+ "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1250
+ 0,
1251
+ "UNSUPPORTED_AUTH_METHOD"
1252
+ )
1178
1253
  );
1179
1254
  }
1180
1255
  /**
@@ -1247,6 +1322,7 @@ var AuthModule = class {
1247
1322
  this.invalidatePendingRefreshes();
1248
1323
  this.#accessToken = token;
1249
1324
  this.#refreshToken = null;
1325
+ this.#allTokens = null;
1250
1326
  const user = await this.getCurrentUser();
1251
1327
  this._currentUser = user;
1252
1328
  this.notifySessionListeners();
@@ -1415,11 +1491,13 @@ var AuthModule = class {
1415
1491
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1416
1492
  }
1417
1493
  /** @deprecated Email/password registration is not implemented by IAM. Use signInWithEmail() or SSO. */
1418
- async signUp(_data) {
1419
- throw new MitraApiError(
1420
- "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1421
- 0,
1422
- "UNSUPPORTED_AUTH_METHOD"
1494
+ signUp(_data) {
1495
+ return Promise.reject(
1496
+ new MitraApiError(
1497
+ "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1498
+ 0,
1499
+ "UNSUPPORTED_AUTH_METHOD"
1500
+ )
1423
1501
  );
1424
1502
  }
1425
1503
  /**
@@ -1544,7 +1622,8 @@ var AuthModule = class {
1544
1622
  /**
1545
1623
  * Sets the access token manually (e.g., from SSO/OAuth callback).
1546
1624
  *
1547
- * Call `me()` afterwards to fetch the associated user data.
1625
+ * Call `me()` afterwards to fetch the associated user data. {@link allTokens}
1626
+ * goes back to `null`, because it belongs to the session being replaced.
1548
1627
  *
1549
1628
  * @param token - JWT access token.
1550
1629
  * @param saveToStorage - Whether to persist to localStorage (default: true).
@@ -1562,6 +1641,7 @@ var AuthModule = class {
1562
1641
  }
1563
1642
  this.invalidatePendingRefreshes();
1564
1643
  this.#accessToken = token;
1644
+ this.#allTokens = null;
1565
1645
  if (saveToStorage) {
1566
1646
  this.saveToStorage();
1567
1647
  }
@@ -1586,6 +1666,8 @@ var AuthModule = class {
1586
1666
  * This preserves the access and refresh tokens together so the normal refresh
1587
1667
  * lifecycle continues after an embedded preview hands its session to the app.
1588
1668
  * Call {@link checkAuth} afterward to validate the token and hydrate the user.
1669
+ * {@link allTokens} goes back to `null`, because it belongs to the session
1670
+ * being replaced.
1589
1671
  */
1590
1672
  setSession(session) {
1591
1673
  return this.adoptSession({
@@ -1641,18 +1723,37 @@ var AuthModule = class {
1641
1723
  *
1642
1724
  * Replaces the in-memory tokens and persists them under the same storage key
1643
1725
  * the rest of the module uses. The current user is left untouched because the
1644
- * legacy SDK does not return one; call `me()` to hydrate it.
1726
+ * legacy SDK does not return one; call `me()` to hydrate it. It is a new
1727
+ * session, so the extra login tokens of the previous one are dropped.
1645
1728
  *
1646
1729
  * @param session - Access token and, when the issuer returned one, refresh token.
1647
1730
  *
1648
1731
  * @internal
1649
1732
  */
1650
1733
  adoptSession(session) {
1734
+ return this.applySession(session, false);
1735
+ }
1736
+ /**
1737
+ * Stores tokens another issuer rotated for the session already in place, such
1738
+ * as a silent refresh performed by the legacy SDK. The extra login tokens are
1739
+ * kept only when the rotated token belongs to the same person.
1740
+ *
1741
+ * @internal
1742
+ */
1743
+ rotateSession(session) {
1744
+ return this.applySession(session, this.isSamePerson(session.token));
1745
+ }
1746
+ isSamePerson(token) {
1747
+ const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
1748
+ return current !== null && current === subjectOf(token);
1749
+ }
1750
+ applySession(session, keepAllTokens) {
1651
1751
  if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
1652
1752
  this.clearAuthState();
1653
1753
  return false;
1654
1754
  }
1655
1755
  this.invalidatePendingRefreshes();
1756
+ if (!keepAllTokens) this.#allTokens = null;
1656
1757
  this.#accessToken = session.token;
1657
1758
  if (session.refreshToken !== void 0) {
1658
1759
  this.#refreshToken = session.refreshToken;
@@ -1728,6 +1829,7 @@ var AuthModule = class {
1728
1829
  }
1729
1830
  this.#accessToken = tokenResponse.accessToken;
1730
1831
  this.#refreshToken = tokenResponse.refreshToken;
1832
+ this.#allTokens = mergeAllTokens(this.#allTokens, tokenResponse.allTokens);
1731
1833
  this.transientRefreshFailureGeneration = null;
1732
1834
  this.saveToStorage();
1733
1835
  this.notifySessionListeners();
@@ -1742,6 +1844,7 @@ var AuthModule = class {
1742
1844
  const generation = this.sessionGeneration;
1743
1845
  this.#accessToken = tokenResponse.accessToken;
1744
1846
  this.#refreshToken = tokenResponse.refreshToken;
1847
+ this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
1745
1848
  try {
1746
1849
  const user = await this.getCurrentUser();
1747
1850
  if (generation !== this.sessionGeneration) {
@@ -1774,6 +1877,7 @@ var AuthModule = class {
1774
1877
  this._currentUser = null;
1775
1878
  this.#accessToken = null;
1776
1879
  this.#refreshToken = null;
1880
+ this.#allTokens = null;
1777
1881
  this.removeFromStorage();
1778
1882
  if (hadAuthState) {
1779
1883
  this.notifySessionListeners();
@@ -1829,7 +1933,11 @@ var AuthModule = class {
1829
1933
  JSON.stringify({
1830
1934
  user: this._currentUser,
1831
1935
  token: this.#accessToken,
1832
- refreshToken: this.#refreshToken
1936
+ refreshToken: this.#refreshToken,
1937
+ // Persisted with the session on purpose: IAM issues mitraSpace and
1938
+ // b2bToken only at login, so keeping them in memory alone would lose
1939
+ // them on the first reload.
1940
+ ...this.#allTokens ? { allTokens: this.#allTokens } : {}
1833
1941
  })
1834
1942
  );
1835
1943
  } catch {
@@ -1840,7 +1948,7 @@ var AuthModule = class {
1840
1948
  try {
1841
1949
  const stored = localStorage.getItem(this.storageKey);
1842
1950
  if (stored) {
1843
- const { user, token, refreshToken } = JSON.parse(stored);
1951
+ const { user, token, refreshToken, allTokens } = JSON.parse(stored);
1844
1952
  if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
1845
1953
  this.clearAuthState();
1846
1954
  return;
@@ -1848,6 +1956,7 @@ var AuthModule = class {
1848
1956
  this._currentUser = user;
1849
1957
  this.#accessToken = token;
1850
1958
  this.#refreshToken = refreshToken ?? null;
1959
+ this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
1851
1960
  this.invalidatePendingRefreshes();
1852
1961
  }
1853
1962
  } catch {
package/dist/index.d.cts CHANGED
@@ -252,6 +252,30 @@ interface EmailCodeVerification {
252
252
  receipt: string;
253
253
  code: string;
254
254
  }
255
+ /** A one-hour IAM session pair, renewed at the `refresh-token` route of the IAM that issued it. */
256
+ interface PlatformSessionTokens {
257
+ readonly accessToken: string;
258
+ readonly refreshToken: string;
259
+ readonly tokenType: string;
260
+ }
261
+ /** Long-lived mitraSpace token issued at login. It has no refresh flow. */
262
+ interface MitraSpaceToken {
263
+ readonly token: string;
264
+ readonly tokenType: string;
265
+ }
266
+ /**
267
+ * Extra tokens IAM returns at login only for apps enabled server-side. The SDK
268
+ * hands out frozen instances: the object is persisted with the session, so a
269
+ * write into it would reach storage on the next save.
270
+ */
271
+ interface AllTokens {
272
+ /** Session in the workspace IAM picked for the person, or null when there is none. */
273
+ readonly platform: PlatformSessionTokens | null;
274
+ /** Null when mitraSpace is unreachable or the person has no account there. */
275
+ readonly mitraSpace: MitraSpaceToken | null;
276
+ /** Session of the same person in the IAM of another environment, or null on any failure there. */
277
+ readonly b2bToken: PlatformSessionTokens | null;
278
+ }
255
279
  /** Callback for auth state changes. Receives the user on login, null on logout. */
256
280
  type AuthStateChangeCallback = (user: User | null) => void;
257
281
 
@@ -299,6 +323,18 @@ declare class AuthModule {
299
323
  get currentUser(): User | null;
300
324
  /** The current JWT access token, or null. */
301
325
  get accessToken(): string | null;
326
+ /**
327
+ * Extra tokens IAM issues at login for apps enabled server-side, or `null`
328
+ * when IAM did not send them. They are reset by every new session and updated
329
+ * on each app refresh, and these changes are not announced to auth-state
330
+ * listeners, so read them here right before use instead of caching them.
331
+ *
332
+ * @example
333
+ * ```typescript
334
+ * const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
335
+ * ```
336
+ */
337
+ get allTokens(): AllTokens | null;
302
338
  /** Whether a user is currently authenticated (local check, not server-validated). */
303
339
  get isAuthenticated(): boolean;
304
340
  /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
@@ -569,7 +605,8 @@ declare class AuthModule {
569
605
  /**
570
606
  * Sets the access token manually (e.g., from SSO/OAuth callback).
571
607
  *
572
- * Call `me()` afterwards to fetch the associated user data.
608
+ * Call `me()` afterwards to fetch the associated user data. {@link allTokens}
609
+ * goes back to `null`, because it belongs to the session being replaced.
573
610
  *
574
611
  * @param token - JWT access token.
575
612
  * @param saveToStorage - Whether to persist to localStorage (default: true).
@@ -598,6 +635,8 @@ declare class AuthModule {
598
635
  * This preserves the access and refresh tokens together so the normal refresh
599
636
  * lifecycle continues after an embedded preview hands its session to the app.
600
637
  * Call {@link checkAuth} afterward to validate the token and hydrate the user.
638
+ * {@link allTokens} goes back to `null`, because it belongs to the session
639
+ * being replaced.
601
640
  */
602
641
  setSession(session: AuthSession): boolean;
603
642
  /**
@@ -634,13 +673,24 @@ declare class AuthModule {
634
673
  *
635
674
  * Replaces the in-memory tokens and persists them under the same storage key
636
675
  * the rest of the module uses. The current user is left untouched because the
637
- * legacy SDK does not return one; call `me()` to hydrate it.
676
+ * legacy SDK does not return one; call `me()` to hydrate it. It is a new
677
+ * session, so the extra login tokens of the previous one are dropped.
638
678
  *
639
679
  * @param session - Access token and, when the issuer returned one, refresh token.
640
680
  *
641
681
  * @internal
642
682
  */
643
683
  private adoptSession;
684
+ /**
685
+ * Stores tokens another issuer rotated for the session already in place, such
686
+ * as a silent refresh performed by the legacy SDK. The extra login tokens are
687
+ * kept only when the rotated token belongs to the same person.
688
+ *
689
+ * @internal
690
+ */
691
+ private rotateSession;
692
+ private isSamePerson;
693
+ private applySession;
644
694
  /**
645
695
  * Redirects to `/login?returnUrl=...` for unauthenticated users.
646
696
  *
@@ -1173,4 +1223,4 @@ type StopServerFunctionExecutionResponse = LegacyTypes.StopServerFunctionExecuti
1173
1223
  /** @deprecated Legacy compatibility type. */
1174
1224
  type UpdateRecordOptions = LegacyTypes.UpdateRecordOptions;
1175
1225
 
1176
- export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type PatchRecordOptions, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
1226
+ export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
package/dist/index.d.ts CHANGED
@@ -252,6 +252,30 @@ interface EmailCodeVerification {
252
252
  receipt: string;
253
253
  code: string;
254
254
  }
255
+ /** A one-hour IAM session pair, renewed at the `refresh-token` route of the IAM that issued it. */
256
+ interface PlatformSessionTokens {
257
+ readonly accessToken: string;
258
+ readonly refreshToken: string;
259
+ readonly tokenType: string;
260
+ }
261
+ /** Long-lived mitraSpace token issued at login. It has no refresh flow. */
262
+ interface MitraSpaceToken {
263
+ readonly token: string;
264
+ readonly tokenType: string;
265
+ }
266
+ /**
267
+ * Extra tokens IAM returns at login only for apps enabled server-side. The SDK
268
+ * hands out frozen instances: the object is persisted with the session, so a
269
+ * write into it would reach storage on the next save.
270
+ */
271
+ interface AllTokens {
272
+ /** Session in the workspace IAM picked for the person, or null when there is none. */
273
+ readonly platform: PlatformSessionTokens | null;
274
+ /** Null when mitraSpace is unreachable or the person has no account there. */
275
+ readonly mitraSpace: MitraSpaceToken | null;
276
+ /** Session of the same person in the IAM of another environment, or null on any failure there. */
277
+ readonly b2bToken: PlatformSessionTokens | null;
278
+ }
255
279
  /** Callback for auth state changes. Receives the user on login, null on logout. */
256
280
  type AuthStateChangeCallback = (user: User | null) => void;
257
281
 
@@ -299,6 +323,18 @@ declare class AuthModule {
299
323
  get currentUser(): User | null;
300
324
  /** The current JWT access token, or null. */
301
325
  get accessToken(): string | null;
326
+ /**
327
+ * Extra tokens IAM issues at login for apps enabled server-side, or `null`
328
+ * when IAM did not send them. They are reset by every new session and updated
329
+ * on each app refresh, and these changes are not announced to auth-state
330
+ * listeners, so read them here right before use instead of caching them.
331
+ *
332
+ * @example
333
+ * ```typescript
334
+ * const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
335
+ * ```
336
+ */
337
+ get allTokens(): AllTokens | null;
302
338
  /** Whether a user is currently authenticated (local check, not server-validated). */
303
339
  get isAuthenticated(): boolean;
304
340
  /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
@@ -569,7 +605,8 @@ declare class AuthModule {
569
605
  /**
570
606
  * Sets the access token manually (e.g., from SSO/OAuth callback).
571
607
  *
572
- * Call `me()` afterwards to fetch the associated user data.
608
+ * Call `me()` afterwards to fetch the associated user data. {@link allTokens}
609
+ * goes back to `null`, because it belongs to the session being replaced.
573
610
  *
574
611
  * @param token - JWT access token.
575
612
  * @param saveToStorage - Whether to persist to localStorage (default: true).
@@ -598,6 +635,8 @@ declare class AuthModule {
598
635
  * This preserves the access and refresh tokens together so the normal refresh
599
636
  * lifecycle continues after an embedded preview hands its session to the app.
600
637
  * Call {@link checkAuth} afterward to validate the token and hydrate the user.
638
+ * {@link allTokens} goes back to `null`, because it belongs to the session
639
+ * being replaced.
601
640
  */
602
641
  setSession(session: AuthSession): boolean;
603
642
  /**
@@ -634,13 +673,24 @@ declare class AuthModule {
634
673
  *
635
674
  * Replaces the in-memory tokens and persists them under the same storage key
636
675
  * the rest of the module uses. The current user is left untouched because the
637
- * legacy SDK does not return one; call `me()` to hydrate it.
676
+ * legacy SDK does not return one; call `me()` to hydrate it. It is a new
677
+ * session, so the extra login tokens of the previous one are dropped.
638
678
  *
639
679
  * @param session - Access token and, when the issuer returned one, refresh token.
640
680
  *
641
681
  * @internal
642
682
  */
643
683
  private adoptSession;
684
+ /**
685
+ * Stores tokens another issuer rotated for the session already in place, such
686
+ * as a silent refresh performed by the legacy SDK. The extra login tokens are
687
+ * kept only when the rotated token belongs to the same person.
688
+ *
689
+ * @internal
690
+ */
691
+ private rotateSession;
692
+ private isSamePerson;
693
+ private applySession;
644
694
  /**
645
695
  * Redirects to `/login?returnUrl=...` for unauthenticated users.
646
696
  *
@@ -1173,4 +1223,4 @@ type StopServerFunctionExecutionResponse = LegacyTypes.StopServerFunctionExecuti
1173
1223
  /** @deprecated Legacy compatibility type. */
1174
1224
  type UpdateRecordOptions = LegacyTypes.UpdateRecordOptions;
1175
1225
 
1176
- export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type PatchRecordOptions, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
1226
+ export { type AgentChat, type AgentCredentialProvider, type AgentCredentialStatus, type AgentCredentialsModule, type AgentDeltaEvent, type AgentDeviceProvider, type AgentErrorEvent, type AgentMessage, type AgentModel, type AgentOAuthProvider, type AgentProvider, type AgentQueueChangeEvent, type AgentRawEvent, type AgentStatusChangeEvent, type AgentTaskCreatedEvent, type AgentTaskEventMap, type AgentTaskEventName, type AgentTaskSession, type AgentTaskStatus, type AgentTaskTransport, type AgentTimelineItem, type AgentToolEvent, type AgentTurnEndEvent, type AgentType, type AllTokens, type AuthAgentCredentialResult, type AuthPageSignInOptions, type CallIntegrationOptions, type CallIntegrationResponse, type ChatManageAction, type ConnectAgentCredentialResult, type CreateRecordOptions, type CreateRecordsBatchOptions, type CredentialAction, type DeleteAgentChatResult, type DeleteRecordOptions, type DeviceAuthAgentCredentialResult, type EmailCodeLanguage, type EmailCodeRequest, type EmailCodeRequestResult, type EmailCodeVerification, type EmailSignInOptions, type ExecutePublicServerFunctionAsyncResponse, type ExecutePublicServerFunctionOptions, type ExecutePublicServerFunctionResponse, type ExecuteServerFunctionAsyncOptions, type ExecuteServerFunctionAsyncResponse, type ExecuteServerFunctionOptions, type ExecuteServerFunctionResponse, type GetAgentTaskCreateOptions, type GetAgentTaskOpenOptions, type GetAgentTaskOptions, type GetPublicServerFunctionExecutionOptions, type GetPublicServerFunctionExecutionResponse, type GetRecordOptions, type GoogleSignInOptions, type IntegrationResponse, type ListAgentModelsResult, type ListAgentProvidersResult, type ListIntegrationsOptions, type ListRecordsOptions, type ListRecordsResponse, type LoginOptions, type LoginResponse, type ManageAgentChatDeleteOptions, type ManageAgentChatListOptions, type ManageAgentChatOptions, type ManageAgentChatRenameOptions, type ManageAgentCredentialOptions, type MicrosoftSignInOptions, MitraApiError, type MitraClient, type MitraClientConfig, type MitraConfig, type MitraInstance, type MitraSpaceToken, type PatchRecordOptions, type PlatformSessionTokens, type QueuedItem, type RenameAgentChatResult, type SendOptions, type SignInCredentials, type SignUpData, type StopServerFunctionExecutionOptions, type StopServerFunctionExecutionResponse, type UpdateRecordOptions, type User, createClient, exchangeSsoCodeMitra, loginMitra, loginWithGoogleMitra, loginWithMicrosoftMitra };
package/dist/index.js CHANGED
@@ -277,6 +277,9 @@ function resolveAuthPageUrl(apiUrl, configuredAuthPageUrl, browserWindow = globa
277
277
  function stripBearer(token) {
278
278
  return token.replace(/^\s*(?:bearer\s+)+/i, "").trim();
279
279
  }
280
+ function toSessionTokens(session) {
281
+ return { token: stripBearer(session.token), refreshToken: session.refreshToken ?? null };
282
+ }
280
283
  var LegacySessionBridge = class {
281
284
  auth;
282
285
  appId;
@@ -321,7 +324,7 @@ var LegacySessionBridge = class {
321
324
  authUrl: this.legacyUrl,
322
325
  authPageUrl,
323
326
  projectId: this.appId,
324
- onTokenRefresh: (session2) => this.adopt(session2),
327
+ onTokenRefresh: (session2) => this.rotate(session2),
325
328
  ...session.token ? { token: session.token } : {},
326
329
  ...session.refreshToken ? { refreshToken: session.refreshToken } : {}
327
330
  });
@@ -332,16 +335,24 @@ var LegacySessionBridge = class {
332
335
  }
333
336
  }
334
337
  /**
335
- * Stores a session produced by the legacy SDK. The AuthModule subscription
338
+ * Stores a session produced by a legacy login. The AuthModule subscription
336
339
  * then writes that session back to the process-wide legacy config and
337
340
  * reinstates the refresh hook removed by legacy login.
338
341
  */
339
342
  adopt(session) {
340
- const adopted = this.auth.adoptSession({
341
- token: stripBearer(session.token),
342
- refreshToken: session.refreshToken ?? null
343
- });
344
- if (!adopted) this.syncToLegacy(this.auth.readSessionTokens());
343
+ if (!this.auth.adoptSession(toSessionTokens(session))) {
344
+ this.syncToLegacy(this.auth.readSessionTokens());
345
+ }
346
+ }
347
+ /**
348
+ * Stores tokens the legacy SDK silently refreshed for the session already in
349
+ * place. Unlike a legacy login, it keeps the extra login tokens of the client
350
+ * when the renewed token belongs to the same person.
351
+ */
352
+ rotate(session) {
353
+ if (!this.auth.rotateSession(toSessionTokens(session))) {
354
+ this.syncToLegacy(this.auth.readSessionTokens());
355
+ }
345
356
  }
346
357
  };
347
358
  var activeBridge = null;
@@ -424,6 +435,34 @@ var PROVIDERS = {
424
435
  var POPUP_WIDTH = 480;
425
436
  var POPUP_HEIGHT = 600;
426
437
  var POPUP_CLOSED_POLL_MS = 500;
438
+ function isPlainObject(value) {
439
+ return typeof value === "object" && value !== null && !Array.isArray(value);
440
+ }
441
+ function isNonEmptyString(value) {
442
+ return typeof value === "string" && value.trim() !== "";
443
+ }
444
+ function readSessionPair(value) {
445
+ if (!isPlainObject(value)) return null;
446
+ const { accessToken, refreshToken, tokenType } = value;
447
+ if (!isNonEmptyString(accessToken) || !isNonEmptyString(refreshToken) || !isNonEmptyString(tokenType)) {
448
+ return null;
449
+ }
450
+ return Object.freeze({ accessToken, refreshToken, tokenType });
451
+ }
452
+ function readMitraSpaceToken(value) {
453
+ if (!isPlainObject(value)) return null;
454
+ const { token, tokenType } = value;
455
+ if (!isNonEmptyString(token) || !isNonEmptyString(tokenType)) return null;
456
+ return Object.freeze({ token, tokenType });
457
+ }
458
+ function normalizeAllTokens(value) {
459
+ if (!isPlainObject(value)) return void 0;
460
+ return Object.freeze({
461
+ platform: readSessionPair(value.platform),
462
+ mitraSpace: readMitraSpaceToken(value.mitraSpace),
463
+ b2bToken: readSessionPair(value.b2bToken)
464
+ });
465
+ }
427
466
  function expectAuthTokenResponse(value) {
428
467
  const response = expectObject(
429
468
  value,
@@ -431,16 +470,18 @@ function expectAuthTokenResponse(value) {
431
470
  coreErrors
432
471
  );
433
472
  for (const field of ["accessToken", "refreshToken", "tokenType"]) {
434
- if (typeof response[field] !== "string" || !response[field].trim()) {
473
+ if (!isNonEmptyString(response[field])) {
435
474
  throw coreErrors.invalidResponse(
436
475
  `Authentication token response has an invalid ${field} field`
437
476
  );
438
477
  }
439
478
  }
479
+ const allTokens = normalizeAllTokens(response.allTokens);
440
480
  return {
441
481
  accessToken: response.accessToken,
442
482
  refreshToken: response.refreshToken,
443
- tokenType: response.tokenType
483
+ tokenType: response.tokenType,
484
+ ...allTokens ? { allTokens } : {}
444
485
  };
445
486
  }
446
487
  var AuthPageFlow = class {
@@ -1025,11 +1066,27 @@ function belongsToApp(token, appId) {
1025
1066
  if (!payload) return true;
1026
1067
  return payload.app_id === appId;
1027
1068
  }
1069
+ function subjectOf(token) {
1070
+ const sub = decodeJwtPayload(token)?.sub;
1071
+ return typeof sub === "string" && sub !== "" ? sub : null;
1072
+ }
1028
1073
  function isTokenExpiring(token, minValidityMs) {
1029
1074
  const exp = decodeJwtPayload(token)?.exp;
1030
1075
  if (typeof exp !== "number" || !Number.isFinite(exp)) return false;
1031
1076
  return exp * 1e3 - Date.now() < minValidityMs;
1032
1077
  }
1078
+ function discardEmptyAllTokens(tokens) {
1079
+ if (!tokens || !tokens.platform && !tokens.mitraSpace && !tokens.b2bToken) return null;
1080
+ return tokens;
1081
+ }
1082
+ function mergeAllTokens(current, incoming) {
1083
+ if (!incoming) return null;
1084
+ return discardEmptyAllTokens(Object.freeze({
1085
+ platform: incoming.platform,
1086
+ mitraSpace: incoming.mitraSpace ?? current?.mitraSpace ?? null,
1087
+ b2bToken: incoming.b2bToken ?? current?.b2bToken ?? null
1088
+ }));
1089
+ }
1033
1090
  function isDefinitiveRefreshFailure(error) {
1034
1091
  return error instanceof MitraApiError && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 429;
1035
1092
  }
@@ -1039,6 +1096,7 @@ var AuthModule = class {
1039
1096
  _currentUser = null;
1040
1097
  #accessToken = null;
1041
1098
  #refreshToken = null;
1099
+ #allTokens = null;
1042
1100
  sessionGeneration = 0;
1043
1101
  refreshFlight = null;
1044
1102
  transientRefreshFailureGeneration = null;
@@ -1104,7 +1162,8 @@ var AuthModule = class {
1104
1162
  handleUnauthorized: (requestToken) => this.handleUnauthorized(requestToken),
1105
1163
  readSessionTokens: () => this.readSessionTokens(),
1106
1164
  onSessionChange: (callback) => this.onSessionChange(callback),
1107
- adoptSession: (session) => this.adoptSession(session)
1165
+ adoptSession: (session) => this.adoptSession(session),
1166
+ rotateSession: (session) => this.rotateSession(session)
1108
1167
  });
1109
1168
  }
1110
1169
  /** The currently authenticated user, or null. */
@@ -1115,16 +1174,32 @@ var AuthModule = class {
1115
1174
  get accessToken() {
1116
1175
  return this.#accessToken;
1117
1176
  }
1177
+ /**
1178
+ * Extra tokens IAM issues at login for apps enabled server-side, or `null`
1179
+ * when IAM did not send them. They are reset by every new session and updated
1180
+ * on each app refresh, and these changes are not announced to auth-state
1181
+ * listeners, so read them here right before use instead of caching them.
1182
+ *
1183
+ * @example
1184
+ * ```typescript
1185
+ * const b2bAccessToken = mitra.auth.allTokens?.b2bToken?.accessToken;
1186
+ * ```
1187
+ */
1188
+ get allTokens() {
1189
+ return this.#allTokens;
1190
+ }
1118
1191
  /** Whether a user is currently authenticated (local check, not server-validated). */
1119
1192
  get isAuthenticated() {
1120
1193
  return this._currentUser !== null && this.#accessToken !== null;
1121
1194
  }
1122
1195
  /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
1123
- async signIn(_credentials) {
1124
- throw new MitraApiError(
1125
- "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1126
- 0,
1127
- "UNSUPPORTED_AUTH_METHOD"
1196
+ signIn(_credentials) {
1197
+ return Promise.reject(
1198
+ new MitraApiError(
1199
+ "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1200
+ 0,
1201
+ "UNSUPPORTED_AUTH_METHOD"
1202
+ )
1128
1203
  );
1129
1204
  }
1130
1205
  /**
@@ -1197,6 +1272,7 @@ var AuthModule = class {
1197
1272
  this.invalidatePendingRefreshes();
1198
1273
  this.#accessToken = token;
1199
1274
  this.#refreshToken = null;
1275
+ this.#allTokens = null;
1200
1276
  const user = await this.getCurrentUser();
1201
1277
  this._currentUser = user;
1202
1278
  this.notifySessionListeners();
@@ -1365,11 +1441,13 @@ var AuthModule = class {
1365
1441
  return tokenResponse ? this.establishSession(tokenResponse) : null;
1366
1442
  }
1367
1443
  /** @deprecated Email/password registration is not implemented by IAM. Use signInWithEmail() or SSO. */
1368
- async signUp(_data) {
1369
- throw new MitraApiError(
1370
- "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1371
- 0,
1372
- "UNSUPPORTED_AUTH_METHOD"
1444
+ signUp(_data) {
1445
+ return Promise.reject(
1446
+ new MitraApiError(
1447
+ "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
1448
+ 0,
1449
+ "UNSUPPORTED_AUTH_METHOD"
1450
+ )
1373
1451
  );
1374
1452
  }
1375
1453
  /**
@@ -1494,7 +1572,8 @@ var AuthModule = class {
1494
1572
  /**
1495
1573
  * Sets the access token manually (e.g., from SSO/OAuth callback).
1496
1574
  *
1497
- * Call `me()` afterwards to fetch the associated user data.
1575
+ * Call `me()` afterwards to fetch the associated user data. {@link allTokens}
1576
+ * goes back to `null`, because it belongs to the session being replaced.
1498
1577
  *
1499
1578
  * @param token - JWT access token.
1500
1579
  * @param saveToStorage - Whether to persist to localStorage (default: true).
@@ -1512,6 +1591,7 @@ var AuthModule = class {
1512
1591
  }
1513
1592
  this.invalidatePendingRefreshes();
1514
1593
  this.#accessToken = token;
1594
+ this.#allTokens = null;
1515
1595
  if (saveToStorage) {
1516
1596
  this.saveToStorage();
1517
1597
  }
@@ -1536,6 +1616,8 @@ var AuthModule = class {
1536
1616
  * This preserves the access and refresh tokens together so the normal refresh
1537
1617
  * lifecycle continues after an embedded preview hands its session to the app.
1538
1618
  * Call {@link checkAuth} afterward to validate the token and hydrate the user.
1619
+ * {@link allTokens} goes back to `null`, because it belongs to the session
1620
+ * being replaced.
1539
1621
  */
1540
1622
  setSession(session) {
1541
1623
  return this.adoptSession({
@@ -1591,18 +1673,37 @@ var AuthModule = class {
1591
1673
  *
1592
1674
  * Replaces the in-memory tokens and persists them under the same storage key
1593
1675
  * the rest of the module uses. The current user is left untouched because the
1594
- * legacy SDK does not return one; call `me()` to hydrate it.
1676
+ * legacy SDK does not return one; call `me()` to hydrate it. It is a new
1677
+ * session, so the extra login tokens of the previous one are dropped.
1595
1678
  *
1596
1679
  * @param session - Access token and, when the issuer returned one, refresh token.
1597
1680
  *
1598
1681
  * @internal
1599
1682
  */
1600
1683
  adoptSession(session) {
1684
+ return this.applySession(session, false);
1685
+ }
1686
+ /**
1687
+ * Stores tokens another issuer rotated for the session already in place, such
1688
+ * as a silent refresh performed by the legacy SDK. The extra login tokens are
1689
+ * kept only when the rotated token belongs to the same person.
1690
+ *
1691
+ * @internal
1692
+ */
1693
+ rotateSession(session) {
1694
+ return this.applySession(session, this.isSamePerson(session.token));
1695
+ }
1696
+ isSamePerson(token) {
1697
+ const current = this.#accessToken ? subjectOf(this.#accessToken) : null;
1698
+ return current !== null && current === subjectOf(token);
1699
+ }
1700
+ applySession(session, keepAllTokens) {
1601
1701
  if (!this.belongsToConfiguredApp(session.token) || typeof session.refreshToken === "string" && !this.belongsToConfiguredApp(session.refreshToken)) {
1602
1702
  this.clearAuthState();
1603
1703
  return false;
1604
1704
  }
1605
1705
  this.invalidatePendingRefreshes();
1706
+ if (!keepAllTokens) this.#allTokens = null;
1606
1707
  this.#accessToken = session.token;
1607
1708
  if (session.refreshToken !== void 0) {
1608
1709
  this.#refreshToken = session.refreshToken;
@@ -1678,6 +1779,7 @@ var AuthModule = class {
1678
1779
  }
1679
1780
  this.#accessToken = tokenResponse.accessToken;
1680
1781
  this.#refreshToken = tokenResponse.refreshToken;
1782
+ this.#allTokens = mergeAllTokens(this.#allTokens, tokenResponse.allTokens);
1681
1783
  this.transientRefreshFailureGeneration = null;
1682
1784
  this.saveToStorage();
1683
1785
  this.notifySessionListeners();
@@ -1692,6 +1794,7 @@ var AuthModule = class {
1692
1794
  const generation = this.sessionGeneration;
1693
1795
  this.#accessToken = tokenResponse.accessToken;
1694
1796
  this.#refreshToken = tokenResponse.refreshToken;
1797
+ this.#allTokens = discardEmptyAllTokens(tokenResponse.allTokens);
1695
1798
  try {
1696
1799
  const user = await this.getCurrentUser();
1697
1800
  if (generation !== this.sessionGeneration) {
@@ -1724,6 +1827,7 @@ var AuthModule = class {
1724
1827
  this._currentUser = null;
1725
1828
  this.#accessToken = null;
1726
1829
  this.#refreshToken = null;
1830
+ this.#allTokens = null;
1727
1831
  this.removeFromStorage();
1728
1832
  if (hadAuthState) {
1729
1833
  this.notifySessionListeners();
@@ -1779,7 +1883,11 @@ var AuthModule = class {
1779
1883
  JSON.stringify({
1780
1884
  user: this._currentUser,
1781
1885
  token: this.#accessToken,
1782
- refreshToken: this.#refreshToken
1886
+ refreshToken: this.#refreshToken,
1887
+ // Persisted with the session on purpose: IAM issues mitraSpace and
1888
+ // b2bToken only at login, so keeping them in memory alone would lose
1889
+ // them on the first reload.
1890
+ ...this.#allTokens ? { allTokens: this.#allTokens } : {}
1783
1891
  })
1784
1892
  );
1785
1893
  } catch {
@@ -1790,7 +1898,7 @@ var AuthModule = class {
1790
1898
  try {
1791
1899
  const stored = localStorage.getItem(this.storageKey);
1792
1900
  if (stored) {
1793
- const { user, token, refreshToken } = JSON.parse(stored);
1901
+ const { user, token, refreshToken, allTokens } = JSON.parse(stored);
1794
1902
  if (typeof token !== "string" || refreshToken !== null && refreshToken !== void 0 && typeof refreshToken !== "string" || !this.belongsToConfiguredApp(token) || typeof refreshToken === "string" && !this.belongsToConfiguredApp(refreshToken)) {
1795
1903
  this.clearAuthState();
1796
1904
  return;
@@ -1798,6 +1906,7 @@ var AuthModule = class {
1798
1906
  this._currentUser = user;
1799
1907
  this.#accessToken = token;
1800
1908
  this.#refreshToken = refreshToken ?? null;
1909
+ this.#allTokens = discardEmptyAllTokens(normalizeAllTokens(allTokens));
1801
1910
  this.invalidatePendingRefreshes();
1802
1911
  }
1803
1912
  } catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/platform-sdk",
3
- "version": "1.4.1",
3
+ "version": "1.5.0-beta.0",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
5
  "type": "module",
6
6
  "sideEffects": false,