@docyrus/signin 0.17.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
@@ -1,9 +1,9 @@
1
- export { D as DocyrusAuthContext, a as DocyrusAuthProvider, b as DocyrusAuthProviderProps, u as useDocyrusAuth, c as useDocyrusClient } from './use-docyrus-client-BYQdgvz1.js';
2
- import { G as GuidyRoute, H as HostNavigationHandler, s as HostNotificationHandler, n as MsGraphClient, t as HostNavigationRequestOptions, g as DocyrusCalendarEventPayload, k as DocyrusSharePayload, h as DocyrusEmailPayload, d as AuthStatus } from './types-CFnKr6T_.js';
3
- export { A as AclOperation, a as AdaptiveCard, u as AppNavigationRequestMessage, v as AppRouteChangeMessage, b as AuthMode, C as CalendarSendAckMessage, w as CalendarSendMessage, x as ChatSendAckMessage, y as ChatSendMessage, z as DocySendAckMessage, B as DocySendMessage, e as DocyrusAclRule, D as DocyrusAuthConfig, f as DocyrusAuthContextValue, E as DocyrusNotification, i as DocyrusRole, j as DocyrusShareAdaptiveCardPayload, l as DocyrusShareTextPayload, m as DocyrusUser, F as EmailSendAckMessage, I as EmailSendMessage, J as GuidyCommandHandler, K as GuidyCommandMessage, L as GuidyElement, N as GuidyElementsMessage, Q as GuidyPointAckMessage, S as GuidyPointMessage, T as GuidyRoutesMessage, U as GuidyScanMessage, V as HostNavigationMessage, W as HostNotificationMessage, X as HostSignInMessage, Y as IframeAuth, M as MsGraphAccount, o as MsGraphRequest, Z as MsGraphRequestMessage, p as MsGraphRequestOptions, q as MsGraphResponse, _ as MsGraphResponseMessage, r as MsGraphStatus, $ as MsGraphStatusRequestMessage, a0 as MsGraphStatusResponseMessage, P as PermissionConfig, R as RouteChangePayload, a1 as TokenRefreshRequestMessage } from './types-CFnKr6T_.js';
1
+ export { D as DocyrusAuthContext, a as DocyrusAuthProvider, b as DocyrusAuthProviderProps, u as useDocyrusAuth, c as useDocyrusClient } from './use-docyrus-client-C9uiHma9.js';
2
+ import { G as GuidyRoute, H as HostNavigationHandler, v as HostNotificationHandler, p as MsGraphClient, w as HostNavigationRequestOptions, h as DocyrusCalendarEventPayload, m as DocyrusSharePayload, i as DocyrusEmailPayload, e as AuthStatus } from './types-BcLDyMdw.js';
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, c as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, d as DEFAULT_SSR_COOKIE_KEY, g as getAllRoles, h as hasPermission, b as hasRole } from './constants-CB5mfHCf.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";
@@ -1753,24 +1791,72 @@ function hasRole(user, role) {
1753
1791
  }
1754
1792
  return allRoles.some((r) => r.slug === role || r.uid === role);
1755
1793
  }
1756
- function hasPermission(user, operation, dataSourceId, config) {
1757
- if (!user) return false;
1758
- if (hasRole(user, "super_admin")) return true;
1759
- if (dataSourceId && hasRole(user, "global_editor")) {
1760
- if (GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
1794
+ var SCOPE_FIELD_BY_TARGET_TYPE = {
1795
+ data_source: "dataSourceId",
1796
+ field: "dataSourceId",
1797
+ app: "appId",
1798
+ ai_tool: "aiToolId"
1799
+ };
1800
+ var GLOBAL_TARGET_TYPES = [
1801
+ "ai",
1802
+ "settings",
1803
+ "devtools"
1804
+ ];
1805
+ function toScope(scope) {
1806
+ if (scope == null) return {};
1807
+ if (typeof scope === "string") return { dataSourceId: scope };
1808
+ return scope;
1809
+ }
1810
+ function resolveTargetTypes(scope) {
1811
+ if (scope.targetType) return [scope.targetType];
1812
+ if (scope.dataSourceId != null) return ["data_source"];
1813
+ if (scope.appId != null) return ["app"];
1814
+ if (scope.aiToolId != null) return ["ai_tool"];
1815
+ return GLOBAL_TARGET_TYPES;
1816
+ }
1817
+ function matchesScope(permission, scope) {
1818
+ const field = SCOPE_FIELD_BY_TARGET_TYPE[permission.targetType];
1819
+ if (!field) return true;
1820
+ return (permission[field] ?? null) === (scope[field] ?? null);
1821
+ }
1822
+ function getAllowedOperations(user, scope) {
1823
+ if (!user) return [];
1824
+ const resolved = toScope(scope);
1825
+ const targetTypes = resolveTargetTypes(resolved);
1826
+ const operations = /* @__PURE__ */ new Set();
1827
+ if (user.permissions) {
1828
+ for (const permission of user.permissions) {
1829
+ if (!targetTypes.includes(permission.targetType)) continue;
1830
+ if (!matchesScope(permission, resolved)) continue;
1831
+ for (const op of permission.allowedOperations ?? []) {
1832
+ operations.add(op);
1833
+ }
1834
+ }
1835
+ return Array.from(operations);
1761
1836
  }
1762
- if (dataSourceId && hasRole(user, "global_viewer")) {
1763
- if (operation === "view") return true;
1837
+ if (resolved.appId != null || resolved.aiToolId != null) return [];
1838
+ const dataSourceId = resolved.dataSourceId ?? null;
1839
+ for (const rule of user.aclRules ?? []) {
1840
+ if ((rule.dataSourceId ?? null) !== dataSourceId) continue;
1841
+ for (const op of rule.allowedOperations ?? []) {
1842
+ operations.add(op);
1843
+ }
1764
1844
  }
1845
+ return Array.from(operations);
1846
+ }
1847
+ function hasPermission(user, operation, scope, config) {
1848
+ if (!user) return false;
1849
+ if (hasRole(user, "super_admin")) return true;
1850
+ const resolved = toScope(scope);
1851
+ const { dataSourceId } = resolved;
1765
1852
  if (dataSourceId) {
1853
+ if (hasRole(user, "global_editor") && GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
1854
+ if (hasRole(user, "global_viewer") && operation === "view") return true;
1766
1855
  const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
1767
1856
  const permittedOps = alwaysPermitted[dataSourceId];
1768
1857
  if (permittedOps?.includes(operation)) return true;
1769
1858
  }
1770
- const rules = user.aclRules ?? [];
1771
- return rules.some(
1772
- (rule) => rule.dataSourceId === dataSourceId && rule.allowedOperations.includes(operation)
1773
- );
1859
+ return getAllowedOperations(user, resolved).includes(operation);
1774
1860
  }
1775
1861
  var DocyrusAuthContext = createContext(null);
1776
1862
  function DocyrusAuthProvider({
@@ -1828,7 +1914,7 @@ function DocyrusAuthProvider({
1828
1914
  return (role) => hasRole(user, role);
1829
1915
  }, [user]);
1830
1916
  const hasPermission2 = useMemo(() => {
1831
- return (operation, dataSourceId) => hasPermission(user, operation, dataSourceId);
1917
+ return (operation, scope) => hasPermission(user, operation, scope);
1832
1918
  }, [user]);
1833
1919
  const refreshUser = useMemo(() => {
1834
1920
  return async () => {
@@ -2098,6 +2184,6 @@ function SignInButton({
2098
2184
  );
2099
2185
  }
2100
2186
 
2101
- export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, DEFAULT_SSR_COOKIE_KEY, DocyrusAuthContext, DocyrusAuthProvider, GuidyBridge, IframeAuth, MsGraphClient, SignInButton, StandaloneOAuth2Auth, clearTokenCookie, detectAuthMode, getAllRoles, getTokenFromCookie, hasPermission, hasRole, syncTokenToCookie, useDocyrusAuth, useDocyrusClient, useDocyrusGuidyRoutes, useDocyrusHostNavigation, useDocyrusHostNotification, useDocyrusHostRouteSync, useDocyrusMsGraph, useDocyrusRequestHostNavigation, useDocyrusSendToCalendar, useDocyrusSendToChat, useDocyrusSendToDocy, useDocyrusSendToEmail };
2187
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, DEFAULT_SSR_COOKIE_KEY, DocyrusAuthContext, DocyrusAuthProvider, GuidyBridge, IframeAuth, MsGraphClient, SignInButton, StandaloneOAuth2Auth, clearTokenCookie, detectAuthMode, getAllRoles, getAllowedOperations, getTokenFromCookie, hasPermission, hasRole, syncTokenToCookie, useDocyrusAuth, useDocyrusClient, useDocyrusGuidyRoutes, useDocyrusHostNavigation, useDocyrusHostNotification, useDocyrusHostRouteSync, useDocyrusMsGraph, useDocyrusRequestHostNavigation, useDocyrusSendToCalendar, useDocyrusSendToChat, useDocyrusSendToDocy, useDocyrusSendToEmail };
2102
2188
  //# sourceMappingURL=index.js.map
2103
2189
  //# sourceMappingURL=index.js.map