@oxyhq/auth 1.0.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.
Files changed (119) hide show
  1. package/README.md +56 -0
  2. package/dist/cjs/WebOxyProvider.js +287 -0
  3. package/dist/cjs/hooks/mutations/index.js +23 -0
  4. package/dist/cjs/hooks/mutations/mutationFactory.js +126 -0
  5. package/dist/cjs/hooks/mutations/useAccountMutations.js +275 -0
  6. package/dist/cjs/hooks/mutations/useServicesMutations.js +149 -0
  7. package/dist/cjs/hooks/queries/index.js +35 -0
  8. package/dist/cjs/hooks/queries/queryKeys.js +82 -0
  9. package/dist/cjs/hooks/queries/useAccountQueries.js +141 -0
  10. package/dist/cjs/hooks/queries/useSecurityQueries.js +45 -0
  11. package/dist/cjs/hooks/queries/useServicesQueries.js +113 -0
  12. package/dist/cjs/hooks/queryClient.js +110 -0
  13. package/dist/cjs/hooks/useAssets.js +225 -0
  14. package/dist/cjs/hooks/useFileDownloadUrl.js +91 -0
  15. package/dist/cjs/hooks/useFileFiltering.js +81 -0
  16. package/dist/cjs/hooks/useFollow.js +159 -0
  17. package/dist/cjs/hooks/useFollow.types.js +4 -0
  18. package/dist/cjs/hooks/useQueryClient.js +16 -0
  19. package/dist/cjs/hooks/useSessionSocket.js +215 -0
  20. package/dist/cjs/hooks/useWebSSO.js +146 -0
  21. package/dist/cjs/index.js +115 -0
  22. package/dist/cjs/stores/accountStore.js +226 -0
  23. package/dist/cjs/stores/assetStore.js +192 -0
  24. package/dist/cjs/stores/authStore.js +47 -0
  25. package/dist/cjs/stores/followStore.js +154 -0
  26. package/dist/cjs/utils/authHelpers.js +154 -0
  27. package/dist/cjs/utils/avatarUtils.js +77 -0
  28. package/dist/cjs/utils/errorHandlers.js +128 -0
  29. package/dist/cjs/utils/sessionHelpers.js +90 -0
  30. package/dist/cjs/utils/storageHelpers.js +147 -0
  31. package/dist/esm/WebOxyProvider.js +282 -0
  32. package/dist/esm/hooks/mutations/index.js +10 -0
  33. package/dist/esm/hooks/mutations/mutationFactory.js +122 -0
  34. package/dist/esm/hooks/mutations/useAccountMutations.js +267 -0
  35. package/dist/esm/hooks/mutations/useServicesMutations.js +141 -0
  36. package/dist/esm/hooks/queries/index.js +14 -0
  37. package/dist/esm/hooks/queries/queryKeys.js +76 -0
  38. package/dist/esm/hooks/queries/useAccountQueries.js +131 -0
  39. package/dist/esm/hooks/queries/useSecurityQueries.js +40 -0
  40. package/dist/esm/hooks/queries/useServicesQueries.js +105 -0
  41. package/dist/esm/hooks/queryClient.js +104 -0
  42. package/dist/esm/hooks/useAssets.js +220 -0
  43. package/dist/esm/hooks/useFileDownloadUrl.js +86 -0
  44. package/dist/esm/hooks/useFileFiltering.js +78 -0
  45. package/dist/esm/hooks/useFollow.js +154 -0
  46. package/dist/esm/hooks/useFollow.types.js +3 -0
  47. package/dist/esm/hooks/useQueryClient.js +12 -0
  48. package/dist/esm/hooks/useSessionSocket.js +209 -0
  49. package/dist/esm/hooks/useWebSSO.js +143 -0
  50. package/dist/esm/index.js +48 -0
  51. package/dist/esm/stores/accountStore.js +219 -0
  52. package/dist/esm/stores/assetStore.js +180 -0
  53. package/dist/esm/stores/authStore.js +44 -0
  54. package/dist/esm/stores/followStore.js +151 -0
  55. package/dist/esm/utils/authHelpers.js +145 -0
  56. package/dist/esm/utils/avatarUtils.js +72 -0
  57. package/dist/esm/utils/errorHandlers.js +121 -0
  58. package/dist/esm/utils/sessionHelpers.js +84 -0
  59. package/dist/esm/utils/storageHelpers.js +108 -0
  60. package/dist/types/WebOxyProvider.d.ts +97 -0
  61. package/dist/types/hooks/mutations/index.d.ts +8 -0
  62. package/dist/types/hooks/mutations/mutationFactory.d.ts +75 -0
  63. package/dist/types/hooks/mutations/useAccountMutations.d.ts +68 -0
  64. package/dist/types/hooks/mutations/useServicesMutations.d.ts +22 -0
  65. package/dist/types/hooks/queries/index.d.ts +10 -0
  66. package/dist/types/hooks/queries/queryKeys.d.ts +64 -0
  67. package/dist/types/hooks/queries/useAccountQueries.d.ts +42 -0
  68. package/dist/types/hooks/queries/useSecurityQueries.d.ts +14 -0
  69. package/dist/types/hooks/queries/useServicesQueries.d.ts +31 -0
  70. package/dist/types/hooks/queryClient.d.ts +18 -0
  71. package/dist/types/hooks/useAssets.d.ts +34 -0
  72. package/dist/types/hooks/useFileDownloadUrl.d.ts +18 -0
  73. package/dist/types/hooks/useFileFiltering.d.ts +28 -0
  74. package/dist/types/hooks/useFollow.d.ts +61 -0
  75. package/dist/types/hooks/useFollow.types.d.ts +32 -0
  76. package/dist/types/hooks/useQueryClient.d.ts +6 -0
  77. package/dist/types/hooks/useSessionSocket.d.ts +13 -0
  78. package/dist/types/hooks/useWebSSO.d.ts +57 -0
  79. package/dist/types/index.d.ts +46 -0
  80. package/dist/types/stores/accountStore.d.ts +33 -0
  81. package/dist/types/stores/assetStore.d.ts +53 -0
  82. package/dist/types/stores/authStore.d.ts +16 -0
  83. package/dist/types/stores/followStore.d.ts +24 -0
  84. package/dist/types/utils/authHelpers.d.ts +98 -0
  85. package/dist/types/utils/avatarUtils.d.ts +33 -0
  86. package/dist/types/utils/errorHandlers.d.ts +34 -0
  87. package/dist/types/utils/sessionHelpers.d.ts +63 -0
  88. package/dist/types/utils/storageHelpers.d.ts +27 -0
  89. package/package.json +71 -0
  90. package/src/WebOxyProvider.tsx +372 -0
  91. package/src/global.d.ts +1 -0
  92. package/src/hooks/mutations/index.ts +25 -0
  93. package/src/hooks/mutations/mutationFactory.ts +215 -0
  94. package/src/hooks/mutations/useAccountMutations.ts +344 -0
  95. package/src/hooks/mutations/useServicesMutations.ts +164 -0
  96. package/src/hooks/queries/index.ts +36 -0
  97. package/src/hooks/queries/queryKeys.ts +88 -0
  98. package/src/hooks/queries/useAccountQueries.ts +152 -0
  99. package/src/hooks/queries/useSecurityQueries.ts +64 -0
  100. package/src/hooks/queries/useServicesQueries.ts +126 -0
  101. package/src/hooks/queryClient.ts +112 -0
  102. package/src/hooks/useAssets.ts +291 -0
  103. package/src/hooks/useFileDownloadUrl.ts +118 -0
  104. package/src/hooks/useFileFiltering.ts +115 -0
  105. package/src/hooks/useFollow.ts +175 -0
  106. package/src/hooks/useFollow.types.ts +33 -0
  107. package/src/hooks/useQueryClient.ts +17 -0
  108. package/src/hooks/useSessionSocket.ts +233 -0
  109. package/src/hooks/useWebSSO.ts +187 -0
  110. package/src/index.ts +144 -0
  111. package/src/stores/accountStore.ts +296 -0
  112. package/src/stores/assetStore.ts +281 -0
  113. package/src/stores/authStore.ts +63 -0
  114. package/src/stores/followStore.ts +181 -0
  115. package/src/utils/authHelpers.ts +183 -0
  116. package/src/utils/avatarUtils.ts +103 -0
  117. package/src/utils/errorHandlers.ts +194 -0
  118. package/src/utils/sessionHelpers.ts +151 -0
  119. package/src/utils/storageHelpers.ts +130 -0
@@ -0,0 +1,154 @@
1
+ import { useCallback, useMemo, useEffect } from 'react';
2
+ import { useFollowStore } from '../stores/followStore';
3
+ import { useWebOxy } from '../WebOxyProvider';
4
+ export const useFollow = (userId) => {
5
+ const { oxyServices } = useWebOxy();
6
+ const userIds = useMemo(() => (Array.isArray(userId) ? userId : userId ? [userId] : []), [userId]);
7
+ const isSingleUser = typeof userId === 'string';
8
+ // Zustand selectors
9
+ const followState = useFollowStore();
10
+ // Single user helpers
11
+ const isFollowing = isSingleUser && userId ? followState.followingUsers[userId] ?? false : false;
12
+ const isLoading = isSingleUser && userId ? followState.loadingUsers[userId] ?? false : false;
13
+ const error = isSingleUser && userId ? followState.errors[userId] ?? null : null;
14
+ // Follower count helpers
15
+ const followerCount = isSingleUser && userId ? followState.followerCounts[userId] ?? null : null;
16
+ const followingCount = isSingleUser && userId ? followState.followingCounts[userId] ?? null : null;
17
+ const isLoadingCounts = isSingleUser && userId ? followState.loadingCounts[userId] ?? false : false;
18
+ const toggleFollow = useCallback(async () => {
19
+ if (!isSingleUser || !userId)
20
+ throw new Error('toggleFollow is only available for single user mode');
21
+ await followState.toggleFollowUser(userId, oxyServices, isFollowing);
22
+ }, [isSingleUser, userId, followState, oxyServices, isFollowing]);
23
+ const setFollowStatus = useCallback((following) => {
24
+ if (!isSingleUser || !userId)
25
+ throw new Error('setFollowStatus is only available for single user mode');
26
+ followState.setFollowingStatus(userId, following);
27
+ }, [isSingleUser, userId, followState]);
28
+ const fetchStatus = useCallback(async () => {
29
+ if (!isSingleUser || !userId)
30
+ throw new Error('fetchStatus is only available for single user mode');
31
+ await followState.fetchFollowStatus(userId, oxyServices);
32
+ }, [isSingleUser, userId, followState, oxyServices]);
33
+ const clearError = useCallback(() => {
34
+ if (!isSingleUser || !userId)
35
+ throw new Error('clearError is only available for single user mode');
36
+ followState.clearFollowError(userId);
37
+ }, [isSingleUser, userId, followState]);
38
+ const fetchUserCounts = useCallback(async () => {
39
+ if (!isSingleUser || !userId)
40
+ throw new Error('fetchUserCounts is only available for single user mode');
41
+ await followState.fetchUserCounts(userId, oxyServices);
42
+ }, [isSingleUser, userId, followState, oxyServices]);
43
+ const setFollowerCount = useCallback((count) => {
44
+ if (!isSingleUser || !userId)
45
+ throw new Error('setFollowerCount is only available for single user mode');
46
+ followState.setFollowerCount(userId, count);
47
+ }, [isSingleUser, userId, followState]);
48
+ const setFollowingCount = useCallback((count) => {
49
+ if (!isSingleUser || !userId)
50
+ throw new Error('setFollowingCount is only available for single user mode');
51
+ followState.setFollowingCount(userId, count);
52
+ }, [isSingleUser, userId, followState]);
53
+ // Auto-fetch counts when hook is used for a single user and counts are missing.
54
+ useEffect(() => {
55
+ if (!isSingleUser || !userId)
56
+ return;
57
+ // If either count is not set and we're not already loading counts, trigger a fetch.
58
+ if ((followerCount === null || followingCount === null) && !isLoadingCounts) {
59
+ fetchUserCounts().catch((err) => console.warn('useFollow: fetchUserCounts failed', err));
60
+ }
61
+ }, [isSingleUser, userId, followerCount, followingCount, isLoadingCounts, fetchUserCounts]);
62
+ // Multiple user helpers
63
+ const followData = useMemo(() => {
64
+ const data = {};
65
+ userIds.forEach(uid => {
66
+ data[uid] = {
67
+ isFollowing: followState.followingUsers[uid] ?? false,
68
+ isLoading: followState.loadingUsers[uid] ?? false,
69
+ error: followState.errors[uid] ?? null,
70
+ };
71
+ });
72
+ return data;
73
+ }, [userIds, followState.followingUsers, followState.loadingUsers, followState.errors]);
74
+ const toggleFollowForUser = useCallback(async (targetUserId) => {
75
+ const currentState = followState.followingUsers[targetUserId] ?? false;
76
+ await followState.toggleFollowUser(targetUserId, oxyServices, currentState);
77
+ }, [followState, oxyServices]);
78
+ const setFollowStatusForUser = useCallback((targetUserId, following) => {
79
+ followState.setFollowingStatus(targetUserId, following);
80
+ }, [followState]);
81
+ const fetchStatusForUser = useCallback(async (targetUserId) => {
82
+ await followState.fetchFollowStatus(targetUserId, oxyServices);
83
+ }, [followState, oxyServices]);
84
+ const fetchAllStatuses = useCallback(async () => {
85
+ await Promise.all(userIds.map(uid => followState.fetchFollowStatus(uid, oxyServices)));
86
+ }, [userIds, followState, oxyServices]);
87
+ const clearErrorForUser = useCallback((targetUserId) => {
88
+ followState.clearFollowError(targetUserId);
89
+ }, [followState]);
90
+ const updateCountsFromFollowAction = useCallback((targetUserId, action, counts) => {
91
+ const currentUserId = oxyServices.getCurrentUserId() || undefined;
92
+ followState.updateCountsFromFollowAction(targetUserId, action, counts, currentUserId);
93
+ }, [followState, oxyServices]);
94
+ // Aggregate helpers for multiple users
95
+ const isAnyLoading = userIds.some(uid => followState.loadingUsers[uid]);
96
+ const hasAnyError = userIds.some(uid => !!followState.errors[uid]);
97
+ const allFollowing = userIds.every(uid => followState.followingUsers[uid]);
98
+ const allNotFollowing = userIds.every(uid => !followState.followingUsers[uid]);
99
+ if (isSingleUser && userId) {
100
+ return {
101
+ isFollowing,
102
+ isLoading,
103
+ error,
104
+ toggleFollow,
105
+ setFollowStatus,
106
+ fetchStatus,
107
+ clearError,
108
+ // Follower count methods
109
+ followerCount,
110
+ followingCount,
111
+ isLoadingCounts,
112
+ fetchUserCounts,
113
+ setFollowerCount,
114
+ setFollowingCount,
115
+ };
116
+ }
117
+ return {
118
+ followData,
119
+ toggleFollowForUser,
120
+ setFollowStatusForUser,
121
+ fetchStatusForUser,
122
+ fetchAllStatuses,
123
+ clearErrorForUser,
124
+ isAnyLoading,
125
+ hasAnyError,
126
+ allFollowing,
127
+ allNotFollowing,
128
+ };
129
+ };
130
+ // Convenience hook for just follower counts
131
+ export const useFollowerCounts = (userId) => {
132
+ const { oxyServices } = useWebOxy();
133
+ const followState = useFollowStore();
134
+ const followerCount = followState.followerCounts[userId] ?? null;
135
+ const followingCount = followState.followingCounts[userId] ?? null;
136
+ const isLoadingCounts = followState.loadingCounts[userId] ?? false;
137
+ const fetchUserCounts = useCallback(async () => {
138
+ await followState.fetchUserCounts(userId, oxyServices);
139
+ }, [userId, followState, oxyServices]);
140
+ const setFollowerCount = useCallback((count) => {
141
+ followState.setFollowerCount(userId, count);
142
+ }, [userId, followState]);
143
+ const setFollowingCount = useCallback((count) => {
144
+ followState.setFollowingCount(userId, count);
145
+ }, [userId, followState]);
146
+ return {
147
+ followerCount,
148
+ followingCount,
149
+ isLoadingCounts,
150
+ fetchUserCounts,
151
+ setFollowerCount,
152
+ setFollowingCount,
153
+ };
154
+ };
@@ -0,0 +1,3 @@
1
+ // Type-only definition for the useFollow hook to allow context exposure without runtime import cycles.
2
+ // Expand this as needed to better reflect the real return type.
3
+ export {};
@@ -0,0 +1,12 @@
1
+ import { useQueryClient as useTanStackQueryClient } from '@tanstack/react-query';
2
+ /**
3
+ * Custom hook to access the QueryClient
4
+ * Provides type safety and ensures client is available
5
+ */
6
+ export const useQueryClient = () => {
7
+ const queryClient = useTanStackQueryClient();
8
+ if (!queryClient) {
9
+ throw new Error('QueryClient is not available. Make sure OxyProvider is wrapping your app.');
10
+ }
11
+ return queryClient;
12
+ };
@@ -0,0 +1,209 @@
1
+ import { useEffect, useRef } from 'react';
2
+ import io from 'socket.io-client';
3
+ import { toast } from 'sonner';
4
+ import { logger } from '@oxyhq/core';
5
+ import { createDebugLogger } from '@oxyhq/core';
6
+ const debug = createDebugLogger('SessionSocket');
7
+ export function useSessionSocket({ userId, activeSessionId, currentDeviceId, refreshSessions, logout, clearSessionState, baseURL, onRemoteSignOut, onSessionRemoved }) {
8
+ const socketRef = useRef(null);
9
+ const joinedRoomRef = useRef(null);
10
+ // Store callbacks in refs to avoid re-joining when they change
11
+ const refreshSessionsRef = useRef(refreshSessions);
12
+ const logoutRef = useRef(logout);
13
+ const clearSessionStateRef = useRef(clearSessionState);
14
+ const onRemoteSignOutRef = useRef(onRemoteSignOut);
15
+ const onSessionRemovedRef = useRef(onSessionRemoved);
16
+ const activeSessionIdRef = useRef(activeSessionId);
17
+ const currentDeviceIdRef = useRef(currentDeviceId);
18
+ // Update refs when callbacks change
19
+ useEffect(() => {
20
+ refreshSessionsRef.current = refreshSessions;
21
+ logoutRef.current = logout;
22
+ clearSessionStateRef.current = clearSessionState;
23
+ onRemoteSignOutRef.current = onRemoteSignOut;
24
+ onSessionRemovedRef.current = onSessionRemoved;
25
+ activeSessionIdRef.current = activeSessionId;
26
+ currentDeviceIdRef.current = currentDeviceId;
27
+ }, [refreshSessions, logout, clearSessionState, onRemoteSignOut, onSessionRemoved, activeSessionId, currentDeviceId]);
28
+ useEffect(() => {
29
+ if (!userId || !baseURL) {
30
+ // Clean up if userId or baseURL becomes invalid
31
+ if (socketRef.current && joinedRoomRef.current) {
32
+ socketRef.current.emit('leave', { userId: joinedRoomRef.current });
33
+ joinedRoomRef.current = null;
34
+ }
35
+ return;
36
+ }
37
+ const roomId = `user:${userId}`;
38
+ // Only create socket if it doesn't exist
39
+ if (!socketRef.current) {
40
+ socketRef.current = io(baseURL, {
41
+ transports: ['websocket'],
42
+ });
43
+ }
44
+ const socket = socketRef.current;
45
+ // Only join if we haven't already joined this room
46
+ if (joinedRoomRef.current !== roomId) {
47
+ // Leave previous room if switching users
48
+ if (joinedRoomRef.current) {
49
+ socket.emit('leave', { userId: joinedRoomRef.current });
50
+ }
51
+ socket.emit('join', { userId: roomId });
52
+ joinedRoomRef.current = roomId;
53
+ debug.log('Emitting join for room:', roomId);
54
+ }
55
+ // Set up event handlers (only once per socket instance)
56
+ const handleConnect = () => {
57
+ debug.log('Socket connected:', socket.id);
58
+ };
59
+ const handleSessionUpdate = async (data) => {
60
+ debug.log('Received session_update:', data);
61
+ const currentActiveSessionId = activeSessionIdRef.current;
62
+ const currentDeviceId = currentDeviceIdRef.current;
63
+ // Handle different event types
64
+ if (data.type === 'session_removed') {
65
+ // Track removed session
66
+ if (data.sessionId && onSessionRemovedRef.current) {
67
+ onSessionRemovedRef.current(data.sessionId);
68
+ }
69
+ // If the removed sessionId matches the current activeSessionId, immediately clear state
70
+ if (data.sessionId === currentActiveSessionId) {
71
+ if (onRemoteSignOutRef.current) {
72
+ onRemoteSignOutRef.current();
73
+ }
74
+ else {
75
+ toast.info('You have been signed out remotely.');
76
+ }
77
+ // Use clearSessionState since session was already removed server-side
78
+ // Await to ensure storage cleanup completes before continuing
79
+ try {
80
+ await clearSessionStateRef.current();
81
+ }
82
+ catch (error) {
83
+ if (__DEV__) {
84
+ logger.error('Failed to clear session state after session_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
85
+ }
86
+ }
87
+ }
88
+ else {
89
+ // Otherwise, just refresh the sessions list (with error handling)
90
+ refreshSessionsRef.current().catch((error) => {
91
+ // Silently handle errors from refresh - they're expected if sessions were removed
92
+ if (__DEV__) {
93
+ logger.debug('Failed to refresh sessions after session_removed', { component: 'useSessionSocket' }, error);
94
+ }
95
+ });
96
+ }
97
+ }
98
+ else if (data.type === 'device_removed') {
99
+ // Track all removed sessions from this device
100
+ if (data.sessionIds && onSessionRemovedRef.current) {
101
+ for (const sessionId of data.sessionIds) {
102
+ onSessionRemovedRef.current(sessionId);
103
+ }
104
+ }
105
+ // If the removed deviceId matches the current device, immediately clear state
106
+ if (data.deviceId && data.deviceId === currentDeviceId) {
107
+ if (onRemoteSignOutRef.current) {
108
+ onRemoteSignOutRef.current();
109
+ }
110
+ else {
111
+ toast.info('This device has been removed. You have been signed out.');
112
+ }
113
+ // Use clearSessionState since sessions were already removed server-side
114
+ // Await to ensure storage cleanup completes before continuing
115
+ try {
116
+ await clearSessionStateRef.current();
117
+ }
118
+ catch (error) {
119
+ if (__DEV__) {
120
+ logger.error('Failed to clear session state after device_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
121
+ }
122
+ }
123
+ }
124
+ else {
125
+ // Otherwise, refresh sessions and device list (with error handling)
126
+ refreshSessionsRef.current().catch((error) => {
127
+ // Silently handle errors from refresh - they're expected if sessions were removed
128
+ if (__DEV__) {
129
+ logger.debug('Failed to refresh sessions after device_removed', { component: 'useSessionSocket' }, error);
130
+ }
131
+ });
132
+ }
133
+ }
134
+ else if (data.type === 'sessions_removed') {
135
+ // Track all removed sessions
136
+ if (data.sessionIds && onSessionRemovedRef.current) {
137
+ for (const sessionId of data.sessionIds) {
138
+ onSessionRemovedRef.current(sessionId);
139
+ }
140
+ }
141
+ // If the current activeSessionId is in the removed sessionIds list, immediately clear state
142
+ if (data.sessionIds && currentActiveSessionId && data.sessionIds.includes(currentActiveSessionId)) {
143
+ if (onRemoteSignOutRef.current) {
144
+ onRemoteSignOutRef.current();
145
+ }
146
+ else {
147
+ toast.info('You have been signed out remotely.');
148
+ }
149
+ // Use clearSessionState since sessions were already removed server-side
150
+ // Await to ensure storage cleanup completes before continuing
151
+ try {
152
+ await clearSessionStateRef.current();
153
+ }
154
+ catch (error) {
155
+ if (__DEV__) {
156
+ logger.error('Failed to clear session state after sessions_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
157
+ }
158
+ }
159
+ }
160
+ else {
161
+ // Otherwise, refresh sessions list (with error handling)
162
+ refreshSessionsRef.current().catch((error) => {
163
+ // Silently handle errors from refresh - they're expected if sessions were removed
164
+ if (__DEV__) {
165
+ logger.debug('Failed to refresh sessions after sessions_removed', { component: 'useSessionSocket' }, error);
166
+ }
167
+ });
168
+ }
169
+ }
170
+ else {
171
+ // For other event types (e.g., session_created), refresh sessions (with error handling)
172
+ refreshSessionsRef.current().catch((error) => {
173
+ // Log but don't throw - refresh errors shouldn't break the socket handler
174
+ if (__DEV__) {
175
+ logger.debug('Failed to refresh sessions after session_update', { component: 'useSessionSocket' }, error);
176
+ }
177
+ });
178
+ // If the current session was logged out (legacy behavior), handle it specially
179
+ if (data.sessionId === currentActiveSessionId) {
180
+ if (onRemoteSignOutRef.current) {
181
+ onRemoteSignOutRef.current();
182
+ }
183
+ else {
184
+ toast.info('You have been signed out remotely.');
185
+ }
186
+ // Use clearSessionState since session was already removed server-side
187
+ // Await to ensure storage cleanup completes before continuing
188
+ try {
189
+ await clearSessionStateRef.current();
190
+ }
191
+ catch (error) {
192
+ debug.error('Failed to clear session state after session_update:', error);
193
+ }
194
+ }
195
+ }
196
+ };
197
+ socket.on('connect', handleConnect);
198
+ socket.on('session_update', handleSessionUpdate);
199
+ return () => {
200
+ socket.off('connect', handleConnect);
201
+ socket.off('session_update', handleSessionUpdate);
202
+ // Only leave on unmount if we're still in this room
203
+ if (joinedRoomRef.current === roomId) {
204
+ socket.emit('leave', { userId: roomId });
205
+ joinedRoomRef.current = null;
206
+ }
207
+ };
208
+ }, [userId, baseURL]); // Only depend on userId and baseURL - callbacks are in refs
209
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Web SSO Hook
3
+ *
4
+ * Handles cross-domain SSO for web apps using FedCM (Federated Credential Management).
5
+ *
6
+ * FedCM is the modern, privacy-preserving standard for cross-domain identity federation.
7
+ * It works across completely different TLDs (alia.onl, mention.earth, homiio.com, etc.)
8
+ * without relying on third-party cookies.
9
+ *
10
+ * For browsers without FedCM support, users will need to click a sign-in button
11
+ * which triggers a popup-based authentication flow.
12
+ *
13
+ * This is called automatically by OxyContext on web platforms.
14
+ *
15
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/FedCM_API
16
+ */
17
+ import { useEffect, useRef, useCallback } from 'react';
18
+ /**
19
+ * Check if we're running in a web browser environment (not React Native)
20
+ */
21
+ function isWebBrowser() {
22
+ return typeof window !== 'undefined' &&
23
+ typeof document !== 'undefined' &&
24
+ typeof document.documentElement !== 'undefined';
25
+ }
26
+ /**
27
+ * Check if we're on the identity provider domain (where FedCM would authenticate against itself)
28
+ * Only auth.oxy.so is the IdP - accounts.oxy.so is a client app like any other
29
+ */
30
+ function isIdentityProvider() {
31
+ if (!isWebBrowser())
32
+ return false;
33
+ const hostname = window.location.hostname;
34
+ return hostname === 'auth.oxy.so';
35
+ }
36
+ /**
37
+ * Hook for automatic cross-domain web SSO
38
+ *
39
+ * Uses FedCM (Federated Credential Management) - the modern browser-native
40
+ * identity federation API. This is the same technology that powers
41
+ * Google's cross-domain SSO (YouTube, Gmail, Maps, etc.).
42
+ *
43
+ * Key benefits:
44
+ * - Works across different TLDs (alia.onl ↔ mention.earth ↔ homiio.com)
45
+ * - No third-party cookies required
46
+ * - Privacy-preserving (browser mediates identity, IdP can't track)
47
+ * - Automatic silent sign-in after initial authentication
48
+ *
49
+ * For browsers without FedCM (Firefox, older browsers), automatic SSO
50
+ * is not possible. Users will see a sign-in button instead.
51
+ */
52
+ export function useWebSSO({ oxyServices, onSessionFound, onSSOUnavailable, onError, enabled = true, }) {
53
+ const isCheckingRef = useRef(false);
54
+ const hasCheckedRef = useRef(false);
55
+ // Check FedCM support once
56
+ const fedCMSupported = isWebBrowser() && oxyServices.isFedCMSupported?.();
57
+ const checkSSO = useCallback(async () => {
58
+ if (!isWebBrowser() || isCheckingRef.current) {
59
+ return null;
60
+ }
61
+ // Don't use FedCM on the auth domain itself - it would authenticate against itself
62
+ if (isIdentityProvider()) {
63
+ onSSOUnavailable?.();
64
+ return null;
65
+ }
66
+ // FedCM is the only reliable cross-domain SSO mechanism
67
+ if (!fedCMSupported) {
68
+ onSSOUnavailable?.();
69
+ return null;
70
+ }
71
+ isCheckingRef.current = true;
72
+ try {
73
+ const session = await oxyServices.silentSignInWithFedCM?.();
74
+ if (session) {
75
+ await onSessionFound(session);
76
+ return session;
77
+ }
78
+ onSSOUnavailable?.();
79
+ return null;
80
+ }
81
+ catch (error) {
82
+ onSSOUnavailable?.();
83
+ onError?.(error instanceof Error ? error : new Error(String(error)));
84
+ return null;
85
+ }
86
+ finally {
87
+ isCheckingRef.current = false;
88
+ }
89
+ }, [oxyServices, onSessionFound, onSSOUnavailable, onError, fedCMSupported]);
90
+ /**
91
+ * Trigger interactive FedCM sign-in
92
+ * This shows the browser's native "Sign in with Oxy" prompt.
93
+ * Use this when silent mediation fails (user hasn't previously consented).
94
+ */
95
+ const signInWithFedCM = useCallback(async () => {
96
+ if (!isWebBrowser() || isCheckingRef.current) {
97
+ return null;
98
+ }
99
+ if (!fedCMSupported) {
100
+ onError?.(new Error('FedCM is not supported in this browser'));
101
+ return null;
102
+ }
103
+ isCheckingRef.current = true;
104
+ try {
105
+ const session = await oxyServices.signInWithFedCM?.();
106
+ if (session) {
107
+ await onSessionFound(session);
108
+ return session;
109
+ }
110
+ return null;
111
+ }
112
+ catch (error) {
113
+ onError?.(error instanceof Error ? error : new Error(String(error)));
114
+ return null;
115
+ }
116
+ finally {
117
+ isCheckingRef.current = false;
118
+ }
119
+ }, [oxyServices, onSessionFound, onError, fedCMSupported]);
120
+ // Auto-check SSO on mount (web only, FedCM only, not on auth domain)
121
+ useEffect(() => {
122
+ if (!enabled || !isWebBrowser() || hasCheckedRef.current || isIdentityProvider()) {
123
+ if (isIdentityProvider()) {
124
+ onSSOUnavailable?.();
125
+ }
126
+ return;
127
+ }
128
+ hasCheckedRef.current = true;
129
+ if (fedCMSupported) {
130
+ checkSSO();
131
+ }
132
+ else {
133
+ onSSOUnavailable?.();
134
+ }
135
+ }, [enabled, checkSSO, fedCMSupported, onSSOUnavailable]);
136
+ return {
137
+ checkSSO,
138
+ signInWithFedCM,
139
+ isChecking: isCheckingRef.current,
140
+ isFedCMSupported: fedCMSupported,
141
+ };
142
+ }
143
+ export { isWebBrowser };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @oxyhq/auth — OxyHQ Web Authentication SDK
3
+ *
4
+ * Headless authentication for React web apps (Next.js, Vite, CRA).
5
+ * Zero React Native / Expo dependencies.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * import { WebOxyProvider, useAuth } from '@oxyhq/auth';
10
+ *
11
+ * function App() {
12
+ * return (
13
+ * <WebOxyProvider baseURL="https://api.oxy.so">
14
+ * <YourApp />
15
+ * </WebOxyProvider>
16
+ * );
17
+ * }
18
+ *
19
+ * function YourApp() {
20
+ * const { user, isAuthenticated, signIn, signOut } = useAuth();
21
+ * // ...
22
+ * }
23
+ * ```
24
+ */
25
+ // --- Provider & Hooks ---
26
+ export { WebOxyProvider, useWebOxy, useAuth } from './WebOxyProvider';
27
+ // --- Stores ---
28
+ export { useAuthStore } from './stores/authStore';
29
+ export { useAssetStore, useAssets as useAssetsStore, useAsset, useUploadProgress, useAssetLoading, useAssetErrors, useAssetsByApp, useAssetsByEntity, useAssetUsageCount, useIsAssetLinked, } from './stores/assetStore';
30
+ // --- Query Hooks ---
31
+ export { useUserProfile, useUserProfiles, useCurrentUser, useUserById, useUserByUsername, useUsersBySessions, usePrivacySettings, useSessions, useSession, useDeviceSessions, useUserDevices, useSecurityInfo, useSecurityActivity, useRecentSecurityActivity, } from './hooks/queries';
32
+ // --- Mutation Hooks ---
33
+ export { useUpdateProfile, useUploadAvatar, useUpdateAccountSettings, useUpdatePrivacySettings, useUploadFile, useSwitchSession, useLogoutSession, useLogoutAll, useUpdateDeviceName, useRemoveDevice, } from './hooks/mutations';
34
+ export { createProfileMutation, createGenericMutation, } from './hooks/mutations/mutationFactory';
35
+ // --- Custom Hooks ---
36
+ export { useSessionSocket } from './hooks/useSessionSocket';
37
+ export { useAssets, setOxyAssetInstance } from './hooks/useAssets';
38
+ export { useFileDownloadUrl, setOxyFileUrlInstance } from './hooks/useFileDownloadUrl';
39
+ export { useFollow, useFollowerCounts } from './hooks/useFollow';
40
+ export { useFileFiltering } from './hooks/useFileFiltering';
41
+ // --- Auth Helpers ---
42
+ export { ensureValidToken, withAuthErrorHandling, authenticatedApiCall, isAuthenticationError, SessionSyncRequiredError, AuthenticationFailedError, } from './utils/authHelpers';
43
+ // --- Error Handlers ---
44
+ export { handleAuthError, isInvalidSessionError, isTimeoutOrNetworkError, extractErrorMessage, } from './utils/errorHandlers';
45
+ // Re-export core for convenience
46
+ export { OxyServices, CrossDomainAuth, AuthManager, createAuthManager, createCrossDomainAuth, } from '@oxyhq/core';
47
+ import { WebOxyProvider as _WebOxyProvider } from './WebOxyProvider';
48
+ export default _WebOxyProvider;