@grantjs/client 1.0.0 → 1.1.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/dist/react.mjs CHANGED
@@ -1,139 +1,243 @@
1
+ import { t as GrantClient } from "./grant-client-BuvFCpqW.js";
2
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
1
3
  import { jsx } from "react/jsx-runtime";
2
- import { useMemo, useContext, createContext, useRef, useState, useCallback, useEffect } from "react";
3
- import { GrantClient } from "./index.mjs";
4
- const GrantContext = createContext(null);
4
+ //#region src/react/context.tsx
5
+ /**
6
+ * Context for the Grant client
7
+ */
8
+ var GrantContext = createContext(null);
9
+ /**
10
+ * Provider component that makes the Grant client available to child components
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * // Option 1: Pass config (cookie-based refresh)
15
+ * <GrantProvider
16
+ * config={{
17
+ * apiUrl: 'https://api.grant.com',
18
+ * getAccessToken: () => localStorage.getItem('accessToken'),
19
+ * onRefreshWithCredentials: async () => {
20
+ * const res = await fetch('https://api.grant.com/api/auth/refresh', { method: 'POST', credentials: 'include' });
21
+ * if (!res.ok) return false;
22
+ * const { data } = await res.json();
23
+ * if (data?.accessToken) { localStorage.setItem('accessToken', data.accessToken); return true; }
24
+ * return false;
25
+ * },
26
+ * onTokenRefresh: (tokens) => { localStorage.setItem('accessToken', tokens.accessToken); },
27
+ * onUnauthorized: () => { window.location.href = '/login'; },
28
+ * }}
29
+ * >
30
+ * <App />
31
+ * </GrantProvider>
32
+ *
33
+ * // Option 2: Pass pre-configured client
34
+ * const grant = new GrantClient({ ... });
35
+ * <GrantProvider client={grant}>
36
+ * <App />
37
+ * </GrantProvider>
38
+ * ```
39
+ */
5
40
  function GrantProvider({ config, client, children }) {
6
- const grantClient = useMemo(() => {
7
- if (client) return client;
8
- return new GrantClient(config);
9
- }, [client, config]);
10
- return /* @__PURE__ */ jsx(GrantContext.Provider, { value: grantClient, children });
41
+ const grantClient = useMemo(() => {
42
+ if (client) return client;
43
+ return new GrantClient(config);
44
+ }, [client, config]);
45
+ return /* @__PURE__ */ jsx(GrantContext.Provider, {
46
+ value: grantClient,
47
+ children
48
+ });
11
49
  }
50
+ /**
51
+ * Hook to access the Grant client from context
52
+ *
53
+ * @throws Error if used outside of GrantProvider
54
+ *
55
+ * @example
56
+ * ```tsx
57
+ * const grant = useGrantClient();
58
+ * const hasPermission = await grant.can('resource', 'action');
59
+ * ```
60
+ */
12
61
  function useGrantClient() {
13
- const client = useContext(GrantContext);
14
- if (!client) {
15
- throw new Error(
16
- "useGrantClient must be used within a GrantProvider. Wrap your app with <GrantProvider config={...}> to fix this error."
17
- );
18
- }
19
- return client;
62
+ const client = useContext(GrantContext);
63
+ if (!client) throw new Error("useGrantClient must be used within a GrantProvider. Wrap your app with <GrantProvider config={...}> to fix this error.");
64
+ return client;
20
65
  }
66
+ /**
67
+ * Hook to optionally access the Grant client
68
+ * Returns null if not in a GrantProvider context
69
+ *
70
+ * Use this when you want to gracefully handle missing provider
71
+ */
21
72
  function useGrantClientOptional() {
22
- return useContext(GrantContext);
73
+ return useContext(GrantContext);
23
74
  }
75
+ //#endregion
76
+ //#region src/react/hooks/useGrant.ts
77
+ /**
78
+ * Serialize scope for stable dependency comparison
79
+ * This prevents re-fetching when scope object reference changes but values are the same
80
+ */
24
81
  function serializeScope(scope) {
25
- if (!scope) return "";
26
- return `${scope.tenant}:${scope.id}`;
82
+ if (!scope) return "";
83
+ return `${scope.tenant}:${scope.id}`;
27
84
  }
85
+ /**
86
+ * Hook to check if a user is granted permission for a specific resource and action
87
+ *
88
+ * By default, returns a simple boolean, defaulting to false while loading.
89
+ * Set `returnLoading: true` to get an object with `isGranted` and `isLoading`.
90
+ *
91
+ * @param resource - The resource slug to check
92
+ * @param action - The action to check
93
+ * @param options - Additional options
94
+ *
95
+ * @example
96
+ * ```tsx
97
+ * // Simple boolean (default)
98
+ * const canEdit = useGrant('document', 'update');
99
+ *
100
+ * return (
101
+ * <div>
102
+ * {canEdit && <EditButton />}
103
+ * </div>
104
+ * );
105
+ *
106
+ * // With loading state
107
+ * const { isGranted, isLoading } = useGrant('document', 'update', {
108
+ * returnLoading: true,
109
+ * });
110
+ *
111
+ * if (isLoading) return <Spinner />;
112
+ * if (!isGranted) return null;
113
+ *
114
+ * return <EditButton />;
115
+ * ```
116
+ */
28
117
  function useGrant(resource, action, options = {}) {
29
- const { scope, enabled = true, useCache = true, returnLoading = false, context } = options;
30
- const client = useGrantClient();
31
- const scopeWasProvidedRef = useRef("scope" in options);
32
- const isEffectivelyEnabled = useMemo(() => {
33
- const hasValidScope = scope && typeof scope === "object" && "tenant" in scope && "id" in scope && scope.id;
34
- const shouldWaitForScope = scopeWasProvidedRef.current && !hasValidScope;
35
- return enabled && !shouldWaitForScope;
36
- }, [scope, enabled]);
37
- const [data, setData] = useState(null);
38
- const [isLoading, setIsLoading] = useState(isEffectivelyEnabled);
39
- const [prevEffectivelyEnabled, setPrevEffectivelyEnabled] = useState(isEffectivelyEnabled);
40
- if (isEffectivelyEnabled !== prevEffectivelyEnabled) {
41
- setPrevEffectivelyEnabled(isEffectivelyEnabled);
42
- if (isEffectivelyEnabled) {
43
- setIsLoading(true);
44
- } else {
45
- setIsLoading(false);
46
- setData(null);
47
- }
48
- }
49
- const isMounted = useRef(true);
50
- const scopeRef = useRef(scope);
51
- scopeRef.current = scope;
52
- const contextRef = useRef(context);
53
- contextRef.current = context;
54
- const scopeKey = serializeScope(scope);
55
- const contextKey = useMemo(
56
- () => context?.resource != null ? JSON.stringify(context.resource) : "",
57
- [context?.resource]
58
- );
59
- const fetchPermission = useCallback(async () => {
60
- if (!isEffectivelyEnabled) {
61
- setIsLoading(false);
62
- return;
63
- }
64
- setIsLoading(true);
65
- try {
66
- const result = await client.isAuthorized(resource, action, {
67
- scope: scopeRef.current ?? void 0,
68
- useCache,
69
- context: contextRef.current
70
- });
71
- if (isMounted.current) {
72
- setData(result);
73
- }
74
- } catch {
75
- if (isMounted.current) {
76
- setData(null);
77
- }
78
- } finally {
79
- if (isMounted.current) {
80
- setIsLoading(false);
81
- }
82
- }
83
- }, [client, resource, action, scopeKey, isEffectivelyEnabled, useCache, contextKey]);
84
- useEffect(() => {
85
- isMounted.current = true;
86
- if (!isEffectivelyEnabled && scopeWasProvidedRef.current) {
87
- setData(null);
88
- setIsLoading(false);
89
- } else {
90
- fetchPermission();
91
- }
92
- return () => {
93
- isMounted.current = false;
94
- };
95
- }, [fetchPermission, isEffectivelyEnabled]);
96
- const isGranted = data?.authorized ?? false;
97
- if (returnLoading) {
98
- return { isGranted, isLoading };
99
- }
100
- return isGranted;
118
+ const { scope, enabled = true, useCache = true, returnLoading = false, context } = options;
119
+ const client = useGrantClient();
120
+ const scopeWasProvidedRef = useRef("scope" in options);
121
+ const isEffectivelyEnabled = useMemo(() => {
122
+ const hasValidScope = scope && typeof scope === "object" && "tenant" in scope && "id" in scope && scope.id;
123
+ const shouldWaitForScope = scopeWasProvidedRef.current && !hasValidScope;
124
+ return enabled && !shouldWaitForScope;
125
+ }, [scope, enabled]);
126
+ const [data, setData] = useState(null);
127
+ const [isLoading, setIsLoading] = useState(isEffectivelyEnabled);
128
+ const [prevEffectivelyEnabled, setPrevEffectivelyEnabled] = useState(isEffectivelyEnabled);
129
+ if (isEffectivelyEnabled !== prevEffectivelyEnabled) {
130
+ setPrevEffectivelyEnabled(isEffectivelyEnabled);
131
+ if (isEffectivelyEnabled) setIsLoading(true);
132
+ else {
133
+ setIsLoading(false);
134
+ setData(null);
135
+ }
136
+ }
137
+ const isMounted = useRef(true);
138
+ const scopeRef = useRef(scope);
139
+ scopeRef.current = scope;
140
+ const contextRef = useRef(context);
141
+ contextRef.current = context;
142
+ const fetchPermission = useCallback(async () => {
143
+ if (!isEffectivelyEnabled) {
144
+ setIsLoading(false);
145
+ return;
146
+ }
147
+ setIsLoading(true);
148
+ try {
149
+ const result = await client.isAuthorized(resource, action, {
150
+ scope: scopeRef.current ?? void 0,
151
+ useCache,
152
+ context: contextRef.current
153
+ });
154
+ if (isMounted.current) setData(result);
155
+ } catch {
156
+ if (isMounted.current) setData(null);
157
+ } finally {
158
+ if (isMounted.current) setIsLoading(false);
159
+ }
160
+ }, [
161
+ client,
162
+ resource,
163
+ action,
164
+ serializeScope(scope),
165
+ isEffectivelyEnabled,
166
+ useCache,
167
+ useMemo(() => context?.resource != null ? JSON.stringify(context.resource) : "", [context?.resource])
168
+ ]);
169
+ useEffect(() => {
170
+ isMounted.current = true;
171
+ if (!isEffectivelyEnabled && scopeWasProvidedRef.current) {
172
+ setData(null);
173
+ setIsLoading(false);
174
+ } else fetchPermission();
175
+ return () => {
176
+ isMounted.current = false;
177
+ };
178
+ }, [fetchPermission, isEffectivelyEnabled]);
179
+ const isGranted = data?.authorized ?? false;
180
+ if (returnLoading) return {
181
+ isGranted,
182
+ isLoading
183
+ };
184
+ return isGranted;
101
185
  }
102
- function GrantGate({
103
- resource,
104
- action,
105
- scope,
106
- enabled,
107
- useCache,
108
- children,
109
- fallback = null,
110
- loading = null
111
- }) {
112
- const options = {
113
- enabled,
114
- useCache,
115
- returnLoading: loading !== null
116
- };
117
- if (scope !== void 0) {
118
- options.scope = scope;
119
- }
120
- const result = useGrant(resource, action, options);
121
- const isGranted = typeof result === "boolean" ? result : result.isGranted;
122
- const isLoading = typeof result === "boolean" ? false : result.isLoading;
123
- if (isLoading && loading !== null) {
124
- return loading;
125
- }
126
- if (isGranted) {
127
- return children;
128
- }
129
- return fallback;
186
+ //#endregion
187
+ //#region src/react/components/GrantGate.tsx
188
+ /**
189
+ * Component that conditionally renders children based on permissions
190
+ *
191
+ * @example
192
+ * ```tsx
193
+ * // Basic usage - hide element if no permission
194
+ * <GrantGate resource="document" action="update">
195
+ * <EditButton />
196
+ * </GrantGate>
197
+ *
198
+ * // With fallback for denied access
199
+ * <GrantGate
200
+ * resource="admin"
201
+ * action="access"
202
+ * fallback={<p>You don't have admin access</p>}
203
+ * >
204
+ * <AdminPanel />
205
+ * </GrantGate>
206
+ *
207
+ * // With loading state
208
+ * <GrantGate
209
+ * resource="report"
210
+ * action="view"
211
+ * loading={<Spinner />}
212
+ * fallback={<AccessDenied />}
213
+ * >
214
+ * <ReportViewer />
215
+ * </GrantGate>
216
+ *
217
+ * // With scope for multi-tenant
218
+ * <GrantGate
219
+ * resource="project"
220
+ * action="delete"
221
+ * scope={{ tenant: 'project', id: projectId }}
222
+ * >
223
+ * <DeleteProjectButton />
224
+ * </GrantGate>
225
+ * ```
226
+ */
227
+ function GrantGate({ resource, action, scope, enabled, useCache, children, fallback = null, loading = null }) {
228
+ const options = {
229
+ enabled,
230
+ useCache,
231
+ returnLoading: loading !== null
232
+ };
233
+ if (scope !== void 0) options.scope = scope;
234
+ const result = useGrant(resource, action, options);
235
+ const isGranted = typeof result === "boolean" ? result : result.isGranted;
236
+ if ((typeof result === "boolean" ? false : result.isLoading) && loading !== null) return loading;
237
+ if (isGranted) return children;
238
+ return fallback;
130
239
  }
131
- export {
132
- GrantClient,
133
- GrantGate,
134
- GrantProvider,
135
- useGrant,
136
- useGrantClient,
137
- useGrantClientOptional
138
- };
139
- //# sourceMappingURL=react.mjs.map
240
+ //#endregion
241
+ export { GrantClient, GrantGate, GrantProvider, useGrant, useGrantClient, useGrantClientOptional };
242
+
243
+ //# sourceMappingURL=react.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.mjs","sources":["../src/react/context.tsx","../src/react/hooks/useGrant.ts","../src/react/components/GrantGate.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\n\nimport { GrantClient } from '../grant-client';\n\nimport type { GrantClientConfig } from '../types';\n\n/**\n * Context for the Grant client\n */\nconst GrantContext = createContext<GrantClient | null>(null);\n\n/**\n * Props for the GrantProvider component\n */\nexport interface GrantProviderProps {\n /**\n * Grant client configuration\n */\n config: GrantClientConfig;\n\n /**\n * Pre-configured GrantClient instance (alternative to config)\n * If provided, config is ignored\n */\n client?: GrantClient;\n\n /**\n * Child components\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that makes the Grant client available to child components\n *\n * @example\n * ```tsx\n * // Option 1: Pass config (cookie-based refresh)\n * <GrantProvider\n * config={{\n * apiUrl: 'https://api.grant.com',\n * getAccessToken: () => localStorage.getItem('accessToken'),\n * onRefreshWithCredentials: async () => {\n * const res = await fetch('https://api.grant.com/api/auth/refresh', { method: 'POST', credentials: 'include' });\n * if (!res.ok) return false;\n * const { data } = await res.json();\n * if (data?.accessToken) { localStorage.setItem('accessToken', data.accessToken); return true; }\n * return false;\n * },\n * onTokenRefresh: (tokens) => { localStorage.setItem('accessToken', tokens.accessToken); },\n * onUnauthorized: () => { window.location.href = '/login'; },\n * }}\n * >\n * <App />\n * </GrantProvider>\n *\n * // Option 2: Pass pre-configured client\n * const grant = new GrantClient({ ... });\n * <GrantProvider client={grant}>\n * <App />\n * </GrantProvider>\n * ```\n */\nexport function GrantProvider({ config, client, children }: GrantProviderProps) {\n const grantClient = useMemo(() => {\n if (client) return client;\n return new GrantClient(config);\n }, [client, config]);\n\n return <GrantContext.Provider value={grantClient}>{children}</GrantContext.Provider>;\n}\n\n/**\n * Hook to access the Grant client from context\n *\n * @throws Error if used outside of GrantProvider\n *\n * @example\n * ```tsx\n * const grant = useGrantClient();\n * const hasPermission = await grant.can('resource', 'action');\n * ```\n */\nexport function useGrantClient(): GrantClient {\n const client = useContext(GrantContext);\n\n if (!client) {\n throw new Error(\n 'useGrantClient must be used within a GrantProvider. ' +\n 'Wrap your app with <GrantProvider config={...}> to fix this error.'\n );\n }\n\n return client;\n}\n\n/**\n * Hook to optionally access the Grant client\n * Returns null if not in a GrantProvider context\n *\n * Use this when you want to gracefully handle missing provider\n */\nexport function useGrantClientOptional(): GrantClient | null {\n return useContext(GrantContext);\n}\n","'use client';\n\nimport { useState, useEffect, useCallback, useRef, useMemo } from 'react';\n\nimport { useGrantClient } from '../context';\n\nimport type { AuthorizationResult, Scope } from '../../types';\n\n/**\n * Options for the useGrant hook\n */\nexport interface UseGrantOptions {\n /** Scope to check the permission in. If provided but null/undefined, hook waits for it to become valid. */\n scope?: Scope | null;\n /** Whether to skip the permission check */\n enabled?: boolean;\n /** Whether to use cached results (default: true) */\n useCache?: boolean;\n /** Whether to return loading state (default: false) */\n returnLoading?: boolean;\n /** Context to check permissions for */\n context?: {\n resource?: Record<string, unknown> | null;\n };\n}\n\n/**\n * Result when returnLoading is true\n */\nexport interface UseGrantResult {\n /** Whether the user is granted permission */\n isGranted: boolean;\n /** Whether the permission check is loading */\n isLoading: boolean;\n}\n\n/**\n * Serialize scope for stable dependency comparison\n * This prevents re-fetching when scope object reference changes but values are the same\n */\nfunction serializeScope(scope?: Scope | null): string {\n if (!scope) return '';\n return `${scope.tenant}:${scope.id}`;\n}\n\n/**\n * Hook to check if a user is granted permission for a specific resource and action\n *\n * By default, returns a simple boolean, defaulting to false while loading.\n * Set `returnLoading: true` to get an object with `isGranted` and `isLoading`.\n *\n * @param resource - The resource slug to check\n * @param action - The action to check\n * @param options - Additional options\n *\n * @example\n * ```tsx\n * // Simple boolean (default)\n * const canEdit = useGrant('document', 'update');\n *\n * return (\n * <div>\n * {canEdit && <EditButton />}\n * </div>\n * );\n *\n * // With loading state\n * const { isGranted, isLoading } = useGrant('document', 'update', {\n * returnLoading: true,\n * });\n *\n * if (isLoading) return <Spinner />;\n * if (!isGranted) return null;\n *\n * return <EditButton />;\n * ```\n */\nexport function useGrant(\n resource: string,\n action: string,\n options: UseGrantOptions = {}\n): boolean | UseGrantResult {\n const { scope, enabled = true, useCache = true, returnLoading = false, context } = options;\n const client = useGrantClient();\n\n // Track if scope was explicitly provided (even if null/undefined)\n // This allows us to distinguish between \"scope not provided\" (optional) vs \"scope provided but falsy\" (wait for it)\n // Check this once at the start - if scope key exists in options, it was provided\n // Note: { scope: undefined } has the key, { } does not have the key\n const scopeWasProvidedRef = useRef('scope' in options);\n\n // Determine if we should wait for scope to become valid\n // If scope was provided but is falsy or invalid, wait for it to become truthy\n // Recalculate when scope changes\n const isEffectivelyEnabled = useMemo(() => {\n const hasValidScope =\n scope && typeof scope === 'object' && 'tenant' in scope && 'id' in scope && scope.id;\n const shouldWaitForScope = scopeWasProvidedRef.current && !hasValidScope;\n return enabled && !shouldWaitForScope;\n }, [scope, enabled]);\n\n const [data, setData] = useState<AuthorizationResult | null>(null);\n const [isLoading, setIsLoading] = useState(isEffectivelyEnabled);\n\n // Synchronously correct isLoading when isEffectivelyEnabled transitions.\n // useState only uses its initializer on first render, so subsequent transitions\n // leave isLoading stale for one render cycle (the effect hasn't run yet).\n // This uses React's \"storing information from previous renders\" pattern to\n // immediately set isLoading before the render completes.\n // See: https://react.dev/reference/react/useState#storing-information-from-previous-renders\n const [prevEffectivelyEnabled, setPrevEffectivelyEnabled] = useState(isEffectivelyEnabled);\n if (isEffectivelyEnabled !== prevEffectivelyEnabled) {\n setPrevEffectivelyEnabled(isEffectivelyEnabled);\n if (isEffectivelyEnabled) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n setData(null);\n }\n }\n\n // Track mounted state to prevent state updates after unmount\n const isMounted = useRef(true);\n\n // Store scope in a ref so we always have the latest value without triggering re-renders\n const scopeRef = useRef(scope);\n scopeRef.current = scope;\n\n // Store context in a ref so the callback always sends the latest context\n const contextRef = useRef(context);\n contextRef.current = context;\n\n // Serialize scope to get a stable string for dependency comparison\n const scopeKey = serializeScope(scope);\n\n // Serialize context so we re-create the callback when context meaningfully changes\n const contextKey = useMemo(\n () => (context?.resource != null ? JSON.stringify(context.resource) : ''),\n [context?.resource]\n );\n\n const fetchPermission = useCallback(async () => {\n if (!isEffectivelyEnabled) {\n setIsLoading(false);\n return;\n }\n\n setIsLoading(true);\n\n try {\n // Use scopeRef.current and contextRef.current to get the latest values\n // Convert null to undefined for the client (which expects Scope | undefined)\n const result = await client.isAuthorized(resource, action, {\n scope: scopeRef.current ?? undefined,\n useCache,\n context: contextRef.current,\n });\n if (isMounted.current) {\n setData(result);\n }\n } catch {\n // On error, set data to null (will return false)\n if (isMounted.current) {\n setData(null);\n }\n } finally {\n if (isMounted.current) {\n setIsLoading(false);\n }\n }\n // contextKey ensures we re-run when context (e.g. resource) changes so the request gets the latest context\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, resource, action, scopeKey, isEffectivelyEnabled, useCache, contextKey]);\n\n useEffect(() => {\n isMounted.current = true;\n\n // Clear data when scope becomes invalid (waiting for valid scope)\n if (!isEffectivelyEnabled && scopeWasProvidedRef.current) {\n setData(null);\n setIsLoading(false);\n } else {\n fetchPermission();\n }\n\n return () => {\n isMounted.current = false;\n };\n }, [fetchPermission, isEffectivelyEnabled]);\n\n const isGranted = data?.authorized ?? false;\n\n // Return object with loading state if requested, otherwise just boolean\n if (returnLoading) {\n return { isGranted, isLoading };\n }\n\n return isGranted;\n}\n","'use client';\n\nimport type { ReactNode } from 'react';\n\nimport { useGrant, type UseGrantOptions } from '../hooks/useGrant';\n\n/**\n * Props for the GrantGate component\n */\nexport interface GrantGateProps extends UseGrantOptions {\n /** The resource slug to check permission for */\n resource: string;\n /** The action to check */\n action: string;\n /** Content to render if permission is granted */\n children: ReactNode;\n /** Content to render if permission is denied (optional) */\n fallback?: ReactNode;\n /** Content to render while loading (optional) */\n loading?: ReactNode;\n}\n\n/**\n * Component that conditionally renders children based on permissions\n *\n * @example\n * ```tsx\n * // Basic usage - hide element if no permission\n * <GrantGate resource=\"document\" action=\"update\">\n * <EditButton />\n * </GrantGate>\n *\n * // With fallback for denied access\n * <GrantGate\n * resource=\"admin\"\n * action=\"access\"\n * fallback={<p>You don't have admin access</p>}\n * >\n * <AdminPanel />\n * </GrantGate>\n *\n * // With loading state\n * <GrantGate\n * resource=\"report\"\n * action=\"view\"\n * loading={<Spinner />}\n * fallback={<AccessDenied />}\n * >\n * <ReportViewer />\n * </GrantGate>\n *\n * // With scope for multi-tenant\n * <GrantGate\n * resource=\"project\"\n * action=\"delete\"\n * scope={{ tenant: 'project', id: projectId }}\n * >\n * <DeleteProjectButton />\n * </GrantGate>\n * ```\n */\nexport function GrantGate({\n resource,\n action,\n scope,\n enabled,\n useCache,\n children,\n fallback = null,\n loading = null,\n}: GrantGateProps): ReactNode {\n // Build options object conditionally\n // Only include scope in options if it's not undefined (null is valid and means \"wait for it\")\n // This allows the hook to distinguish between \"scope not provided\" (undefined) vs \"scope provided but null\"\n const options: Parameters<typeof useGrant>[2] = {\n enabled,\n useCache,\n returnLoading: loading !== null,\n };\n\n // Only add scope to options if it's explicitly null or a valid object\n // If scope is undefined, don't include it so hook treats it as optional\n if (scope !== undefined) {\n options.scope = scope;\n }\n\n // Use loading state if loading prop is provided\n const result = useGrant(resource, action, options);\n\n const isGranted = typeof result === 'boolean' ? result : result.isGranted;\n const isLoading = typeof result === 'boolean' ? false : result.isLoading;\n\n if (isLoading && loading !== null) {\n return loading;\n }\n\n if (isGranted) {\n return children;\n }\n\n return fallback;\n}\n"],"names":[],"mappings":";;;AAWA,MAAM,eAAe,cAAkC,IAAI;AAsDpD,SAAS,cAAc,EAAE,QAAQ,QAAQ,YAAgC;AAC9E,QAAM,cAAc,QAAQ,MAAM;AAChC,QAAI,OAAQ,QAAO;AACnB,WAAO,IAAI,YAAY,MAAM;AAAA,EAC/B,GAAG,CAAC,QAAQ,MAAM,CAAC;AAEnB,6BAAQ,aAAa,UAAb,EAAsB,OAAO,aAAc,UAAS;AAC9D;AAaO,SAAS,iBAA8B;AAC5C,QAAM,SAAS,WAAW,YAAY;AAEtC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAGJ;AAEA,SAAO;AACT;AAQO,SAAS,yBAA6C;AAC3D,SAAO,WAAW,YAAY;AAChC;AClEA,SAAS,eAAe,OAA8B;AACpD,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,GAAG,MAAM,MAAM,IAAI,MAAM,EAAE;AACpC;AAkCO,SAAS,SACd,UACA,QACA,UAA2B,CAAA,GACD;AAC1B,QAAM,EAAE,OAAO,UAAU,MAAM,WAAW,M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,MAAM;AAAA,MAChB;AAAA,IACF,QAAQ;AAEN,UAAI,UAAU,SAAS;AACrB,gBAAQ,IAAI;AAAA,MACd;AAAA,IACF,UAAA;AACE,UAAI,UAAU,SAAS;AACrB,qBAAa,KAAK;AAAA,MACpB;AAAA,IACF;AAAA,EAGF,GAAG,CAAC,QAAQ,UAAU,QAAQ,UAAU,sBAAsB,UAAU,UAAU,CAAC;AAEnF,YAAU,MAAM;AACd,cAAU,UAAU;AAGpB,QAAI,CAAC,wBAAwB,oBAAoB,SAAS;AACxD,cAAQ,IAAI;AACZ,mBAAa,KAAK;AAAA,IACpB,OAAO;AACL,sBAAA;AAAA,IACF;AAEA,WAAO,MAAM;AACX,gBAAU,UAAU;AAAA,IACtB;AAAA,EACF,GAAG,CAAC,iBAAiB,oBAAoB,CAAC;AAE1C,QAAM,YAAY,MAAM,cAAc;AAGtC,MAAI,eAAe;AACjB,WAAO,EAAE,WAAW,UAAA;AAAA,EACtB;AAEA,SAAO;AACT;ACzIO,SAAS,UAAU;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,UAAU;AACZ,GAA8B;AAI5B,QAAM,UAA0C;AAAA,IAC9C;AAAA,IACA;AAAA,IACA,eAAe,YAAY;AAAA,EAAA;AAK7B,MAAI,UAAU,QAAW;AACvB,YAAQ,QAAQ;AAAA,EAClB;AAGA,QAAM,SAAS,SAAS,UAAU,QAAQ,OAAO;AAEjD,QAAM,YAAY,OAAO,WAAW,YAAY,SAAS,OAAO;AAChE,QAAM,YAAY,OAAO,WAAW,YAAY,QAAQ,OAAO;AAE/D,MAAI,aAAa,YAAY,MAAM;AACjC,WAAO;AAAA,EACT;AAEA,MAAI,WAAW;AACb,WAAO;AAAA,EACT;AAEA,SAAO;AACT;"}
1
+ {"version":3,"file":"react.mjs","names":[],"sources":["../src/react/context.tsx","../src/react/hooks/useGrant.ts","../src/react/components/GrantGate.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, type ReactNode, useContext, useMemo } from 'react';\n\nimport { GrantClient } from '../grant-client';\nimport type { GrantClientConfig } from '../types';\n\n/**\n * Context for the Grant client\n */\nconst GrantContext = createContext<GrantClient | null>(null);\n\n/**\n * Props for the GrantProvider component\n */\nexport interface GrantProviderProps {\n /**\n * Grant client configuration\n */\n config: GrantClientConfig;\n\n /**\n * Pre-configured GrantClient instance (alternative to config)\n * If provided, config is ignored\n */\n client?: GrantClient;\n\n /**\n * Child components\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that makes the Grant client available to child components\n *\n * @example\n * ```tsx\n * // Option 1: Pass config (cookie-based refresh)\n * <GrantProvider\n * config={{\n * apiUrl: 'https://api.grant.com',\n * getAccessToken: () => localStorage.getItem('accessToken'),\n * onRefreshWithCredentials: async () => {\n * const res = await fetch('https://api.grant.com/api/auth/refresh', { method: 'POST', credentials: 'include' });\n * if (!res.ok) return false;\n * const { data } = await res.json();\n * if (data?.accessToken) { localStorage.setItem('accessToken', data.accessToken); return true; }\n * return false;\n * },\n * onTokenRefresh: (tokens) => { localStorage.setItem('accessToken', tokens.accessToken); },\n * onUnauthorized: () => { window.location.href = '/login'; },\n * }}\n * >\n * <App />\n * </GrantProvider>\n *\n * // Option 2: Pass pre-configured client\n * const grant = new GrantClient({ ... });\n * <GrantProvider client={grant}>\n * <App />\n * </GrantProvider>\n * ```\n */\nexport function GrantProvider({ config, client, children }: GrantProviderProps) {\n const grantClient = useMemo(() => {\n if (client) return client;\n return new GrantClient(config);\n }, [client, config]);\n\n return <GrantContext.Provider value={grantClient}>{children}</GrantContext.Provider>;\n}\n\n/**\n * Hook to access the Grant client from context\n *\n * @throws Error if used outside of GrantProvider\n *\n * @example\n * ```tsx\n * const grant = useGrantClient();\n * const hasPermission = await grant.can('resource', 'action');\n * ```\n */\nexport function useGrantClient(): GrantClient {\n const client = useContext(GrantContext);\n\n if (!client) {\n throw new Error(\n 'useGrantClient must be used within a GrantProvider. ' +\n 'Wrap your app with <GrantProvider config={...}> to fix this error.'\n );\n }\n\n return client;\n}\n\n/**\n * Hook to optionally access the Grant client\n * Returns null if not in a GrantProvider context\n *\n * Use this when you want to gracefully handle missing provider\n */\nexport function useGrantClientOptional(): GrantClient | null {\n return useContext(GrantContext);\n}\n","'use client';\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport type { AuthorizationResult, Scope } from '../../types';\nimport { useGrantClient } from '../context';\n\n/**\n * Options for the useGrant hook\n */\nexport interface UseGrantOptions {\n /** Scope to check the permission in. If provided but null/undefined, hook waits for it to become valid. */\n scope?: Scope | null;\n /** Whether to skip the permission check */\n enabled?: boolean;\n /** Whether to use cached results (default: true) */\n useCache?: boolean;\n /** Whether to return loading state (default: false) */\n returnLoading?: boolean;\n /** Context to check permissions for */\n context?: {\n resource?: Record<string, unknown> | null;\n };\n}\n\n/**\n * Result when returnLoading is true\n */\nexport interface UseGrantResult {\n /** Whether the user is granted permission */\n isGranted: boolean;\n /** Whether the permission check is loading */\n isLoading: boolean;\n}\n\n/**\n * Serialize scope for stable dependency comparison\n * This prevents re-fetching when scope object reference changes but values are the same\n */\nfunction serializeScope(scope?: Scope | null): string {\n if (!scope) return '';\n return `${scope.tenant}:${scope.id}`;\n}\n\n/**\n * Hook to check if a user is granted permission for a specific resource and action\n *\n * By default, returns a simple boolean, defaulting to false while loading.\n * Set `returnLoading: true` to get an object with `isGranted` and `isLoading`.\n *\n * @param resource - The resource slug to check\n * @param action - The action to check\n * @param options - Additional options\n *\n * @example\n * ```tsx\n * // Simple boolean (default)\n * const canEdit = useGrant('document', 'update');\n *\n * return (\n * <div>\n * {canEdit && <EditButton />}\n * </div>\n * );\n *\n * // With loading state\n * const { isGranted, isLoading } = useGrant('document', 'update', {\n * returnLoading: true,\n * });\n *\n * if (isLoading) return <Spinner />;\n * if (!isGranted) return null;\n *\n * return <EditButton />;\n * ```\n */\nexport function useGrant(\n resource: string,\n action: string,\n options: UseGrantOptions = {}\n): boolean | UseGrantResult {\n const { scope, enabled = true, useCache = true, returnLoading = false, context } = options;\n const client = useGrantClient();\n\n // Track if scope was explicitly provided (even if null/undefined)\n // This allows us to distinguish between \"scope not provided\" (optional) vs \"scope provided but falsy\" (wait for it)\n // Check this once at the start - if scope key exists in options, it was provided\n // Note: { scope: undefined } has the key, { } does not have the key\n const scopeWasProvidedRef = useRef('scope' in options);\n\n // Determine if we should wait for scope to become valid\n // If scope was provided but is falsy or invalid, wait for it to become truthy\n // Recalculate when scope changes\n const isEffectivelyEnabled = useMemo(() => {\n const hasValidScope =\n scope && typeof scope === 'object' && 'tenant' in scope && 'id' in scope && scope.id;\n const shouldWaitForScope = scopeWasProvidedRef.current && !hasValidScope;\n return enabled && !shouldWaitForScope;\n }, [scope, enabled]);\n\n const [data, setData] = useState<AuthorizationResult | null>(null);\n const [isLoading, setIsLoading] = useState(isEffectivelyEnabled);\n\n // Synchronously correct isLoading when isEffectivelyEnabled transitions.\n // useState only uses its initializer on first render, so subsequent transitions\n // leave isLoading stale for one render cycle (the effect hasn't run yet).\n // This uses React's \"storing information from previous renders\" pattern to\n // immediately set isLoading before the render completes.\n // See: https://react.dev/reference/react/useState#storing-information-from-previous-renders\n const [prevEffectivelyEnabled, setPrevEffectivelyEnabled] = useState(isEffectivelyEnabled);\n if (isEffectivelyEnabled !== prevEffectivelyEnabled) {\n setPrevEffectivelyEnabled(isEffectivelyEnabled);\n if (isEffectivelyEnabled) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n setData(null);\n }\n }\n\n // Track mounted state to prevent state updates after unmount\n const isMounted = useRef(true);\n\n // Store scope in a ref so we always have the latest value without triggering re-renders\n const scopeRef = useRef(scope);\n scopeRef.current = scope;\n\n // Store context in a ref so the callback always sends the latest context\n const contextRef = useRef(context);\n contextRef.current = context;\n\n // Serialize scope to get a stable string for dependency comparison\n const scopeKey = serializeScope(scope);\n\n // Serialize context so we re-create the callback when context meaningfully changes\n const contextKey = useMemo(\n () => (context?.resource != null ? JSON.stringify(context.resource) : ''),\n [context?.resource]\n );\n\n const fetchPermission = useCallback(async () => {\n if (!isEffectivelyEnabled) {\n setIsLoading(false);\n return;\n }\n\n setIsLoading(true);\n\n try {\n // Use scopeRef.current and contextRef.current to get the latest values\n // Convert null to undefined for the client (which expects Scope | undefined)\n const result = await client.isAuthorized(resource, action, {\n scope: scopeRef.current ?? undefined,\n useCache,\n context: contextRef.current,\n });\n if (isMounted.current) {\n setData(result);\n }\n } catch {\n // On error, set data to null (will return false)\n if (isMounted.current) {\n setData(null);\n }\n } finally {\n if (isMounted.current) {\n setIsLoading(false);\n }\n }\n // contextKey ensures we re-run when context (e.g. resource) changes so the request gets the latest context\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, resource, action, scopeKey, isEffectivelyEnabled, useCache, contextKey]);\n\n useEffect(() => {\n isMounted.current = true;\n\n // Clear data when scope becomes invalid (waiting for valid scope)\n if (!isEffectivelyEnabled && scopeWasProvidedRef.current) {\n setData(null);\n setIsLoading(false);\n } else {\n fetchPermission();\n }\n\n return () => {\n isMounted.current = false;\n };\n }, [fetchPermission, isEffectivelyEnabled]);\n\n const isGranted = data?.authorized ?? false;\n\n // Return object with loading state if requested, otherwise just boolean\n if (returnLoading) {\n return { isGranted, isLoading };\n }\n\n return isGranted;\n}\n","'use client';\n\nimport type { ReactNode } from 'react';\n\nimport { useGrant, type UseGrantOptions } from '../hooks/useGrant';\n\n/**\n * Props for the GrantGate component\n */\nexport interface GrantGateProps extends UseGrantOptions {\n /** The resource slug to check permission for */\n resource: string;\n /** The action to check */\n action: string;\n /** Content to render if permission is granted */\n children: ReactNode;\n /** Content to render if permission is denied (optional) */\n fallback?: ReactNode;\n /** Content to render while loading (optional) */\n loading?: ReactNode;\n}\n\n/**\n * Component that conditionally renders children based on permissions\n *\n * @example\n * ```tsx\n * // Basic usage - hide element if no permission\n * <GrantGate resource=\"document\" action=\"update\">\n * <EditButton />\n * </GrantGate>\n *\n * // With fallback for denied access\n * <GrantGate\n * resource=\"admin\"\n * action=\"access\"\n * fallback={<p>You don't have admin access</p>}\n * >\n * <AdminPanel />\n * </GrantGate>\n *\n * // With loading state\n * <GrantGate\n * resource=\"report\"\n * action=\"view\"\n * loading={<Spinner />}\n * fallback={<AccessDenied />}\n * >\n * <ReportViewer />\n * </GrantGate>\n *\n * // With scope for multi-tenant\n * <GrantGate\n * resource=\"project\"\n * action=\"delete\"\n * scope={{ tenant: 'project', id: projectId }}\n * >\n * <DeleteProjectButton />\n * </GrantGate>\n * ```\n */\nexport function GrantGate({\n resource,\n action,\n scope,\n enabled,\n useCache,\n children,\n fallback = null,\n loading = null,\n}: GrantGateProps): ReactNode {\n // Build options object conditionally\n // Only include scope in options if it's not undefined (null is valid and means \"wait for it\")\n // This allows the hook to distinguish between \"scope not provided\" (undefined) vs \"scope provided but null\"\n const options: Parameters<typeof useGrant>[2] = {\n enabled,\n useCache,\n returnLoading: loading !== null,\n };\n\n // Only add scope to options if it's explicitly null or a valid object\n // If scope is undefined, don't include it so hook treats it as optional\n if (scope !== undefined) {\n options.scope = scope;\n }\n\n // Use loading state if loading prop is provided\n const result = useGrant(resource, action, options);\n\n const isGranted = typeof result === 'boolean' ? result : result.isGranted;\n const isLoading = typeof result === 'boolean' ? false : result.isLoading;\n\n if (isLoading && loading !== null) {\n return loading;\n }\n\n if (isGranted) {\n return children;\n }\n\n return fallback;\n}\n"],"mappings":";;;;;;;AAUA,IAAM,eAAe,cAAkC,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsD5D,SAAgB,cAAc,EAAE,QAAQ,QAAQ,YAAgC;CAC9E,MAAM,cAAc,cAAc;AAChC,MAAI,OAAQ,QAAO;AACnB,SAAO,IAAI,YAAY,OAAO;IAC7B,CAAC,QAAQ,OAAO,CAAC;AAEpB,QAAO,oBAAC,aAAa,UAAd;EAAuB,OAAO;EAAc;EAAiC,CAAA;;;;;;;;;;;;;AActF,SAAgB,iBAA8B;CAC5C,MAAM,SAAS,WAAW,aAAa;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,WAAW,KAAA;IAC3B;IACA,SAAS,WAAW;IACrB,CAAC;AACF,OAAI,UAAU,QACZ,SAAQ,OAAO;UAEX;AAEN,OAAI,UAAU,QACZ,SAAQ,KAAK;YAEP;AACR,OAAI,UAAU,QACZ,cAAa,MAAM;;IAKtB;EAAC;EAAQ;EAAU;EAvCL,eAAe,MAuCF;EAAU;EAAsB;EApC3C,cACV,SAAS,YAAY,OAAO,KAAK,UAAU,QAAQ,SAAS,GAAG,IACtE,CAAC,SAAS,SAAS,CAkCmD;EAAW,CAAC;AAEpF,iBAAgB;AACd,YAAU,UAAU;AAGpB,MAAI,CAAC,wBAAwB,oBAAoB,SAAS;AACxD,WAAQ,KAAK;AACb,gBAAa,MAAM;QAEnB,kBAAiB;AAGnB,eAAa;AACX,aAAU,UAAU;;IAErB,CAAC,iBAAiB,qBAAqB,CAAC;CAE3C,MAAM,YAAY,MAAM,cAAc;AAGtC,KAAI,cACF,QAAO;EAAE;EAAW;EAAW;AAGjC,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvIT,SAAgB,UAAU,EACxB,UACA,QACA,OACA,SACA,UACA,UACA,WAAW,MACX,UAAU,QACkB;CAI5B,MAAM,UAA0C;EAC9C;EACA;EACA,eAAe,YAAY;EAC5B;AAID,KAAI,UAAU,KAAA,EACZ,SAAQ,QAAQ;CAIlB,MAAM,SAAS,SAAS,UAAU,QAAQ,QAAQ;CAElD,MAAM,YAAY,OAAO,WAAW,YAAY,SAAS,OAAO;AAGhE,MAFkB,OAAO,WAAW,YAAY,QAAQ,OAAO,cAE9C,YAAY,KAC3B,QAAO;AAGT,KAAI,UACF,QAAO;AAGT,QAAO"}
package/dist/types.d.ts CHANGED
@@ -53,6 +53,12 @@ export interface GrantClientConfig {
53
53
  * Refresh tokens are not sent in the request body; the API uses only the HttpOnly refresh cookie.
54
54
  */
55
55
  onRefreshWithCredentials?: () => Promise<boolean>;
56
+ /**
57
+ * Called when a request is rejected with MFA_REQUIRED (HTTP 403).
58
+ * Return `true` after the user completes MFA verification so the client retries the request
59
+ * with the updated access token, or `false` to accept the denial.
60
+ */
61
+ onMfaRequired?: () => Promise<boolean>;
56
62
  /**
57
63
  * Custom fetch implementation
58
64
  * Defaults to globalThis.fetch
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAG7C,YAAY,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAErD;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C,4BAA4B;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,WAAW,EAAE,MAAM,CAAC;IACpB,qDAAqD;IACrD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mCAAmC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAE9D;;;;OAIG;IACH,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE9D;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAE5B;;;;;;;OAOG;IACH,wBAAwB,CAAC,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAElD;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IAErB;;;OAGG;IACH,WAAW,CAAC,EA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AE,OAAO,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@grantjs/client",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Browser SDK for Grant authorization - React hooks and components for permission-based UI rendering",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -40,13 +40,13 @@
40
40
  "browser"
41
41
  ],
42
42
  "author": {
43
- "name": "Alejandro Heredia",
44
- "email": "ale@logus.graphics",
45
- "url": "https://logus.graphics"
43
+ "name": "Ale Heredia",
44
+ "email": "ale@grantjs.org",
45
+ "url": "https://grantjs.org"
46
46
  },
47
47
  "repository": {
48
48
  "type": "git",
49
- "url": "https://github.com/logusgraphics/grant.git",
49
+ "url": "https://github.com/grant-js/grant.git",
50
50
  "directory": "packages/@grantjs/client"
51
51
  },
52
52
  "license": "MIT",
@@ -55,23 +55,23 @@
55
55
  "registry": "https://registry.npmjs.org/"
56
56
  },
57
57
  "dependencies": {
58
- "@grantjs/schema": "1.0.0"
58
+ "@grantjs/schema": "1.1.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@tanstack/react-query": "^5.0.0",
61
+ "@tanstack/react-query": "^5.100.9",
62
62
  "@testing-library/jest-dom": "^6.9.1",
63
63
  "@testing-library/react": "^16.0.0",
64
- "@types/node": "^24.7.2",
64
+ "@types/node": "^25.6.0",
65
65
  "@types/react": "^19",
66
- "@vitejs/plugin-react": "^4.3.0",
67
- "@vitest/coverage-v8": "^3.2.4",
68
- "eslint": "^9.37.0",
69
- "jsdom": "^26.0.0",
70
- "react": "^19.0.0",
71
- "typescript": "^5",
72
- "vite": "^6.0.0",
73
- "vite-plugin-dts": "^4.3.0",
74
- "vitest": "^3.2.4"
66
+ "@vitejs/plugin-react": "^6.0.1",
67
+ "@vitest/coverage-v8": "^4.1.5",
68
+ "eslint": "^10.3.0",
69
+ "jsdom": "^29.1.1",
70
+ "react": "^19.2.5",
71
+ "typescript": "^6",
72
+ "vite": "^8.0.10",
73
+ "vite-plugin-dts": "^5.0.0",
74
+ "vitest": "^4.1.5"
75
75
  },
76
76
  "peerDependencies": {
77
77
  "@tanstack/react-query": "^5",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/grant-client.ts"],"sourcesContent":["import type {\n GrantClientConfig,\n AuthorizationResult,\n PermissionQueryOptions,\n Scope,\n SignInWithProjectAppOptions,\n} from './types';\n\n/**\n * Module-level shared promise for cookie-only refresh so that all 401s\n * (across all GrantClient instances and in-flight requests) coalesce into one refresh.\n */\nlet sharedCredentialsRefreshPromise: Promise<boolean> | null = null;\n\n/**\n * Grant Client for browser applications\n *\n * Makes HTTP requests to the Grant API to check permissions\n * and retrieve authorization data. Supports both token-based\n * and cookie-based authentication with automatic token refresh.\n */\nexport class GrantClient {\n private config: Required<Pick<GrantClientConfig, 'apiUrl'>> & GrantClientConfig;\n private cache: Map<string, { data: unknown; expires: number }> = new Map();\n private defaultTtl: number;\n\n constructor(config: GrantClientConfig) {\n this.config = config;\n this.defaultTtl = config.cache?.ttl ?? 5 * 60 * 1000; // 5 minutes default\n }\n\n // ============================================================================\n // Public API - Permission Checks\n // ============================================================================\n\n /**\n * Check if the current user has a specific permission\n *\n * @example\n * ```ts\n * const canEdit = await grant.can('document', 'update');\n * if (canEdit) {\n * // Show edit button\n * }\n * ```\n */\n async can(resource: string, action: string, options?: PermissionQueryOptions): Promise<boolean> {\n const result = await this.isAuthorized(resource, action, options);\n return result.authorized;\n }\n\n /**\n * Alias for `can` - check if user has permission\n */\n async hasPermission(\n resource: string,\n action: string,\n options?: PermissionQueryOptions\n ): Promise<boolean> {\n return this.can(resource, action, options);\n }\n\n // ============================================================================\n // Public API - Project OAuth (sign-in with project app)\n // ============================================================================\n\n /**\n * Start project-app OAuth flow (redirect only).\n * Navigates the current window to the Grant OAuth entry page; after sign-in and consent,\n * the user is redirected to the app's `redirect_uri` with token in the URL fragment.\n *\n * Requires `config.frontendUrl` and `redirectUri`.\n */\n async signInWithProjectApp(options: SignInWithProjectAppOptions): Promise<void> {\n const frontendUrl = this.config.frontendUrl;\n if (!frontendUrl) {\n throw new Error('GrantClient: frontendUrl is required for signInWithProjectApp');\n }\n const locale = options.locale ?? 'en';\n const redirectUri = options.redirectUri;\n if (!redirectUri) {\n throw new Error('redirectUri is required for signInWithProjectApp');\n }\n\n const entryPath = `/${locale}/auth/project`;\n const params = new URLSearchParams({\n client_id: options.clientId,\n redirect_uri: redirectUri,\n state: options.state ?? '',\n });\n if (options.scope) params.set('scope', options.scope);\n\n const entryUrl = `${frontendUrl.replace(/\\/$/, '')}${entryPath}?${params.toString()}`;\n if (typeof window !== 'undefined') {\n window.location.href = entryUrl;\n }\n }\n\n /**\n * Check authorization with full result details\n *\n * @example\n * ```ts\n * const result = await grant.isAuthorized('document', 'update');\n * if (!result.authorized) {\n * console.log('Denied:', result.reason);\n * }\n * ```\n */\n async isAuthorized(\n resource: string,\n action: string,\n options?: PermissionQueryOptions\n ): Promise<AuthorizationResult> {\n const contextResourceKey =\n options?.context?.resource != null ? JSON.stringify(options.context.resource) : undefined;\n const cacheKey = this.getCacheKey('auth', resource, action, options?.scope, contextResourceKey);\n\n // Check cache first (unless explicitly disabled)\n if (options?.useCache !== false) {\n const cached = this.getFromCache<AuthorizationResult>(cacheKey);\n if (cached) return cached;\n }\n\n try {\n // API expects: { permission: { resource, action }, context: { resource?: any }, scope?: { tenant, id } }\n // scope is optional - for session tokens it enables dynamic scope switching\n const scope = options?.scope;\n const hasValidScope =\n scope && typeof scope === 'object' && 'tenant' in scope && 'id' in scope;\n // When scope is provided and context.resource is not, derive context.resource from scope.id\n const contextResource =\n options?.context?.resource ??\n (hasValidScope && scope && 'id' in scope && scope.id != null ? { id: scope.id } : null);\n\n const response = await this.fetchWithAuth('/api/auth/is-authorized', {\n method: 'POST',\n body: JSON.stringify({\n permission: {\n resource,\n action,\n },\n context: {\n resource: contextResource,\n },\n // Pass scope for dynamic scope override (only works with session tokens)\n ...(hasValidScope && { scope }),\n }),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n return {\n authorized: false,\n reason: error.message || `API error: ${response.status}`,\n };\n }\n\n const json = await response.json();\n // API returns { success: true, data: { authorized, ... } }\n const result: AuthorizationResult = json.data ?? json;\n this.setCache(cacheKey, result);\n return result;\n } catch (error) {\n return {\n authorized: false,\n reason: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n // ============================================================================\n // Public API - Cache Management\n // ============================================================================\n\n /**\n * Clear all cached data\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n /**\n * Clear cached data for a specific scope\n */\n clearScopeCache(scope?: Scope): void {\n const scopeKey = scope ? JSON.stringify(scope) : 'default';\n for (const key of this.cache.keys()) {\n if (key.includes(scopeKey)) {\n this.cache.delete(key);\n }\n }\n }\n\n // ============================================================================\n // Private - HTTP & Authentication\n // ============================================================================\n\n /**\n * Make an authenticated fetch request with automatic token refresh on 401\n */\n private async fetchWithAuth(url: string, init?: RequestInit): Promise<Response> {\n const response = await this.doFetch(url, init);\n\n if (response.status !== 401) return response;\n\n // Cookie-based refresh (HttpOnly refresh cookie). Body-based refresh is not supported.\n // Module-level shared promise so all 401s (any client instance) coalesce into one refresh.\n if (this.config.onRefreshWithCredentials) {\n if (!sharedCredentialsRefreshPromise) {\n sharedCredentialsRefreshPromise = this.config.onRefreshWithCredentials().finally(() => {\n sharedCredentialsRefreshPromise = null;\n });\n }\n const refreshed = await sharedCredentialsRefreshPromise;\n if (refreshed) return this.doFetch(url, init);\n this.config.onUnauthorized?.();\n }\n\n return response;\n }\n\n /**\n * Perform the actual fetch request\n */\n private async doFetch(url: string, init?: RequestInit): Promise<Response> {\n const fetchFn = this.config.fetch ?? globalThis.fetch;\n const fullUrl = url.startsWith('http') ? url : `${this.config.apiUrl}${url}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(init?.headers as Record<string, string>),\n };\n\n // Add authorization header if token is available\n const token = await this.getToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n return fetchFn(fullUrl, {\n ...init,\n headers,\n // Include cookies for same-origin requests (supports cookie-based auth)\n credentials: this.config.credentials ?? 'include',\n });\n }\n\n /**\n * Get the current access token\n */\n private async getToken(): Promise<string | null> {\n if (this.config.getAccessToken) {\n const token = this.config.getAccessToken();\n return token instanceof Promise ? token : token;\n }\n return null;\n }\n\n // ============================================================================\n // Private - Cache & URL Helpers\n // ============================================================================\n\n private buildUrl(path: string, scope?: Scope): string {\n const url = new URL(path, this.config.apiUrl);\n if (scope) {\n url.searchParams.set('scope', JSON.stringify(scope));\n }\n return url.toString();\n }\n\n private getCacheKey(...parts: (string | Scope | undefined)[]): string {\n const prefix = this.config.cache?.prefix ?? 'grant';\n return `${prefix}:${parts.map((p) => (p ? JSON.stringify(p) : 'default')).join(':')}`;\n }\n\n private getFromCache<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n if (Date.now() > entry.expires) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data as T;\n }\n\n private setCache(key: string, data: unknown): void {\n this.cache.set(key, {\n data,\n expires: Date.now() + this.defaultTtl,\n });\n }\n}\n"],"names":[],"mappings":";;;;;AAYA,IAAI,kCAA2D;AASxD,MAAM,YAAY;AAAA,EAKvB,YAAY,QAA2B;AAJ/B;AACA,qDAA6D,IAAA;AAC7D;AAGN,SAAK,SAAS;AACd,SAAK,aAA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AAI,KAAK,OAAO,gBAAgB;AAC9B,YAAM,QAAQ,KAAK,OAAO,eAAA;AAC1B,aAAO,iBAAiB,UAAU,QAAQ;AAAA,IAC5C;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAMQ,SAAS,MAAc,OAAuB;AACpD,UAAM,MAAM,IAAI,IAAI,MAAM,KAAK,OAAO,MAAM;AAC5C,QAAI,OAAO;AACT,UAAI,aAAa,IAAI,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA,IACrD;AACA,WAAO,IAAI,SAAA;AAAA,EACb;AAAA,EAEQ,eAAe,OAA+C;AACpE,UAAM,SAAS,KAAK,OAAO,OAAO,UAAU;AAC5C,WAAO,GAAG,MAAM,IAAI,MAAM,IAAI,CAAC,MAAO,IAAI,KAAK,UAAU,CAAC,IAAI,SAAU,EAAE,KAAK,GAAG,CAAC;AAAA,EACrF;AAAA,EAEQ,aAAgB,KAAuB;AAC7C,UAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;AAChC,QAAI,CAAC,MAAO,QAAO;AAEnB,QAAI,KAAK,QAAQ,MAAM,SAAS;AAC9B,WAAK,MAAM,OAAO,GAAG;AACrB,aAAO;AAAA,IACT;AAEA,WAAO,MAAM;AAAA,EACf;AAAA,EAEQ,SAAS,KAAa,MAAqB;AACjD,SAAK,MAAM,IAAI,KAAK;AAAA,MAClB;AAAA,MACA,SAAS,KAAK,IAAA,IAAQ,KAAK;AAAA,IAAA,CAC5B;AAAA,EACH;AACF;;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/grant-client.ts"],"sourcesContent":["import type {\n GrantClientConfig,\n AuthorizationResult,\n PermissionQueryOptions,\n Scope,\n SignInWithProjectAppOptions,\n} from './types';\n\n/**\n * Module-level shared promise for cookie-only refresh so that all 401s\n * (across all GrantClient instances and in-flight requests) coalesce into one refresh.\n */\nlet sharedCredentialsRefreshPromise: Promise<boolean> | null = null;\n\n/**\n * Grant Client for browser applications\n *\n * Makes HTTP requests to the Grant API to check permissions\n * and retrieve authorization data. Supports both token-based\n * and cookie-based authentication with automatic token refresh.\n */\nexport class GrantClient {\n private config: Required<Pick<GrantClientConfig, 'apiUrl'>> & GrantClientConfig;\n private cache: Map<string, { data: unknown; expires: number }> = new Map();\n private defaultTtl: number;\n\n constructor(config: GrantClientConfig) {\n this.config = config;\n this.defaultTtl = config.cache?.ttl ?? 5 * 60 * 1000; // 5 minutes default\n }\n\n // ============================================================================\n // Public API - Permission Checks\n // ============================================================================\n\n /**\n * Check if the current user has a specific permission\n *\n * @example\n * ```ts\n * const canEdit = await grant.can('document', 'update');\n * if (canEdit) {\n * // Show edit button\n * }\n * ```\n */\n async can(resource: string, action: string, options?: PermissionQueryOptions): Promise<boolean> {\n const result = await this.isAuthorized(resource, action, options);\n return result.authorized;\n }\n\n /**\n * Alias for `can` - check if user has permission\n */\n async hasPermission(\n resource: string,\n action: string,\n options?: PermissionQueryOptions\n ): Promise<boolean> {\n return this.can(resource, action, options);\n }\n\n // ============================================================================\n // Public API - Project OAuth (sign-in with project app)\n // ============================================================================\n\n /**\n * Start project-app OAuth flow (redirect only).\n * Navigates the current window to the Grant OAuth entry page; after sign-in and consent,\n * the user is redirected to the app's `redirect_uri` with token in the URL fragment.\n *\n * Requires `config.frontendUrl` and `redirectUri`.\n */\n async signInWithProjectApp(options: SignInWithProjectAppOptions): Promise<void> {\n const frontendUrl = this.config.frontendUrl;\n if (!frontendUrl) {\n throw new Error('GrantClient: frontendUrl is required for signInWithProjectApp');\n }\n const locale = options.locale ?? 'en';\n const redirectUri = options.redirectUri;\n if (!redirectUri) {\n throw new Error('redirectUri is required for signInWithProjectApp');\n }\n\n const entryPath = `/${locale}/auth/project`;\n const params = new URLSearchParams({\n client_id: options.clientId,\n redirect_uri: redirectUri,\n state: options.state ?? '',\n });\n if (options.scope) params.set('scope', options.scope);\n\n const entryUrl = `${frontendUrl.replace(/\\/$/, '')}${entryPath}?${params.toString()}`;\n if (typeof window !== 'undefined') {\n window.location.href = entryUrl;\n }\n }\n\n /**\n * Check authorization with full result details\n *\n * @example\n * ```ts\n * const result = await grant.isAuthorized('document', 'update');\n * if (!result.authorized) {\n * console.log('Denied:', result.reason);\n * }\n * ```\n */\n async isAuthorized(\n resource: string,\n action: string,\n options?: PermissionQueryOptions\n ): Promise<AuthorizationResult> {\n const contextResourceKey =\n options?.context?.resource != null ? JSON.stringify(options.context.resource) : undefined;\n const cacheKey = this.getCacheKey('auth', resource, action, options?.scope, contextResourceKey);\n\n // Check cache first (unless explicitly disabled)\n if (options?.useCache !== false) {\n const cached = this.getFromCache<AuthorizationResult>(cacheKey);\n if (cached) return cached;\n }\n\n try {\n // API expects: { permission: { resource, action }, context: { resource?: any }, scope?: { tenant, id } }\n // scope is optional - for session tokens it enables dynamic scope switching\n const scope = options?.scope;\n const hasValidScope =\n scope && typeof scope === 'object' && 'tenant' in scope && 'id' in scope;\n // When scope is provided and context.resource is not, derive context.resource from scope.id\n const contextResource =\n options?.context?.resource ??\n (hasValidScope && scope && 'id' in scope && scope.id != null ? { id: scope.id } : null);\n\n const response = await this.fetchWithAuth('/api/auth/is-authorized', {\n method: 'POST',\n body: JSON.stringify({\n permission: {\n resource,\n action,\n },\n context: {\n resource: contextResource,\n },\n // Pass scope for dynamic scope override (only works with session tokens)\n ...(hasValidScope && { scope }),\n }),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n return {\n authorized: false,\n reason: error.message || `API error: ${response.status}`,\n };\n }\n\n const json = await response.json();\n // API returns { success: true, data: { authorized, ... } }\n const result: AuthorizationResult = json.data ?? json;\n this.setCache(cacheKey, result);\n return result;\n } catch (error) {\n return {\n authorized: false,\n reason: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n }\n\n // ============================================================================\n // Public API - Cache Management\n // ============================================================================\n\n /**\n * Clear all cached data\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n /**\n * Clear cached data for a specific scope\n */\n clearScopeCache(scope?: Scope): void {\n const scopeKey = scope ? JSON.stringify(scope) : 'default';\n for (const key of this.cache.keys()) {\n if (key.includes(scopeKey)) {\n this.cache.delete(key);\n }\n }\n }\n\n // ============================================================================\n // Private - HTTP & Authentication\n // ============================================================================\n\n /**\n * Make an authenticated fetch request with automatic token refresh on 401\n */\n private async fetchWithAuth(url: string, init?: RequestInit): Promise<Response> {\n const response = await this.doFetch(url, init);\n\n if (response.status !== 401) return response;\n\n // Cookie-based refresh (HttpOnly refresh cookie). Body-based refresh is not supported.\n // Module-level shared promise so all 401s (any client instance) coalesce into one refresh.\n if (this.config.onRefreshWithCredentials) {\n if (!sharedCredentialsRefreshPromise) {\n sharedCredentialsRefreshPromise = this.config.onRefreshWithCredentials().finally(() => {\n sharedCredentialsRefreshPromise = null;\n });\n }\n const refreshed = await sharedCredentialsRefreshPromise;\n if (refreshed) return this.doFetch(url, init);\n this.config.onUnauthorized?.();\n }\n\n return response;\n }\n\n /**\n * Perform the actual fetch request\n */\n private async doFetch(url: string, init?: RequestInit): Promise<Response> {\n const fetchFn = this.config.fetch ?? globalThis.fetch;\n const fullUrl = url.startsWith('http') ? url : `${this.config.apiUrl}${url}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...(init?.headers as Record<string, string>),\n };\n\n // Add authorization header if token is available\n const token = await this.getToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n return fetchFn(fullUrl, {\n ...init,\n headers,\n // Include cookies for same-origin requests (supports cookie-based auth)\n credentials: this.config.credentials ?? 'include',\n });\n }\n\n /**\n * Get the current access token\n */\n private async getToken(): Promise<string | null> {\n if (this.config.getAccessToken) {\n const token = this.config.getAccessToken();\n return token instanceof Promise ? token : token;\n }\n return null;\n }\n\n // ============================================================================\n // Private - Cache & URL Helpers\n // ============================================================================\n\n private buildUrl(path: string, scope?: Scope): string {\n const url = new URL(path, this.config.apiUrl);\n if (scope) {\n url.searchParams.set('scope', JSON.stringify(scope));\n }\n return url.toString();\n }\n\n private getCacheKey(...parts: (string | Scope | undefined)[]): string {\n const prefix = this.config.cache?.prefix ?? 'grant';\n return `${prefix}:${parts.map((p) => (p ? JSON.stringify(p) : 'default')).join(':')}`;\n }\n\n private getFromCache<T>(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n\n if (Date.now() > entry.expires) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.data as T;\n }\n\n private setCache(key: string, data: unknown): void {\n this.cache.set(key, {\n data,\n expires: Date.now() + this.defaultTtl,\n });\n }\n}\n"],"names":[],"mappings":";;;AAYA,IAAI,kCAA2D;AASxD,MAAM,YAAY;AAAA,EAKvB,YAAY,QAA2B;AAJ/B;AACA,qDAA6D,IAAA;AAC7D;AAGN,SAAK,SAAS;AACd,SAAK,aAAa,OAAO,OAAO,OAAO,IAAI,KAAK;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,MAAM,IAAI,UAAkB,QAAgB,SAAoD;AAC9F,UAAM,SAAS,MAAM,KAAK,aAAa,UAAU,QAAQ,OAAO;AAChE,WAAO,OAAO;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cACJ,UACA,QACA,SACkB;AAClB,WAAO,KAAK,IAAI,UAAU,QAAQ,OAAO;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,qBAAqB,SAAqD;AAC9E,UAAM,cAAc,KAAK,OAAO;AAChC,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,+DAA+D;AAAA,IACjF;AACA,UAAM,SAAS,QAAQ,UAAU;AACjC,UAAM,cAAc,QAAQ;AAC5B,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,kDAAkD;AAAA,IACpE;AAEA,UAAM,YAAY,IAAI,MAAM;AAC5B,UAAM,SAAS,IAAI,gBAAgB;AAAA,M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