@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/README.md CHANGED
@@ -523,7 +523,7 @@ const {
523
523
  getAuthorizationUrl, // () => Promise<string | null> (returns URL without navigating — for Electron)
524
524
  signOut, // () => Promise<void>
525
525
  hasRole, // (role) => boolean — check if user has a role by slug or uid
526
- hasPermission, // (operation, dataSourceId?) => boolean — check ACL permission
526
+ hasPermission, // (operation, scope?) => boolean — check ACL permission (scope: data source id, {appId}/{aiToolId}, or omitted for tenant-wide)
527
527
  refreshUser, // () => Promise<void> — re-fetch user from API
528
528
  onHostNavigation, // (handler) => () => void — subscribe to host navigation messages (iframe mode)
529
529
  onHostNotification, // (handler) => () => void — subscribe to host notification messages (iframe mode)
@@ -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
 
@@ -1010,6 +1021,12 @@ function DataSourceView({ dataSourceId }: { dataSourceId: string }) {
1010
1021
  const canEdit = hasPermission('edit', dataSourceId);
1011
1022
  const canDelete = hasPermission('delete', dataSourceId);
1012
1023
 
1024
+ // Check a tenant-wide operation — no entity to scope it to
1025
+ const canUseAi = hasPermission('ai-access');
1026
+
1027
+ // Check an app / AI tool operation
1028
+ const canOpenApp = hasPermission('app_access', { appId });
1029
+
1013
1030
  // Check multiple roles
1014
1031
  if (hasRole(['editor', 'reviewer'])) {
1015
1032
  return <EditorView canEdit={canEdit} canDelete={canDelete} />;
@@ -1022,7 +1039,7 @@ function DataSourceView({ dataSourceId }: { dataSourceId: string }) {
1022
1039
  ### Via Pure Functions (Framework-Agnostic)
1023
1040
 
1024
1041
  ```tsx
1025
- import { hasRole, hasPermission } from '@docyrus/signin/core';
1042
+ import { hasRole, hasPermission, getAllowedOperations } from '@docyrus/signin/core';
1026
1043
  import type { DocyrusUser } from '@docyrus/signin/core';
1027
1044
 
1028
1045
  function checkAccess(user: DocyrusUser) {
@@ -1031,19 +1048,56 @@ function checkAccess(user: DocyrusUser) {
1031
1048
  hasRole(user, 'super_admin'); // checks slug or uid
1032
1049
  hasRole(user, ['editor', 'viewer']); // any match
1033
1050
 
1034
- // hasPermission checks: super_admin → global_editor → global_viewer → always-permitted → aclRules
1051
+ // hasPermission checks: super_admin → global_editor → global_viewer → always-permitted → rules
1035
1052
  hasPermission(user, 'view', 'some-ds-id');
1036
1053
  hasPermission(user, 'edit', 'some-ds-id');
1054
+
1055
+ // Everything the user may do within a scope
1056
+ getAllowedOperations(user, 'some-ds-id'); // ['view', 'edit', ...]
1057
+ getAllowedOperations(user); // tenant-wide: ['ai-access', 'manage_users', ...]
1037
1058
  }
1038
1059
  ```
1039
1060
 
1061
+ ### Permission Scopes
1062
+
1063
+ `hasPermission` and `getAllowedOperations` take an optional scope as their last
1064
+ positional argument. What you pass decides which ACL target type answers the
1065
+ check:
1066
+
1067
+ | Scope argument | Target type | Example operations |
1068
+ | --- | --- | --- |
1069
+ | `'ds-id'` or `{ dataSourceId }` | `data_source` | `view`, `create`, `edit`, `delete`, `export`, `print` |
1070
+ | `{ appId }` | `app` | `app_access` |
1071
+ | `{ aiToolId }` | `ai_tool` | `allow` |
1072
+ | omitted / `null` | `ai`, `settings`, `devtools` | `ai-access`, `manage_users`, `studio`, `automations` |
1073
+
1074
+ Pass `{ targetType }` alongside an id to pin the check to a single target type
1075
+ (for example `{ dataSourceId, targetType: 'field' }` to read field
1076
+ restrictions, which are never treated as grants otherwise).
1077
+
1078
+ ```tsx
1079
+ // Tenant-wide capabilities carry no entity id
1080
+ hasPermission(user, 'ai-access');
1081
+ hasPermission(user, 'manage_users');
1082
+
1083
+ // Entity-scoped, but not a data source
1084
+ hasPermission(user, 'app_access', { appId });
1085
+ hasPermission(user, 'allow', { aiToolId });
1086
+ ```
1087
+
1040
1088
  ### Permission Resolution Order
1041
1089
 
1042
1090
  1. `super_admin` role → always granted
1043
- 2. `global_editor` role → granted for: view, create, edit, delete, create_bulk, export, import, print
1044
- 3. `global_viewer` role → granted only for: view
1091
+ 2. `global_editor` role + data source scope → granted for: view, create, edit, delete, create_bulk, export, import, print
1092
+ 3. `global_viewer` role + data source scope → granted only for: view
1045
1093
  4. Always-permitted system data sources (reports, todos, notes, etc.)
1046
- 5. User's `aclRules` array (merged from all roles by the server)
1094
+ 5. The user's rules for the scope — `permissions` when the API returns it, otherwise the legacy `aclRules` array (both merged from all roles by the server)
1095
+
1096
+ > `permissions` is the target-type-aware shape (`{ targetType, dataSourceId?,
1097
+ > appId?, aiToolId?, allowedOperations }`). The older `aclRules` shape is keyed
1098
+ > by data source alone, so it collapses every entity-less rule into a single
1099
+ > null-keyed entry and cannot answer app or AI tool scopes; it is used only when
1100
+ > `permissions` is absent.
1047
1101
 
1048
1102
  ### Refreshing User Data
1049
1103
 
@@ -1,5 +1,5 @@
1
1
  import { OAuth2Tokens, RestApiClient } from '@docyrus/api-client';
2
- import { D as DocyrusAuthConfig, b as AuthMode, d as AuthStatus, m as DocyrusUser, G as GuidyRoute, R as RouteChangePayload, t as HostNavigationRequestOptions, k as DocyrusSharePayload, h as DocyrusEmailPayload, g as DocyrusCalendarEventPayload, n as MsGraphClient, H as HostNavigationHandler, s as HostNotificationHandler, i as DocyrusRole, P as PermissionConfig } from './types-CFnKr6T_.js';
2
+ import { D as DocyrusAuthConfig, c as AuthMode, e as AuthStatus, o as DocyrusUser, G as GuidyRoute, R as RouteChangePayload, w as HostNavigationRequestOptions, m as DocyrusSharePayload, i as DocyrusEmailPayload, h as DocyrusCalendarEventPayload, p as MsGraphClient, H as HostNavigationHandler, v as HostNotificationHandler, k as DocyrusRole, u as PermissionScope, P as PermissionConfig } from './types-BcLDyMdw.js';
3
3
 
4
4
  type AuthStateListener = (state: {
5
5
  status: AuthStatus;
@@ -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. */
@@ -212,16 +225,30 @@ declare function getAllRoles(user: DocyrusUser | null | undefined): DocyrusRole[
212
225
  */
213
226
  declare function hasRole(user: DocyrusUser | null | undefined, role: string | string[] | null | undefined): boolean;
214
227
  /**
215
- * Check if the user has permission for an operation on a data source.
228
+ * Every operation the user is granted within a scope, merged across roles.
229
+ *
230
+ * Omit `scope` (or pass one with no ids) for tenant-wide operations; pass a
231
+ * data source id, or a {@link PermissionScope} for app / AI tool targets.
232
+ *
233
+ * Role shortcuts are deliberately excluded — this reports what the user's rules
234
+ * actually carry. Use {@link hasPermission} for an access decision.
235
+ */
236
+ declare function getAllowedOperations(user: DocyrusUser | null | undefined, scope?: string | null | PermissionScope): string[];
237
+ /**
238
+ * Check if the user has permission for an operation.
239
+ *
240
+ * `scope` accepts a data source id, a {@link PermissionScope} for app / AI tool
241
+ * targets, or nothing at all for tenant-wide operations such as `ai-access`,
242
+ * `manage_users` or `studio`.
216
243
  *
217
244
  * Permission resolution order:
218
245
  * 1. super_admin role → always true
219
246
  * 2. global_editor role + dataSourceId → true if operation is in the global_editor set
220
247
  * 3. global_viewer role + dataSourceId → true only for 'view'
221
248
  * 4. Always-permitted data sources (configurable)
222
- * 5. User's aclRules array
249
+ * 5. The user's permissions for the scope (`permissions`, falling back to `aclRules`)
223
250
  */
224
- declare function hasPermission(user: DocyrusUser | null | undefined, operation: string, dataSourceId?: string | null, config?: PermissionConfig): boolean;
251
+ declare function hasPermission(user: DocyrusUser | null | undefined, operation: string, scope?: string | null | PermissionScope, config?: PermissionConfig): boolean;
225
252
 
226
253
  declare const DEFAULT_API_URL = "https://alpha-api.docyrus.com";
227
254
  declare const DEFAULT_OAUTH_SCOPES: string[];
@@ -229,4 +256,4 @@ declare const DEFAULT_CALLBACK_PATH = "/auth/callback";
229
256
  /** Default cookie name for SSR token sync */
230
257
  declare const DEFAULT_SSR_COOKIE_KEY = "docyrus-token";
231
258
 
232
- export { AuthManager as A, DEFAULT_API_URL as D, DEFAULT_OAUTH_SCOPES as a, hasRole as b, DEFAULT_CALLBACK_PATH as c, DEFAULT_SSR_COOKIE_KEY as d, type AuthStateListener as e, getAllRoles as g, hasPermission as h };
259
+ export { AuthManager as A, DEFAULT_API_URL as D, DEFAULT_OAUTH_SCOPES as a, getAllowedOperations as b, hasRole as c, DEFAULT_CALLBACK_PATH as d, DEFAULT_SSR_COOKIE_KEY as e, type AuthStateListener as f, getAllRoles as g, hasPermission as h };
@@ -1,7 +1,7 @@
1
- export { A as AuthManager, e as AuthStateListener, D as DEFAULT_API_URL, c as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES, g as getAllRoles, h as hasPermission, b as hasRole } from './constants-CB5mfHCf.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
- import { D as DocyrusAuthConfig, N as GuidyElementsMessage, T as GuidyRoutesMessage, Q as GuidyPointAckMessage, G as GuidyRoute, K as GuidyCommandMessage, b as AuthMode } from './types-CFnKr6T_.js';
4
- export { A as AclOperation, a as AdaptiveCard, u as AppNavigationRequestMessage, v as AppRouteChangeMessage, d as AuthStatus, C as CalendarSendAckMessage, w as CalendarSendMessage, x as ChatSendAckMessage, y as ChatSendMessage, z as DocySendAckMessage, B as DocySendMessage, e as DocyrusAclRule, f as DocyrusAuthContextValue, g as DocyrusCalendarEventPayload, h as DocyrusEmailPayload, E as DocyrusNotification, i as DocyrusRole, j as DocyrusShareAdaptiveCardPayload, k as DocyrusSharePayload, l as DocyrusShareTextPayload, m as DocyrusUser, F as EmailSendAckMessage, I as EmailSendMessage, J as GuidyCommandHandler, L as GuidyElement, S as GuidyPointMessage, U as GuidyScanMessage, H as HostNavigationHandler, V as HostNavigationMessage, t as HostNavigationRequestOptions, s as HostNotificationHandler, W as HostNotificationMessage, X as HostSignInMessage, Y as IframeAuth, M as MsGraphAccount, n as MsGraphClient, 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';
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
+ 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';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -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";
@@ -1744,26 +1782,74 @@ function hasRole(user, role) {
1744
1782
  }
1745
1783
  return allRoles.some((r) => r.slug === role || r.uid === role);
1746
1784
  }
1747
- function hasPermission(user, operation, dataSourceId, config) {
1748
- if (!user) return false;
1749
- if (hasRole(user, "super_admin")) return true;
1750
- if (dataSourceId && hasRole(user, "global_editor")) {
1751
- if (GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
1785
+ var SCOPE_FIELD_BY_TARGET_TYPE = {
1786
+ data_source: "dataSourceId",
1787
+ field: "dataSourceId",
1788
+ app: "appId",
1789
+ ai_tool: "aiToolId"
1790
+ };
1791
+ var GLOBAL_TARGET_TYPES = [
1792
+ "ai",
1793
+ "settings",
1794
+ "devtools"
1795
+ ];
1796
+ function toScope(scope) {
1797
+ if (scope == null) return {};
1798
+ if (typeof scope === "string") return { dataSourceId: scope };
1799
+ return scope;
1800
+ }
1801
+ function resolveTargetTypes(scope) {
1802
+ if (scope.targetType) return [scope.targetType];
1803
+ if (scope.dataSourceId != null) return ["data_source"];
1804
+ if (scope.appId != null) return ["app"];
1805
+ if (scope.aiToolId != null) return ["ai_tool"];
1806
+ return GLOBAL_TARGET_TYPES;
1807
+ }
1808
+ function matchesScope(permission, scope) {
1809
+ const field = SCOPE_FIELD_BY_TARGET_TYPE[permission.targetType];
1810
+ if (!field) return true;
1811
+ return (permission[field] ?? null) === (scope[field] ?? null);
1812
+ }
1813
+ function getAllowedOperations(user, scope) {
1814
+ if (!user) return [];
1815
+ const resolved = toScope(scope);
1816
+ const targetTypes = resolveTargetTypes(resolved);
1817
+ const operations = /* @__PURE__ */ new Set();
1818
+ if (user.permissions) {
1819
+ for (const permission of user.permissions) {
1820
+ if (!targetTypes.includes(permission.targetType)) continue;
1821
+ if (!matchesScope(permission, resolved)) continue;
1822
+ for (const op of permission.allowedOperations ?? []) {
1823
+ operations.add(op);
1824
+ }
1825
+ }
1826
+ return Array.from(operations);
1752
1827
  }
1753
- if (dataSourceId && hasRole(user, "global_viewer")) {
1754
- if (operation === "view") return true;
1828
+ if (resolved.appId != null || resolved.aiToolId != null) return [];
1829
+ const dataSourceId = resolved.dataSourceId ?? null;
1830
+ for (const rule of user.aclRules ?? []) {
1831
+ if ((rule.dataSourceId ?? null) !== dataSourceId) continue;
1832
+ for (const op of rule.allowedOperations ?? []) {
1833
+ operations.add(op);
1834
+ }
1755
1835
  }
1836
+ return Array.from(operations);
1837
+ }
1838
+ function hasPermission(user, operation, scope, config) {
1839
+ if (!user) return false;
1840
+ if (hasRole(user, "super_admin")) return true;
1841
+ const resolved = toScope(scope);
1842
+ const { dataSourceId } = resolved;
1756
1843
  if (dataSourceId) {
1844
+ if (hasRole(user, "global_editor") && GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
1845
+ if (hasRole(user, "global_viewer") && operation === "view") return true;
1757
1846
  const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
1758
1847
  const permittedOps = alwaysPermitted[dataSourceId];
1759
1848
  if (permittedOps?.includes(operation)) return true;
1760
1849
  }
1761
- const rules = user.aclRules ?? [];
1762
- return rules.some(
1763
- (rule) => rule.dataSourceId === dataSourceId && rule.allowedOperations.includes(operation)
1764
- );
1850
+ return getAllowedOperations(user, resolved).includes(operation);
1765
1851
  }
1766
1852
 
1767
- export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, GuidyBridge, IframeAuth, MsGraphClient, StandaloneOAuth2Auth, detectAuthMode, getAllRoles, hasPermission, hasRole };
1853
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, GuidyBridge, IframeAuth, MsGraphClient, StandaloneOAuth2Auth, detectAuthMode, getAllRoles, getAllowedOperations, hasPermission, hasRole };
1768
1854
  //# sourceMappingURL=core-index.js.map
1769
1855
  //# sourceMappingURL=core-index.js.map