@oxyhq/auth 2.0.5 → 2.0.7

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.
Files changed (34) hide show
  1. package/dist/cjs/.tsbuildinfo +1 -1
  2. package/dist/cjs/WebOxyProvider.js +30 -8
  3. package/dist/cjs/hooks/mutations/index.js +5 -1
  4. package/dist/cjs/hooks/mutations/useAppData.js +133 -0
  5. package/dist/cjs/hooks/queries/appDataQueryKeys.js +46 -0
  6. package/dist/cjs/hooks/queries/index.js +8 -1
  7. package/dist/cjs/hooks/queries/useAppData.js +87 -0
  8. package/dist/cjs/hooks/useWebSSO.js +46 -2
  9. package/dist/cjs/index.js +8 -2
  10. package/dist/esm/.tsbuildinfo +1 -1
  11. package/dist/esm/WebOxyProvider.js +30 -8
  12. package/dist/esm/hooks/mutations/index.js +2 -0
  13. package/dist/esm/hooks/mutations/useAppData.js +128 -0
  14. package/dist/esm/hooks/queries/appDataQueryKeys.js +42 -0
  15. package/dist/esm/hooks/queries/index.js +3 -0
  16. package/dist/esm/hooks/queries/useAppData.js +82 -0
  17. package/dist/esm/hooks/useWebSSO.js +46 -2
  18. package/dist/esm/index.js +2 -2
  19. package/dist/types/.tsbuildinfo +1 -1
  20. package/dist/types/hooks/mutations/index.d.ts +1 -0
  21. package/dist/types/hooks/mutations/useAppData.d.ts +47 -0
  22. package/dist/types/hooks/queries/appDataQueryKeys.d.ts +24 -0
  23. package/dist/types/hooks/queries/index.d.ts +2 -0
  24. package/dist/types/hooks/queries/useAppData.d.ts +46 -0
  25. package/dist/types/index.d.ts +2 -2
  26. package/package.json +1 -1
  27. package/src/WebOxyProvider.tsx +31 -7
  28. package/src/hooks/mutations/index.ts +3 -0
  29. package/src/hooks/mutations/useAppData.ts +167 -0
  30. package/src/hooks/queries/appDataQueryKeys.ts +53 -0
  31. package/src/hooks/queries/index.ts +4 -0
  32. package/src/hooks/queries/useAppData.ts +105 -0
  33. package/src/hooks/useWebSSO.ts +48 -2
  34. package/src/index.ts +6 -0
@@ -11,6 +11,21 @@ import { OxyServices, CrossDomainAuth, createAuthManager, } from '@oxyhq/core';
11
11
  import { QueryClientProvider } from '@tanstack/react-query';
12
12
  import { attachQueryPersistence, createQueryClient } from './hooks/queryClient';
13
13
  const WebOxyContext = createContext(null);
14
+ /**
15
+ * Module-level run-once guard for FedCM silent sign-in.
16
+ *
17
+ * The init effect runs again whenever the provider remounts (route change,
18
+ * StrictMode double-invoke, error-boundary recovery). The redirect-callback
19
+ * and local-session-restore steps are cheap and idempotent, but the FedCM
20
+ * `silentSignIn()` step triggers `navigator.credentials.get`, which must fire
21
+ * AT MOST ONCE per page load — otherwise a remount storm becomes a credential
22
+ * request storm. Keyed by origin so the guard survives instance churn; never
23
+ * cleared because only a fresh page load can change the IdP session state.
24
+ */
25
+ const fedcmSilentSignInAttempted = new Set();
26
+ function silentSignInKey() {
27
+ return typeof window !== 'undefined' ? window.location.origin : 'no-origin';
28
+ }
14
29
  /**
15
30
  * Web-only Oxy Provider
16
31
  *
@@ -112,15 +127,22 @@ export function WebOxyProvider({ children, baseURL, authWebUrl, onAuthStateChang
112
127
  await authManager.signOut();
113
128
  }
114
129
  }
115
- try {
116
- const session = await crossDomainAuth.silentSignIn();
117
- if (mounted && session?.user) {
118
- await handleAuthSuccess(session, 'fedcm');
119
- return;
130
+ // FedCM silent sign-in: run AT MOST ONCE per page load. A remount
131
+ // (route change / StrictMode / error recovery) must not re-trigger
132
+ // the browser credential request.
133
+ const ssoKey = silentSignInKey();
134
+ if (!fedcmSilentSignInAttempted.has(ssoKey)) {
135
+ fedcmSilentSignInAttempted.add(ssoKey);
136
+ try {
137
+ const session = await crossDomainAuth.silentSignIn();
138
+ if (mounted && session?.user) {
139
+ await handleAuthSuccess(session, 'fedcm');
140
+ return;
141
+ }
142
+ }
143
+ catch {
144
+ // Silent sign-in failed — resolve to unauthenticated below.
120
145
  }
121
- }
122
- catch {
123
- // Silent sign-in failed
124
146
  }
125
147
  if (mounted)
126
148
  setIsLoading(false);
@@ -8,3 +8,5 @@
8
8
  export { useUpdateProfile, useUploadAvatar, useUpdateAccountSettings, useUpdatePrivacySettings, useUploadFile, } from './useAccountMutations';
9
9
  // Service mutation hooks (sessions, devices)
10
10
  export { useSwitchSession, useLogoutSession, useLogoutAll, useUpdateDeviceName, useRemoveDevice, } from './useServicesMutations';
11
+ // App-data KV store mutation hooks
12
+ export { useSetAppData, useDeleteAppData } from './useAppData';
@@ -0,0 +1,128 @@
1
+ /**
2
+ * App-Data Mutation Hooks
3
+ *
4
+ * Write side of the per-user JSON KV store. Both `useSetAppData` and
5
+ * `useDeleteAppData` apply optimistic updates against the two query keys
6
+ * that observe this data (`appDataQueryKeys.value` and the surrounding
7
+ * `appDataQueryKeys.namespace`) and roll back on error.
8
+ *
9
+ * When the underlying request fails because the endpoint isn't reachable
10
+ * (404 / network), the mutation still surfaces the error — write attempts
11
+ * are user-initiated and the caller may want to retry or fall back to
12
+ * local persistence. Reads are silent about missing endpoints; writes are
13
+ * not.
14
+ */
15
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
16
+ import { authenticatedApiCall } from '@oxyhq/core';
17
+ import { useWebOxy } from '../../WebOxyProvider';
18
+ import { appDataQueryKeys } from '../queries/appDataQueryKeys';
19
+ /**
20
+ * Upsert a per-user JSON value. Returns the value the server confirmed it
21
+ * stored — typically identical to the input but consumers should prefer the
22
+ * returned value (the server is the source of truth).
23
+ *
24
+ * Applies optimistic updates against both the single-value query key and
25
+ * the surrounding namespace query key, then rolls back on error.
26
+ */
27
+ export const useSetAppData = () => {
28
+ const { oxyServices, activeSessionId } = useWebOxy();
29
+ const queryClient = useQueryClient();
30
+ return useMutation({
31
+ mutationKey: ['appData', 'set'],
32
+ mutationFn: async ({ namespace, key, value }) => {
33
+ return authenticatedApiCall(oxyServices, activeSessionId, () => oxyServices.setAppData(namespace, key, value));
34
+ },
35
+ onMutate: async ({ namespace, key, value }) => {
36
+ const valueKey = appDataQueryKeys.value(namespace, key);
37
+ const namespaceKey = appDataQueryKeys.namespace(namespace);
38
+ await Promise.all([
39
+ queryClient.cancelQueries({ queryKey: valueKey }),
40
+ queryClient.cancelQueries({ queryKey: namespaceKey }),
41
+ ]);
42
+ const previousValue = queryClient.getQueryData(valueKey);
43
+ const previousNamespace = queryClient.getQueryData(namespaceKey);
44
+ queryClient.setQueryData(valueKey, value);
45
+ if (previousNamespace) {
46
+ queryClient.setQueryData(namespaceKey, {
47
+ ...previousNamespace,
48
+ [key]: value,
49
+ });
50
+ }
51
+ return { previousValue, previousNamespace };
52
+ },
53
+ onError: (_error, { namespace, key }, context) => {
54
+ if (!context)
55
+ return;
56
+ const valueKey = appDataQueryKeys.value(namespace, key);
57
+ const namespaceKey = appDataQueryKeys.namespace(namespace);
58
+ // Restore exactly the snapshots we captured in onMutate. Don't merge
59
+ // with whatever's currently in the cache — that could splice in writes
60
+ // from concurrent mutations and undo their state.
61
+ queryClient.setQueryData(valueKey, context.previousValue ?? null);
62
+ if (context.previousNamespace !== undefined) {
63
+ queryClient.setQueryData(namespaceKey, context.previousNamespace);
64
+ }
65
+ },
66
+ onSuccess: (data, { namespace, key }) => {
67
+ const valueKey = appDataQueryKeys.value(namespace, key);
68
+ const namespaceKey = appDataQueryKeys.namespace(namespace);
69
+ queryClient.setQueryData(valueKey, data);
70
+ const existingNamespace = queryClient.getQueryData(namespaceKey);
71
+ if (existingNamespace) {
72
+ queryClient.setQueryData(namespaceKey, {
73
+ ...existingNamespace,
74
+ [key]: data,
75
+ });
76
+ }
77
+ },
78
+ });
79
+ };
80
+ /**
81
+ * Delete a per-user JSON value. Optimistically removes the entry from the
82
+ * single-value cache and from the surrounding namespace map, then rolls back
83
+ * on error.
84
+ */
85
+ export const useDeleteAppData = () => {
86
+ const { oxyServices, activeSessionId } = useWebOxy();
87
+ const queryClient = useQueryClient();
88
+ return useMutation({
89
+ mutationKey: ['appData', 'delete'],
90
+ mutationFn: async ({ namespace, key }) => {
91
+ await authenticatedApiCall(oxyServices, activeSessionId, () => oxyServices.deleteAppData(namespace, key));
92
+ },
93
+ onMutate: async ({ namespace, key }) => {
94
+ const valueKey = appDataQueryKeys.value(namespace, key);
95
+ const namespaceKey = appDataQueryKeys.namespace(namespace);
96
+ await Promise.all([
97
+ queryClient.cancelQueries({ queryKey: valueKey }),
98
+ queryClient.cancelQueries({ queryKey: namespaceKey }),
99
+ ]);
100
+ const previousValue = queryClient.getQueryData(valueKey);
101
+ const previousNamespace = queryClient.getQueryData(namespaceKey);
102
+ queryClient.setQueryData(valueKey, null);
103
+ if (previousNamespace && key in previousNamespace) {
104
+ const next = { ...previousNamespace };
105
+ delete next[key];
106
+ queryClient.setQueryData(namespaceKey, next);
107
+ }
108
+ return { previousValue, previousNamespace };
109
+ },
110
+ onError: (_error, { namespace, key }, context) => {
111
+ if (!context)
112
+ return;
113
+ const valueKey = appDataQueryKeys.value(namespace, key);
114
+ const namespaceKey = appDataQueryKeys.namespace(namespace);
115
+ queryClient.setQueryData(valueKey, context.previousValue ?? null);
116
+ if (context.previousNamespace !== undefined) {
117
+ queryClient.setQueryData(namespaceKey, context.previousNamespace);
118
+ }
119
+ },
120
+ onSuccess: (_data, { namespace, key }) => {
121
+ queryClient.setQueryData(appDataQueryKeys.value(namespace, key), null);
122
+ // Confirm the value is gone from the namespace cache too. If the
123
+ // optimistic update wasn't applied (e.g. cache was empty), this is a
124
+ // no-op; if it was, we already removed it in onMutate, so this is also
125
+ // a no-op. The work happens in onMutate — onSuccess is the commit point.
126
+ },
127
+ });
128
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Query keys + error utilities for `useAppData` hooks.
3
+ *
4
+ * Lives next to the hook file so consumers can import the keys directly
5
+ * when they need to imperatively invalidate a value (e.g. after a non-React
6
+ * write through `oxyServices.setAppData`).
7
+ */
8
+ export const appDataQueryKeys = {
9
+ all: ['appData'],
10
+ namespaces: () => [...appDataQueryKeys.all, 'namespace'],
11
+ namespace: (namespace) => [...appDataQueryKeys.namespaces(), namespace],
12
+ values: () => [...appDataQueryKeys.all, 'value'],
13
+ value: (namespace, key) => [...appDataQueryKeys.values(), namespace, key],
14
+ };
15
+ /**
16
+ * True when `error` indicates the app-data endpoint isn't reachable — either
17
+ * because the API deployment doesn't have it yet (404) or there's a network
18
+ * failure with no response. We treat these as "no value stored" so consumers
19
+ * fall back to local persistence without surfacing a user-facing error.
20
+ *
21
+ * Anything else (401, 403, 500) propagates normally — those are real bugs
22
+ * the auth or retry pipeline needs to see.
23
+ */
24
+ export function isMissingAppDataEndpointError(error) {
25
+ if (!error || typeof error !== 'object') {
26
+ return false;
27
+ }
28
+ const candidate = error;
29
+ const status = candidate.status ?? candidate.statusCode ?? candidate.response?.status;
30
+ // 404: endpoint not deployed on this API instance yet.
31
+ if (status === 404)
32
+ return true;
33
+ // Network errors: no response received at all. Common during local dev
34
+ // when the API server is down, or when offline.
35
+ if (candidate.code === 'NETWORK_ERROR')
36
+ return true;
37
+ const message = typeof candidate.message === 'string' ? candidate.message : '';
38
+ if (message.includes('Network Error') || message.includes('Failed to fetch')) {
39
+ return true;
40
+ }
41
+ return false;
42
+ }
@@ -12,3 +12,6 @@ export { useSessions, useSession, useDeviceSessions, useUserDevices, useSecurity
12
12
  export { useSecurityActivity, useRecentSecurityActivity, } from './useSecurityQueries';
13
13
  // Query keys and invalidation helpers (for advanced usage)
14
14
  export { queryKeys, invalidateAccountQueries, invalidateUserQueries, invalidateSessionQueries } from './queryKeys';
15
+ // App-data KV store query hooks
16
+ export { useAppData, useAppDataNamespace } from './useAppData';
17
+ export { appDataQueryKeys, isMissingAppDataEndpointError } from './appDataQueryKeys';
@@ -0,0 +1,82 @@
1
+ /**
2
+ * App-Data Query Hooks
3
+ *
4
+ * Read side of the `/users/me/app-data/...` per-user JSON KV store. Gated on
5
+ * `isAuthenticated` — when signed out the query stays `enabled: false` and
6
+ * `data` is `null`, so consumers can fall back to localStorage without ever
7
+ * issuing a doomed request.
8
+ *
9
+ * Errors from the network (404 because the endpoint isn't deployed yet,
10
+ * 401 because the session lapsed, etc.) are not user-facing here. Hooks
11
+ * return `data: null` on error so the calling component renders the
12
+ * "nothing yet" state and the consuming app can quietly fall back to local
13
+ * persistence. Mutations still propagate errors so write attempts surface
14
+ * a toast — only reads are silent.
15
+ */
16
+ import { useQuery } from '@tanstack/react-query';
17
+ import { authenticatedApiCall } from '@oxyhq/core';
18
+ import { useWebOxy } from '../../WebOxyProvider';
19
+ import { appDataQueryKeys, isMissingAppDataEndpointError } from './appDataQueryKeys';
20
+ /**
21
+ * Read a single per-user JSON value.
22
+ *
23
+ * @param namespace - kebab/snake-case identifier (e.g. `"academy"`).
24
+ * @param key - kebab/snake-case identifier (e.g. course slug).
25
+ * @param options - optional `enabled`/`staleTime`/`gcTime` overrides.
26
+ *
27
+ * @returns A `useQuery` result with `data` of type `T | null`. The query
28
+ * stays disabled when the user is signed out; when enabled but the server
29
+ * has no stored value, `data` is `null`. Reads that fail because the
30
+ * endpoint isn't reachable also resolve to `null` so the consumer can
31
+ * fall back to local persistence.
32
+ */
33
+ export const useAppData = (namespace, key, options) => {
34
+ const { oxyServices, activeSessionId, isAuthenticated } = useWebOxy();
35
+ return useQuery({
36
+ queryKey: appDataQueryKeys.value(namespace, key),
37
+ queryFn: async () => {
38
+ try {
39
+ return await authenticatedApiCall(oxyServices, activeSessionId, () => oxyServices.getAppData(namespace, key));
40
+ }
41
+ catch (error) {
42
+ // Endpoint not deployed yet, no network, etc. — return null so the
43
+ // consumer falls back to localStorage rather than rendering a broken
44
+ // UI state. Authentication errors still bubble up so the auth retry
45
+ // pipeline can surface them at the provider level.
46
+ if (isMissingAppDataEndpointError(error)) {
47
+ return null;
48
+ }
49
+ throw error;
50
+ }
51
+ },
52
+ enabled: (options?.enabled !== false) && isAuthenticated,
53
+ staleTime: options?.staleTime ?? 60 * 1000,
54
+ gcTime: options?.gcTime ?? 30 * 60 * 1000,
55
+ });
56
+ };
57
+ /**
58
+ * Read every value in a namespace.
59
+ *
60
+ * @returns A `useQuery` result with `data` as a `Record<string, T>`. Empty
61
+ * object when the namespace contains nothing (or when fetching failed).
62
+ */
63
+ export const useAppDataNamespace = (namespace, options) => {
64
+ const { oxyServices, activeSessionId, isAuthenticated } = useWebOxy();
65
+ return useQuery({
66
+ queryKey: appDataQueryKeys.namespace(namespace),
67
+ queryFn: async () => {
68
+ try {
69
+ return await authenticatedApiCall(oxyServices, activeSessionId, () => oxyServices.listAppData(namespace));
70
+ }
71
+ catch (error) {
72
+ if (isMissingAppDataEndpointError(error)) {
73
+ return {};
74
+ }
75
+ throw error;
76
+ }
77
+ },
78
+ enabled: (options?.enabled !== false) && isAuthenticated,
79
+ staleTime: options?.staleTime ?? 60 * 1000,
80
+ gcTime: options?.gcTime ?? 30 * 60 * 1000,
81
+ });
82
+ };
@@ -15,6 +15,35 @@
15
15
  * @see https://developer.mozilla.org/en-US/docs/Web/API/FedCM_API
16
16
  */
17
17
  import { useEffect, useRef, useCallback } from 'react';
18
+ /**
19
+ * Module-level guard tracking which (origin + API) signatures have already
20
+ * had a silent SSO attempt this page load.
21
+ *
22
+ * A per-component `useRef` guard resets whenever the provider remounts (route
23
+ * churn, StrictMode double-invoke, error-boundary recovery), which previously
24
+ * allowed silent SSO to re-fire and — combined with a routing redirect loop —
25
+ * produced an accelerating `navigator.credentials.get` retry storm. Keying the
26
+ * guard on a stable signature instead of the component instance makes silent
27
+ * SSO fire EXACTLY ONCE per page load regardless of how many times the
28
+ * provider mounts. The set is intentionally never cleared: a fresh page load
29
+ * (the only thing that can change the answer) starts a fresh module scope.
30
+ */
31
+ const silentSSOAttempted = new Set();
32
+ /**
33
+ * Build a stable signature for the silent-SSO run-once guard. Two providers
34
+ * pointed at the same API from the same origin share one attempt.
35
+ */
36
+ function ssoSignature(oxyServices) {
37
+ const origin = typeof window !== 'undefined' ? window.location.origin : 'no-origin';
38
+ let baseURL = '';
39
+ try {
40
+ baseURL = oxyServices.getBaseURL();
41
+ }
42
+ catch {
43
+ baseURL = '';
44
+ }
45
+ return `${origin}|${baseURL}`;
46
+ }
18
47
  /**
19
48
  * Check if we're running in a web browser environment (not React Native)
20
49
  */
@@ -117,7 +146,14 @@ export function useWebSSO({ oxyServices, onSessionFound, onSSOUnavailable, onErr
117
146
  isCheckingRef.current = false;
118
147
  }
119
148
  }, [oxyServices, onSessionFound, onError, fedCMSupported]);
120
- // Auto-check SSO on mount (web only, FedCM only, not on auth domain)
149
+ // Auto-check SSO on mount (web only, FedCM only, not on auth domain).
150
+ //
151
+ // Run-once is enforced by TWO guards:
152
+ // 1. `hasCheckedRef` — cheap per-instance fast-path so effect re-runs
153
+ // (from changing deps) within one mount never re-fire.
154
+ // 2. `silentSSOAttempted` — module-level, survives remounts/StrictMode so
155
+ // silent SSO fires exactly once per page load even if the provider
156
+ // unmounts and remounts.
121
157
  useEffect(() => {
122
158
  if (!enabled || !isWebBrowser() || hasCheckedRef.current || isIdentityProvider()) {
123
159
  if (isIdentityProvider()) {
@@ -125,14 +161,22 @@ export function useWebSSO({ oxyServices, onSessionFound, onSSOUnavailable, onErr
125
161
  }
126
162
  return;
127
163
  }
164
+ const signature = ssoSignature(oxyServices);
165
+ if (silentSSOAttempted.has(signature)) {
166
+ // Already attempted this page load (e.g. before a remount) — do not
167
+ // re-fire. Mark the local fast-path too so subsequent re-renders skip.
168
+ hasCheckedRef.current = true;
169
+ return;
170
+ }
128
171
  hasCheckedRef.current = true;
172
+ silentSSOAttempted.add(signature);
129
173
  if (fedCMSupported) {
130
174
  checkSSO();
131
175
  }
132
176
  else {
133
177
  onSSOUnavailable?.();
134
178
  }
135
- }, [enabled, checkSSO, fedCMSupported, onSSOUnavailable]);
179
+ }, [enabled, checkSSO, fedCMSupported, onSSOUnavailable, oxyServices]);
136
180
  return {
137
181
  checkSSO,
138
182
  signInWithFedCM,
package/dist/esm/index.js CHANGED
@@ -30,9 +30,9 @@ export { useAssetStore, useAssets as useAssetsStore, useAsset, useUploadProgress
30
30
  export { useAccountStore, useAccounts, useAccountLoading, useAccountError, useAccountLoadingSession, } from './stores/accountStore';
31
31
  export { useFollowStore, } from './stores/followStore';
32
32
  // --- Query Hooks ---
33
- export { useUserProfile, useUserProfiles, useCurrentUser, useUserById, useUserByUsername, useUsersBySessions, usePrivacySettings, useSessions, useSession, useDeviceSessions, useUserDevices, useSecurityInfo, useSecurityActivity, useRecentSecurityActivity, } from './hooks/queries';
33
+ export { useUserProfile, useUserProfiles, useCurrentUser, useUserById, useUserByUsername, useUsersBySessions, usePrivacySettings, useSessions, useSession, useDeviceSessions, useUserDevices, useSecurityInfo, useSecurityActivity, useRecentSecurityActivity, useAppData, useAppDataNamespace, appDataQueryKeys, isMissingAppDataEndpointError, } from './hooks/queries';
34
34
  // --- Mutation Hooks ---
35
- export { useUpdateProfile, useUploadAvatar, useUpdateAccountSettings, useUpdatePrivacySettings, useUploadFile, useSwitchSession, useLogoutSession, useLogoutAll, useUpdateDeviceName, useRemoveDevice, } from './hooks/mutations';
35
+ export { useUpdateProfile, useUploadAvatar, useUpdateAccountSettings, useUpdatePrivacySettings, useUploadFile, useSwitchSession, useLogoutSession, useLogoutAll, useUpdateDeviceName, useRemoveDevice, useSetAppData, useDeleteAppData, } from './hooks/mutations';
36
36
  export { createProfileMutation, createGenericMutation, } from './hooks/mutations/mutationFactory';
37
37
  // --- Custom Hooks ---
38
38
  export { useWebSSO, isWebBrowser } from './hooks/useWebSSO';