@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.
@@ -293,8 +293,12 @@ interface DocyrusAuthContextValue {
293
293
  signOut: () => Promise<void>;
294
294
  /** Check if the current user has a specific role (by slug or uid) */
295
295
  hasRole: (role: string | string[] | null | undefined) => boolean;
296
- /** Check if the current user has permission for an operation on a data source */
297
- hasPermission: (operation: string, dataSourceId?: string | null) => boolean;
296
+ /**
297
+ * Check if the current user has permission for an operation. Pass a data
298
+ * source id (or a {@link PermissionScope}) to scope it to an entity; omit it
299
+ * for tenant-wide operations such as `ai-access`.
300
+ */
301
+ hasPermission: (operation: string, scope?: string | null | PermissionScope) => boolean;
298
302
  /** Re-fetch the current user from the API */
299
303
  refreshUser: () => Promise<void>;
300
304
  /**
@@ -735,11 +739,43 @@ interface DocyrusRole {
735
739
  slug: string;
736
740
  rules: DocyrusAclRule[];
737
741
  }
738
- /** An ACL rule — maps a data source to its allowed operations */
742
+ /**
743
+ * An ACL rule — maps a data source to its allowed operations.
744
+ *
745
+ * Legacy shape, superseded by {@link DocyrusPermission}: every entity-less rule
746
+ * (ai/settings/devtools) and every app/ai-tool rule collapses into the single
747
+ * entry whose `dataSourceId` is null.
748
+ */
739
749
  interface DocyrusAclRule {
740
- dataSourceId: string;
750
+ dataSourceId: string | null;
751
+ allowedOperations: string[];
752
+ }
753
+ /** The entity an ACL rule applies to (`core_acl_operation.target_type`) */
754
+ type AclTargetType = 'data_source' | 'field' | 'app' | 'ai_tool' | 'ai' | 'settings' | 'devtools';
755
+ /**
756
+ * A permission as returned by GET /v1/users/me, merged across the user's roles
757
+ * and keyed by target type. Entity-scoped targets carry the single id that
758
+ * scopes them (`data_source`/`field` → dataSourceId, `app` → appId, `ai_tool`
759
+ * → aiToolId); `ai`, `settings` and `devtools` are tenant-wide and carry none.
760
+ */
761
+ interface DocyrusPermission {
762
+ targetType: AclTargetType;
763
+ dataSourceId?: string | null;
764
+ appId?: string | null;
765
+ aiToolId?: string | null;
741
766
  allowedOperations: string[];
742
767
  }
768
+ /**
769
+ * What a permission check applies to. Omit every id to check a tenant-wide
770
+ * operation such as `ai-access` or `manage_users`.
771
+ */
772
+ interface PermissionScope {
773
+ dataSourceId?: string | null;
774
+ appId?: string | null;
775
+ aiToolId?: string | null;
776
+ /** Narrow the check to one target type; inferred from the ids when omitted. */
777
+ targetType?: AclTargetType;
778
+ }
743
779
  /** The user object as returned by GET /v1/users/me */
744
780
  interface DocyrusUser {
745
781
  id: string;
@@ -750,6 +786,11 @@ interface DocyrusUser {
750
786
  primaryRole: DocyrusRole | null;
751
787
  roles: DocyrusRole[];
752
788
  aclRules: DocyrusAclRule[];
789
+ /**
790
+ * Target-type-aware permissions. Absent on older API versions, where
791
+ * `aclRules` is the only shape available.
792
+ */
793
+ permissions?: DocyrusPermission[];
753
794
  tenant?: {
754
795
  id: string;
755
796
  name: string;
@@ -771,4 +812,4 @@ interface PermissionConfig {
771
812
  alwaysPermittedDataSources?: Record<string, AclOperation[]>;
772
813
  }
773
814
 
774
- export { type MsGraphStatusRequestMessage as $, type AclOperation as A, type DocySendMessage as B, type CalendarSendAckMessage as C, type DocyrusAuthConfig as D, type DocyrusNotification as E, type EmailSendAckMessage as F, type GuidyRoute as G, type HostNavigationHandler as H, type EmailSendMessage as I, type GuidyCommandHandler as J, type GuidyCommandMessage as K, type GuidyElement as L, type MsGraphAccount as M, type GuidyElementsMessage as N, type OpenAuthSessionFn as O, type PermissionConfig as P, type GuidyPointAckMessage as Q, type RouteChangePayload as R, type GuidyPointMessage as S, type GuidyRoutesMessage as T, type GuidyScanMessage as U, type HostNavigationMessage as V, type HostNotificationMessage as W, type HostSignInMessage as X, IframeAuth as Y, type MsGraphRequestMessage as Z, type MsGraphResponseMessage as _, type AdaptiveCard as a, type MsGraphStatusResponseMessage as a0, type TokenRefreshRequestMessage as a1, type AuthMode as b, type AuthSessionResult as c, type AuthStatus as d, type DocyrusAclRule as e, type DocyrusAuthContextValue as f, type DocyrusCalendarEventPayload as g, type DocyrusEmailPayload as h, type DocyrusRole as i, type DocyrusShareAdaptiveCardPayload as j, type DocyrusSharePayload as k, type DocyrusShareTextPayload as l, type DocyrusUser as m, MsGraphClient as n, type MsGraphRequest as o, type MsGraphRequestOptions as p, type MsGraphResponse as q, type MsGraphStatus as r, type HostNotificationHandler as s, type HostNavigationRequestOptions as t, type AppNavigationRequestMessage as u, type AppRouteChangeMessage as v, type CalendarSendMessage as w, type ChatSendAckMessage as x, type ChatSendMessage as y, type DocySendAckMessage as z };
815
+ export { IframeAuth as $, type AclOperation as A, type ChatSendAckMessage as B, type CalendarSendAckMessage as C, type DocyrusAuthConfig as D, type ChatSendMessage as E, type DocySendAckMessage as F, type GuidyRoute as G, type HostNavigationHandler as H, type DocySendMessage as I, type DocyrusNotification as J, type EmailSendAckMessage as K, type EmailSendMessage as L, type MsGraphAccount as M, type GuidyCommandHandler as N, type OpenAuthSessionFn as O, type PermissionConfig as P, type GuidyCommandMessage as Q, type RouteChangePayload as R, type GuidyElement as S, type GuidyElementsMessage as T, type GuidyPointAckMessage as U, type GuidyPointMessage as V, type GuidyRoutesMessage as W, type GuidyScanMessage as X, type HostNavigationMessage as Y, type HostNotificationMessage as Z, type HostSignInMessage as _, type AclTargetType as a, type MsGraphRequestMessage as a0, type MsGraphResponseMessage as a1, type MsGraphStatusRequestMessage as a2, type MsGraphStatusResponseMessage as a3, type TokenRefreshRequestMessage as a4, type AdaptiveCard as b, type AuthMode as c, type AuthSessionResult as d, type AuthStatus as e, type DocyrusAclRule as f, type DocyrusAuthContextValue as g, type DocyrusCalendarEventPayload as h, type DocyrusEmailPayload as i, type DocyrusPermission as j, type DocyrusRole as k, type DocyrusShareAdaptiveCardPayload as l, type DocyrusSharePayload as m, type DocyrusShareTextPayload as n, type DocyrusUser as o, MsGraphClient as p, type MsGraphRequest as q, type MsGraphRequestOptions as r, type MsGraphResponse as s, type MsGraphStatus as t, type PermissionScope as u, type HostNotificationHandler as v, type HostNavigationRequestOptions as w, type AppNavigationRequestMessage as x, type AppRouteChangeMessage as y, type CalendarSendMessage as z };
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { D as DocyrusAuthConfig, f as DocyrusAuthContextValue } from './types-CFnKr6T_.js';
3
+ import { D as DocyrusAuthConfig, g as DocyrusAuthContextValue } from './types-BcLDyMdw.js';
4
4
  import { RestApiClient } from '@docyrus/api-client';
5
5
 
6
6
  interface DocyrusAuthProviderProps extends DocyrusAuthConfig {
@@ -1,8 +1,8 @@
1
1
  import * as vue from 'vue';
2
2
  import { PropType } from 'vue';
3
3
  import { OAuth2TokenStorage, OAuth2Tokens, RestApiClient } from '@docyrus/api-client';
4
- import { b as AuthMode, d as AuthStatus, H as HostNavigationHandler, s as HostNotificationHandler, R as RouteChangePayload, t as HostNavigationRequestOptions, k as DocyrusSharePayload, h as DocyrusEmailPayload, g as DocyrusCalendarEventPayload, n as MsGraphClient } from '../types-CFnKr6T_.js';
5
- export { a as AdaptiveCard, D as DocyrusAuthConfig, j as DocyrusShareAdaptiveCardPayload, l as DocyrusShareTextPayload, M as MsGraphAccount, o as MsGraphRequest, p as MsGraphRequestOptions, q as MsGraphResponse, r as MsGraphStatus } from '../types-CFnKr6T_.js';
4
+ import { c as AuthMode, e as AuthStatus, H as HostNavigationHandler, v as HostNotificationHandler, R as RouteChangePayload, w as HostNavigationRequestOptions, m as DocyrusSharePayload, i as DocyrusEmailPayload, h as DocyrusCalendarEventPayload, p as MsGraphClient } from '../types-BcLDyMdw.js';
5
+ export { b as AdaptiveCard, D as DocyrusAuthConfig, l as DocyrusShareAdaptiveCardPayload, n as DocyrusShareTextPayload, M as MsGraphAccount, q as MsGraphRequest, r as MsGraphRequestOptions, s as MsGraphResponse, t as MsGraphStatus } from '../types-BcLDyMdw.js';
6
6
 
7
7
  interface DocyrusAuthState {
8
8
  status: AuthStatus;
package/dist/vue/index.js CHANGED
@@ -16,6 +16,7 @@ var DEFAULT_CALLBACK_PATH = "/auth/callback";
16
16
  var DEFAULT_ALLOWED_HOST_PATTERN = /^https:\/\/[^/]+\.docyrus\.app$/;
17
17
  var REDIRECT_RETURN_KEY = "docyrus_auth_return_url";
18
18
  var TOKEN_EXPIRY_BUFFER_SECONDS = 60;
19
+ var MIN_TOKEN_REFRESH_INTERVAL_MS = 1e4;
19
20
  var IFRAME_TOKEN_REFRESH_TIMEOUT_MS = 1e4;
20
21
  var HOST_ACTION_TIMEOUT_MS = 15e3;
21
22
  var MSGRAPH_REQUEST_TIMEOUT_MS = 3e4;
@@ -152,18 +153,34 @@ var StandaloneOAuth2Auth = class {
152
153
  };
153
154
 
154
155
  // src/core/jwt.ts
155
- function parseJwtExp(accessToken) {
156
+ var PER_ISSUANCE_CLAIMS = /* @__PURE__ */ new Set([
157
+ "exp",
158
+ "iat",
159
+ "nbf",
160
+ "jti"
161
+ ]);
162
+ function decodeJwtPayload(accessToken) {
156
163
  const parts = accessToken?.split(".");
157
164
  if (!parts || parts.length < 2) return null;
158
165
  try {
159
166
  const payload = JSON.parse(
160
167
  atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
161
168
  );
162
- return typeof payload["exp"] === "number" ? payload["exp"] : null;
169
+ return payload && typeof payload === "object" ? payload : null;
163
170
  } catch {
164
171
  return null;
165
172
  }
166
173
  }
174
+ function parseJwtExp(accessToken) {
175
+ const exp = decodeJwtPayload(accessToken)?.["exp"];
176
+ return typeof exp === "number" ? exp : null;
177
+ }
178
+ function getJwtSessionKey(accessToken) {
179
+ const payload = decodeJwtPayload(accessToken);
180
+ if (!payload) return null;
181
+ const stableClaims = Object.keys(payload).filter((claim) => !PER_ISSUANCE_CLAIMS.has(claim)).sort().map((claim) => [claim, payload[claim]]);
182
+ return JSON.stringify(stableClaims);
183
+ }
167
184
 
168
185
  // src/core/iframe-auth.ts
169
186
  function postToHost(data) {
@@ -1094,6 +1111,10 @@ var AuthManager = class {
1094
1111
  msGraphClient = null;
1095
1112
  reactNativeAuth = null;
1096
1113
  tokenRefreshTimer = null;
1114
+ /** When the refresh timer last fired (ms), to keep proactive refreshes apart. */
1115
+ lastScheduledRefreshAt = 0;
1116
+ /** Session the current client was created for — see `getJwtSessionKey`. */
1117
+ sessionKey = null;
1097
1118
  /** Shared in-flight refresh, so concurrent requests don't trigger parallel refreshes. */
1098
1119
  refreshInFlight = null;
1099
1120
  listeners = /* @__PURE__ */ new Set();
@@ -1485,28 +1506,50 @@ var AuthManager = class {
1485
1506
  }
1486
1507
  this.tokens = null;
1487
1508
  this.client = null;
1509
+ this.sessionKey = null;
1488
1510
  this.user = null;
1489
1511
  this.status = "unauthenticated";
1490
1512
  this.error = null;
1491
1513
  this.notify();
1492
1514
  }
1493
1515
  /**
1494
- * Called when valid tokens are received (either mode).
1495
- * Creates/updates the RestApiClient and schedules token refresh.
1496
- * Fires a user fetch in the background — the first notify() fires with user: null,
1497
- * and a second notify() fires once the user is fetched.
1516
+ * Called when valid tokens are received (any mode). In iframe mode that is
1517
+ * every host `signin` message — the first sign-in, the host's answer to each
1518
+ * `token-refresh-request`, and repeats of a token we already hold (the host
1519
+ * answering more than one `signin-ready`, e.g. under React StrictMode).
1520
+ *
1521
+ * The RestApiClient reads tokens lazily through its TokenManager, so a
1522
+ * refreshed token needs no new client. A new client — plus a user fetch —
1523
+ * is reserved for a new session (first sign-in, or the host switching user
1524
+ * or tenant): consumers key caches on client identity, so a fresh instance
1525
+ * makes them reload everything.
1526
+ *
1527
+ * On a new session the first notify() fires with user: null, and a second
1528
+ * one fires once the user is fetched.
1498
1529
  */
1499
1530
  setAuthenticated(tokens) {
1531
+ const isRepeat = this.status === "authenticated" && tokens.accessToken === this.tokens?.accessToken && tokens.refreshToken === this.tokens?.refreshToken;
1532
+ if (isRepeat) {
1533
+ this.scheduleTokenRefresh(tokens);
1534
+ return;
1535
+ }
1536
+ const sessionKey = getJwtSessionKey(tokens.accessToken);
1537
+ const isNewSession = !this.client || sessionKey === null || sessionKey !== this.sessionKey;
1500
1538
  this.tokens = tokens;
1539
+ this.sessionKey = sessionKey;
1501
1540
  this.error = null;
1502
1541
  this.status = "authenticated";
1503
1542
  if (this.config.ssr) {
1504
1543
  syncTokenToCookie(tokens.accessToken, this.config.ssrCookieKey, tokens.expiresAt);
1505
1544
  }
1506
- this.createClient();
1545
+ if (isNewSession) {
1546
+ this.createClient();
1547
+ }
1507
1548
  this.scheduleTokenRefresh(tokens);
1508
1549
  this.notify();
1509
- this.fetchUser();
1550
+ if (isNewSession || !this.user) {
1551
+ this.fetchUser();
1552
+ }
1510
1553
  }
1511
1554
  /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
1512
1555
  async fetchUser() {
@@ -1617,18 +1660,13 @@ var AuthManager = class {
1617
1660
  if (!this.autoRefreshEnabled) return;
1618
1661
  const expiresAt = this.resolveExpiry(tokens);
1619
1662
  if (!expiresAt) return;
1620
- const expiresAtMs = expiresAt * 1e3;
1621
- const bufferMs = TOKEN_EXPIRY_BUFFER_SECONDS * 1e3;
1622
- const refreshInMs = expiresAtMs - bufferMs - Date.now();
1623
- if (refreshInMs <= 0) {
1624
- this.handleTokenRefresh().catch((err) => {
1625
- this.error = err instanceof Error ? err : new Error(String(err));
1626
- this.status = "unauthenticated";
1627
- this.notify();
1628
- });
1629
- return;
1630
- }
1663
+ const now = Date.now();
1664
+ const dueInMs = expiresAt * 1e3 - TOKEN_EXPIRY_BUFFER_SECONDS * 1e3 - now;
1665
+ const throttleMs = this.lastScheduledRefreshAt + MIN_TOKEN_REFRESH_INTERVAL_MS - now;
1666
+ const refreshInMs = Math.max(dueInMs, throttleMs, 0);
1631
1667
  this.tokenRefreshTimer = setTimeout(() => {
1668
+ this.tokenRefreshTimer = null;
1669
+ this.lastScheduledRefreshAt = Date.now();
1632
1670
  this.handleTokenRefresh().catch((err) => {
1633
1671
  this.error = err instanceof Error ? err : new Error(String(err));
1634
1672
  this.status = "unauthenticated";