@docyrus/signin 0.4.0 → 0.6.0

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
@@ -10,8 +10,10 @@ Supports **React**, **Vue**, **React Native**, **Electron**, and **Next.js SSR**
10
10
  - **OAuth2 PKCE**: Full Authorization Code flow with PKCE (S256) for standalone apps
11
11
  - **Iframe Auth**: Receives tokens via `postMessage` from `*.docyrus.app` hosts
12
12
  - **Token Auto-Refresh**: Proactive token refresh before expiry in both modes
13
+ - **Token Bootstrap**: Start a session from existing access/refresh tokens (e.g. device flow handoff)
13
14
  - **React Hooks**: `useDocyrusAuth()` and `useDocyrusClient()` for easy integration
14
15
  - **Vue Composables**: `useDocyrusAuth()` and `useDocyrusClient()` for Vue 3
16
+ - **Authorization Helpers**: `hasRole()` and `hasPermission()` for role-based access control
15
17
  - **Electron Support**: `ElectronTokenStorage` for IPC-based token storage + `getAuthorizationUrl()` for external browser login
16
18
  - **Ready-to-Use API Client**: Exposes a configured `RestApiClient` from `@docyrus/api-client`
17
19
  - **SignInButton**: Unstyled, customizable sign-in button component (React + Vue)
@@ -244,6 +246,7 @@ Pass props to `DocyrusAuthProvider` to override defaults:
244
246
  | `cryptoProvider` | `CryptoProvider` | Browser crypto | Custom crypto for PKCE (React Native) |
245
247
  | `storageKeyPrefix` | `string` | `docyrus_oauth2_` | localStorage key prefix |
246
248
  | `tokenStorage` | `OAuth2TokenStorage` | Browser localStorage | Custom token storage (e.g., `ElectronTokenStorage`) |
249
+ | `initialTokens` | `OAuth2Tokens` | `undefined` | Bootstrap a standalone / React Native session from existing tokens |
247
250
  | `allowedHostOrigins` | `string[]` | `undefined` | Extra trusted iframe origins |
248
251
  | `ssr` | `boolean` | `false` | Sync access token to cookie for server components |
249
252
  | `ssrCookieKey` | `string` | `docyrus-token` | Cookie name for SSR token sync |
@@ -260,9 +263,14 @@ const {
260
263
  mode, // 'standalone' | 'iframe'
261
264
  client, // RestApiClient | null
262
265
  tokens, // { accessToken, refreshToken, ... } | null
266
+ user, // DocyrusUser | null (auto-fetched from /v1/users/me)
263
267
  signIn, // () => void (redirects to Docyrus login)
268
+ signInWithTokens, // (tokens) => Promise<void> (bootstrap from device flow / external auth)
264
269
  getAuthorizationUrl, // () => Promise<string | null> (returns URL without navigating — for Electron)
265
270
  signOut, // () => Promise<void>
271
+ hasRole, // (role) => boolean — check if user has a role by slug or uid
272
+ hasPermission, // (operation, dataSourceId?) => boolean — check ACL permission
273
+ refreshUser, // () => Promise<void> — re-fetch user from API
266
274
  error // Error | null
267
275
  } = useDocyrusAuth();
268
276
  ```
@@ -336,6 +344,42 @@ const storage = new ElectronTokenStorage(undefined, 'my_app_oauth2');
336
344
 
337
345
  The Electron preload script must expose `storeGet`, `storeSet`, and `storeDelete` IPC methods via `contextBridge`.
338
346
 
347
+ ## Bootstrap From Existing Tokens
348
+
349
+ If you already have Docyrus `accessToken` and `refreshToken` from another flow such as device authorization, you can start a web session without redirecting through the browser login flow again.
350
+
351
+ The simplest option is `initialTokens`:
352
+
353
+ ```tsx
354
+ <DocyrusAuthProvider
355
+ apiUrl="https://alpha-api.docyrus.com"
356
+ clientId="your-oauth2-client-id"
357
+ initialTokens={deviceFlowTokens}
358
+ forceMode="standalone">
359
+ <App />
360
+ </DocyrusAuthProvider>
361
+ ```
362
+
363
+ Or bootstrap later with `signInWithTokens()`:
364
+
365
+ ```tsx
366
+ import { useEffect } from 'react';
367
+ import { useDocyrusAuth } from '@docyrus/signin';
368
+
369
+ function TokenHandoff({ deviceFlowTokens }) {
370
+ const { signInWithTokens } = useDocyrusAuth();
371
+
372
+ useEffect(() => {
373
+ if (!deviceFlowTokens) return;
374
+ signInWithTokens(deviceFlowTokens).catch(console.error);
375
+ }, [deviceFlowTokens, signInWithTokens]);
376
+
377
+ return null;
378
+ }
379
+ ```
380
+
381
+ `@docyrus/signin` will persist those tokens into its configured storage, create the authenticated API client, and continue normal refresh-token handling. In iframe mode this bootstrap path is intentionally unsupported; use the host `postMessage` signin flow instead.
382
+
339
383
  ## Auth Modes
340
384
 
341
385
  ### Standalone Mode (OAuth2 PKCE)
@@ -471,6 +515,73 @@ const token = getTokenFromCookie(); // reads 'docyrus-token' cookie
471
515
  const token = getTokenFromCookie('custom-key'); // custom cookie name
472
516
  ```
473
517
 
518
+ ## Authorization (Roles & Permissions)
519
+
520
+ The provider auto-fetches the current user from `/v1/users/me` after authentication and exposes `hasRole` and `hasPermission` helpers.
521
+
522
+ ### Via Hooks (React / React Native)
523
+
524
+ ```tsx
525
+ function DataSourceView({ dataSourceId }: { dataSourceId: string }) {
526
+ const { user, hasRole, hasPermission } = useDocyrusAuth();
527
+
528
+ if (!user) return <div>Loading user...</div>;
529
+
530
+ // Check role by slug or uid
531
+ if (hasRole('super_admin')) {
532
+ return <AdminPanel />;
533
+ }
534
+
535
+ // Check data source permission
536
+ const canEdit = hasPermission('edit', dataSourceId);
537
+ const canDelete = hasPermission('delete', dataSourceId);
538
+
539
+ // Check multiple roles
540
+ if (hasRole(['editor', 'reviewer'])) {
541
+ return <EditorView canEdit={canEdit} canDelete={canDelete} />;
542
+ }
543
+
544
+ return <ReadOnlyView />;
545
+ }
546
+ ```
547
+
548
+ ### Via Pure Functions (Framework-Agnostic)
549
+
550
+ ```tsx
551
+ import { hasRole, hasPermission } from '@docyrus/signin/core';
552
+ import type { DocyrusUser } from '@docyrus/signin/core';
553
+
554
+ function checkAccess(user: DocyrusUser) {
555
+ // hasRole returns true when role arg is null/undefined (no requirement)
556
+ hasRole(user, null); // true
557
+ hasRole(user, 'super_admin'); // checks slug or uid
558
+ hasRole(user, ['editor', 'viewer']); // any match
559
+
560
+ // hasPermission checks: super_admin → global_editor → global_viewer → always-permitted → aclRules
561
+ hasPermission(user, 'view', 'some-ds-id');
562
+ hasPermission(user, 'edit', 'some-ds-id');
563
+ }
564
+ ```
565
+
566
+ ### Permission Resolution Order
567
+
568
+ 1. `super_admin` role → always granted
569
+ 2. `global_editor` role → granted for: view, create, edit, delete, create_bulk, export, import, print
570
+ 3. `global_viewer` role → granted only for: view
571
+ 4. Always-permitted system data sources (reports, todos, notes, etc.)
572
+ 5. User's `aclRules` array (merged from all roles by the server)
573
+
574
+ ### Refreshing User Data
575
+
576
+ If roles or permissions change while the app is running:
577
+
578
+ ```tsx
579
+ const { refreshUser } = useDocyrusAuth();
580
+
581
+ // After a role change
582
+ await refreshUser();
583
+ ```
584
+
474
585
  ## Advanced Usage
475
586
 
476
587
  ### Core (Framework-Agnostic)
@@ -1,10 +1,11 @@
1
1
  import { OAuth2Tokens, RestApiClient } from '@docyrus/api-client';
2
- import { D as DocyrusAuthConfig, A as AuthMode, b as AuthStatus } from './types-CmNZOfNS.js';
2
+ import { D as DocyrusAuthConfig, a as AuthMode, c as AuthStatus, g as DocyrusUser, f as DocyrusRole, P as PermissionConfig } from './types-CxRNvqus.js';
3
3
 
4
4
  type AuthStateListener = (state: {
5
5
  status: AuthStatus;
6
6
  tokens: OAuth2Tokens | null;
7
7
  error: Error | null;
8
+ user: DocyrusUser | null;
8
9
  }) => void;
9
10
  /**
10
11
  * Unified authentication manager.
@@ -17,6 +18,7 @@ declare class AuthManager {
17
18
  private tokens;
18
19
  private error;
19
20
  private client;
21
+ private user;
20
22
  private standaloneAuth;
21
23
  private iframeAuth;
22
24
  private reactNativeAuth;
@@ -29,8 +31,12 @@ declare class AuthManager {
29
31
  getTokens(): OAuth2Tokens | null;
30
32
  getClient(): RestApiClient | null;
31
33
  getError(): Error | null;
34
+ getUser(): DocyrusUser | null;
35
+ /** Re-fetch the current user from the API. No-op if not authenticated. */
36
+ refreshUser(): Promise<void>;
32
37
  subscribe(listener: AuthStateListener): () => void;
33
38
  private notify;
39
+ private getInitialTokens;
34
40
  /** Initialize the auth manager. Must be called once on mount. */
35
41
  initialize(): Promise<void>;
36
42
  /**
@@ -54,6 +60,11 @@ declare class AuthManager {
54
60
  private initializeReactNativeMode;
55
61
  /** Initiate sign-in. Works in standalone and react-native modes. */
56
62
  signIn(): Promise<void>;
63
+ /**
64
+ * Bootstrap an authenticated session from tokens obtained outside the
65
+ * browser redirect flow, such as a prior device authorization flow.
66
+ */
67
+ signInWithTokens(tokens: OAuth2Tokens): Promise<void>;
57
68
  /**
58
69
  * Get the OAuth2 authorization URL without navigating.
59
70
  * Use this in Electron apps to open the URL in an external browser.
@@ -69,8 +80,12 @@ declare class AuthManager {
69
80
  /**
70
81
  * Called when valid tokens are received (either mode).
71
82
  * Creates/updates the RestApiClient and schedules token refresh.
83
+ * Fires a user fetch in the background — the first notify() fires with user: null,
84
+ * and a second notify() fires once the user is fetched.
72
85
  */
73
86
  private setAuthenticated;
87
+ /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
88
+ private fetchUser;
74
89
  /**
75
90
  * Create a RestApiClient with a custom TokenManager that proactively
76
91
  * refreshes the token in getToken(). This is necessary because
@@ -96,10 +111,34 @@ declare class AuthManager {
96
111
  destroy(): void;
97
112
  }
98
113
 
114
+ /**
115
+ * Get all roles for a user (primaryRole + roles array), deduplicated by uid.
116
+ */
117
+ declare function getAllRoles(user: DocyrusUser | null | undefined): DocyrusRole[];
118
+ /**
119
+ * Check if the user has a specific role.
120
+ *
121
+ * - If `role` is null/undefined, returns true (no role requirement).
122
+ * - Checks both primaryRole and roles array.
123
+ * - Matches by slug or uid.
124
+ */
125
+ declare function hasRole(user: DocyrusUser | null | undefined, role: string | string[] | null | undefined): boolean;
126
+ /**
127
+ * Check if the user has permission for an operation on a data source.
128
+ *
129
+ * Permission resolution order:
130
+ * 1. super_admin role → always true
131
+ * 2. global_editor role + dataSourceId → true if operation is in the global_editor set
132
+ * 3. global_viewer role + dataSourceId → true only for 'view'
133
+ * 4. Always-permitted data sources (configurable)
134
+ * 5. User's aclRules array
135
+ */
136
+ declare function hasPermission(user: DocyrusUser | null | undefined, operation: string, dataSourceId?: string | null, config?: PermissionConfig): boolean;
137
+
99
138
  declare const DEFAULT_API_URL = "https://alpha-api.docyrus.com";
100
139
  declare const DEFAULT_OAUTH_SCOPES: string[];
101
140
  declare const DEFAULT_CALLBACK_PATH = "/auth/callback";
102
141
  /** Default cookie name for SSR token sync */
103
142
  declare const DEFAULT_SSR_COOKIE_KEY = "docyrus-token";
104
143
 
105
- export { AuthManager as A, DEFAULT_API_URL as D, DEFAULT_OAUTH_SCOPES as a, DEFAULT_CALLBACK_PATH as b, DEFAULT_SSR_COOKIE_KEY as c, type AuthStateListener as d };
144
+ 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 };
@@ -1,7 +1,7 @@
1
- export { A as AuthManager, d as AuthStateListener, D as DEFAULT_API_URL, b as DEFAULT_CALLBACK_PATH, a as DEFAULT_OAUTH_SCOPES } from './constants-CKGcqYM4.js';
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-piCFw8QN.js';
2
2
  import { OAuth2Tokens } from '@docyrus/api-client';
3
- import { D as DocyrusAuthConfig, A as AuthMode } from './types-CmNZOfNS.js';
4
- export { b as AuthStatus, c as DocyrusAuthContextValue, H as HostSignInMessage, T as TokenRefreshRequestMessage } from './types-CmNZOfNS.js';
3
+ import { D as DocyrusAuthConfig, a as AuthMode } from './types-CxRNvqus.js';
4
+ export { A as AclOperation, c as AuthStatus, d as DocyrusAclRule, e as DocyrusAuthContextValue, f as DocyrusRole, g as DocyrusUser, H as HostSignInMessage, P as PermissionConfig, T as TokenRefreshRequestMessage } from './types-CxRNvqus.js';
5
5
 
6
6
  /**
7
7
  * Standalone OAuth2 authorization code flow with PKCE via page redirect.
@@ -45,6 +45,8 @@ declare class StandaloneOAuth2Auth {
45
45
  getReturnUrl(): string | null;
46
46
  /** Get currently stored tokens (e.g., on page reload). */
47
47
  getStoredTokens(): Promise<OAuth2Tokens | null>;
48
+ /** Persist externally obtained tokens for immediate authenticated use. */
49
+ setTokens(tokens: OAuth2Tokens): Promise<void>;
48
50
  /** Check if the stored token is expired (with 60s buffer). */
49
51
  isTokenExpired(): Promise<boolean>;
50
52
  /** Refresh the access token using the stored refresh token. */
@@ -124,6 +124,10 @@ var StandaloneOAuth2Auth = class {
124
124
  async getStoredTokens() {
125
125
  return this.oauth2Client.getTokens();
126
126
  }
127
+ /** Persist externally obtained tokens for immediate authenticated use. */
128
+ async setTokens(tokens) {
129
+ await Promise.resolve(this.storage.setTokens(tokens));
130
+ }
127
131
  /** Check if the stored token is expired (with 60s buffer). */
128
132
  async isTokenExpired() {
129
133
  return this.oauth2Client.isTokenExpired();
@@ -181,8 +185,8 @@ var IframeAuth = class {
181
185
  */
182
186
  requestTokenRefresh() {
183
187
  if (this.refreshPromise) {
188
+ const existing = this.refreshPromise;
184
189
  return new Promise((resolve, reject) => {
185
- const existing = this.refreshPromise;
186
190
  const originalResolve = existing.resolve;
187
191
  const originalReject = existing.reject;
188
192
  existing.resolve = (tokens) => {
@@ -294,6 +298,10 @@ var ReactNativeOAuth2Auth = class {
294
298
  async getStoredTokens() {
295
299
  return this.oauth2Client.getTokens();
296
300
  }
301
+ /** Persist externally obtained tokens for immediate authenticated use. */
302
+ async setTokens(tokens) {
303
+ await Promise.resolve(this.storage.setTokens(tokens));
304
+ }
297
305
  /** Check if the stored token is expired (with 60s buffer). */
298
306
  async isTokenExpired() {
299
307
  return this.oauth2Client.isTokenExpired();
@@ -339,6 +347,7 @@ var AuthManager = class {
339
347
  tokens = null;
340
348
  error = null;
341
349
  client = null;
350
+ user = null;
342
351
  standaloneAuth = null;
343
352
  iframeAuth = null;
344
353
  reactNativeAuth = null;
@@ -364,6 +373,13 @@ var AuthManager = class {
364
373
  getError() {
365
374
  return this.error;
366
375
  }
376
+ getUser() {
377
+ return this.user;
378
+ }
379
+ /** Re-fetch the current user from the API. No-op if not authenticated. */
380
+ async refreshUser() {
381
+ await this.fetchUser();
382
+ }
367
383
  subscribe(listener) {
368
384
  this.listeners.add(listener);
369
385
  return () => this.listeners.delete(listener);
@@ -373,13 +389,22 @@ var AuthManager = class {
373
389
  listener({
374
390
  status: this.status,
375
391
  tokens: this.tokens,
376
- error: this.error
392
+ error: this.error,
393
+ user: this.user
377
394
  });
378
395
  }
379
396
  }
397
+ getInitialTokens() {
398
+ return this.config.initialTokens ?? null;
399
+ }
380
400
  /** Initialize the auth manager. Must be called once on mount. */
381
401
  async initialize() {
382
402
  try {
403
+ if (this.mode === "iframe" && this.getInitialTokens()) {
404
+ throw new Error(
405
+ "initialTokens is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
406
+ );
407
+ }
383
408
  if (this.mode === "react-native") {
384
409
  await this.initializeReactNativeMode();
385
410
  } else if (this.mode === "iframe") {
@@ -412,6 +437,12 @@ var AuthManager = class {
412
437
  }
413
438
  return;
414
439
  }
440
+ const initialTokens = this.getInitialTokens();
441
+ if (initialTokens) {
442
+ await this.standaloneAuth.setTokens(initialTokens);
443
+ this.setAuthenticated(initialTokens);
444
+ return;
445
+ }
415
446
  const stored = await this.standaloneAuth.getStoredTokens();
416
447
  if (stored) {
417
448
  const isExpired = await this.standaloneAuth.isTokenExpired();
@@ -449,6 +480,12 @@ var AuthManager = class {
449
480
  */
450
481
  async initializeReactNativeMode() {
451
482
  this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
483
+ const initialTokens = this.getInitialTokens();
484
+ if (initialTokens) {
485
+ await this.reactNativeAuth.setTokens(initialTokens);
486
+ this.setAuthenticated(initialTokens);
487
+ return;
488
+ }
452
489
  const stored = await this.reactNativeAuth.getStoredTokens();
453
490
  if (stored) {
454
491
  const isExpired = await this.reactNativeAuth.isTokenExpired();
@@ -483,6 +520,30 @@ var AuthManager = class {
483
520
  if (this.mode !== "standalone" || !this.standaloneAuth) return;
484
521
  await this.standaloneAuth.initiateLogin();
485
522
  }
523
+ /**
524
+ * Bootstrap an authenticated session from tokens obtained outside the
525
+ * browser redirect flow, such as a prior device authorization flow.
526
+ */
527
+ async signInWithTokens(tokens) {
528
+ if (this.mode === "iframe") {
529
+ throw new Error(
530
+ "signInWithTokens() is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
531
+ );
532
+ }
533
+ if (this.mode === "react-native") {
534
+ if (!this.reactNativeAuth) {
535
+ this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
536
+ }
537
+ await this.reactNativeAuth.setTokens(tokens);
538
+ this.setAuthenticated(tokens);
539
+ return;
540
+ }
541
+ if (!this.standaloneAuth) {
542
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
543
+ }
544
+ await this.standaloneAuth.setTokens(tokens);
545
+ this.setAuthenticated(tokens);
546
+ }
486
547
  /**
487
548
  * Get the OAuth2 authorization URL without navigating.
488
549
  * Use this in Electron apps to open the URL in an external browser.
@@ -513,6 +574,7 @@ var AuthManager = class {
513
574
  }
514
575
  this.tokens = null;
515
576
  this.client = null;
577
+ this.user = null;
516
578
  this.status = "unauthenticated";
517
579
  this.error = null;
518
580
  this.notify();
@@ -520,6 +582,8 @@ var AuthManager = class {
520
582
  /**
521
583
  * Called when valid tokens are received (either mode).
522
584
  * Creates/updates the RestApiClient and schedules token refresh.
585
+ * Fires a user fetch in the background — the first notify() fires with user: null,
586
+ * and a second notify() fires once the user is fetched.
523
587
  */
524
588
  setAuthenticated(tokens) {
525
589
  this.tokens = tokens;
@@ -531,6 +595,18 @@ var AuthManager = class {
531
595
  this.createClient();
532
596
  this.scheduleTokenRefresh(tokens);
533
597
  this.notify();
598
+ this.fetchUser();
599
+ }
600
+ /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
601
+ async fetchUser() {
602
+ if (!this.client) return;
603
+ try {
604
+ const response = await this.client.get("/v1/users/me");
605
+ this.user = response.data;
606
+ } catch {
607
+ this.user = null;
608
+ }
609
+ this.notify();
534
610
  }
535
611
  /**
536
612
  * Create a RestApiClient with a custom TokenManager that proactively
@@ -642,6 +718,106 @@ var AuthManager = class {
642
718
  }
643
719
  };
644
720
 
645
- export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, IframeAuth, StandaloneOAuth2Auth, detectAuthMode };
721
+ // src/core/permissions.ts
722
+ var DEFAULT_ALWAYS_PERMITTED = {
723
+ "24ea9b34-4d74-11ef-bf16-6313ac30ce0e": [
724
+ "view",
725
+ "create",
726
+ "edit",
727
+ "delete"
728
+ ],
729
+ // report
730
+ "95406630-4d7d-11ef-a5cf-d7d8ab9d2310": [
731
+ "view",
732
+ "create",
733
+ "edit",
734
+ "delete"
735
+ ],
736
+ // report_widget
737
+ "996745ae-1744-11ef-a79c-abe22c3d5e97": ["view"],
738
+ // tenant_html_template
739
+ "0191e152-4619-7c08-bfc7-606f216d2757": ["view"],
740
+ // tenant_action_external_request_log
741
+ "01938bba-49ea-7b2f-8c09-adf14ab8c116": ["view"],
742
+ // tenant_data_source_child_removal_rule
743
+ "b413176e-175f-11ef-9df6-9f1f45cc8869": [
744
+ "view",
745
+ "create",
746
+ "edit",
747
+ "delete"
748
+ ],
749
+ // user_todo
750
+ "0191b75e-79cd-7344-93f3-81a3a3f52497": [
751
+ "view",
752
+ "create",
753
+ "edit",
754
+ "delete"
755
+ ],
756
+ // user_todo_list
757
+ "7756d784-175f-11ef-ac3b-0ba18bcdf569": [
758
+ "view",
759
+ "create",
760
+ "edit",
761
+ "delete"
762
+ ]
763
+ // user_note
764
+ };
765
+ var GLOBAL_EDITOR_OPERATIONS = /* @__PURE__ */ new Set([
766
+ "view",
767
+ "create",
768
+ "edit",
769
+ "delete",
770
+ "create_bulk",
771
+ "export",
772
+ "import",
773
+ "print"
774
+ ]);
775
+ function getAllRoles(user) {
776
+ if (!user) return [];
777
+ const roles = [];
778
+ if (user.primaryRole) {
779
+ roles.push(user.primaryRole);
780
+ }
781
+ if (user.roles?.length) {
782
+ for (const role of user.roles) {
783
+ if (!user.primaryRole || role.uid !== user.primaryRole.uid) {
784
+ roles.push(role);
785
+ }
786
+ }
787
+ }
788
+ return roles;
789
+ }
790
+ function hasRole(user, role) {
791
+ if (role == null) return true;
792
+ if (!user) return false;
793
+ const allRoles = getAllRoles(user);
794
+ if (allRoles.length === 0) return false;
795
+ if (Array.isArray(role)) {
796
+ if (role.length === 0) return true;
797
+ return allRoles.some((r) => role.includes(r.slug) || role.includes(r.uid));
798
+ }
799
+ return allRoles.some((r) => r.slug === role || r.uid === role);
800
+ }
801
+ function hasPermission(user, operation, dataSourceId, config) {
802
+ if (!user) return false;
803
+ if (hasRole(user, "super_admin")) return true;
804
+ if (dataSourceId && hasRole(user, "global_editor")) {
805
+ if (GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
806
+ }
807
+ if (dataSourceId && hasRole(user, "global_viewer")) {
808
+ if (operation === "view") return true;
809
+ }
810
+ if (dataSourceId) {
811
+ const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
812
+ const permittedOps = alwaysPermitted[dataSourceId];
813
+ if (permittedOps?.includes(operation)) return true;
814
+ }
815
+ const rules = user.aclRules ?? [];
816
+ return rules.some(
817
+ (rule) => rule.dataSourceId === dataSourceId && rule.allowedOperations.includes(operation)
818
+ );
819
+ }
820
+
821
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_CALLBACK_PATH, DEFAULT_OAUTH_SCOPES, IframeAuth, StandaloneOAuth2Auth, detectAuthMode, getAllRoles, hasPermission, hasRole };
646
822
  //# sourceMappingURL=core-index.js.map
647
823
  //# sourceMappingURL=core-index.js.map