@docyrus/signin 0.18.0 → 0.18.2

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.ts CHANGED
@@ -3,7 +3,7 @@ import { G as GuidyRoute, H as HostNavigationHandler, v as HostNotificationHandl
3
3
  export { A as AclOperation, a as AclTargetType, b as AdaptiveCard, x as AppNavigationRequestMessage, y as AppRouteChangeMessage, c as AuthMode, C as CalendarSendAckMessage, z as CalendarSendMessage, B as ChatSendAckMessage, E as ChatSendMessage, F as DocySendAckMessage, I as DocySendMessage, f as DocyrusAclRule, D as DocyrusAuthConfig, g as DocyrusAuthContextValue, J as DocyrusNotification, j as DocyrusPermission, k as DocyrusRole, l as DocyrusShareAdaptiveCardPayload, n as DocyrusShareTextPayload, o as DocyrusUser, K as EmailSendAckMessage, L as EmailSendMessage, N as GuidyCommandHandler, Q as GuidyCommandMessage, S as GuidyElement, T as GuidyElementsMessage, U as GuidyPointAckMessage, V as GuidyPointMessage, W as GuidyRoutesMessage, X as GuidyScanMessage, Y as HostNavigationMessage, Z as HostNotificationMessage, _ as HostSignInMessage, $ as IframeAuth, M as MsGraphAccount, q as MsGraphRequest, a0 as MsGraphRequestMessage, r as MsGraphRequestOptions, s as MsGraphResponse, a1 as MsGraphResponseMessage, t as MsGraphStatus, a2 as MsGraphStatusRequestMessage, a3 as MsGraphStatusResponseMessage, P as PermissionConfig, u as PermissionScope, R as RouteChangePayload, a4 as TokenRefreshRequestMessage } from './types-BcLDyMdw.js';
4
4
  import * as react from 'react';
5
5
  import { CSSProperties, ReactNode } from 'react';
6
- export { A as AuthManager, D as DEFAULT_API_URL, d as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, e as DEFAULT_SSR_COOKIE_KEY, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from './constants-C9ezX9zG.js';
6
+ export { A as AuthManager, D as DEFAULT_API_URL, d as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, e as DEFAULT_SSR_COOKIE_KEY, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from './constants-CvMiR-RM.js';
7
7
  export { GuidyBridge, StandaloneOAuth2Auth, detectAuthMode } from './core-index.js';
8
8
  import '@docyrus/api-client';
9
9
 
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ var DEFAULT_CALLBACK_PATH = "/auth/callback";
17
17
  var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
18
18
  var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
19
19
  var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
20
+ var MIN_TOKEN_REFRESH_INTERVAL_MS = 1e4;
20
21
  var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
21
22
  var HOST_ACTION_TIMEOUT_MS = 15e3;
22
23
  var MSGRAPH_REQUEST_TIMEOUT_MS = 3e4;
@@ -154,18 +155,34 @@ var StandaloneOAuth2Auth = class {
154
155
  };
155
156
 
156
157
  // src/core/jwt.ts
157
- function parseJwtExp(accessToken) {
158
+ var PER_ISSUANCE_CLAIMS = /* @__PURE__ */ new Set([
159
+ "exp",
160
+ "iat",
161
+ "nbf",
162
+ "jti"
163
+ ]);
164
+ function decodeJwtPayload(accessToken) {
158
165
  const parts = accessToken?.split(".");
159
166
  if (!parts || parts.length < 2) return null;
160
167
  try {
161
168
  const payload = JSON.parse(
162
169
  atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
163
170
  );
164
- return typeof payload["exp"] === "number" ? payload["exp"] : null;
171
+ return payload && typeof payload === "object" ? payload : null;
165
172
  } catch {
166
173
  return null;
167
174
  }
168
175
  }
176
+ function parseJwtExp(accessToken) {
177
+ const exp = decodeJwtPayload(accessToken)?.["exp"];
178
+ return typeof exp === "number" ? exp : null;
179
+ }
180
+ function getJwtSessionKey(accessToken) {
181
+ const payload = decodeJwtPayload(accessToken);
182
+ if (!payload) return null;
183
+ const stableClaims = Object.keys(payload).filter((claim) => !PER_ISSUANCE_CLAIMS.has(claim)).sort().map((claim) => [claim, payload[claim]]);
184
+ return JSON.stringify(stableClaims);
185
+ }
169
186
 
170
187
  // src/core/iframe-auth.ts
171
188
  function postToHost(data) {
@@ -1096,12 +1113,18 @@ var AuthManager = class {
1096
1113
  error = null;
1097
1114
  client = null;
1098
1115
  user = null;
1116
+ /** In-flight `/v1/users/me` request, tied to the client that issued it. */
1117
+ userFetch = null;
1099
1118
  standaloneAuth = null;
1100
1119
  iframeAuth = null;
1101
1120
  guidyBridge = null;
1102
1121
  msGraphClient = null;
1103
1122
  reactNativeAuth = null;
1104
1123
  tokenRefreshTimer = null;
1124
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1125
+ lastScheduledRefreshAt = 0;
1126
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1127
+ sessionKey = null;
1105
1128
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1106
1129
  refreshInFlight = null;
1107
1130
  listeners = /* @__PURE__ */ new Set();
@@ -1493,40 +1516,82 @@ var AuthManager = class {
1493
1516
  }
1494
1517
  this.tokens = null;
1495
1518
  this.client = null;
1519
+ this.sessionKey = null;
1496
1520
  this.user = null;
1497
1521
  this.status = "unauthenticated";
1498
1522
  this.error = null;
1499
1523
  this.notify();
1500
1524
  }
1501
1525
  /**
1502
- * Called when valid tokens are received (either mode).
1503
- * Creates/updates the RestApiClient and schedules token refresh.
1504
- * Fires a user fetch in the background — the first notify() fires with user: null,
1505
- * and a second notify() fires once the user is fetched.
1526
+ * Called when valid tokens are received (any mode). In iframe mode that is
1527
+ * every host `signin` message — the first sign-in, the host's answer to each
1528
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1529
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1530
+ *
1531
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1532
+ * refreshed token needs no new client. A new client — plus a user fetch —
1533
+ * is reserved for a new session (first sign-in, or the host switching user
1534
+ * or tenant): consumers key caches on client identity, so a fresh instance
1535
+ * makes them reload everything.
1536
+ *
1537
+ * On a new session the first notify() fires with user: null, and a second
1538
+ * one fires once the user is fetched.
1506
1539
  */
1507
1540
  setAuthenticated(tokens) {
1541
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1542
+ if (isRepeat) {
1543
+ this.scheduleTokenRefresh(tokens);
1544
+ return;
1545
+ }
1546
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1547
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1508
1548
  this.tokens = tokens;
1549
+ this.sessionKey = sessionKey;
1509
1550
  this.error = null;
1510
1551
  this.status = "authenticated";
1511
1552
  if (this.config.ssr) {
1512
1553
  syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1513
1554
  }
1514
- this.createClient();
1555
+ if (isNewSession) {
1556
+ this.createClient();
1557
+ }
1515
1558
  this.scheduleTokenRefresh(tokens);
1516
1559
  this.notify();
1517
- this.fetchUser();
1518
- }
1519
- /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
1520
- async fetchUser() {
1521
- if (!this.client) return;
1522
- try {
1523
- const response = await this.client.get("/v1/users/me");
1524
- const maybeUser = response;
1525
- this.user = maybeUser && typeof maybeUser === "object" && "id" in maybeUser && "email" in maybeUser ? maybeUser : response.data;
1526
- } catch {
1527
- this.user = null;
1560
+ if (isNewSession || !this.user) {
1561
+ void this.fetchUser();
1528
1562
  }
1529
- this.notify();
1563
+ }
1564
+ /**
1565
+ * Fetch the current user from /v1/users/me. Silently sets user to null on failure.
1566
+ *
1567
+ * Concurrent calls share one request: `setAuthenticated` fetches whenever the
1568
+ * user is still missing, so a second token push that lands while the first
1569
+ * fetch is in flight (e.g. stored tokens restored on load, then the host or a
1570
+ * bridge pushing its session) would otherwise fire a duplicate request. A
1571
+ * result is dropped if the client changed meanwhile (sign-out or a new
1572
+ * session), so a stale user never overwrites the current one.
1573
+ */
1574
+ fetchUser() {
1575
+ const { client } = this;
1576
+ if (!client) return Promise.resolve();
1577
+ if (this.userFetch?.client === client) return this.userFetch.promise;
1578
+ const promise = (async () => {
1579
+ let user = null;
1580
+ try {
1581
+ const response = await client.get("/v1/users/me");
1582
+ const maybeUser = response;
1583
+ user = maybeUser && typeof maybeUser === "object" && "id" in maybeUser && "email" in maybeUser ? maybeUser : response.data;
1584
+ } catch {
1585
+ user = null;
1586
+ }
1587
+ if (this.client !== client) return;
1588
+ this.user = user;
1589
+ this.notify();
1590
+ })().finally(() => {
1591
+ if (this.userFetch?.promise === promise) this.userFetch = null;
1592
+ });
1593
+ this.userFetch = { client, promise };
1594
+ return promise;
1530
1595
  }
1531
1596
  /**
1532
1597
  * Create a RestApiClient with a custom TokenManager that proactively
@@ -1625,18 +1690,13 @@ var AuthManager = class {
1625
1690
  if (!this.autoRefreshEnabled) return;
1626
1691
  const expiresAt = this.resolveExpiry(tokens);
1627
1692
  if (!expiresAt) return;
1628
- const expiresAtMs = expiresAt * 1e3;
1629
- const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
1630
- const refreshInMs = expiresAtMs - bufferMs - Date.now();
1631
- if (refreshInMs <= 0) {
1632
- this.handleTokenRefresh().catch((err) => {
1633
- this.error = err instanceof Error ? err : new Error(String(err));
1634
- this.status = "unauthenticated";
1635
- this.notify();
1636
- });
1637
- return;
1638
- }
1693
+ const now = Date.now();
1694
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1695
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1696
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1639
1697
  this.tokenRefreshTimer = setTimeout(() => {
1698
+ this.tokenRefreshTimer = null;
1699
+ this.lastScheduledRefreshAt = Date.now();
1640
1700
  this.handleTokenRefresh().catch((err) => {
1641
1701
  this.error = err instanceof Error ? err : new Error(String(err));
1642
1702
  this.status = "unauthenticated";