@mitralab.io/platform-sdk 1.4.1 → 1.5.0-beta.1

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.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.1",
4
4
  "description": "JavaScript/TypeScript SDK for building apps on the Mitra Platform",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -62,7 +62,7 @@
62
62
  "url": "https://github.com/mitralab-dev/mitra-platform-sdk/issues"
63
63
  },
64
64
  "dependencies": {
65
- "@mitralab.io/sdk-core": "0.2.11",
65
+ "@mitralab.io/sdk-core": "0.2.12-beta.1",
66
66
  "mitra-interactions-sdk": "1.0.60-beta.48"
67
67
  },
68
68
  "devDependencies": {