@docyrus/signin 0.18.0 → 0.18.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.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-BVfrHdk1.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) {
@@ -1102,6 +1119,10 @@ var AuthManager = class {
1102
1119
  msGraphClient = null;
1103
1120
  reactNativeAuth = null;
1104
1121
  tokenRefreshTimer = null;
1122
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1123
+ lastScheduledRefreshAt = 0;
1124
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1125
+ sessionKey = null;
1105
1126
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1106
1127
  refreshInFlight = null;
1107
1128
  listeners = /* @__PURE__ */ new Set();
@@ -1493,28 +1514,50 @@ var AuthManager = class {
1493
1514
  }
1494
1515
  this.tokens = null;
1495
1516
  this.client = null;
1517
+ this.sessionKey = null;
1496
1518
  this.user = null;
1497
1519
  this.status = "unauthenticated";
1498
1520
  this.error = null;
1499
1521
  this.notify();
1500
1522
  }
1501
1523
  /**
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.
1524
+ * Called when valid tokens are received (any mode). In iframe mode that is
1525
+ * every host `signin` message — the first sign-in, the host's answer to each
1526
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1527
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1528
+ *
1529
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1530
+ * refreshed token needs no new client. A new client — plus a user fetch —
1531
+ * is reserved for a new session (first sign-in, or the host switching user
1532
+ * or tenant): consumers key caches on client identity, so a fresh instance
1533
+ * makes them reload everything.
1534
+ *
1535
+ * On a new session the first notify() fires with user: null, and a second
1536
+ * one fires once the user is fetched.
1506
1537
  */
1507
1538
  setAuthenticated(tokens) {
1539
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1540
+ if (isRepeat) {
1541
+ this.scheduleTokenRefresh(tokens);
1542
+ return;
1543
+ }
1544
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1545
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1508
1546
  this.tokens = tokens;
1547
+ this.sessionKey = sessionKey;
1509
1548
  this.error = null;
1510
1549
  this.status = "authenticated";
1511
1550
  if (this.config.ssr) {
1512
1551
  syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1513
1552
  }
1514
- this.createClient();
1553
+ if (isNewSession) {
1554
+ this.createClient();
1555
+ }
1515
1556
  this.scheduleTokenRefresh(tokens);
1516
1557
  this.notify();
1517
- this.fetchUser();
1558
+ if (isNewSession || !this.user) {
1559
+ this.fetchUser();
1560
+ }
1518
1561
  }
1519
1562
  /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
1520
1563
  async fetchUser() {
@@ -1625,18 +1668,13 @@ var AuthManager = class {
1625
1668
  if (!this.autoRefreshEnabled) return;
1626
1669
  const expiresAt = this.resolveExpiry(tokens);
1627
1670
  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
- }
1671
+ const now = Date.now();
1672
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1673
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1674
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1639
1675
  this.tokenRefreshTimer = setTimeout(() => {
1676
+ this.tokenRefreshTimer = null;
1677
+ this.lastScheduledRefreshAt = Date.now();
1640
1678
  this.handleTokenRefresh().catch((err) => {
1641
1679
  this.error = err instanceof Error ? err : new Error(String(err));
1642
1680
  this.status = "unauthenticated";