@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/README.md CHANGED
@@ -694,6 +694,17 @@ Used when the app is embedded in an iframe on `*.docyrus.app`. The flow:
694
694
  4. When tokens expire, provider sends `{ type: 'token-refresh-request' }` to host
695
695
  5. Host responds with fresh tokens
696
696
 
697
+ The host may post `signin` as often as it likes. Only a new session — the
698
+ first token, or one for a different user/tenant — creates a new `client` and
699
+ re-fetches the user. Repeats of the current token are ignored, and refreshed
700
+ tokens for the same session just update `tokens`, so `client` keeps its
701
+ identity and anything keyed on it (query caches, inventory) stays warm. Two
702
+ tokens belong to the same session when their JWT payloads match apart from
703
+ `exp`, `iat`, `nbf` and `jti`; a token that isn't a decodable JWT always counts
704
+ as a new session. Proactive refreshes are spaced at least 10s apart, so a host
705
+ that answers with a token still inside the 60s expiry buffer can't cause a
706
+ refresh loop.
707
+
697
708
  In addition to auth messages, the host may push two side-channel messages
698
709
  that the embedded app can subscribe to:
699
710
 
@@ -25,6 +25,10 @@ declare class AuthManager {
25
25
  private msGraphClient;
26
26
  private reactNativeAuth;
27
27
  private tokenRefreshTimer;
28
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
29
+ private lastScheduledRefreshAt;
30
+ /** Session the current client was created for — see `getJwtSessionKey`. */
31
+ private sessionKey;
28
32
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
29
33
  private refreshInFlight;
30
34
  private listeners;
@@ -152,10 +156,19 @@ declare class AuthManager {
152
156
  */
153
157
  signOut(): Promise<void>;
154
158
  /**
155
- * Called when valid tokens are received (either mode).
156
- * Creates/updates the RestApiClient and schedules token refresh.
157
- * Fires a user fetch in the background — the first notify() fires with user: null,
158
- * and a second notify() fires once the user is fetched.
159
+ * Called when valid tokens are received (any mode). In iframe mode that is
160
+ * every host `signin` message — the first sign-in, the host's answer to each
161
+ * `token-refresh-request`, and repeats of a token we already hold (the host
162
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
163
+ *
164
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
165
+ * refreshed token needs no new client. A new client — plus a user fetch —
166
+ * is reserved for a new session (first sign-in, or the host switching user
167
+ * or tenant): consumers key caches on client identity, so a fresh instance
168
+ * makes them reload everything.
169
+ *
170
+ * On a new session the first notify() fires with user: null, and a second
171
+ * one fires once the user is fetched.
159
172
  */
160
173
  private setAuthenticated;
161
174
  /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
@@ -1,4 +1,4 @@
1
- export { A as AuthManager, f as AuthStateListener, D as DEFAULT_API_URL, d as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from './constants-C9ezX9zG.js';
1
+ export { A as AuthManager, f as AuthStateListener, D as DEFAULT_API_URL, d as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, b as getAllowedOperations, h as hasPermission, c as hasRole } from './constants-BVfrHdk1.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
3
  import { D as DocyrusAuthConfig, T as GuidyElementsMessage, W as GuidyRoutesMessage, U as GuidyPointAckMessage, G as GuidyRoute, Q as GuidyCommandMessage, c as AuthMode } from './types-BcLDyMdw.js';
4
4
  export { A as AclOperation, a as AclTargetType, b as AdaptiveCard, x as AppNavigationRequestMessage, y as AppRouteChangeMessage, e as AuthStatus, C as CalendarSendAckMessage, z as CalendarSendMessage, B as ChatSendAckMessage, E as ChatSendMessage, F as DocySendAckMessage, I as DocySendMessage, f as DocyrusAclRule, g as DocyrusAuthContextValue, h as DocyrusCalendarEventPayload, i as DocyrusEmailPayload, J as DocyrusNotification, j as DocyrusPermission, k as DocyrusRole, l as DocyrusShareAdaptiveCardPayload, m as DocyrusSharePayload, n as DocyrusShareTextPayload, o as DocyrusUser, K as EmailSendAckMessage, L as EmailSendMessage, N as GuidyCommandHandler, S as GuidyElement, V as GuidyPointMessage, X as GuidyScanMessage, H as HostNavigationHandler, Y as HostNavigationMessage, w as HostNavigationRequestOptions, v as HostNotificationHandler, Z as HostNotificationMessage, _ as HostSignInMessage, $ as IframeAuth, M as MsGraphAccount, p as MsGraphClient, 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';
@@ -15,6 +15,7 @@ var DEFAULT_CALLBACK_PATH = "/auth/callback";
15
15
  var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
16
16
  var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
17
17
  var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
18
+ var MIN_TOKEN_REFRESH_INTERVAL_MS = 1e4;
18
19
  var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
19
20
  var HOST_ACTION_TIMEOUT_MS = 15e3;
20
21
  var MSGRAPH_REQUEST_TIMEOUT_MS = 3e4;
@@ -151,18 +152,34 @@ var StandaloneOAuth2Auth = class {
151
152
  };
152
153
 
153
154
  // src/core/jwt.ts
154
- function parseJwtExp(accessToken) {
155
+ var PER_ISSUANCE_CLAIMS = /* @__PURE__ */ new Set([
156
+ "exp",
157
+ "iat",
158
+ "nbf",
159
+ "jti"
160
+ ]);
161
+ function decodeJwtPayload(accessToken) {
155
162
  const parts = accessToken?.split(".");
156
163
  if (!parts || parts.length < 2) return null;
157
164
  try {
158
165
  const payload = JSON.parse(
159
166
  atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
160
167
  );
161
- return typeof payload["exp"] === "number" ? payload["exp"] : null;
168
+ return payload && typeof payload === "object" ? payload : null;
162
169
  } catch {
163
170
  return null;
164
171
  }
165
172
  }
173
+ function parseJwtExp(accessToken) {
174
+ const exp = decodeJwtPayload(accessToken)?.["exp"];
175
+ return typeof exp === "number" ? exp : null;
176
+ }
177
+ function getJwtSessionKey(accessToken) {
178
+ const payload = decodeJwtPayload(accessToken);
179
+ if (!payload) return null;
180
+ const stableClaims = Object.keys(payload).filter((claim) => !PER_ISSUANCE_CLAIMS.has(claim)).sort().map((claim) => [claim, payload[claim]]);
181
+ return JSON.stringify(stableClaims);
182
+ }
166
183
 
167
184
  // src/core/iframe-auth.ts
168
185
  function postToHost(data) {
@@ -1093,6 +1110,10 @@ var AuthManager = class {
1093
1110
  msGraphClient = null;
1094
1111
  reactNativeAuth = null;
1095
1112
  tokenRefreshTimer = null;
1113
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1114
+ lastScheduledRefreshAt = 0;
1115
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1116
+ sessionKey = null;
1096
1117
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1097
1118
  refreshInFlight = null;
1098
1119
  listeners = /* @__PURE__ */ new Set();
@@ -1484,28 +1505,50 @@ var AuthManager = class {
1484
1505
  }
1485
1506
  this.tokens = null;
1486
1507
  this.client = null;
1508
+ this.sessionKey = null;
1487
1509
  this.user = null;
1488
1510
  this.status = "unauthenticated";
1489
1511
  this.error = null;
1490
1512
  this.notify();
1491
1513
  }
1492
1514
  /**
1493
- * Called when valid tokens are received (either mode).
1494
- * Creates/updates the RestApiClient and schedules token refresh.
1495
- * Fires a user fetch in the background — the first notify() fires with user: null,
1496
- * and a second notify() fires once the user is fetched.
1515
+ * Called when valid tokens are received (any mode). In iframe mode that is
1516
+ * every host `signin` message — the first sign-in, the host's answer to each
1517
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1518
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1519
+ *
1520
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1521
+ * refreshed token needs no new client. A new client — plus a user fetch —
1522
+ * is reserved for a new session (first sign-in, or the host switching user
1523
+ * or tenant): consumers key caches on client identity, so a fresh instance
1524
+ * makes them reload everything.
1525
+ *
1526
+ * On a new session the first notify() fires with user: null, and a second
1527
+ * one fires once the user is fetched.
1497
1528
  */
1498
1529
  setAuthenticated(tokens) {
1530
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1531
+ if (isRepeat) {
1532
+ this.scheduleTokenRefresh(tokens);
1533
+ return;
1534
+ }
1535
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1536
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1499
1537
  this.tokens = tokens;
1538
+ this.sessionKey = sessionKey;
1500
1539
  this.error = null;
1501
1540
  this.status = "authenticated";
1502
1541
  if (this.config.ssr) {
1503
1542
  syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1504
1543
  }
1505
- this.createClient();
1544
+ if (isNewSession) {
1545
+ this.createClient();
1546
+ }
1506
1547
  this.scheduleTokenRefresh(tokens);
1507
1548
  this.notify();
1508
- this.fetchUser();
1549
+ if (isNewSession || !this.user) {
1550
+ this.fetchUser();
1551
+ }
1509
1552
  }
1510
1553
  /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
1511
1554
  async fetchUser() {
@@ -1616,18 +1659,13 @@ var AuthManager = class {
1616
1659
  if (!this.autoRefreshEnabled) return;
1617
1660
  const expiresAt = this.resolveExpiry(tokens);
1618
1661
  if (!expiresAt) return;
1619
- const expiresAtMs = expiresAt * 1e3;
1620
- const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
1621
- const refreshInMs = expiresAtMs - bufferMs - Date.now();
1622
- if (refreshInMs <= 0) {
1623
- this.handleTokenRefresh().catch((err) => {
1624
- this.error = err instanceof Error ? err : new Error(String(err));
1625
- this.status = "unauthenticated";
1626
- this.notify();
1627
- });
1628
- return;
1629
- }
1662
+ const now = Date.now();
1663
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1664
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1665
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1630
1666
  this.tokenRefreshTimer = setTimeout(() => {
1667
+ this.tokenRefreshTimer = null;
1668
+ this.lastScheduledRefreshAt = Date.now();
1631
1669
  this.handleTokenRefresh().catch((err) => {
1632
1670
  this.error = err instanceof Error ? err : new Error(String(err));
1633
1671
  this.status = "unauthenticated";